diff --git a/src/components/KYCWall/types.ts b/src/components/KYCWall/types.ts index 55973cd139ba..46129d4b2bd7 100644 --- a/src/components/KYCWall/types.ts +++ b/src/components/KYCWall/types.ts @@ -68,7 +68,7 @@ type KYCWallProps = { shouldShowPersonalBankAccountOption?: boolean; /** Callback for the end of the onContinue trigger on option selection */ - onSuccessfulKYC: (iouPaymentType?: PaymentMethodType, currentSource?: Source) => void; + onSuccessfulKYC: (iouPaymentType?: PaymentMethodType, currentSource?: Source) => void | Promise; /** Children to build the KYC */ children: (continueAction: (params?: ContinueActionParams) => void, anchorRef: RefObject | null>) => void; diff --git a/src/components/MoneyReportHeaderPrimaryAction/PayPrimaryAction.tsx b/src/components/MoneyReportHeaderPrimaryAction/PayPrimaryAction.tsx index c0470de23ef7..0905d34358a8 100644 --- a/src/components/MoneyReportHeaderPrimaryAction/PayPrimaryAction.tsx +++ b/src/components/MoneyReportHeaderPrimaryAction/PayPrimaryAction.tsx @@ -38,6 +38,7 @@ import type {Transaction} from '@src/types/onyx'; import {hasSeenTourSelector} from '@selectors/Onboarding'; import React from 'react'; +import Onyx from 'react-native-onyx'; import useTransactionThreadData from './useTransactionThreadData'; @@ -63,15 +64,7 @@ function PayPrimaryAction({reportID, chatReportID, isDisabled}: PayPrimaryAction const [policy] = useOnyx(`${ONYXKEYS.COLLECTION.POLICY}${getNonEmptyStringOnyxID(moneyRequestReport?.policyID)}`); const [bankAccountList] = useOnyx(ONYXKEYS.BANK_ACCOUNT_LIST); - const [introSelected] = useOnyx(ONYXKEYS.NVP_INTRO_SELECTED); - const [isSelfTourViewed = false] = useOnyx(ONYXKEYS.NVP_ONBOARDING, {selector: hasSeenTourSelector}); - const [userBillingGracePeriodEnds] = useOnyx(ONYXKEYS.COLLECTION.SHARED_NVP_PRIVATE_USER_BILLING_GRACE_PERIOD_END); - const [amountOwed] = useOnyx(ONYXKEYS.NVP_PRIVATE_AMOUNT_OWED); - const [ownerBillingGracePeriodEnd] = useOnyx(ONYXKEYS.NVP_PRIVATE_OWNER_BILLING_GRACE_PERIOD_END); const [activePolicyID] = useOnyx(ONYXKEYS.NVP_ACTIVE_POLICY_ID); - const [conciergeReportID] = useOnyx(ONYXKEYS.CONCIERGE_REPORT_ID); - const [conciergeChat] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${conciergeReportID}`); - const [rules] = useOnyx(ONYXKEYS.COLLECTION.RULE); const activePolicy = usePolicy(activePolicyID); const chatReportPolicy = usePolicy(chatReport?.policyID); @@ -81,7 +74,6 @@ function PayPrimaryAction({reportID, chatReportID, isDisabled}: PayPrimaryAction const existingB2BInvoiceReport = useParticipantsInvoiceReport(activePolicyID, CONST.REPORT.INVOICE_RECEIVER_TYPE.BUSINESS, chatReport?.policyID); const getChatReportActions = usePayChatReportActions(chatReport, existingB2BInvoiceReport); const {getCurrencyDecimals, convertToDisplayString} = useCurrencyListActions(); - const isTrackIntentUser = isTrackOnboardingChoice(introSelected?.choice); const isInvoiceReport = isInvoiceReportUtil(moneyRequestReport); @@ -127,20 +119,38 @@ function PayPrimaryAction({reportID, chatReportID, isDisabled}: PayPrimaryAction const {openHoldMenu} = useMoneyReportHeaderModals(); - const confirmPayment = ({paymentType: type, payAsBusiness, methodID, paymentMethod}: PaymentActionParams) => { + const runPayment = async ({paymentType: type, payAsBusiness, methodID, paymentMethod}: PaymentActionParams) => { if (!type || !chatReport) { return; } if (isDelegateAccessRestricted) { showDelegateNoAccessModal(); - } else if (isAnyTransactionOnHold) { + return; + } + if (isAnyTransactionOnHold) { openHoldMenu({ requestType: CONST.IOU.REPORT_ACTION_TYPE.PAY, paymentType: type, methodID, onConfirm: () => startAnimation(), }); - } else if (isInvoiceReport) { + return; + } + + const [conciergeReportID, introSelected, onboarding, rules, userBillingGracePeriodEnds, amountOwed, ownerBillingGracePeriodEnd] = await Onyx.multiGet([ + ONYXKEYS.CONCIERGE_REPORT_ID, + ONYXKEYS.NVP_INTRO_SELECTED, + ONYXKEYS.NVP_ONBOARDING, + ONYXKEYS.COLLECTION.RULE, + ONYXKEYS.COLLECTION.SHARED_NVP_PRIVATE_USER_BILLING_GRACE_PERIOD_END, + ONYXKEYS.NVP_PRIVATE_AMOUNT_OWED, + ONYXKEYS.NVP_PRIVATE_OWNER_BILLING_GRACE_PERIOD_END, + ]); + const conciergeChat = await Onyx.get(`${ONYXKEYS.COLLECTION.REPORT}${conciergeReportID}`); + const isSelfTourViewed = hasSeenTourSelector(onboarding); + const isTrackIntentUser = isTrackOnboardingChoice(introSelected?.choice); + + if (isInvoiceReport) { startAnimation(); payInvoice({ bankAccountList, @@ -167,44 +177,45 @@ function PayPrimaryAction({reportID, chatReportID, isDisabled}: PayPrimaryAction isTrackIntentUser, rules, }); - } else { - payMoneyRequest({ - bankAccountList, - isASAPSubmitBetaEnabled: isBetaEnabled(CONST.BETAS.ASAP_SUBMIT), - getCurrencyDecimals, - paymentType: type, - chatReport, - iouReport: moneyRequestReport, - iouReportTransactions: transactions, - introSelected, - currentUserAccountID: accountID, - currentUserLogin: currentUserLogin ?? '', - activePolicy, - policy, - chatReportPolicy, - isSelfTourViewed, - userBillingGracePeriodEnds, - amountOwed, - ownerBillingGracePeriodEnd, - methodID: type === CONST.IOU.PAYMENT_TYPE.VBBA ? methodID : undefined, - isWiseReimbursementsBetaEnabled: isBetaEnabled(CONST.BETAS.WISE_REIMBURSEMENTS), - onPaid: startAnimation, - chatReportActions: getChatReportActions(false), - delegateAccountID, - isTrackIntentUser, - conciergeChat, - rules, + return; + } + + payMoneyRequest({ + bankAccountList, + isASAPSubmitBetaEnabled: isBetaEnabled(CONST.BETAS.ASAP_SUBMIT), + getCurrencyDecimals, + paymentType: type, + chatReport, + iouReport: moneyRequestReport, + iouReportTransactions: transactions, + introSelected, + currentUserAccountID: accountID, + currentUserLogin: currentUserLogin ?? '', + activePolicy, + policy, + chatReportPolicy, + isSelfTourViewed, + userBillingGracePeriodEnds, + amountOwed, + ownerBillingGracePeriodEnd, + methodID: type === CONST.IOU.PAYMENT_TYPE.VBBA ? methodID : undefined, + isWiseReimbursementsBetaEnabled: isBetaEnabled(CONST.BETAS.WISE_REIMBURSEMENTS), + onPaid: startAnimation, + chatReportActions: getChatReportActions(false), + delegateAccountID, + isTrackIntentUser, + conciergeChat, + rules, + }); + if (currentSearchQueryJSON && !isOffline) { + search({ + searchKey: currentSearchKey, + shouldCalculateTotals, + offset: 0, + queryJSON: currentSearchQueryJSON, + isLoading: !!currentSearchResults?.search?.isLoading, + shouldReturnTripRooms, }); - if (currentSearchQueryJSON && !isOffline) { - search({ - searchKey: currentSearchKey, - shouldCalculateTotals, - offset: 0, - queryJSON: currentSearchQueryJSON, - isLoading: !!currentSearchResults?.search?.isLoading, - shouldReturnTripRooms, - }); - } } }; @@ -222,7 +233,7 @@ function PayPrimaryAction({reportID, chatReportID, isDisabled}: PayPrimaryAction policyID={moneyRequestReport?.policyID} chatReportID={chatReport?.reportID} iouReport={moneyRequestReport} - onPress={confirmPayment} + onPress={runPayment} enablePaymentsRoute={ROUTES.ENABLE_PAYMENTS} shouldHidePaymentOptions={!shouldShowPayButton} isDisabled={(isOffline && !canAllowSettlement) || isDisabled} diff --git a/src/components/MoneyRequestReportView/MoneyRequestReportView.tsx b/src/components/MoneyRequestReportView/MoneyRequestReportView.tsx index db388b9692bf..6fbd17e6eb30 100644 --- a/src/components/MoneyRequestReportView/MoneyRequestReportView.tsx +++ b/src/components/MoneyRequestReportView/MoneyRequestReportView.tsx @@ -124,8 +124,6 @@ function MoneyRequestReportView({report, reportIDFromRoute, reportLoadingState, const isAppLoadPending = useIsAppLoadPending(); const {reportPendingAction, reportErrors: allReportErrors} = getReportOfflinePendingActionAndErrors(report); const [chatReport] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${getNonEmptyStringOnyxID(report?.chatReportID)}`); - const [conciergeReportID] = useOnyx(ONYXKEYS.CONCIERGE_REPORT_ID); - const [conciergeChat] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${conciergeReportID}`); const {reportActions: unfilteredReportActions} = usePaginatedReportActions(reportID); @@ -268,7 +266,6 @@ function MoneyRequestReportView({report, reportIDFromRoute, reportLoadingState, <> diff --git a/src/components/ReportActionItem/MoneyRequestReportPreview/PayActionButton.tsx b/src/components/ReportActionItem/MoneyRequestReportPreview/PayActionButton.tsx index be8711222e1f..c9778c7a3025 100644 --- a/src/components/ReportActionItem/MoneyRequestReportPreview/PayActionButton.tsx +++ b/src/components/ReportActionItem/MoneyRequestReportPreview/PayActionButton.tsx @@ -31,6 +31,7 @@ import type {PaymentMethodType} from '@src/types/onyx/OriginalMessage'; import {hasSeenTourSelector} from '@selectors/Onboarding'; import React from 'react'; +import Onyx from 'react-native-onyx'; import {useReportPreviewActions, useReportPreviewActionState, useReportPreviewAnimationState, useReportPreviewData, useReportPreviewUIState} from './MoneyRequestReportPreviewContext'; import useReportPreviewActionButtonData from './useReportPreviewActionButtonData'; @@ -55,19 +56,11 @@ function PayActionButton() { const {buttonMaxWidth} = useReportPreviewUIState(); const {reportPreviewAction, canIOUBePaid, onlyShowPayElsewhere, shouldShowPayButton} = useReportPreviewActionState(); - const [bankAccountList] = useOnyx(ONYXKEYS.BANK_ACCOUNT_LIST); const [activePolicyID] = useOnyx(ONYXKEYS.NVP_ACTIVE_POLICY_ID); - const [conciergeReportID] = useOnyx(ONYXKEYS.CONCIERGE_REPORT_ID); - const [conciergeChat] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${conciergeReportID}`); const activePolicy = usePolicy(activePolicyID); const actionButtonData = useReportPreviewActionButtonData(iouReportID); const {iouReport, policy, userBillingGracePeriodEnds, amountOwed, ownerBillingGracePeriodEnd} = actionButtonData; const chatReportPolicy = usePolicy(chatReport?.policyID); - const [introSelected] = useOnyx(ONYXKEYS.NVP_INTRO_SELECTED); - const [isSelfTourViewed] = useOnyx(ONYXKEYS.NVP_ONBOARDING, {selector: hasSeenTourSelector}); - const [rules] = useOnyx(ONYXKEYS.COLLECTION.RULE); - - const isTrackIntentUser = isTrackOnboardingChoice(introSelected?.choice); const existingB2BInvoiceReport = useParticipantsInvoiceReport(activePolicyID, CONST.REPORT.INVOICE_RECEIVER_TYPE.BUSINESS, chatReport?.policyID); const getChatReportActions = usePayChatReportActions(chatReport, existingB2BInvoiceReport); @@ -96,7 +89,7 @@ function PayActionButton() { }); }; - const confirmPayment = ({paymentType: type, payAsBusiness, methodID, paymentMethod}: PaymentActionParams) => { + const runPayment = async ({paymentType: type, payAsBusiness, methodID, paymentMethod}: PaymentActionParams) => { if (!type) { return; } @@ -105,6 +98,16 @@ function PayActionButton() { } else if (hasHeldExpensesReportUtils(transactions)) { openHoldMenu(type, methodID); } else if (chatReport && iouReport) { + const [conciergeReportID, introSelected, onboarding, rules, bankAccountList] = await Onyx.multiGet([ + ONYXKEYS.CONCIERGE_REPORT_ID, + ONYXKEYS.NVP_INTRO_SELECTED, + ONYXKEYS.NVP_ONBOARDING, + ONYXKEYS.COLLECTION.RULE, + ONYXKEYS.BANK_ACCOUNT_LIST, + ]); + const conciergeChat = await Onyx.get(`${ONYXKEYS.COLLECTION.REPORT}${conciergeReportID}`); + const isSelfTourViewed = hasSeenTourSelector(onboarding); + const isTrackIntentUser = isTrackOnboardingChoice(introSelected?.choice); const currentChatReport = getReportOrDraftReport({reportID: chatReportID}) ?? chatReport; if (isInvoiceReportUtils(iouReport)) { startAnimation(); @@ -179,7 +182,7 @@ function PayActionButton() { iouReport={iouReport} currency={iouReport?.currency} wrapperStyle={buttonMaxWidth} - onPress={confirmPayment} + onPress={runPayment} onPaymentOptionsShow={onPaymentOptionsShow} onPaymentOptionsHide={onPaymentOptionsHide} formattedAmount={formattedAmount} diff --git a/src/components/ReportActionItem/MoneyRequestReportPreview/index.tsx b/src/components/ReportActionItem/MoneyRequestReportPreview/index.tsx index 64a6b4eca202..78e4a97a8d9b 100644 --- a/src/components/ReportActionItem/MoneyRequestReportPreview/index.tsx +++ b/src/components/ReportActionItem/MoneyRequestReportPreview/index.tsx @@ -39,7 +39,7 @@ import ONYXKEYS from '@src/ONYXKEYS'; import ROUTES from '@src/ROUTES'; import {fullPolicySnapshotLastModifiedSelector} from '@src/selectors/Policy'; import {hasOnceLoadedReportActionsSelector, isLoadingInitialReportActionsSelector, pendingNewTransactionIDsSelector} from '@src/selectors/ReportMetaData'; -import type {ReportAction, ReportActions, Transaction} from '@src/types/onyx'; +import type {Report, ReportAction, ReportActions, Transaction} from '@src/types/onyx'; import type {ListRenderItem} from '@shopify/flash-list'; import type {LayoutChangeEvent} from 'react-native'; @@ -47,6 +47,7 @@ import type {OnyxEntry} from 'react-native-onyx'; import {useIsFocused} from '@react-navigation/core'; import React, {useEffect, useRef, useState} from 'react'; +import Onyx from 'react-native-onyx'; import type {MoneyRequestReportPreviewProps} from './types'; @@ -83,8 +84,6 @@ function MoneyRequestReportPreview({ const personalDetailsList = usePersonalDetails(); const {email: currentUserEmail, accountID: currentUserAccountID} = useCurrentUserPersonalDetails(); const [introSelected] = useOnyx(ONYXKEYS.NVP_INTRO_SELECTED); - const [conciergeReportID] = useOnyx(ONYXKEYS.CONCIERGE_REPORT_ID); - const [conciergeChat] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${conciergeReportID}`); const invoiceReceiverPolicyID = chatReport?.invoiceReceiver && 'policyID' in chatReport.invoiceReceiver ? chatReport.invoiceReceiver.policyID : undefined; const [invoiceReceiverPolicy] = useOnyx(`${ONYXKEYS.COLLECTION.POLICY}${getNonEmptyStringOnyxID(invoiceReceiverPolicyID)}`); const invoiceReceiverPersonalDetail = chatReport?.invoiceReceiver && 'accountID' in chatReport.invoiceReceiver ? personalDetailsList?.[chatReport.invoiceReceiver.accountID] : null; @@ -102,7 +101,7 @@ function MoneyRequestReportPreview({ const [hasIOUReportActions] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${getNonEmptyStringOnyxID(iouReportID)}`, { selector: hasReportActionsSelector, }); - const pendingExpenseTransactionRef = useRef<{transaction: Transaction; originRoute: string} | null>(null); + const pendingExpenseTransactionRef = useRef<{transaction: Transaction; originRoute: string; conciergeChat: OnyxEntry} | null>(null); // Subscribing to the whole action list re-rendered every card on each write, and a split writes a burst of // them. Narrow it to the one action a deferred press is waiting for, so nothing pending means nothing changes. const pendingPressActionCountSelector = (reportActions: OnyxEntry) => { @@ -223,7 +222,7 @@ function MoneyRequestReportPreview({ const transactionPreviewContainerStyles = [styles.h100, reportPreviewStyles.transactionPreviewCarouselStyle]; - const resolveChildReportID = (transaction: Transaction) => { + const resolveChildReportID = (transaction: Transaction, conciergeChat: OnyxEntry) => { let transactionIOUAction = getIOUActionForReportID(transaction.reportID, transaction.transactionID); if (transactionIOUAction && !isLiveIOUAction(transactionIOUAction)) { const liveIOUAction = getIOUActionForTransactionID(Object.values(getAllReportActions(transaction.reportID) ?? {}).filter(isLiveIOUAction), transaction.transactionID); @@ -329,7 +328,7 @@ function MoneyRequestReportPreview({ }); }; - const openTransactionFromPreview = (transaction: Transaction) => { + const openTransactionFromPreview = async (transaction: Transaction) => { if (contextMenuRef.current?.isContextMenuOpening) { return; } @@ -353,8 +352,11 @@ function MoneyRequestReportPreview({ return; } + // Read once per press and carry it to the deferred continuation below, which runs in an effect and must not read Onyx itself + const conciergeReportID = await Onyx.get(ONYXKEYS.CONCIERGE_REPORT_ID); + const conciergeChat = await Onyx.get(`${ONYXKEYS.COLLECTION.REPORT}${conciergeReportID}`); const isIOUActionLoaded = !!getIOUActionForReportID(transaction.reportID, transaction.transactionID); - const childReportID = resolveChildReportID(transaction); + const childReportID = resolveChildReportID(transaction, conciergeChat); const fullPolicySnapshot = policyID && fullPolicySnapshotLastModified ? {policyID, lastModified: fullPolicySnapshotLastModified} : undefined; if (childReportID) { if (!isIOUActionLoaded && iouReportID) { @@ -369,7 +371,7 @@ function MoneyRequestReportPreview({ } if (!isIOUActionLoaded && iouReportID && !isOffline) { - pendingExpenseTransactionRef.current = {transaction, originRoute: routeAtPress}; + pendingExpenseTransactionRef.current = {transaction, originRoute: routeAtPress, conciergeChat}; openReport({reportID: iouReportID, introSelected, conciergeChat, currentUserAccountID, hasReportActions: !!hasIOUReportActions, fullPolicySnapshot}); return; } @@ -387,7 +389,7 @@ function MoneyRequestReportPreview({ return; } const pendingTransaction = pendingPress.transaction; - const childReportID = resolveChildReportID(pendingTransaction); + const childReportID = resolveChildReportID(pendingTransaction, pendingPress.conciergeChat); if (childReportID) { pendingExpenseTransactionRef.current = null; navigateToExpense(childReportID, pendingPress.originRoute); @@ -426,7 +428,9 @@ function MoneyRequestReportPreview({ transactionPreviewWidth={reportPreviewStyles.transactionPreviewCarouselStyle.width} transactionID={item.transactionID} reportPreviewAction={action} - onPreviewPressed={() => openTransactionFromPreview(item)} + onPreviewPressed={() => { + openTransactionFromPreview(item); + }} shouldShowPayerAndReceiver={shouldShowPayerAndReceiver} shouldHighlight={!!newTransactionIDs?.has(item.transactionID)} /> diff --git a/src/components/ReportSubmitToPopoverAnchor.tsx b/src/components/ReportSubmitToPopoverAnchor.tsx index 1e22157a68fd..dd6e648ad8f1 100644 --- a/src/components/ReportSubmitToPopoverAnchor.tsx +++ b/src/components/ReportSubmitToPopoverAnchor.tsx @@ -2,6 +2,7 @@ import useReportSubmitToPopover from '@hooks/useReportSubmitToPopover'; import type {ReportSubmitToPopoverOpenOptions} from '@hooks/useReportSubmitToPopover'; import CONST from '@src/CONST'; +import type {SearchTransactionAction} from '@src/types/onyx/SearchResults'; import type AnchorAlignment from '@src/types/utils/AnchorAlignment'; import type {ComponentRef, RefObject} from 'react'; @@ -35,14 +36,15 @@ type SearchSubmitPopoverGuardContextValue = { isReportSubmitToPopoverVisible: boolean; isReportSubmitToDismissGuardActive: boolean; shouldDisableSearchSubmitPress: boolean; - consumeIgnoreNextSearchSubmitPress: () => boolean; + /** True for a Submit press while the submit-to popover is open or closing, or when this press just dismissed it. Consumes the one-shot flag, so call it once per press, before any await. */ + interceptSearchSubmitPress: (action: SearchTransactionAction | undefined) => boolean; }; const defaultSearchSubmitPopoverGuard: SearchSubmitPopoverGuardContextValue = { isReportSubmitToPopoverVisible: false, isReportSubmitToDismissGuardActive: false, shouldDisableSearchSubmitPress: false, - consumeIgnoreNextSearchSubmitPress: () => false, + interceptSearchSubmitPress: () => false, }; const SearchSubmitPopoverGuardContext = createContext(defaultSearchSubmitPopoverGuard); @@ -141,7 +143,7 @@ function ReportSubmitToPopoverHost({children, anchorAlignment}: ReportSubmitToPo openReportSubmitToPopover: openPopoverForActiveReport, isReportSubmitToPopoverVisible, isReportSubmitToDismissGuardActive, - consumeIgnoreNextSearchSubmitPress, + interceptSearchSubmitPress, } = useReportSubmitToPopover({ reportID: activeReportID, anchorAlignment, @@ -152,7 +154,7 @@ function ReportSubmitToPopoverHost({children, anchorAlignment}: ReportSubmitToPo isReportSubmitToPopoverVisible, isReportSubmitToDismissGuardActive, shouldDisableSearchSubmitPress: isReportSubmitToPopoverVisible || isReportSubmitToDismissGuardActive, - consumeIgnoreNextSearchSubmitPress, + interceptSearchSubmitPress, }; const openReportSubmitToPopoverForHost = (reportID: string | undefined, options?: ReportSubmitToPopoverOpenOptions, anchorRef?: RefObject | null>) => { @@ -240,7 +242,7 @@ function ReportSubmitToPopoverRootWithHost({reportID, host, children}: {reportID } function ReportSubmitToPopoverRootWithLocalPopover({reportID, onSubmitSuccess, anchorAlignment, children}: ReportSubmitToPopoverRootProps) { - const {anchorRef, openReportSubmitToPopover, reportSubmitToPopover, isReportSubmitToPopoverVisible, isReportSubmitToDismissGuardActive, consumeIgnoreNextSearchSubmitPress} = + const {anchorRef, openReportSubmitToPopover, reportSubmitToPopover, isReportSubmitToPopoverVisible, isReportSubmitToDismissGuardActive, interceptSearchSubmitPress} = useReportSubmitToPopover({ reportID, onSubmitSuccess, @@ -251,7 +253,7 @@ function ReportSubmitToPopoverRootWithLocalPopover({reportID, onSubmitSuccess, a isReportSubmitToPopoverVisible, isReportSubmitToDismissGuardActive, shouldDisableSearchSubmitPress: isReportSubmitToPopoverVisible || isReportSubmitToDismissGuardActive, - consumeIgnoreNextSearchSubmitPress, + interceptSearchSubmitPress, }; return ( diff --git a/src/components/Search/SearchBulkActionsButton.tsx b/src/components/Search/SearchBulkActionsButton.tsx index e27ffc59fa1d..7b1aac18dd5c 100644 --- a/src/components/Search/SearchBulkActionsButton.tsx +++ b/src/components/Search/SearchBulkActionsButton.tsx @@ -59,7 +59,7 @@ function SearchBulkActionsButton({queryJSON}: SearchBulkActionsButtonProps) { const [userBillingGracePeriodEnds] = useOnyx(ONYXKEYS.COLLECTION.SHARED_NVP_PRIVATE_USER_BILLING_GRACE_PERIOD_END); const [bankAccountList] = useOnyx(ONYXKEYS.BANK_ACCOUNT_LIST); // Sends an unvalidated user to the verify-account (security code) screen and resumes the stored bulk pay once they validate. - const {isUserValidated, verifyAccountAndResume} = useVerifyAccountAndResume((retry) => retry?.()); + const {isUserValidated, verifyAccountAndResume} = useVerifyAccountAndResume((retry?: () => void) => retry?.()); const activeAdminPolicies = useSortedActiveAdminPolicies(); const [amountOwed] = useOnyx(ONYXKEYS.NVP_PRIVATE_AMOUNT_OWED); const [ownerBillingGracePeriodEnd] = useOnyx(ONYXKEYS.NVP_PRIVATE_OWNER_BILLING_GRACE_PERIOD_END); diff --git a/src/components/Search/SearchList/ListItem/ActionCell/PayActionCell.tsx b/src/components/Search/SearchList/ListItem/ActionCell/PayActionCell.tsx index 704d4cd5d27c..40b7da9dcc6a 100644 --- a/src/components/Search/SearchList/ListItem/ActionCell/PayActionCell.tsx +++ b/src/components/Search/SearchList/ListItem/ActionCell/PayActionCell.tsx @@ -25,8 +25,9 @@ import type {Report} from '@src/types/onyx'; import type {OnyxEntry} from 'react-native-onyx'; -import {isTrackIntentUserSelector} from '@selectors/Onboarding'; +import {hasSeenTourSelector, isTrackIntentUserSelector} from '@selectors/Onboarding'; import React from 'react'; +import Onyx from 'react-native-onyx'; type PayActionCellProps = { isLoading: boolean; @@ -50,8 +51,6 @@ function PayActionCell({isLoading, policyID, reportID, hash, amount, shouldDisab const [allReports] = useOnyx(ONYXKEYS.COLLECTION.REPORT); const [allReportActions] = useOnyx(ONYXKEYS.COLLECTION.REPORT_ACTIONS); const [reportNameValuePairs] = useOnyx(ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS); - const [isTrackIntentUser] = useOnyx(ONYXKEYS.NVP_INTRO_SELECTED, {selector: isTrackIntentUserSelector}); - const [rules] = useOnyx(ONYXKEYS.COLLECTION.RULE); const invoiceReceiverPolicyID = chatReport?.invoiceReceiver && 'policyID' in chatReport.invoiceReceiver ? chatReport.invoiceReceiver.policyID : undefined; const invoiceReceiverPolicy = usePolicy(invoiceReceiverPolicyID); @@ -60,16 +59,10 @@ function PayActionCell({isLoading, policyID, reportID, hash, amount, shouldDisab currentUserAccountID, email, localCurrencyCode, - introSelected, isASAPSubmitBetaEnabled, isWiseReimbursementsBetaEnabled, - isSelfTourViewed, - userBillingGracePeriodEnds, - amountOwed, - ownerBillingGracePeriodEnd, activePolicyID, activePolicy, - conciergeChat, defaultWorkspaceName, chatReportPolicy, delegateAccountID, @@ -96,7 +89,7 @@ function PayActionCell({isLoading, policyID, reportID, hash, amount, shouldDisab const {currency} = iouReport ?? {}; - const confirmPayment = ({paymentType: type, payAsBusiness, methodID, paymentMethod}: PaymentActionParams) => { + const runPayment = async ({paymentType: type, payAsBusiness, methodID, paymentMethod}: PaymentActionParams) => { if (!type || !reportID || !hash || !amount) { Log.info('[SearchPay] Dropping row pay: missing required data', false, { hasPaymentType: !!type, @@ -114,6 +107,29 @@ function PayActionCell({isLoading, policyID, reportID, hash, amount, shouldDisab const additionalOnyxData = getSearchPayOnyxData(hash, reportID); + const readPaymentInputs = async () => { + const [conciergeReportID, rules, introSelected, onboarding, userBillingGracePeriodEnds, amountOwed, ownerBillingGracePeriodEnd] = await Onyx.multiGet([ + ONYXKEYS.CONCIERGE_REPORT_ID, + ONYXKEYS.COLLECTION.RULE, + ONYXKEYS.NVP_INTRO_SELECTED, + ONYXKEYS.NVP_ONBOARDING, + ONYXKEYS.COLLECTION.SHARED_NVP_PRIVATE_USER_BILLING_GRACE_PERIOD_END, + ONYXKEYS.NVP_PRIVATE_AMOUNT_OWED, + ONYXKEYS.NVP_PRIVATE_OWNER_BILLING_GRACE_PERIOD_END, + ]); + const conciergeChat = await Onyx.get(`${ONYXKEYS.COLLECTION.REPORT}${conciergeReportID}`); + return { + conciergeChat, + rules, + introSelected, + userBillingGracePeriodEnds, + amountOwed, + ownerBillingGracePeriodEnd, + isTrackIntentUser: isTrackIntentUserSelector(introSelected), + isSelfTourViewed: hasSeenTourSelector(onboarding), + }; + }; + if (isInvoiceReport(iouReport)) { // Invoice payments rely on the invoice room data, so they can't proceed without the chat report. if (!chatReport) { @@ -135,6 +151,7 @@ function PayActionCell({isLoading, policyID, reportID, hash, amount, shouldDisab const chatReportActions = allReportActions?.[`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${getNonEmptyStringOnyxID(shouldUseB2BInvoiceReport ? existingB2BInvoiceReport?.reportID : chatReport?.reportID)}`]; + const {conciergeChat, rules, introSelected, isTrackIntentUser, isSelfTourViewed} = await readPaymentInputs(); payInvoice({ bankAccountList, isASAPSubmitBetaEnabled, @@ -174,6 +191,7 @@ function PayActionCell({isLoading, policyID, reportID, hash, amount, shouldDisab return; } + const {conciergeChat, rules, introSelected, userBillingGracePeriodEnds, amountOwed, ownerBillingGracePeriodEnd, isTrackIntentUser, isSelfTourViewed} = await readPaymentInputs(); payMoneyRequest({ bankAccountList, isASAPSubmitBetaEnabled, @@ -215,7 +233,7 @@ function PayActionCell({isLoading, policyID, reportID, hash, amount, shouldDisab iouReport={iouReport} chatReportID={iouReport?.chatReportID} enablePaymentsRoute={ROUTES.ENABLE_PAYMENTS} - onPress={confirmPayment} + onPress={runPayment} style={[styles.w100, shouldDisablePointerEvents && styles.pointerEventsNone]} wrapperStyle={[styles.w100]} shouldShowPersonalBankAccountOption={!policyID && !iouReport?.policyID} diff --git a/src/components/Search/SearchList/ListItem/ActionCell/index.tsx b/src/components/Search/SearchList/ListItem/ActionCell/index.tsx index b6ab872eb42d..d052874f2bca 100644 --- a/src/components/Search/SearchList/ListItem/ActionCell/index.tsx +++ b/src/components/Search/SearchList/ListItem/ActionCell/index.tsx @@ -22,7 +22,7 @@ import PayActionCell from './PayActionCell'; type ActionCellProps = { action?: SearchTransactionAction; isSelected?: boolean; - onButtonPress: (event?: ModifiedMouseEvent) => void; + onButtonPress: (event?: ModifiedMouseEvent) => void | Promise; isChildListItem?: boolean; isLoading?: boolean; policyID?: string; diff --git a/src/components/Search/SearchList/ListItem/ExpenseReportListItem.tsx b/src/components/Search/SearchList/ListItem/ExpenseReportListItem.tsx index 4e997042c717..4b98042db83d 100644 --- a/src/components/Search/SearchList/ListItem/ExpenseReportListItem.tsx +++ b/src/components/Search/SearchList/ListItem/ExpenseReportListItem.tsx @@ -25,6 +25,7 @@ import {useReportPaymentContext} from '@hooks/usePaymentContext'; import {useGetPersonalDetailsByLogin} from '@hooks/usePersonalDetailByLogin'; import {useAllPersonalDetailsWithoutSnapshots} from '@hooks/usePersonalDetails'; import useResponsiveLayout from '@hooks/useResponsiveLayout'; +import useSearchActionPress from '@hooks/useSearchActionPress'; import useStyleUtils from '@hooks/useStyleUtils'; import useTheme from '@hooks/useTheme'; import useThemeStyles from '@hooks/useThemeStyles'; @@ -213,7 +214,8 @@ function ExpenseReportListItemInner({ const {showDelegateNoAccessModal} = useDelegateNoAccessActions(); const {showConfirmModal} = useConfirmModal(); const openReportSubmitToPopover = useOpenReportSubmitToPopover(); - const {shouldDisableSearchSubmitPress, consumeIgnoreNextSearchSubmitPress} = useSearchSubmitPopoverGuard(); + const {shouldDisableSearchSubmitPress} = useSearchSubmitPopoverGuard(); + const beginSearchActionPress = useSearchActionPress(); const {transactions: reportTransactions, violations: reportViolations} = useTransactionsAndViolationsForReport(reportItem.reportID); const liveReportTransactions = Object.values(reportTransactions); const confirmSubmitReportViolations = useConfirmSubmitReportViolations({ @@ -245,25 +247,16 @@ function ExpenseReportListItemInner({ const [liveViolationsForSnapshotTransactions] = useOnyxWithoutSnapshots(ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS, { selector: transactionViolationsByIDsSelector(snapshotTransactionIDs), }); - const { - currentUserAccountID, - currentUserLogin, - introSelected, - isASAPSubmitBetaEnabled, - isWiseReimbursementsBetaEnabled, - isSelfTourViewed, - activePolicy, - chatReportPolicy, - amountOwed, - delegateEmail, - delegateAccountID, - conciergeChat, - bankAccountList, - } = useReportPaymentContext({ - chatReportPolicyID: chatReport?.policyID, - }); + const {currentUserAccountID, currentUserLogin, isASAPSubmitBetaEnabled, isWiseReimbursementsBetaEnabled, activePolicy, chatReportPolicy, delegateEmail, delegateAccountID} = + useReportPaymentContext({ + chatReportPolicyID: chatReport?.policyID, + }); - const handleOnButtonPress = () => { + const handleOnButtonPress = async () => { + const pressTimeInputs = await beginSearchActionPress(liveReportItem.action); + if (!pressTimeInputs) { + return; + } handleActionButtonPress({ isASAPSubmitBetaEnabled, isWiseReimbursementsBetaEnabled, @@ -283,16 +276,11 @@ function ExpenseReportListItemInner({ personalPolicyID, confirmSubmitReportViolations, ownerBillingGracePeriodEnd, - amountOwed, openReportSubmitToPopover, - shouldDisableSearchSubmitPress, - consumeIgnoreNextSearchSubmitPress, onPendingCardTransactionsBlock: () => showPendingCardTransactionsBlockModal(showConfirmModal, translate, shouldShowMarkAsDoneCopy), onAllHeldExpensesBlock: () => showHeldExpensesBlockModal(showConfirmModal, translate, shouldShowMarkAsDoneCopy), currentUserAccountID, currentUserLogin, - introSelected, - isSelfTourViewed, activePolicy, chatReport, chatReportPolicy, @@ -307,8 +295,7 @@ function ExpenseReportListItemInner({ allViolations: liveViolationsForSnapshotTransactions, rules, personalDetailsByLogins: getPersonalDetailsByLogin(), - conciergeChat, - bankAccountList, + ...pressTimeInputs, }); }; diff --git a/src/components/Search/SearchList/ListItem/ExpenseReportListItemRow/types.ts b/src/components/Search/SearchList/ListItem/ExpenseReportListItemRow/types.ts index 4fbc13b9c723..ebd822639d06 100644 --- a/src/components/Search/SearchList/ListItem/ExpenseReportListItemRow/types.ts +++ b/src/components/Search/SearchList/ListItem/ExpenseReportListItemRow/types.ts @@ -17,7 +17,7 @@ type ExpenseReportListItemRowNarrowProps = { type ExpenseReportListItemRowWideProps = ExpenseReportListItemRowNarrowProps & { reportActions?: ReportAction[]; isActionLoading?: boolean; - onButtonPress?: () => void; + onButtonPress?: () => void | Promise; chatReport?: OnyxEntry; shouldDisableActionPointerEvents?: boolean; columns?: SearchColumnType[]; diff --git a/src/components/Search/SearchList/ListItem/ReportListItemHeader.tsx b/src/components/Search/SearchList/ListItem/ReportListItemHeader.tsx index 777f9d5e33b6..6f53c845f239 100644 --- a/src/components/Search/SearchList/ListItem/ReportListItemHeader.tsx +++ b/src/components/Search/SearchList/ListItem/ReportListItemHeader.tsx @@ -23,6 +23,7 @@ import {useReportPaymentContext} from '@hooks/usePaymentContext'; import {useGetPersonalDetailsByLogin} from '@hooks/usePersonalDetailByLogin'; import {useAllPersonalDetailsWithoutSnapshots} from '@hooks/usePersonalDetails'; import useResponsiveLayout from '@hooks/useResponsiveLayout'; +import useSearchActionPress from '@hooks/useSearchActionPress'; import useStyleUtils from '@hooks/useStyleUtils'; import useTheme from '@hooks/useTheme'; import useThemeStyles from '@hooks/useThemeStyles'; @@ -95,7 +96,7 @@ type FirstRowReportHeaderProps = { canSelectMultiple: boolean | undefined; /** Callback passed as goToItem in actionCell, triggered by clicking actionButton */ - handleOnButtonPress?: (event?: ModifiedMouseEvent) => void; + handleOnButtonPress?: (event?: ModifiedMouseEvent) => void | Promise; /** Color of the secondary avatar border, usually should match the container background */ avatarBorderColor?: ColorValue; @@ -298,23 +299,10 @@ function ReportListItemHeaderInner({ const reportTransactionIDs = (reportItem.transactions ?? []).map((transaction) => transaction.transactionID); const [allViolations] = useOnyxWithoutSnapshots(ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS, {selector: transactionViolationsByIDsSelector(reportTransactionIDs)}); - const { - currentUserAccountID, - currentUserLogin, - introSelected, - isASAPSubmitBetaEnabled, - isWiseReimbursementsBetaEnabled, - isSelfTourViewed, - activePolicy, - chatReportPolicy, - amountOwed, - delegateEmail, - delegateAccountID, - conciergeChat, - bankAccountList, - } = useReportPaymentContext({ - chatReportPolicyID: chatReport?.policyID, - }); + const {currentUserAccountID, currentUserLogin, isASAPSubmitBetaEnabled, isWiseReimbursementsBetaEnabled, activePolicy, chatReportPolicy, delegateEmail, delegateAccountID} = + useReportPaymentContext({ + chatReportPolicyID: chatReport?.policyID, + }); const {isDelegateAccessRestricted} = useDelegateNoAccessState(); const {showDelegateNoAccessModal} = useDelegateNoAccessActions(); const {translate} = useLocalize(); @@ -325,9 +313,14 @@ function ReportListItemHeaderInner({ StyleUtils.getItemBackgroundColorStyle(isSelected, !!isFocused || !!isHovered, !!isDisabled, theme.activeComponentBG, theme.hoverComponentBG)?.backgroundColor ?? theme.highlightBG; const openReportSubmitToPopover = useOpenReportSubmitToPopover(); - const {shouldDisableSearchSubmitPress, consumeIgnoreNextSearchSubmitPress} = useSearchSubmitPopoverGuard(); + const {shouldDisableSearchSubmitPress} = useSearchSubmitPopoverGuard(); + const beginSearchActionPress = useSearchActionPress(); - const handleOnButtonPress = (event?: ModifiedMouseEvent) => { + const handleOnButtonPress = async (event?: ModifiedMouseEvent) => { + const pressTimeInputs = await beginSearchActionPress(reportItem.action); + if (!pressTimeInputs) { + return; + } handleActionButtonPress({ isASAPSubmitBetaEnabled, isWiseReimbursementsBetaEnabled, @@ -346,17 +339,12 @@ function ReportListItemHeaderInner({ onDelegateAccessRestricted: showDelegateNoAccessModal, personalPolicyID, ownerBillingGracePeriodEnd, - amountOwed, confirmSubmitReportViolations, openReportSubmitToPopover, - shouldDisableSearchSubmitPress, - consumeIgnoreNextSearchSubmitPress, onPendingCardTransactionsBlock: () => showPendingCardTransactionsBlockModal(showConfirmModal, translate, shouldShowMarkAsDoneCopy), onAllHeldExpensesBlock: () => showHeldExpensesBlockModal(showConfirmModal, translate, shouldShowMarkAsDoneCopy), currentUserAccountID, currentUserLogin, - introSelected, - isSelfTourViewed, activePolicy, chatReport, chatReportPolicy, @@ -368,10 +356,10 @@ function ReportListItemHeaderInner({ allViolations, rules, personalDetailsByLogins: getPersonalDetailsByLogin(), - conciergeChat, - bankAccountList, + ...pressTimeInputs, }); }; + return !isLargeScreenWidth ? ( ({ const snapshotChatReport = chatReportID ? snapshotData?.[`${ONYXKEYS.COLLECTION.REPORT}${chatReportID}`] : undefined; const chatReport = parentChatReport ?? snapshotChatReport; const [chatReportActions] = useOnyxWithoutSnapshots(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${getNonEmptyStringOnyxID(chatReport?.reportID ?? chatReportID)}`); - const { - amountOwed, - currentUserAccountID, - currentUserLogin, - introSelected, - isASAPSubmitBetaEnabled, - isWiseReimbursementsBetaEnabled, - isSelfTourViewed, - activePolicy, - chatReportPolicy, - delegateEmail, - delegateAccountID, - conciergeChat, - bankAccountList, - } = useReportPaymentContext({ - chatReportPolicyID: chatReport?.policyID, - }); + const {currentUserAccountID, currentUserLogin, isASAPSubmitBetaEnabled, isWiseReimbursementsBetaEnabled, activePolicy, chatReportPolicy, delegateEmail, delegateAccountID} = + useReportPaymentContext({ + chatReportPolicyID: chatReport?.policyID, + }); const [isTrackIntentUser] = useOnyx(ONYXKEYS.NVP_INTRO_SELECTED, {selector: isTrackIntentUserSelector}); const [rules] = useOnyx(ONYXKEYS.COLLECTION.RULE); const getPersonalDetailsByLogin = useGetPersonalDetailsByLogin(); @@ -242,9 +230,14 @@ function TransactionListItemInner({ const {getCurrencyDecimals} = useCurrencyListActions(); const {showConfirmModal} = useConfirmModal(); const openReportSubmitToPopover = useOpenReportSubmitToPopover(); - const {shouldDisableSearchSubmitPress, consumeIgnoreNextSearchSubmitPress} = useSearchSubmitPopoverGuard(); + const {shouldDisableSearchSubmitPress} = useSearchSubmitPopoverGuard(); + const beginSearchActionPress = useSearchActionPress(); - const handleActionButtonPress = (event?: Parameters[2]) => { + const handleActionButtonPress = async (event?: Parameters[2]) => { + const pressTimeInputs = await beginSearchActionPress(liveTransactionItem.action); + if (!pressTimeInputs) { + return; + } handleActionButtonPressUtil({ isASAPSubmitBetaEnabled, isWiseReimbursementsBetaEnabled, @@ -263,18 +256,13 @@ function TransactionListItemInner({ onDelegateAccessRestricted: showDelegateNoAccessModal, personalPolicyID, ownerBillingGracePeriodEnd, - amountOwed, onUndelete: () => onUndelete?.(transactionItem), openReportSubmitToPopover, - shouldDisableSearchSubmitPress, - consumeIgnoreNextSearchSubmitPress, onPendingCardTransactionsBlock: () => showPendingCardTransactionsBlockModal(showConfirmModal, translate, shouldShowMarkAsDoneCopy), onAllHeldExpensesBlock: () => showHeldExpensesBlockModal(showConfirmModal, translate, shouldShowMarkAsDoneCopy), confirmSubmitReportViolations, currentUserAccountID, currentUserLogin, - introSelected, - isSelfTourViewed, activePolicy, chatReport, chatReportPolicy, @@ -286,8 +274,7 @@ function TransactionListItemInner({ allViolations, rules, personalDetailsByLogins: getPersonalDetailsByLogin(), - conciergeChat, - bankAccountList, + ...pressTimeInputs, }); }; diff --git a/src/components/Search/SearchList/ListItem/TransactionListItem/types.ts b/src/components/Search/SearchList/ListItem/TransactionListItem/types.ts index ea6c44d9cfbd..83e6348a944f 100644 --- a/src/components/Search/SearchList/ListItem/TransactionListItem/types.ts +++ b/src/components/Search/SearchList/ListItem/TransactionListItem/types.ts @@ -25,7 +25,7 @@ type TransactionListItemSharedProps = { isActionLoading?: boolean; isLastItem?: boolean; transactionViolations: TransactionViolation[]; - handleActionButtonPress: (event?: ModifiedMouseEvent) => void; + handleActionButtonPress: (event?: ModifiedMouseEvent) => void | Promise; shouldDisableActionPointerEvents?: boolean; transactionPreviewData: TransactionPreviewData; reportActions: ReportAction[]; diff --git a/src/components/Search/index.tsx b/src/components/Search/index.tsx index 2304035742de..9df705d22c7f 100644 --- a/src/components/Search/index.tsx +++ b/src/components/Search/index.tsx @@ -105,6 +105,7 @@ import {findFocusedRoute, useFocusEffect, useIsFocused, useNavigation} from '@re import * as Sentry from '@sentry/react-native'; import React, {startTransition, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState} from 'react'; import {View} from 'react-native'; +import Onyx from 'react-native-onyx'; import Animated, {useAnimatedStyle, useSharedValue, withTiming} from 'react-native-reanimated'; import type {ReportActionListItemType, SearchListItem, TransactionGroupListItemType, TransactionListItemType} from './SearchList/ListItem/types'; @@ -189,8 +190,6 @@ function Search({ const [transactions] = useOnyx(ONYXKEYS.COLLECTION.TRANSACTION); const [introSelected] = useOnyx(ONYXKEYS.NVP_INTRO_SELECTED); - const [conciergeReportID] = useOnyx(ONYXKEYS.CONCIERGE_REPORT_ID); - const [conciergeChat] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${conciergeReportID}`); const [isSelfTourViewed] = useOnyx(ONYXKEYS.NVP_ONBOARDING, { selector: hasSeenTourSelector, }); @@ -684,8 +683,12 @@ function Search({ hasSeededCarouselRef.current = false; }, [carouselSource, hash]); - const onSelectRow = useCallback( - (item: SearchListItem, transactionPreviewData?: TransactionPreviewData, event?: ModifiedMouseEvent) => { + const selectRow = useCallback( + async (item: SearchListItem, transactionPreviewData?: TransactionPreviewData, event?: ModifiedMouseEvent) => { + const readConciergeChat = async () => { + const conciergeReportID = await Onyx.get(ONYXKEYS.CONCIERGE_REPORT_ID); + return Onyx.get(`${ONYXKEYS.COLLECTION.REPORT}${conciergeReportID}`); + }; // A cash back row has no expenses to open, and Enter on a focused row still lands here. if (item.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE || isCashBackWithdrawalGroup(item)) { return; @@ -713,6 +716,7 @@ function Search({ if (shouldOpenTransactionThread && !shouldOpenTransactionThreadInNewTab) { seedCarouselForOpenedExpense(); } + const conciergeChat = await readConciergeChat(); const targetReportID = createAndOpenSearchTransactionThread({ conciergeChat, getCurrencyDecimals, @@ -785,22 +789,25 @@ function Search({ const firstTransaction = item.transactions.at(0); if (item.isOneTransactionReport && firstTransaction && transactionPreviewData) { if (!firstTransaction?.reportAction?.childReportID) { - createAndOpenSearchTransactionThread({ - conciergeChat, - getCurrencyDecimals, - item: firstTransaction, - introSelected, - backTo, - currentUserLogin: email ?? '', - currentUserAccountID: accountID, - personalDetails, - isSelfTourViewed, - hasCompletedGuidedSetupFlow, - delegateAccountID, - IOUTransactionID: firstTransaction?.reportAction?.childReportID, - transactionPreviewData, - shouldNavigate: false, - fullPolicySnapshotLastModifiedByPolicyID, + // Nothing after this needs the thread ID, so read the Concierge chat without awaiting and keep the new-tab and navigation code inside the click + readConciergeChat().then((conciergeChat) => { + createAndOpenSearchTransactionThread({ + conciergeChat, + getCurrencyDecimals, + item: firstTransaction, + introSelected, + backTo, + currentUserLogin: email ?? '', + currentUserAccountID: accountID, + personalDetails, + isSelfTourViewed, + hasCompletedGuidedSetupFlow, + delegateAccountID, + IOUTransactionID: firstTransaction?.reportAction?.childReportID, + transactionPreviewData, + shouldNavigate: false, + fullPolicySnapshotLastModifiedByPolicyID, + }); }); } else { setOptimisticDataForTransactionThreadPreview( @@ -903,12 +910,18 @@ function Search({ currentSearchKey, seedCarouselForOpenedExpense, getCurrencyDecimals, - conciergeChat, delegateAccountID, fullPolicySnapshotLastModifiedByPolicyID, ], ); + const onSelectRow = useCallback( + (item: SearchListItem, transactionPreviewData?: TransactionPreviewData, event?: ModifiedMouseEvent) => { + selectRow(item, transactionPreviewData, event); + }, + [selectRow], + ); + const carouselSiblingsKey = carouselSiblingTransactionIDs.join(','); const [activeCarouselTransactionIDs] = useOnyx(ONYXKEYS.TRANSACTION_THREAD_NAVIGATION_TRANSACTION_IDS); diff --git a/src/components/SettlementButton/index.tsx b/src/components/SettlementButton/index.tsx index 2d024c41e059..663c3404210f 100644 --- a/src/components/SettlementButton/index.tsx +++ b/src/components/SettlementButton/index.tsx @@ -61,6 +61,7 @@ import {guidedSetupAndTourStatusSelector} from '@selectors/Onboarding'; import truncate from 'lodash/truncate'; import React, {useContext} from 'react'; import {View} from 'react-native'; +import Onyx from 'react-native-onyx'; import type SettlementButtonProps from './types'; @@ -116,7 +117,6 @@ function SettlementButton({ // eslint-disable-next-line rulesdir/no-default-id-values const [chatReport] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${chatReportID || CONST.DEFAULT_NUMBER_ID}`); const [conciergeReportID] = useOnyx(ONYXKEYS.CONCIERGE_REPORT_ID); - const [conciergeChat] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${conciergeReportID}`); const [amountOwed] = useOnyx(ONYXKEYS.NVP_PRIVATE_AMOUNT_OWED); const reportBelongsToWorkspace = policyID ? doesReportBelongToWorkspace(chatReport, policyID, conciergeReportID) : false; const policyIDKey = reportBelongsToWorkspace ? policyID : (iouReport?.policyID ?? CONST.POLICY.ID_FAKE); @@ -158,13 +158,8 @@ function SettlementButton({ (policy?.achAccount?.state === CONST.BANK_ACCOUNT.STATE.OPEN || policy?.achAccount?.state === CONST.BANK_ACCOUNT.STATE.LOCKED))) && !lastPaymentMethod; const {isBetaEnabled} = usePermissions(); - const [introSelected] = useOnyx(ONYXKEYS.NVP_INTRO_SELECTED); - const [guidedSetupAndTourStatus] = useOnyx(ONYXKEYS.NVP_ONBOARDING, {selector: guidedSetupAndTourStatusSelector}); - const isSelfTourViewed = guidedSetupAndTourStatus?.isSelfTourViewed; - const hasCompletedGuidedSetupFlow = guidedSetupAndTourStatus?.hasCompletedGuidedSetupFlow; // eslint-disable-next-line rulesdir/no-default-id-values const [unlockRequestedAt] = useOnyx(`${ONYXKEYS.COLLECTION.NVP_LOCKED_VBA_UNLOCK_REQUESTED}${policy?.achAccount?.bankAccountID ?? CONST.DEFAULT_NUMBER_ID}`); - const [initiatingBankAccountUnlock] = useOnyx(ONYXKEYS.INITIATING_BANK_ACCOUNT_UNLOCK); const currentUserPersonalDetails = useCurrentUserPersonalDetails(); const delegateAccountID = useDelegateAccountID(); @@ -203,14 +198,20 @@ function SettlementButton({ confirmText: translate('bankAccount.unlockBankAccount'), cancelText: translate('common.cancel'), shouldDisableConfirmButtonWhenOffline: true, - }).then(({action}) => { + }).then(async ({action}) => { if (action !== ModalActions.CONFIRM) { return; } if (policy?.achAccount?.bankAccountID === undefined) { return; } + const [initiatingBankAccountUnlock, introSelected, onboarding] = await Onyx.multiGet([ + ONYXKEYS.INITIATING_BANK_ACCOUNT_UNLOCK, + ONYXKEYS.NVP_INTRO_SELECTED, + ONYXKEYS.NVP_ONBOARDING, + ]); pressLockedBankAccount(policy?.achAccount?.bankAccountID, translate, conciergeReportID, delegateAccountID, initiatingBankAccountUnlock); + const {isSelfTourViewed, hasCompletedGuidedSetupFlow} = guidedSetupAndTourStatusSelector(onboarding); navigateToConciergeChat({conciergeReportID, introSelected, currentUserAccountID, isSelfTourViewed, hasCompletedGuidedSetupFlow, conciergePersonalDetails}); }); } @@ -225,7 +226,7 @@ function SettlementButton({ return false; }; - const {isUserValidated, verifyAccountAndResume} = useVerifyAccountAndResume((retry?: () => void) => { + const {isUserValidated, verifyAccountAndResume} = useVerifyAccountAndResume((retry?: () => void | Promise) => { // The validation gate returned before these guards could run, so apply them to the resumed. if (checkForPostValidationBlockers()) { return; @@ -233,7 +234,7 @@ function SettlementButton({ retry?.(); }); - const checkForNecessaryAction = (paymentMethodType?: PaymentMethodType, retry?: () => void) => { + const checkForNecessaryAction = (paymentMethodType?: PaymentMethodType, retry?: () => void | Promise) => { if (isDelegateAccessRestricted) { showDelegateNoAccessModal(); return true; @@ -252,7 +253,7 @@ function SettlementButton({ return checkForPostValidationBlockers(); }; - const runPaymentAction = (paymentMethodType: PaymentMethodType | undefined, action: () => void) => { + const runPaymentAction = (paymentMethodType: PaymentMethodType | undefined, action: () => void | Promise) => { if (checkForNecessaryAction(paymentMethodType, action)) { return; } @@ -395,30 +396,35 @@ function SettlementButton({ })); }; - const getPolicyID = () => { + const navigateToBusinessBankAccountRoute = async () => { if (chatReport?.invoiceReceiver?.type === CONST.REPORT.INVOICE_RECEIVER_TYPE.BUSINESS) { - return chatReport?.invoiceReceiver?.policyID; + navigateToBankAccountRoute({policyID: chatReport?.invoiceReceiver?.policyID}); + return; } // Currency only decides whether direct reimbursement is offered, so it must not gate reuse here: // the setup flow we navigate to next is what brings the workspace to a supported currency. if (hasActivePolicyAsAdmin) { - return activePolicy.id; + navigateToBankAccountRoute({policyID: activePolicy.id}); + return; } - return createWorkspace({ + const [introSelected, onboarding] = await Onyx.multiGet([ONYXKEYS.NVP_INTRO_SELECTED, ONYXKEYS.NVP_ONBOARDING]); + const conciergeChat = await Onyx.get(`${ONYXKEYS.COLLECTION.REPORT}${conciergeReportID}`); + const {policyID: createdPolicyID} = createWorkspace({ introSelected, activePolicy, conciergeChat, currentUserAccountIDParam: currentUserPersonalDetails.accountID, currentUserEmailParam: email, currency: currentUserPersonalDetails.localCurrencyCode ?? CONST.CURRENCY.USD, - isSelfTourViewed, + isSelfTourViewed: guidedSetupAndTourStatusSelector(onboarding).isSelfTourViewed, hasActiveAdminPolicies: !!activeAdminPolicies.length, hasOwnedPaidPolicy, policyName: generateDefaultWorkspaceName(email, displayName, lastWorkspaceNumber, translate), delegateAccountID, - }).policyID; + }); + navigateToBankAccountRoute({policyID: createdPolicyID}); }; const getInvoicesOptions = (payAsBusiness: boolean) => { @@ -427,7 +433,7 @@ function SettlementButton({ icon: icons.Bank, onSelected: () => { if (payAsBusiness) { - navigateToBankAccountRoute({policyID: getPolicyID()}); + navigateToBusinessBankAccountRoute(); } else { clearPersonalBankAccount(); Navigation.navigate(ROUTES.SETTINGS_ADD_BANK_ACCOUNT.getRoute()); diff --git a/src/components/SettlementButton/types.ts b/src/components/SettlementButton/types.ts index b5f507ebfbd7..60dc58707c54 100644 --- a/src/components/SettlementButton/types.ts +++ b/src/components/SettlementButton/types.ts @@ -24,7 +24,7 @@ type PaymentActionParams = { type SettlementButtonProps = WithSentryLabel & { /** Callback to execute when this button is pressed. Receives payment action params. */ - onPress: (params: PaymentActionParams) => void; + onPress: (params: PaymentActionParams) => void | Promise; /** Callback when the payment options popover is shown */ onPaymentOptionsShow?: () => void; diff --git a/src/components/TransactionItemRow/types.ts b/src/components/TransactionItemRow/types.ts index d52c72aaab18..1f8ff27d2cbe 100644 --- a/src/components/TransactionItemRow/types.ts +++ b/src/components/TransactionItemRow/types.ts @@ -14,7 +14,7 @@ type TransactionWithOptionalSearchFields = TransactionWithOptionalHighlight & { action?: SearchTransactionAction; /** Function passed to the action button, triggered when the button is pressed */ - onButtonPress?: (event?: ModifiedMouseEvent) => void; + onButtonPress?: (event?: ModifiedMouseEvent) => void | Promise; /** The personal details of the user requesting money */ from?: PersonalDetails; @@ -90,7 +90,7 @@ type TransactionItemRowProps = { onCheckboxPress?: (transactionID: string, shiftKey?: boolean) => void; shouldShowCheckbox?: boolean; columns?: SearchColumnType[]; - onButtonPress?: (event?: ModifiedMouseEvent) => void; + onButtonPress?: (event?: ModifiedMouseEvent) => void | Promise; style?: StyleProp; dataSet?: Record; isReportItemChild?: boolean; diff --git a/src/hooks/usePaymentContext.tsx b/src/hooks/usePaymentContext.tsx index 066f9616612b..36b6e7b307d3 100644 --- a/src/hooks/usePaymentContext.tsx +++ b/src/hooks/usePaymentContext.tsx @@ -4,11 +4,12 @@ import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import {delegateEmailSelector} from '@src/selectors/Account'; import {hasSeenTourSelector} from '@src/selectors/Onboarding'; -import type {BankAccountList, BillingGraceEndPeriod, IntroSelected, Policy, Report} from '@src/types/onyx'; +import type {BankAccountList, IntroSelected, Policy, Report} from '@src/types/onyx'; -import type {OnyxCollection, OnyxEntry} from 'react-native-onyx'; +import type {OnyxEntry} from 'react-native-onyx'; import React, {createContext, useContext} from 'react'; +import Onyx from 'react-native-onyx'; import useCurrentUserPersonalDetails from './useCurrentUserPersonalDetails'; import useDelegateAccountID from './useDelegateAccountID'; @@ -18,26 +19,27 @@ import useOnyx from './useOnyx'; import usePermissions from './usePermissions'; import usePolicy from './usePolicy'; +type SearchActionInputs = { + conciergeChat: OnyxEntry; + introSelected: OnyxEntry; + isSelfTourViewed: boolean; + amountOwed: OnyxEntry; + bankAccountList: OnyxEntry; +}; + type PaymentContextValue = { currentUserAccountID: number; currentUserLogin: string | undefined; email: string | undefined; localCurrencyCode: string | undefined; - introSelected: OnyxEntry; isASAPSubmitBetaEnabled: boolean; isWiseReimbursementsBetaEnabled: boolean; - isSelfTourViewed: boolean; - userBillingGracePeriodEnds: OnyxCollection; - amountOwed: OnyxEntry; - ownerBillingGracePeriodEnd: OnyxEntry; activePolicyID: string | undefined; activePolicy: OnyxEntry; - conciergeReportID: string | undefined; - conciergeChat: OnyxEntry; defaultWorkspaceName: string; delegateEmail: string | undefined; delegateAccountID: number | undefined; - bankAccountList: OnyxEntry; + readSearchActionInputs: () => Promise; }; type ReportPaymentContextValue = PaymentContextValue & { @@ -58,42 +60,39 @@ function usePaymentContextValues(): PaymentContextValue { const {translate} = useLocalize(); const {login: currentUserLogin, accountID: currentUserAccountID, email, displayName, localCurrencyCode} = useCurrentUserPersonalDetails(); const lastWorkspaceNumber = useLastWorkspaceNumber(); - const [introSelected] = useOnyx(ONYXKEYS.NVP_INTRO_SELECTED); const {isBetaEnabled} = usePermissions(); - const [isSelfTourViewed = false] = useOnyx(ONYXKEYS.NVP_ONBOARDING, {selector: hasSeenTourSelector}); - const [userBillingGracePeriodEnds] = useOnyx(ONYXKEYS.COLLECTION.SHARED_NVP_PRIVATE_USER_BILLING_GRACE_PERIOD_END); - const [amountOwed] = useOnyx(ONYXKEYS.NVP_PRIVATE_AMOUNT_OWED); - const [ownerBillingGracePeriodEnd] = useOnyx(ONYXKEYS.NVP_PRIVATE_OWNER_BILLING_GRACE_PERIOD_END); const [activePolicyID] = useOnyx(ONYXKEYS.NVP_ACTIVE_POLICY_ID); - const [conciergeReportID] = useOnyx(ONYXKEYS.CONCIERGE_REPORT_ID); - const [conciergeChat] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${conciergeReportID}`); const [delegateEmail] = useOnyx(ONYXKEYS.ACCOUNT, {selector: delegateEmailSelector}); const delegateAccountID = useDelegateAccountID(); const activePolicy = usePolicy(activePolicyID); - const [bankAccountList] = useOnyx(ONYXKEYS.BANK_ACCOUNT_LIST); const defaultWorkspaceName = generateDefaultWorkspaceName(email ?? '', displayName, lastWorkspaceNumber, translate); + const readSearchActionInputs = async (): Promise => { + const [conciergeReportID, introSelected, onboarding, amountOwed, bankAccountList] = await Onyx.multiGet([ + ONYXKEYS.CONCIERGE_REPORT_ID, + ONYXKEYS.NVP_INTRO_SELECTED, + ONYXKEYS.NVP_ONBOARDING, + ONYXKEYS.NVP_PRIVATE_AMOUNT_OWED, + ONYXKEYS.BANK_ACCOUNT_LIST, + ]); + const conciergeChat = await Onyx.get(`${ONYXKEYS.COLLECTION.REPORT}${conciergeReportID}`); + return {conciergeChat, introSelected, isSelfTourViewed: hasSeenTourSelector(onboarding), amountOwed, bankAccountList}; + }; + return { currentUserAccountID, currentUserLogin, email, localCurrencyCode, - introSelected, isASAPSubmitBetaEnabled: isBetaEnabled(CONST.BETAS.ASAP_SUBMIT), isWiseReimbursementsBetaEnabled: isBetaEnabled(CONST.BETAS.WISE_REIMBURSEMENTS), - isSelfTourViewed, - userBillingGracePeriodEnds, - amountOwed, - ownerBillingGracePeriodEnd, activePolicyID, activePolicy, - conciergeReportID, - conciergeChat, defaultWorkspaceName, delegateEmail, delegateAccountID, - bankAccountList, + readSearchActionInputs, }; } @@ -123,3 +122,4 @@ function useReportPaymentContext({chatReportPolicyID}: UseReportPaymentContextPa export default usePaymentContext; export {PaymentContextProvider, useReportPaymentContext}; +export type {PaymentContextValue, SearchActionInputs}; diff --git a/src/hooks/useReportActionsScroll.ts b/src/hooks/useReportActionsScroll.ts index a35efeb84297..674143d4031c 100644 --- a/src/hooks/useReportActionsScroll.ts +++ b/src/hooks/useReportActionsScroll.ts @@ -14,8 +14,6 @@ import {useActionListContext} from '@pages/inbox/ActionListContext'; import useReportActionsNewActionLiveTail from '@pages/inbox/report/useReportActionsNewActionLiveTail'; import useReportUnreadMessageScrollTracking from '@pages/inbox/report/useReportUnreadMessageScrollTracking'; -import {openReport} from '@userActions/Report'; - import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import ROUTES from '@src/ROUTES'; @@ -27,11 +25,8 @@ import type {NativeScrollEvent, NativeSyntheticEvent} from 'react-native'; import type {OnyxEntry} from 'react-native-onyx'; import {useRoute} from '@react-navigation/native'; -import {guidedSetupAndTourStatusSelector} from '@selectors/Onboarding'; -import {fullPolicySnapshotLastModifiedSelector} from '@selectors/Policy'; import {useEffect, useEffectEvent, useState} from 'react'; -import useCurrentUserPersonalDetails from './useCurrentUserPersonalDetails'; import useNetworkWithOfflineStatus from './useNetworkWithOfflineStatus'; import useOnyx from './useOnyx'; import usePrevious from './usePrevious'; @@ -40,9 +35,6 @@ import useScrollToEndOnNewMessageReceived from './useScrollToEndOnNewMessageRece import useWindowDimensions from './useWindowDimensions'; type UseReportActionsScrollParams = { - /** The Concierge chat report */ - conciergeChat: OnyxEntry; - /** The ID of the report currently being looked at */ reportID: string; @@ -143,7 +135,6 @@ type UseReportActionsScrollResult = { }; function useReportActionsScroll({ - conciergeChat, reportID, report, transactionThreadReport, @@ -171,15 +162,8 @@ function useReportActionsScroll({ const linkedReportActionID = route?.params?.reportActionID; const backTo = route?.params?.backTo; const {isOffline} = useNetworkWithOfflineStatus(); - const [introSelected] = useOnyx(ONYXKEYS.NVP_INTRO_SELECTED); - const [guidedSetupAndTourStatus] = useOnyx(ONYXKEYS.NVP_ONBOARDING, {selector: guidedSetupAndTourStatusSelector}); - const {accountID: currentUserAccountID} = useCurrentUserPersonalDetails(); const [reportLoadingState] = useOnyx(`${ONYXKEYS.COLLECTION.RAM_ONLY_REPORT_LOADING_STATE}${reportID}`); const [reportActionPages] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS_PAGES}${getNonEmptyStringOnyxID(reportID)}`); - const [fullPolicySnapshotLastModified] = useOnyx(`${ONYXKEYS.COLLECTION.RAM_ONLY_FULL_POLICY_SNAPSHOT}${getNonEmptyStringOnyxID(report?.policyID)}`, { - selector: fullPolicySnapshotLastModifiedSelector, - }); - const fullPolicySnapshot = report?.policyID && fullPolicySnapshotLastModified ? {policyID: report.policyID, lastModified: fullPolicySnapshotLastModified} : undefined; const [isComposerFullSize = false] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT_IS_COMPOSER_FULL_SIZE}${reportID}`); const prevIsLoadingInitialReportActions = usePrevious(reportLoadingState?.isLoadingInitialReportActions); @@ -272,12 +256,9 @@ function useReportActionsScroll({ syncPillAfterComposerCollapse(); }, [isComposerFullSize]); - const {isScrollToBottomEnabled, setIsScrollToBottomEnabled, completeLiveTailPruneAfterScrollToBottom} = useReportActionsNewActionLiveTail({ - conciergeChat, + const {isScrollToBottomEnabled, setIsScrollToBottomEnabled, completeLiveTailPruneAfterScrollToBottom, openReportAtLiveTail} = useReportActionsNewActionLiveTail({ reportID, - introSelected, - isSelfTourViewed: guidedSetupAndTourStatus?.isSelfTourViewed, - hasCompletedGuidedSetupFlow: guidedSetupAndTourStatus?.hasCompletedGuidedSetupFlow, + policyID: report?.policyID, isOffline, reportScrollManager, setIsFloatingMessageCounterVisible, @@ -293,7 +274,6 @@ function useReportActionsScroll({ treatAsNoPaginationAnchor, prevIsLoadingInitialReportActions, reportLoadingState, - fullPolicySnapshot, }); useScrollToEndOnNewMessageReceived({ @@ -420,16 +400,7 @@ function useReportActionsScroll({ if (!Navigation.getReportRHPActiveRoute()) { Navigation.navigate(ROUTES.REPORT_WITH_ID.getRoute(reportID, undefined, undefined, backTo)); } - openReport({ - reportID, - introSelected, - conciergeChat, - hasReportActions: true, - currentUserAccountID, - isSelfTourViewed: guidedSetupAndTourStatus?.isSelfTourViewed, - hasCompletedGuidedSetupFlow: guidedSetupAndTourStatus?.hasCompletedGuidedSetupFlow, - fullPolicySnapshot, - }); + openReportAtLiveTail(); reportScrollManager.scrollToBottom(); return; } diff --git a/src/hooks/useReportSubmitToPopover.tsx b/src/hooks/useReportSubmitToPopover.tsx index 6c3ea8b8c0a6..5536971cb2c4 100644 --- a/src/hooks/useReportSubmitToPopover.tsx +++ b/src/hooks/useReportSubmitToPopover.tsx @@ -7,6 +7,7 @@ import ReportSubmitToContent from '@pages/ReportSubmitToContent'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; +import type {SearchTransactionAction} from '@src/types/onyx/SearchResults'; import type AnchorAlignment from '@src/types/utils/AnchorAlignment'; import calculateModalHeightInLandscapeMode from '@src/utils/calculateModalHeightInLandscapeMode'; @@ -133,6 +134,9 @@ function useReportSubmitToPopover({reportID, onSubmitSuccess, anchorAlignment = return true; }; + const interceptSearchSubmitPress = (action: SearchTransactionAction | undefined) => + action === CONST.SEARCH.ACTION_TYPES.SUBMIT && (isVisible || isDismissGuardActive || consumeIgnoreNextSearchSubmitPress()); + const closeReportSubmitToPopover = () => { canSubmitRef.current = false; onSubmitWithManagerEmailRef.current = undefined; @@ -293,7 +297,7 @@ function useReportSubmitToPopover({reportID, onSubmitSuccess, anchorAlignment = closeReportSubmitToPopover, isReportSubmitToPopoverVisible: isVisible, isReportSubmitToDismissGuardActive: isDismissGuardActive, - consumeIgnoreNextSearchSubmitPress, + interceptSearchSubmitPress, reportSubmitToPopover, }; } diff --git a/src/hooks/useSearchActionPress.ts b/src/hooks/useSearchActionPress.ts new file mode 100644 index 000000000000..25ab8a49bc6d --- /dev/null +++ b/src/hooks/useSearchActionPress.ts @@ -0,0 +1,36 @@ +import {useSearchSubmitPopoverGuard} from '@components/ReportSubmitToPopoverAnchor'; + +import {doesSearchActionUsePressTimeInputs} from '@libs/actions/Search'; + +import type {SearchTransactionAction} from '@src/types/onyx/SearchResults'; + +import type {SearchActionInputs} from './usePaymentContext'; + +import usePaymentContext from './usePaymentContext'; + +const EMPTY_SEARCH_ACTION_INPUTS: SearchActionInputs = { + conciergeChat: undefined, + introSelected: undefined, + isSelfTourViewed: false, + amountOwed: undefined, + bankAccountList: undefined, +}; + +/** + * Begins a Search row action press: resolves its press-time inputs, or undefined when the submit-to popover intercepted the press. + * The intercept runs before the first await because its one-shot flag resets in a microtask. + */ +function useSearchActionPress() { + const {interceptSearchSubmitPress} = useSearchSubmitPopoverGuard(); + const {readSearchActionInputs} = usePaymentContext(); + + return async (action: SearchTransactionAction | undefined): Promise => { + if (interceptSearchSubmitPress(action)) { + return undefined; + } + return doesSearchActionUsePressTimeInputs(action) ? readSearchActionInputs() : EMPTY_SEARCH_ACTION_INPUTS; + }; +} + +export default useSearchActionPress; +export {EMPTY_SEARCH_ACTION_INPUTS}; diff --git a/src/hooks/useSearchBulkActions.ts b/src/hooks/useSearchBulkActions.ts index c16059952241..995342a17ad1 100644 --- a/src/hooks/useSearchBulkActions.ts +++ b/src/hooks/useSearchBulkActions.ts @@ -137,9 +137,10 @@ import type {OnyxCollection, OnyxEntry} from 'react-native-onyx'; import type {ValueOf} from 'type-fest'; /* eslint-disable react-hooks/refs -- Refs in this hook are used inside callbacks that capture stable references; the lint rule flags false positives for these patterns */ -import {isTrackIntentUserSelector} from '@selectors/Onboarding'; +import {hasSeenTourSelector, isTrackIntentUserSelector} from '@selectors/Onboarding'; import {policyExpenseChatSelector} from '@selectors/Report'; import {useCallback, useEffect, useMemo, useRef} from 'react'; +import Onyx from 'react-native-onyx'; import type {RejectModalAction} from './useHoldRejectEducationalModal'; @@ -640,18 +641,10 @@ function useSearchBulkActions({queryJSON}: UseSearchBulkActionsParams) { const currentUserPersonalDetails = useCurrentUserPersonalDetails(); const {accountID, email, login: currentUserLogin, localCurrencyCode} = currentUserPersonalDetails; const delegateAccountID = useDelegateAccountID(); - const { - introSelected, - isSelfTourViewed, - activePolicyID, - activePolicy, - conciergeChat, - defaultWorkspaceName, - userBillingGracePeriodEnds, - amountOwed, - ownerBillingGracePeriodEnd, - delegateEmail, - } = usePaymentContext(); + const {activePolicyID, activePolicy, defaultWorkspaceName, delegateEmail} = usePaymentContext(); + const [userBillingGracePeriodEnds] = useOnyx(ONYXKEYS.COLLECTION.SHARED_NVP_PRIVATE_USER_BILLING_GRACE_PERIOD_END); + const [amountOwed] = useOnyx(ONYXKEYS.NVP_PRIVATE_AMOUNT_OWED); + const [ownerBillingGracePeriodEnd] = useOnyx(ONYXKEYS.NVP_PRIVATE_OWNER_BILLING_GRACE_PERIOD_END); const allTransactions = useAllTransactions(); const allReportsTransactionsAndViolations = useAllReportsTransactionsAndViolations(); const [allReports] = useOnyx(ONYXKEYS.COLLECTION.REPORT); @@ -1655,7 +1648,7 @@ function useSearchBulkActions({queryJSON}: UseSearchBulkActionsParams) { ]); const onBulkPaySelected = useCallback( - (paymentMethod?: PaymentMethodType, additionalData?: BulkPaySelectionData) => { + async (paymentMethod?: PaymentMethodType, additionalData?: BulkPaySelectionData) => { if (!hash) { Log.info('[BulkPay] Dropping bulk pay: no search hash'); return; @@ -1695,6 +1688,9 @@ function useSearchBulkActions({queryJSON}: UseSearchBulkActionsParams) { return; } + const [conciergeReportID, introSelected, onboarding] = await Onyx.multiGet([ONYXKEYS.CONCIERGE_REPORT_ID, ONYXKEYS.NVP_INTRO_SELECTED, ONYXKEYS.NVP_ONBOARDING]); + const conciergeChat = await Onyx.get(`${ONYXKEYS.COLLECTION.REPORT}${conciergeReportID}`); + const isSelfTourViewed = hasSeenTourSelector(onboarding); const activeRoute = Navigation.getActiveRoute(); const searchData = searchResults?.data; const policyExpenseChatReportActions = getAllPolicyExpenseChatReportActions(allReports, allReportActions); @@ -1990,8 +1986,6 @@ function useSearchBulkActions({queryJSON}: UseSearchBulkActionsParams) { localCurrencyCode, defaultWorkspaceName, personalDetails, - introSelected, - isSelfTourViewed, activePolicy, activePolicyID, allReportNameValuePairs, @@ -1999,7 +1993,6 @@ function useSearchBulkActions({queryJSON}: UseSearchBulkActionsParams) { searchResults?.data, delegateAccountID, isTrackIntentUser, - conciergeChat, getCurrencyDecimals, rules, ], diff --git a/src/hooks/useSelectionModePayment.ts b/src/hooks/useSelectionModePayment.ts index 46662f2d65d9..2da686732098 100644 --- a/src/hooks/useSelectionModePayment.ts +++ b/src/hooks/useSelectionModePayment.ts @@ -132,7 +132,7 @@ function useSelectionModePayment({ const kycWallRef = useContext(KYCWallContext); // Store the pending payment and resume it after the user validates, instead of dropping it on the way to the magic-code screen. - const {isUserValidated, verifyAccountAndResume} = useVerifyAccountAndResume((retry) => retry?.()); + const {isUserValidated, verifyAccountAndResume} = useVerifyAccountAndResume((retry?: () => void) => retry?.()); const expensifyIcons = useMemoizedLazyExpensifyIcons(['Cash', 'ArrowRight', 'Building'] as const); diff --git a/src/hooks/useVerifyAccountAndResume.ts b/src/hooks/useVerifyAccountAndResume.ts index 07201ab75c45..e9c51316dffd 100644 --- a/src/hooks/useVerifyAccountAndResume.ts +++ b/src/hooks/useVerifyAccountAndResume.ts @@ -11,7 +11,7 @@ import {useEffect, useEffectEvent, useState} from 'react'; import useOnyx from './useOnyx'; -type ResumePayload = (() => void) | undefined; +type ResumePayload = (() => void | Promise) | undefined; /** * Returns a trigger that sends an unvalidated user to the verify-account (security code) screen and, diff --git a/src/libs/IOUAmountSubmission.ts b/src/libs/IOUAmountSubmission.ts index b4476bf79aab..48304087758b 100644 --- a/src/libs/IOUAmountSubmission.ts +++ b/src/libs/IOUAmountSubmission.ts @@ -389,7 +389,7 @@ function submitSkipConfirmationExpense(args: SubmitAmountArgs, ctx: SubmitAmount // "route to Spend > Expenses" behaviour to the self-DM case (matches the confirmation step). const isSelfDMDestination = isSelfDMSoleDestination(participants, iouType, currentUserAccountID); const draftTransactionIDsList = Object.keys(transactionDrafts ?? {}); - const isSelfTourViewed = hasSeenTourSelector(onboarding) ?? false; + const isSelfTourViewed = hasSeenTourSelector(onboarding); const executeExpenseWrite = (overrides: WriteOverrides) => { if (isTrackExpenseSubmit) { trackExpense({ diff --git a/src/libs/actions/Search.ts b/src/libs/actions/Search.ts index 0005c05d4a04..aa05c05524be 100644 --- a/src/libs/actions/Search.ts +++ b/src/libs/actions/Search.ts @@ -104,7 +104,7 @@ import type {PaymentInformation} from '@src/types/onyx/LastPaymentMethod'; import type {ConnectionName} from '@src/types/onyx/Policy'; import type {AnyOnyxUpdate, OnyxData} from '@src/types/onyx/Request'; import type SearchFooterConversion from '@src/types/onyx/SearchFooterConversion'; -import type {SearchResultDataType} from '@src/types/onyx/SearchResults'; +import type {SearchResultDataType, SearchTransactionAction} from '@src/types/onyx/SearchResults'; import type Nullable from '@src/types/utils/Nullable'; import type {OnyxCollection, OnyxEntry, OnyxUpdate} from 'react-native-onyx'; @@ -278,9 +278,6 @@ type HandleActionButtonPressParams = { /** Confirms any unacknowledged report violations before proceeding with the SUBMIT action. */ confirmSubmitReportViolations: (onProceed: ConfirmSubmitReportViolationsOnProceed) => void; openReportSubmitToPopover?: (options?: ReportSubmitToPopoverOpenOptions) => void; - shouldDisableSearchSubmitPress?: boolean; - /** Consumes a one-shot flag set when the submit-to popover dismisses (prevents click-through on the row Submit button). */ - consumeIgnoreNextSearchSubmitPress?: () => boolean; currentUserAccountID: number; currentUserLogin?: string; introSelected?: OnyxEntry; @@ -303,6 +300,10 @@ type HandleActionButtonPressParams = { bankAccountList: OnyxEntry; }; +function doesSearchActionUsePressTimeInputs(action: SearchTransactionAction | undefined) { + return action === CONST.SEARCH.ACTION_TYPES.PAY || action === CONST.SEARCH.ACTION_TYPES.APPROVE || action === CONST.SEARCH.ACTION_TYPES.SUBMIT; +} + function handleActionButtonPress({ hash, item, @@ -325,8 +326,6 @@ function handleActionButtonPress({ confirmSubmitReportViolations, currentUserAccountID, openReportSubmitToPopover, - shouldDisableSearchSubmitPress, - consumeIgnoreNextSearchSubmitPress, currentUserLogin, introSelected, isASAPSubmitBetaEnabled, @@ -433,9 +432,6 @@ function handleActionButtonPress({ }); return; case CONST.SEARCH.ACTION_TYPES.SUBMIT: { - if (shouldDisableSearchSubmitPress || consumeIgnoreNextSearchSubmitPress?.()) { - return; - } if (snapshotReport.policyID && shouldRestrictUserBillableActions(policy, ownerBillingGracePeriodEnd, userBillingGracePeriodEnds, amountOwed, currentUserAccountID)) { Navigation.navigate(ROUTES.RESTRICTED_ACTION.getRoute(snapshotReport.policyID)); return; @@ -2772,6 +2768,7 @@ export { getChatReportWithFallback, getSearchApproveOnyxData, handleActionButtonPress, + doesSearchActionUsePressTimeInputs, submitMoneyRequestOnSearch, openSearchPage as openSearch, openBulkChangeApproverPage, diff --git a/src/pages/inbox/ReportActions.tsx b/src/pages/inbox/ReportActions.tsx index 71d15523c1d2..633e720169a6 100644 --- a/src/pages/inbox/ReportActions.tsx +++ b/src/pages/inbox/ReportActions.tsx @@ -46,7 +46,6 @@ function ReportActions() { const [report] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${reportIDFromRoute}`); const [conciergeReportID] = useOnyx(ONYXKEYS.CONCIERGE_REPORT_ID); - const [conciergeChat] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${conciergeReportID}`); const [reportLoadingState = defaultReportLoadingState] = useOnyx(`${ONYXKEYS.COLLECTION.RAM_ONLY_REPORT_LOADING_STATE}${reportIDFromRoute}`); const isAppLoadPending = useIsAppLoadPending(); const isReportLoadPending = useIsReportLoadPending(reportIDFromRoute); @@ -93,7 +92,6 @@ function ReportActions() { return ( <> diff --git a/src/pages/inbox/report/ReportActionItemMessageWithExplain.tsx b/src/pages/inbox/report/ReportActionItemMessageWithExplain.tsx index 7152c0a8e57a..e3c108068a59 100644 --- a/src/pages/inbox/report/ReportActionItemMessageWithExplain.tsx +++ b/src/pages/inbox/report/ReportActionItemMessageWithExplain.tsx @@ -5,7 +5,6 @@ import useCurrentUserPersonalDetails from '@hooks/useCurrentUserPersonalDetails' import useDelegateAccountID from '@hooks/useDelegateAccountID'; import useEnvironment from '@hooks/useEnvironment'; import useLocalize from '@hooks/useLocalize'; -import useOnyx from '@hooks/useOnyx'; import useResponsiveLayout from '@hooks/useResponsiveLayout'; import {openLink} from '@libs/actions/Link'; @@ -23,6 +22,7 @@ import type {OnyxEntry} from 'react-native-onyx'; import {hasSeenTourSelector} from '@selectors/Onboarding'; import React from 'react'; +import Onyx from 'react-native-onyx'; import ReportActionItemBasicMessage from './ReportActionItemBasicMessage'; @@ -45,33 +45,35 @@ function ReportActionItemMessageWithExplain({message, action, childReport, origi const {environmentURL} = useEnvironment(); const session = useSession(); const {shouldUseNarrowLayout} = useResponsiveLayout(); - const [introSelected] = useOnyx(ONYXKEYS.NVP_INTRO_SELECTED); - const [isSelfTourViewed] = useOnyx(ONYXKEYS.NVP_ONBOARDING, {selector: hasSeenTourSelector}); - const [conciergeReportID] = useOnyx(ONYXKEYS.CONCIERGE_REPORT_ID); - const [conciergeChat] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${conciergeReportID}`); const delegateAccountID = useDelegateAccountID(); const personalDetails = usePersonalDetails(); const actionHasReasoning = hasReasoning(action); const computedMessage = actionHasReasoning ? `${message}${translate('iou.AskToExplain')}` : message; + const explainAction = async () => { + const [introSelected, onboarding, conciergeReportID] = await Onyx.multiGet([ONYXKEYS.NVP_INTRO_SELECTED, ONYXKEYS.NVP_ONBOARDING, ONYXKEYS.CONCIERGE_REPORT_ID]); + const conciergeChat = await Onyx.get(`${ONYXKEYS.COLLECTION.REPORT}${conciergeReportID}`); + const participantsPersonalDetails = getParticipantsPersonalDetails([personalDetail.accountID, Number(action?.actorAccountID)], personalDetails); + explain({ + childReport, + originalReport, + reportAction: action, + translate, + currentUserAccountID: personalDetail.accountID, + introSelected, + conciergeChat, + isSelfTourViewed: hasSeenTourSelector(onboarding), + delegateAccountID, + participantsPersonalDetails, + timezone: personalDetail?.timezone, + }); + }; + const handleLinkPress = (event: GestureResponderEvent | KeyboardEvent, href: string) => { // Handle the special "Explain" link if (href.endsWith(CONST.CONCIERGE_EXPLAIN_LINK_PATH)) { - const participantsPersonalDetails = getParticipantsPersonalDetails([personalDetail.accountID, Number(action?.actorAccountID)], personalDetails); - explain({ - childReport, - originalReport, - reportAction: action, - translate, - currentUserAccountID: personalDetail.accountID, - introSelected, - conciergeChat, - isSelfTourViewed, - delegateAccountID, - participantsPersonalDetails, - timezone: personalDetail?.timezone, - }); + explainAction(); return; } diff --git a/src/pages/inbox/report/ReportActionsList/ReportActionsListContent.tsx b/src/pages/inbox/report/ReportActionsList/ReportActionsListContent.tsx index 54c8fdb9a294..c2ede5315711 100644 --- a/src/pages/inbox/report/ReportActionsList/ReportActionsListContent.tsx +++ b/src/pages/inbox/report/ReportActionsList/ReportActionsListContent.tsx @@ -55,7 +55,7 @@ import useReportActionsListTelemetry from './useReportActionsListTelemetry'; * UI-close hooks (`useUnreadMarker` / `useMarkAsRead` / `useReportActionsScroll`). `ReportActionsSkeletonGuard` * mounts it only once content is ready, so those hooks never run while a skeleton shows. */ -function ReportActionsListContent({reportID, conciergeChat, onLayout}: ReportActionsListProps) { +function ReportActionsListContent({reportID, onLayout}: ReportActionsListProps) { const styles = useThemeStyles(); const {translate} = useLocalize(); const {isProduction} = useEnvironment(); @@ -149,7 +149,6 @@ function ReportActionsListContent({reportID, conciergeChat, onLayout}: ReportAct const {listID, listProps, shouldBeAlignedToTop, isFloatingMessageCounterVisible, isActionBadgeAboveViewport, scrollToBottomAndMarkReportAsRead, scrollToActionBadgeTarget} = useReportActionsListScroll({ reportID, - conciergeChat, sortedVisibleReportActions, renderedVisibleReportActions: listData, reportActionIDToDisplayIndex, diff --git a/src/pages/inbox/report/ReportActionsList/index.tsx b/src/pages/inbox/report/ReportActionsList/index.tsx index 36db621a513e..047b3d8083db 100644 --- a/src/pages/inbox/report/ReportActionsList/index.tsx +++ b/src/pages/inbox/report/ReportActionsList/index.tsx @@ -10,13 +10,12 @@ import ReportActionsListContent from './ReportActionsListContent'; * Public report-actions list. Thin composition that wraps the content in `ReportActionsSkeletonGuard`, * which owns the data pipeline + skeleton decision and only mounts the content once it is ready. */ -function ReportActionsList({reportID, conciergeChat, onLayout}: ReportActionsListProps) { +function ReportActionsList({reportID, onLayout}: ReportActionsListProps) { return ( diff --git a/src/pages/inbox/report/ReportActionsList/types.ts b/src/pages/inbox/report/ReportActionsList/types.ts index 583eeb6cef57..2e9aac5c8da5 100644 --- a/src/pages/inbox/report/ReportActionsList/types.ts +++ b/src/pages/inbox/report/ReportActionsList/types.ts @@ -13,7 +13,6 @@ type ReportActionsListProps = { /** The ID of the report to display actions for */ reportID: string; - conciergeChat: OnyxEntry; onLayout?: (event: LayoutChangeEvent) => void; }; @@ -28,7 +27,6 @@ type UseReportActionsListDataParams = { type UseReportActionsListScrollParams = Pick< Parameters[0], | 'reportID' - | 'conciergeChat' | 'sortedVisibleReportActions' | 'renderedVisibleReportActions' | 'hasScrolledOverThreshold' diff --git a/src/pages/inbox/report/ReportActionsList/useReportActionsListScroll.ts b/src/pages/inbox/report/ReportActionsList/useReportActionsListScroll.ts index 855c227ebda8..e4de34fece9d 100644 --- a/src/pages/inbox/report/ReportActionsList/useReportActionsListScroll.ts +++ b/src/pages/inbox/report/ReportActionsList/useReportActionsListScroll.ts @@ -36,7 +36,6 @@ function keyExtractor(item: OnyxTypes.ReportAction): string { /** Owns initial positioning, pagination, unread tracking, and scroll events for the report-actions list. */ function useReportActionsListScroll({ reportID, - conciergeChat, sortedVisibleReportActions, renderedVisibleReportActions: listData, reportActionIDToDisplayIndex, @@ -124,7 +123,6 @@ function useReportActionsListScroll({ onLoad, } = useReportActionsScroll({ reportID, - conciergeChat, report, transactionThreadReport, parentReportAction, diff --git a/src/pages/inbox/report/actionContents/ChatTransactionPreview.tsx b/src/pages/inbox/report/actionContents/ChatTransactionPreview.tsx index e14f60f25977..5a77e8106637 100644 --- a/src/pages/inbox/report/actionContents/ChatTransactionPreview.tsx +++ b/src/pages/inbox/report/actionContents/ChatTransactionPreview.tsx @@ -2,7 +2,6 @@ import {usePersonalDetails} from '@components/OnyxListItemProvider'; import TransactionPreview from '@components/ReportActionItem/TransactionPreview'; import useCurrentUserPersonalDetails from '@hooks/useCurrentUserPersonalDetails'; -import useOnyx from '@hooks/useOnyx'; import useResponsiveLayout from '@hooks/useResponsiveLayout'; import useStyleUtils from '@hooks/useStyleUtils'; import useThemeStyles from '@hooks/useThemeStyles'; @@ -25,6 +24,7 @@ import {guidedSetupAndTourStatusSelector} from '@selectors/Onboarding'; import {fullPolicySnapshotLastModifiedSelector} from '@selectors/Policy'; import React from 'react'; import {View} from 'react-native'; +import Onyx from 'react-native-onyx'; type ChatTransactionPreviewProps = { /** All the data of the action, used for showing context menu and deriving the IOU report */ @@ -51,13 +51,33 @@ function ChatTransactionPreview({action, reportID, chatReport, iouReport, should const {shouldUseNarrowLayout} = useResponsiveLayout(); const personalDetail = useCurrentUserPersonalDetails(); const personalDetails = usePersonalDetails(); - const [introSelected] = useOnyx(ONYXKEYS.NVP_INTRO_SELECTED); - const [conciergeReportID] = useOnyx(ONYXKEYS.CONCIERGE_REPORT_ID); - const [conciergeChat] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${conciergeReportID}`); - const [guidedSetupAndTourStatus] = useOnyx(ONYXKEYS.NVP_ONBOARDING, {selector: guidedSetupAndTourStatusSelector}); - const [fullPolicySnapshotLastModified] = useOnyx(`${ONYXKEYS.COLLECTION.RAM_ONLY_FULL_POLICY_SNAPSHOT}${getNonEmptyStringOnyxID(iouReport?.policyID)}`, { - selector: fullPolicySnapshotLastModifiedSelector, - }); + + const createAndOpenTransactionThread = async () => { + const [introSelected, conciergeReportID, onboarding, fullPolicySnapshotData] = await Onyx.multiGet([ + ONYXKEYS.NVP_INTRO_SELECTED, + ONYXKEYS.CONCIERGE_REPORT_ID, + ONYXKEYS.NVP_ONBOARDING, + `${ONYXKEYS.COLLECTION.RAM_ONLY_FULL_POLICY_SNAPSHOT}${getNonEmptyStringOnyxID(iouReport?.policyID)}`, + ]); + const conciergeChat = await Onyx.get(`${ONYXKEYS.COLLECTION.REPORT}${conciergeReportID}`); + const {isSelfTourViewed, hasCompletedGuidedSetupFlow} = guidedSetupAndTourStatusSelector(onboarding); + const createdTransactionThreadReport = createTransactionThreadReport({ + introSelected, + conciergeChat, + isSelfTourViewed, + hasCompletedGuidedSetupFlow, + currentUserLogin: personalDetail.email ?? '', + currentUserAccountID: personalDetail.accountID, + iouReport, + iouReportAction: action, + personalDetails, + fullPolicySnapshotLastModified: fullPolicySnapshotLastModifiedSelector(fullPolicySnapshotData), + }); + if (!createdTransactionThreadReport?.reportID) { + return; + } + Navigation.navigate(getReportRouteForCurrentContext({reportID: createdTransactionThreadReport.reportID})); + }; const reportPreviewStyles = StyleUtils.getMoneyRequestReportPreviewStyle(shouldUseNarrowLayout, 1, undefined, undefined); @@ -80,22 +100,7 @@ function ChatTransactionPreview({action, reportID, chatReport, iouReport, should // If no childReportID exists, create transaction thread on-demand if (!action.childReportID) { - const createdTransactionThreadReport = createTransactionThreadReport({ - introSelected, - conciergeChat, - isSelfTourViewed: guidedSetupAndTourStatus?.isSelfTourViewed, - hasCompletedGuidedSetupFlow: guidedSetupAndTourStatus?.hasCompletedGuidedSetupFlow, - currentUserLogin: personalDetail.email ?? '', - currentUserAccountID: personalDetail.accountID, - iouReport, - iouReportAction: action, - personalDetails, - fullPolicySnapshotLastModified, - }); - if (createdTransactionThreadReport?.reportID) { - Navigation.navigate(getReportRouteForCurrentContext({reportID: createdTransactionThreadReport.reportID})); - return; - } + createAndOpenTransactionThread(); return; } diff --git a/src/pages/inbox/report/useReportActionsNewActionLiveTail.ts b/src/pages/inbox/report/useReportActionsNewActionLiveTail.ts index f76ae15c2135..5ab67c386188 100644 --- a/src/pages/inbox/report/useReportActionsNewActionLiveTail.ts +++ b/src/pages/inbox/report/useReportActionsNewActionLiveTail.ts @@ -1,10 +1,9 @@ -import useCurrentUserPersonalDetails from '@hooks/useCurrentUserPersonalDetails'; import useIsInSidePanel from '@hooks/useIsInSidePanel'; import type useReportScrollManager from '@hooks/useReportScrollManager'; -import type {OpenReportActionParams} from '@libs/actions/Report'; import {openReport, pruneReportActionPagesToNewestWindow} from '@libs/actions/Report'; import {subscribeToNewActionEvent} from '@libs/actions/Report/reportActionSubscribers'; +import getNonEmptyStringOnyxID from '@libs/getNonEmptyStringOnyxID'; import isReportTopmostSplitNavigator from '@libs/Navigation/helpers/isReportTopmostSplitNavigator'; import Navigation from '@libs/Navigation/Navigation'; import type {PlatformStackNavigationProp} from '@libs/Navigation/PlatformStackNavigation/types'; @@ -13,13 +12,17 @@ import TransitionTracker from '@libs/Navigation/TransitionTracker'; import type {ReportsSplitNavigatorParamList} from '@navigation/types'; import CONST from '@src/CONST'; +import ONYXKEYS from '@src/ONYXKEYS'; import type SCREENS from '@src/SCREENS'; import type * as OnyxTypes from '@src/types/onyx'; import type {OnyxEntry} from 'react-native-onyx'; import {useNavigation} from '@react-navigation/native'; +import {guidedSetupAndTourStatusSelector} from '@selectors/Onboarding'; +import {fullPolicySnapshotLastModifiedSelector} from '@selectors/Policy'; import {useEffect, useEffectEvent, useRef, useState} from 'react'; +import Onyx from 'react-native-onyx'; // In the component we are subscribing to the arrival of new actions. // As there is the possibility that there are multiple instances of a ReportScreen @@ -35,10 +38,7 @@ type RAMOnlyReportLoadingState = OnyxEntry<{ type UseReportActionsNewActionLiveTailParams = { reportID: string; - introSelected: OpenReportActionParams['introSelected']; - conciergeChat: OpenReportActionParams['conciergeChat']; - isSelfTourViewed: OpenReportActionParams['isSelfTourViewed']; - hasCompletedGuidedSetupFlow: OpenReportActionParams['hasCompletedGuidedSetupFlow']; + policyID: string | undefined; isOffline: boolean; reportScrollManager: ReportScrollManager; setIsFloatingMessageCounterVisible: (visible: boolean) => void; @@ -54,7 +54,6 @@ type UseReportActionsNewActionLiveTailParams = { treatAsNoPaginationAnchor: boolean; prevIsLoadingInitialReportActions: boolean | undefined; reportLoadingState: RAMOnlyReportLoadingState; - fullPolicySnapshot?: OpenReportActionParams['fullPolicySnapshot']; }; type LiveTailJumpStage = 'idle' | 'open_report' | 'await_scroll' | 'await_prune'; @@ -66,11 +65,8 @@ type LiveTailJumpStage = 'idle' | 'open_report' | 'await_scroll' | 'await_prune' * it from list `onLayout` outside this hook. */ function useReportActionsNewActionLiveTail({ - conciergeChat, reportID, - introSelected, - isSelfTourViewed, - hasCompletedGuidedSetupFlow, + policyID, isOffline, reportScrollManager, setIsFloatingMessageCounterVisible, @@ -86,14 +82,35 @@ function useReportActionsNewActionLiveTail({ treatAsNoPaginationAnchor, prevIsLoadingInitialReportActions, reportLoadingState, - fullPolicySnapshot, }: UseReportActionsNewActionLiveTailParams) { const navigation = useNavigation>(); const isInSidePanel = useIsInSidePanel(); - const {accountID: currentUserAccountID} = useCurrentUserPersonalDetails(); const liveTailJumpRef = useRef<{stage: LiveTailJumpStage}>({stage: 'idle'}); const [isScrollToBottomEnabled, setIsScrollToBottomEnabled] = useState(false); + const openReportAtLiveTail = async () => { + const [conciergeReportID, introSelected, onboarding, session, fullPolicySnapshotData] = await Onyx.multiGet([ + ONYXKEYS.CONCIERGE_REPORT_ID, + ONYXKEYS.NVP_INTRO_SELECTED, + ONYXKEYS.NVP_ONBOARDING, + ONYXKEYS.SESSION, + `${ONYXKEYS.COLLECTION.RAM_ONLY_FULL_POLICY_SNAPSHOT}${getNonEmptyStringOnyxID(policyID)}`, + ]); + const conciergeChat = await Onyx.get(`${ONYXKEYS.COLLECTION.REPORT}${conciergeReportID}`); + const {isSelfTourViewed, hasCompletedGuidedSetupFlow} = guidedSetupAndTourStatusSelector(onboarding); + const fullPolicySnapshotLastModified = fullPolicySnapshotLastModifiedSelector(fullPolicySnapshotData); + openReport({ + reportID, + introSelected, + conciergeChat, + hasReportActions: true, + currentUserAccountID: session?.accountID ?? CONST.DEFAULT_NUMBER_ID, + isSelfTourViewed, + hasCompletedGuidedSetupFlow, + fullPolicySnapshot: policyID && fullPolicySnapshotLastModified ? {policyID, lastModified: fullPolicySnapshotLastModified} : undefined, + }); + }; + const scrollToBottomForCurrentUserAction = useEffectEvent((isFromCurrentUser: boolean, action?: OnyxTypes.ReportAction) => { TransitionTracker.runAfterTransitions({ callback: () => { @@ -113,16 +130,7 @@ function useReportActionsNewActionLiveTail({ if (shouldJumpToLiveTail) { if (liveTailJumpRef.current.stage === 'idle') { liveTailJumpRef.current = {stage: 'open_report'}; - openReport({ - reportID, - introSelected, - conciergeChat, - hasReportActions: true, - currentUserAccountID, - isSelfTourViewed, - hasCompletedGuidedSetupFlow, - fullPolicySnapshot, - }); + openReportAtLiveTail(); } return; } @@ -243,6 +251,7 @@ function useReportActionsNewActionLiveTail({ isScrollToBottomEnabled, setIsScrollToBottomEnabled, completeLiveTailPruneAfterScrollToBottom, + openReportAtLiveTail, }; } diff --git a/src/selectors/Onboarding.ts b/src/selectors/Onboarding.ts index 1e19dae0e229..8d937921095b 100644 --- a/src/selectors/Onboarding.ts +++ b/src/selectors/Onboarding.ts @@ -50,11 +50,10 @@ function tryNewDotOnyxSelector(tryNewDotData: OnyxValue): boolean | undefined { +function hasSeenTourSelector(onboarding: OnyxValue): boolean { if (isEmptyObject(onboarding)) { return false; } @@ -78,7 +77,7 @@ function wasInvitedToNewDotSelector(introSelected: OnyxValue): {isSelfTourViewed: boolean | undefined; hasCompletedGuidedSetupFlow: boolean | undefined} { +function guidedSetupAndTourStatusSelector(onboarding: OnyxValue): {isSelfTourViewed: boolean; hasCompletedGuidedSetupFlow: boolean} { return { isSelfTourViewed: hasSeenTourSelector(onboarding), hasCompletedGuidedSetupFlow: hasCompletedGuidedSetupFlowSelector(onboarding), diff --git a/tests/perf-test/ReportActionsList.perf-test.tsx b/tests/perf-test/ReportActionsList.perf-test.tsx index d39902dc322c..734a60dde85b 100644 --- a/tests/perf-test/ReportActionsList.perf-test.tsx +++ b/tests/perf-test/ReportActionsList.perf-test.tsx @@ -110,7 +110,6 @@ function ReportActionsListWrapper() { diff --git a/tests/perf-test/ReportActionsListRowWrites.perf-test.tsx b/tests/perf-test/ReportActionsListRowWrites.perf-test.tsx index bdcdc991d237..6779a76506a4 100644 --- a/tests/perf-test/ReportActionsListRowWrites.perf-test.tsx +++ b/tests/perf-test/ReportActionsListRowWrites.perf-test.tsx @@ -127,7 +127,6 @@ function ReportActionsListWrapper() { diff --git a/tests/ui/ChatTransactionPreviewTest.tsx b/tests/ui/ChatTransactionPreviewTest.tsx index 2f0e2373075d..2c61c6f101e5 100644 --- a/tests/ui/ChatTransactionPreviewTest.tsx +++ b/tests/ui/ChatTransactionPreviewTest.tsx @@ -99,6 +99,7 @@ describe('ChatTransactionPreview', () => { ); await waitForBatchedUpdatesWithAct(); fireEvent.press(screen.getByText('Transaction preview')); + await waitForBatchedUpdatesWithAct(); // Then the thread is created with the marker, so OpenReport can skip the large policy collections expect(createTransactionThreadReport).toHaveBeenCalledWith(expect.objectContaining({fullPolicySnapshotLastModified: LIVE_FULL_POLICY_SNAPSHOT_LAST_MODIFIED})); diff --git a/tests/ui/ReportActionItemMessageWithExplainTest.tsx b/tests/ui/ReportActionItemMessageWithExplainTest.tsx new file mode 100644 index 000000000000..002008b65be3 --- /dev/null +++ b/tests/ui/ReportActionItemMessageWithExplainTest.tsx @@ -0,0 +1,101 @@ +import {act, fireEvent, render, screen} from '@testing-library/react-native'; + +import ComposeProviders from '@components/ComposeProviders'; +import {CurrentUserPersonalDetailsProvider} from '@components/CurrentUserPersonalDetailsProvider'; +import HTMLEngineProvider from '@components/HTMLEngineProvider'; +import {LocaleContextProvider} from '@components/LocaleContextProvider'; +import OnyxListItemProvider from '@components/OnyxListItemProvider'; + +import {explain} from '@libs/actions/Report'; + +import ReportActionItemMessageWithExplain from '@pages/inbox/report/ReportActionItemMessageWithExplain'; + +import CONST from '@src/CONST'; +import ONYXKEYS from '@src/ONYXKEYS'; +import type {Report, ReportAction} from '@src/types/onyx'; + +import React from 'react'; +import Onyx from 'react-native-onyx'; + +import waitForBatchedUpdatesWithAct from '../utils/waitForBatchedUpdatesWithAct'; + +jest.mock('@libs/actions/Report', () => { + const actual = jest.requireActual>('@libs/actions/Report'); + return { + ...actual, + explain: jest.fn(), + }; +}); + +const CURRENT_USER_ACCOUNT_ID = 1; +const CURRENT_USER_EMAIL = 'explainer@example.com'; +const CONCIERGE_REPORT_ID = 'concierge1'; +const ORIGINAL_REPORT_ID = 'report1'; +const CONCIERGE_REPORT_KEY = `${ONYXKEYS.COLLECTION.REPORT}${CONCIERGE_REPORT_ID}` as const; + +const originalReport = {reportID: ORIGINAL_REPORT_ID, type: CONST.REPORT.TYPE.EXPENSE} as Report; +const conciergeChat = {reportID: CONCIERGE_REPORT_ID} as Report; +const reimbursedAction = { + reportActionID: 'action1', + actorAccountID: 2, + actionName: CONST.REPORT.ACTIONS.TYPE.REIMBURSED, + created: '2026-10-20 00:00:00.000', + // eslint-disable-next-line @typescript-eslint/no-deprecated -- hasReasoning() reads the deprecated field for actions stored before the original-message migration. + originalMessage: {reasoning: 'Routed through Corpay because the withdrawal account is outside the United States.'}, +} as ReportAction; + +describe('ReportActionItemMessageWithExplain', () => { + beforeAll(() => { + Onyx.init({keys: ONYXKEYS}); + }); + + afterEach(async () => { + jest.clearAllMocks(); + await act(async () => { + await Onyx.clear(); + }); + }); + + it('passes the Onyx-backed values to explain when the link is pressed', async () => { + // Given a signed-in user whose onboarding, intro choice and Concierge chat live in Onyx + await act(async () => { + await Onyx.multiSet({ + [ONYXKEYS.SESSION]: {accountID: CURRENT_USER_ACCOUNT_ID, email: CURRENT_USER_EMAIL}, + [ONYXKEYS.PERSONAL_DETAILS_LIST]: {[CURRENT_USER_ACCOUNT_ID]: {accountID: CURRENT_USER_ACCOUNT_ID, login: CURRENT_USER_EMAIL}}, + [ONYXKEYS.NVP_INTRO_SELECTED]: {choice: CONST.ONBOARDING_CHOICES.MANAGE_TEAM}, + [ONYXKEYS.NVP_ONBOARDING]: {selfTourViewed: true}, + [ONYXKEYS.CONCIERGE_REPORT_ID]: CONCIERGE_REPORT_ID, + [CONCIERGE_REPORT_KEY]: conciergeChat, + }); + }); + + render( + + + , + ); + await waitForBatchedUpdatesWithAct(); + + // When the user presses the Explain link + fireEvent.press(screen.getByText('Explain')); + await waitForBatchedUpdatesWithAct(); + + // Then explain receives the press-time reads, because the thread it creates depends on the tour state, intro choice and Concierge chat + expect(explain).toHaveBeenCalledTimes(1); + expect(explain).toHaveBeenCalledWith( + expect.objectContaining({ + originalReport, + reportAction: reimbursedAction, + currentUserAccountID: CURRENT_USER_ACCOUNT_ID, + introSelected: expect.objectContaining({choice: CONST.ONBOARDING_CHOICES.MANAGE_TEAM}), + isSelfTourViewed: true, + conciergeChat: expect.objectContaining({reportID: CONCIERGE_REPORT_ID}), + }), + ); + }); +}); diff --git a/tests/ui/ReportActionsListTest.tsx b/tests/ui/ReportActionsListTest.tsx index 8d9cd2fc7d2b..f57b884af786 100644 --- a/tests/ui/ReportActionsListTest.tsx +++ b/tests/ui/ReportActionsListTest.tsx @@ -275,12 +275,7 @@ const mockReportActions: OnyxTypes.ReportAction[] = [ const renderReportActionsList = (props: {reportID?: string} = {}) => { const reportID = props.reportID ?? mockReport.reportID; - return render( - , - ); + return render(); }; // useReportActionsListModel derives app-load state from the request queue via useIsAppLoadPending, @@ -879,10 +874,7 @@ describe('ReportActionsList (body)', () => { // When the list reconciles against all saved actions const {rerender} = render( - + , ); @@ -896,10 +888,7 @@ describe('ReportActionsList (body)', () => { // When the reveal completes without changing the visible pagination window rerender( - + , ); diff --git a/tests/ui/components/PayActionButtonTest.tsx b/tests/ui/components/PayActionButtonTest.tsx index 487b8549c9af..76f24de62f80 100644 --- a/tests/ui/components/PayActionButtonTest.tsx +++ b/tests/ui/components/PayActionButtonTest.tsx @@ -17,6 +17,8 @@ import type {OnyxCollection, UseOnyxResult} from 'react-native-onyx'; import React from 'react'; +import waitForBatchedUpdates from '../../utils/waitForBatchedUpdates'; + const TEST_IOU_REPORT_ID = '1001'; const TEST_CHAT_REPORT_ID = '2002'; const SELECTED_BANK_ACCOUNT_ID = 9999; @@ -177,9 +179,11 @@ describe('PayActionButton', () => { }); }); - it('forwards the selected bank account to payMoneyRequest when paying with a business bank account', () => { + it('forwards the selected bank account to payMoneyRequest when paying with a business bank account', async () => { + // Given a report preview Pay button for a report without held expenses renderPayActionButton(); + // When the user pays with a business bank account act(() => { mockOnPressHolder.current?.({ paymentType: CONST.IOU.PAYMENT_TYPE.VBBA, @@ -188,7 +192,9 @@ describe('PayActionButton', () => { paymentMethod: CONST.PAYMENT_METHODS.BUSINESS_BANK_ACCOUNT, }); }); + await waitForBatchedUpdates(); + // Then the payment uses the selected bank account, because the business bank account choice must reach the API expect(mockedPayMoneyRequest).toHaveBeenCalledWith( expect.objectContaining({ paymentType: CONST.IOU.PAYMENT_TYPE.VBBA, @@ -197,20 +203,24 @@ describe('PayActionButton', () => { ); }); - it('does not send a bank account for non-VBBA payment types', () => { + it('does not send a bank account for non-VBBA payment types', async () => { + // Given a report preview Pay button for a report without held expenses renderPayActionButton(); + // When the user pays elsewhere while a bank account ID is still attached to the press act(() => { mockOnPressHolder.current?.({ paymentType: CONST.IOU.PAYMENT_TYPE.ELSEWHERE, methodID: SELECTED_BANK_ACCOUNT_ID, }); }); + await waitForBatchedUpdates(); + // Then no bank account is sent, because only business bank account payments use one expect(mockedPayMoneyRequest).toHaveBeenCalledWith(expect.objectContaining({methodID: undefined})); }); - it('opens the global hold menu with the selected bank account when the report has held expenses', () => { + it('opens the global hold menu with the selected bank account when the report has held expenses', async () => { // Given a report preview whose report has held expenses mockedHasHeldExpenses.mockReturnValue(true); renderPayActionButton(); @@ -224,6 +234,7 @@ describe('PayActionButton', () => { paymentMethod: CONST.PAYMENT_METHODS.BUSINESS_BANK_ACCOUNT, }); }); + await waitForBatchedUpdates(); // Then the global hold menu opens for this report with the chosen account, and the payment waits for the user's choice expect(mockShowHoldMenu).toHaveBeenCalledWith( @@ -239,7 +250,7 @@ describe('PayActionButton', () => { expect(mockedPayMoneyRequest).not.toHaveBeenCalled(); }); - it('does not open the hold menu when the report has no held expenses', () => { + it('does not open the hold menu when the report has no held expenses', async () => { // Given a report preview without held expenses renderPayActionButton(); @@ -247,6 +258,7 @@ describe('PayActionButton', () => { act(() => { mockOnPressHolder.current?.({paymentType: CONST.IOU.PAYMENT_TYPE.ELSEWHERE}); }); + await waitForBatchedUpdates(); // Then the payment goes straight through without asking about held expenses expect(mockShowHoldMenu).not.toHaveBeenCalled(); diff --git a/tests/ui/components/PayActionCellTest.tsx b/tests/ui/components/PayActionCellTest.tsx index b3749b67a819..aeba38d1de15 100644 --- a/tests/ui/components/PayActionCellTest.tsx +++ b/tests/ui/components/PayActionCellTest.tsx @@ -18,6 +18,8 @@ import type {UseOnyxResult} from 'react-native-onyx'; import React from 'react'; +import waitForBatchedUpdates from '../../utils/waitForBatchedUpdates'; + const TEST_INVOICE_REPORT_ID = '1001'; const TEST_CHAT_REPORT_ID = '2002'; const TEST_HASH = 12345; @@ -100,12 +102,7 @@ jest.mock('@hooks/usePaymentContext', () => ({ currentUserAccountID: 1, email: 'payer@test.com', localCurrencyCode: 'USD', - introSelected: undefined, isASAPSubmitBetaEnabled: false, - isSelfTourViewed: false, - userBillingGracePeriodEnds: undefined, - amountOwed: undefined, - ownerBillingGracePeriodEnd: undefined, activePolicyID: undefined, activePolicy: undefined, defaultWorkspaceName: '', @@ -146,7 +143,7 @@ describe('PayActionCell', () => { mockedUseOnyx.mockImplementation(() => createOnyxResult(undefined)); }); - it('calls payInvoice with the chatReport supplied as a prop (the flat `type:invoice columns:...` transaction row now resolves and passes it)', () => { + it('calls payInvoice with the chatReport supplied as a prop (the flat `type:invoice columns:...` transaction row now resolves and passes it)', async () => { // Given an invoice report row whose invoice chat is resolved and passed down as a prop render( { payAsBusiness: false, }); }); + await waitForBatchedUpdates(); // Then the invoice payment should use the supplied chat report because paying an invoice needs the real invoice chat data expect(mockedPayInvoice).toHaveBeenCalledWith( @@ -177,7 +175,7 @@ describe('PayActionCell', () => { ); }); - it('does not call payInvoice when no chatReport prop is supplied', () => { + it('does not call payInvoice when no chatReport prop is supplied', async () => { // Given an invoice report row whose invoice chat is not loaded (no chatReport prop) render( { }); }); + await waitForBatchedUpdates(); + // Then no invoice payment should happen and the drop should be logged because a fallback chat report is not safe for invoices expect(mockedPayInvoice).not.toHaveBeenCalled(); expect(mockLogInfo).toHaveBeenCalledWith('[SearchPay] Dropping invoice row pay: chat report is not loaded', false, {reportID: TEST_INVOICE_REPORT_ID}); }); - it('pays a money request with a fallback chat report when no chatReport prop is supplied', () => { + it('pays a money request with a fallback chat report when no chatReport prop is supplied', async () => { // Given an expense report row whose chat report is not loaded (no chatReport prop) while the report itself carries a chatReportID mockedIsInvoiceReport.mockReturnValue(false); mockedUseReportWithTransactionsAndViolations.mockReturnValue([expenseReport, [], undefined]); @@ -226,6 +226,7 @@ describe('PayActionCell', () => { payAsBusiness: false, }); }); + await waitForBatchedUpdates(); // Then the payment should proceed with a minimal fallback chat report built from the known IDs expect(mockedPayMoneyRequest).toHaveBeenCalledWith( @@ -236,7 +237,7 @@ describe('PayActionCell', () => { ); }); - it('pays a money request with the loaded chat report when it is supplied', () => { + it('pays a money request with the loaded chat report when it is supplied', async () => { // Given an expense report row whose chat report is loaded and passed down as a prop mockedIsInvoiceReport.mockReturnValue(false); mockedUseReportWithTransactionsAndViolations.mockReturnValue([expenseReport, [], undefined]); @@ -259,6 +260,7 @@ describe('PayActionCell', () => { payAsBusiness: false, }); }); + await waitForBatchedUpdates(); // Then the payment should use the loaded chat report expect(mockedPayMoneyRequest).toHaveBeenCalledWith( @@ -269,7 +271,7 @@ describe('PayActionCell', () => { ); }); - it('does not pay a money request and logs the reason when the chat is not loaded and no chatReportID is available', () => { + it('does not pay a money request and logs the reason when the chat is not loaded and no chatReportID is available', async () => { // Given an expense report row whose chat report is not loaded and which has no chatReportID to build a fallback from mockedIsInvoiceReport.mockReturnValue(false); mockedUseReportWithTransactionsAndViolations.mockReturnValue([{...expenseReport, chatReportID: undefined, parentReportID: undefined}, [], undefined]); @@ -293,6 +295,8 @@ describe('PayActionCell', () => { }); }); + await waitForBatchedUpdates(); + // Then no payment should happen and the drop should be logged because there is no way to resolve any chat report expect(mockedPayMoneyRequest).not.toHaveBeenCalled(); expect(mockLogInfo).toHaveBeenCalledWith('[SearchPay] Dropping row pay: chat report is not loaded and no chatReportID is available', false, {reportID: TEST_EXPENSE_REPORT_ID}); diff --git a/tests/unit/ReportActionsListThresholdTest.tsx b/tests/unit/ReportActionsListThresholdTest.tsx index d8ce64ac8449..ba7c5238ab7f 100644 --- a/tests/unit/ReportActionsListThresholdTest.tsx +++ b/tests/unit/ReportActionsListThresholdTest.tsx @@ -105,10 +105,7 @@ async function renderList(initialOffset: number) { - + diff --git a/tests/unit/hooks/usePaymentContextTest.tsx b/tests/unit/hooks/usePaymentContextTest.tsx new file mode 100644 index 000000000000..0bbf652975ac --- /dev/null +++ b/tests/unit/hooks/usePaymentContextTest.tsx @@ -0,0 +1,145 @@ +import {act, renderHook} from '@testing-library/react-native'; + +import {CurrentUserPersonalDetailsProvider} from '@components/CurrentUserPersonalDetailsProvider'; +import {LocaleContextProvider} from '@components/LocaleContextProvider'; +import OnyxListItemProvider from '@components/OnyxListItemProvider'; + +import usePaymentContext, {PaymentContextProvider, useReportPaymentContext} from '@hooks/usePaymentContext'; + +import CONST from '@src/CONST'; +import ONYXKEYS from '@src/ONYXKEYS'; + +import React from 'react'; +import Onyx from 'react-native-onyx'; + +import createRandomPolicy from '../../utils/collections/policies'; +import waitForBatchedUpdatesWithAct from '../../utils/waitForBatchedUpdatesWithAct'; + +const CURRENT_USER_ACCOUNT_ID = 1; +const CURRENT_USER_EMAIL = 'payer@example.com'; +const DELEGATE_ACCOUNT_ID = 2; +const DELEGATE_EMAIL = 'delegate@example.com'; +const ACTIVE_POLICY_ID = 'activePolicy'; +const CHAT_REPORT_POLICY_ID = 'chatPolicy'; +const CONCIERGE_REPORT_ID = 'concierge1'; +const CONCIERGE_REPORT_KEY = `${ONYXKEYS.COLLECTION.REPORT}${CONCIERGE_REPORT_ID}` as const; +const AMOUNT_OWED = 1234; +const BANK_ACCOUNT_ID = 42; +const ACTIVE_POLICY_KEY = `${ONYXKEYS.COLLECTION.POLICY}${ACTIVE_POLICY_ID}` as const; +const CHAT_REPORT_POLICY_KEY = `${ONYXKEYS.COLLECTION.POLICY}${CHAT_REPORT_POLICY_ID}` as const; + +const activePolicy = {...createRandomPolicy(1), id: ACTIVE_POLICY_ID}; +const chatReportPolicy = {...createRandomPolicy(2), id: CHAT_REPORT_POLICY_ID}; + +function wrapper({children}: {children: React.ReactNode}) { + return ( + + + + {children} + + + + ); +} + +describe('usePaymentContext', () => { + beforeAll(() => { + Onyx.init({keys: ONYXKEYS}); + }); + + beforeEach(async () => { + // Given a signed-in payer acting as a delegate, with an active workspace and the ASAP submit beta on + await act(async () => { + await Onyx.multiSet({ + [ONYXKEYS.SESSION]: {accountID: CURRENT_USER_ACCOUNT_ID, email: CURRENT_USER_EMAIL}, + [ONYXKEYS.PERSONAL_DETAILS_LIST]: { + [CURRENT_USER_ACCOUNT_ID]: {accountID: CURRENT_USER_ACCOUNT_ID, login: CURRENT_USER_EMAIL, displayName: 'Payer', localCurrencyCode: CONST.CURRENCY.EUR}, + [DELEGATE_ACCOUNT_ID]: {accountID: DELEGATE_ACCOUNT_ID, login: DELEGATE_EMAIL}, + }, + [ONYXKEYS.ACCOUNT]: {delegatedAccess: {delegate: DELEGATE_EMAIL}}, + [ONYXKEYS.NVP_ACTIVE_POLICY_ID]: ACTIVE_POLICY_ID, + [ACTIVE_POLICY_KEY]: activePolicy, + [CHAT_REPORT_POLICY_KEY]: chatReportPolicy, + [ONYXKEYS.BETAS]: [CONST.BETAS.ASAP_SUBMIT], + }); + }); + await waitForBatchedUpdatesWithAct(); + }); + + afterEach(async () => { + await act(async () => { + await Onyx.clear(); + }); + }); + + it('exposes the shared payment inputs from the provider', async () => { + // Given the payer state seeded in beforeEach + // When a consumer reads the payment context under the provider + const {result} = renderHook(() => usePaymentContext(), {wrapper}); + await waitForBatchedUpdatesWithAct(); + + // Then it gets the current user, the delegate resolved to an account ID, the active policy, the beta flags and a workspace name built from the email domain, because + // pay flows pass these straight into payMoneyRequest and payInvoice + expect(result.current.currentUserAccountID).toBe(CURRENT_USER_ACCOUNT_ID); + expect(result.current.currentUserLogin).toBe(CURRENT_USER_EMAIL); + expect(result.current.localCurrencyCode).toBe(CONST.CURRENCY.EUR); + expect(result.current.delegateEmail).toBe(DELEGATE_EMAIL); + expect(result.current.delegateAccountID).toBe(DELEGATE_ACCOUNT_ID); + expect(result.current.activePolicyID).toBe(ACTIVE_POLICY_ID); + expect(result.current.activePolicy).toEqual(expect.objectContaining({id: ACTIVE_POLICY_ID})); + expect(result.current.isASAPSubmitBetaEnabled).toBe(true); + expect(result.current.isWiseReimbursementsBetaEnabled).toBe(false); + expect(result.current.defaultWorkspaceName).toContain('Example'); + }); + + it('adds the chat report policy on top of the shared values', async () => { + // Given the payer state seeded in beforeEach and a chat report on a different workspace + // When a row reads the report-scoped context for its chat report's policy + const {result} = renderHook(() => useReportPaymentContext({chatReportPolicyID: CHAT_REPORT_POLICY_ID}), {wrapper}); + await waitForBatchedUpdatesWithAct(); + + // Then the shared values are kept and the chat report policy is resolved per row, because each row may belong to a different workspace + expect(result.current.currentUserAccountID).toBe(CURRENT_USER_ACCOUNT_ID); + expect(result.current.chatReportPolicy).toEqual(expect.objectContaining({id: CHAT_REPORT_POLICY_ID})); + }); + + it('reads the press-time inputs for a row action from Onyx', async () => { + // Given the Concierge chat, the intro choice, a viewed tour, an amount owed and a bank account list in Onyx + await act(async () => { + await Onyx.multiSet({ + [ONYXKEYS.CONCIERGE_REPORT_ID]: CONCIERGE_REPORT_ID, + [CONCIERGE_REPORT_KEY]: {reportID: CONCIERGE_REPORT_ID}, + [ONYXKEYS.NVP_INTRO_SELECTED]: {choice: CONST.ONBOARDING_CHOICES.MANAGE_TEAM}, + [ONYXKEYS.NVP_ONBOARDING]: {selfTourViewed: true}, + [ONYXKEYS.NVP_PRIVATE_AMOUNT_OWED]: AMOUNT_OWED, + [ONYXKEYS.BANK_ACCOUNT_LIST]: {[BANK_ACCOUNT_ID]: {methodID: BANK_ACCOUNT_ID}}, + }); + }); + const {result} = renderHook(() => usePaymentContext(), {wrapper}); + await waitForBatchedUpdatesWithAct(); + + // When a row reads the inputs at press time + const inputs = await result.current.readSearchActionInputs(); + + // Then each value comes from its own key, because Pay, Approve and Submit pass them straight into the payment helpers and a swapped key would pay with the wrong data + expect(inputs.conciergeChat).toEqual(expect.objectContaining({reportID: CONCIERGE_REPORT_ID})); + expect(inputs.introSelected).toEqual(expect.objectContaining({choice: CONST.ONBOARDING_CHOICES.MANAGE_TEAM})); + expect(inputs.isSelfTourViewed).toBe(true); + expect(inputs.amountOwed).toBe(AMOUNT_OWED); + expect(inputs.bankAccountList).toEqual(expect.objectContaining({[BANK_ACCOUNT_ID]: expect.objectContaining({methodID: BANK_ACCOUNT_ID})})); + }); + + it('throws when read outside the provider', () => { + // Given no PaymentContextProvider above the consumer + const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {}); + + try { + // When the hook is read without a provider + // Then it throws, because the Search page must mount the provider once instead of rows subscribing on their own + expect(() => renderHook(() => usePaymentContext())).toThrow('usePaymentContext must be used within a PaymentContextProvider'); + } finally { + consoleErrorSpy.mockRestore(); + } + }); +}); diff --git a/tests/unit/hooks/useReportSubmitToPopoverTest.tsx b/tests/unit/hooks/useReportSubmitToPopoverTest.tsx new file mode 100644 index 000000000000..da7ec0b0b74b --- /dev/null +++ b/tests/unit/hooks/useReportSubmitToPopoverTest.tsx @@ -0,0 +1,69 @@ +import {act, renderHook} from '@testing-library/react-native'; + +import {LocaleContextProvider} from '@components/LocaleContextProvider'; +import OnyxListItemProvider from '@components/OnyxListItemProvider'; + +import useReportSubmitToPopover from '@hooks/useReportSubmitToPopover'; + +import CONST from '@src/CONST'; +import ONYXKEYS from '@src/ONYXKEYS'; + +import React from 'react'; +import Onyx from 'react-native-onyx'; + +import waitForBatchedUpdatesWithAct from '../../utils/waitForBatchedUpdatesWithAct'; + +const REPORT_ID = 'report1'; + +function wrapper({children}: {children: React.ReactNode}) { + return ( + + {children} + + ); +} + +describe('useReportSubmitToPopover', () => { + beforeAll(() => { + Onyx.init({keys: ONYXKEYS}); + }); + + afterEach(async () => { + await act(async () => { + await Onyx.clear(); + }); + }); + + it('drops only the Submit press that dismissed the popover, in the same tick', async () => { + // Given a submit-to popover that a Search row press just dismissed, before React has re-rendered the guard state + const {result} = renderHook(() => useReportSubmitToPopover({reportID: REPORT_ID}), {wrapper}); + await waitForBatchedUpdatesWithAct(); + const {closeReportSubmitToPopover, interceptSearchSubmitPress} = result.current; + closeReportSubmitToPopover(); + + // When the row checks the press that closed the popover, then checks a later press, then an action that is not Submit + const isFirstSubmitIgnored = interceptSearchSubmitPress(CONST.SEARCH.ACTION_TYPES.SUBMIT); + const isSecondSubmitIgnored = interceptSearchSubmitPress(CONST.SEARCH.ACTION_TYPES.SUBMIT); + const isViewIgnored = interceptSearchSubmitPress(CONST.SEARCH.ACTION_TYPES.VIEW); + + // Then only the first Submit press is dropped, because the dismiss click must not reopen the popover, while View never waits on the guard + expect(isFirstSubmitIgnored).toBe(true); + expect(isSecondSubmitIgnored).toBe(false); + expect(isViewIgnored).toBe(false); + }); + + it('resets the one-shot guard in a microtask, so rows must check it before their first await', async () => { + // Given a submit-to popover that was just dismissed + const {result} = renderHook(() => useReportSubmitToPopover({reportID: REPORT_ID}), {wrapper}); + await waitForBatchedUpdatesWithAct(); + const {closeReportSubmitToPopover, interceptSearchSubmitPress} = result.current; + closeReportSubmitToPopover(); + + // When a row checks the guard only after awaiting something + await Promise.resolve(); + const isSubmitIgnoredAfterAwait = interceptSearchSubmitPress(CONST.SEARCH.ACTION_TYPES.SUBMIT); + + // Then the one-shot guard is already gone, which is why the row handlers call it before any Onyx read + expect(isSubmitIgnoredAfterAwait).toBe(false); + }); +}); diff --git a/tests/unit/hooks/useSearchActionPressTest.tsx b/tests/unit/hooks/useSearchActionPressTest.tsx new file mode 100644 index 000000000000..6aff8a9e8d96 --- /dev/null +++ b/tests/unit/hooks/useSearchActionPressTest.tsx @@ -0,0 +1,65 @@ +import {renderHook} from '@testing-library/react-native'; + +import useSearchActionPress, {EMPTY_SEARCH_ACTION_INPUTS} from '@hooks/useSearchActionPress'; + +import CONST from '@src/CONST'; + +const mockInterceptSearchSubmitPress = jest.fn(); +const mockReadSearchActionInputs = jest.fn(); + +jest.mock('@components/ReportSubmitToPopoverAnchor', () => ({ + useSearchSubmitPopoverGuard: () => ({interceptSearchSubmitPress: mockInterceptSearchSubmitPress}), +})); + +jest.mock('@hooks/usePaymentContext', () => ({ + __esModule: true, + default: () => ({readSearchActionInputs: mockReadSearchActionInputs}), +})); + +const PRESS_TIME_INPUTS = {...EMPTY_SEARCH_ACTION_INPUTS, amountOwed: 1234}; + +describe('useSearchActionPress', () => { + beforeEach(() => { + mockInterceptSearchSubmitPress.mockReset().mockReturnValue(false); + mockReadSearchActionInputs.mockReset().mockResolvedValue(PRESS_TIME_INPUTS); + }); + + it('intercepts the press before the first await when the submit-to popover just closed', async () => { + // Given this press just dismissed the submit-to popover, so the intercept reports it + mockInterceptSearchSubmitPress.mockReturnValue(true); + const {result} = renderHook(() => useSearchActionPress()); + + // When the row reads its press-time inputs for Submit + const pendingInputs = result.current(CONST.SEARCH.ACTION_TYPES.SUBMIT); + + // Then the intercept ran before the first await, ahead of the microtask that resets the flag + expect(mockInterceptSearchSubmitPress).toHaveBeenCalledTimes(1); + expect(mockInterceptSearchSubmitPress).toHaveBeenCalledWith(CONST.SEARCH.ACTION_TYPES.SUBMIT); + await expect(pendingInputs).resolves.toBeUndefined(); + expect(mockReadSearchActionInputs).not.toHaveBeenCalled(); + }); + + it('reads the inputs once for an action that uses them', async () => { + // Given no popover to intercept the press and a Submit action + const {result} = renderHook(() => useSearchActionPress()); + + // When the row reads its press-time inputs + const inputs = await result.current(CONST.SEARCH.ACTION_TYPES.SUBMIT); + + // Then the shared reader ran once and its values reach the row + expect(mockReadSearchActionInputs).toHaveBeenCalledTimes(1); + expect(inputs).toEqual(PRESS_TIME_INPUTS); + }); + + it('skips the read for an action that only navigates', async () => { + // Given no popover to intercept the press and a View action + const {result} = renderHook(() => useSearchActionPress()); + + // When the row reads its press-time inputs + const inputs = await result.current(CONST.SEARCH.ACTION_TYPES.VIEW); + + // Then the hook skips the read and returns the empty inputs, so the handler call keeps one shape + expect(mockReadSearchActionInputs).not.toHaveBeenCalled(); + expect(inputs).toBe(EMPTY_SEARCH_ACTION_INPUTS); + }); +}); diff --git a/tests/unit/hooks/useSearchBulkActionsPayTest.ts b/tests/unit/hooks/useSearchBulkActionsPayTest.ts index 1754f20ba513..5502ee35984f 100644 --- a/tests/unit/hooks/useSearchBulkActionsPayTest.ts +++ b/tests/unit/hooks/useSearchBulkActionsPayTest.ts @@ -174,14 +174,9 @@ jest.mock('@hooks/usePolicyForMovingExpenses', () => ({ jest.mock('@hooks/usePaymentContext', () => ({ __esModule: true, default: () => ({ - introSelected: undefined, - isSelfTourViewed: false, activePolicyID: undefined, activePolicy: undefined, defaultWorkspaceName: undefined, - userBillingGracePeriodEnds: undefined, - amountOwed: undefined, - ownerBillingGracePeriodEnd: undefined, }), PaymentContextProvider: ({children}: {children: unknown}) => children, useReportPaymentContext: () => ({}), diff --git a/tests/unit/hooks/useSearchBulkActionsTest.ts b/tests/unit/hooks/useSearchBulkActionsTest.ts index 8f1e79cb85de..7d6239d0f73f 100644 --- a/tests/unit/hooks/useSearchBulkActionsTest.ts +++ b/tests/unit/hooks/useSearchBulkActionsTest.ts @@ -159,14 +159,9 @@ jest.mock('@hooks/usePolicyForMovingExpenses', () => ({ jest.mock('@hooks/usePaymentContext', () => ({ __esModule: true, default: () => ({ - introSelected: undefined, - isSelfTourViewed: false, activePolicyID: undefined, activePolicy: undefined, defaultWorkspaceName: undefined, - userBillingGracePeriodEnds: undefined, - amountOwed: undefined, - ownerBillingGracePeriodEnd: undefined, }), PaymentContextProvider: ({children}: {children: unknown}) => children, useReportPaymentContext: () => ({}), diff --git a/tests/unit/useReportActionsNewActionLiveTailTest.ts b/tests/unit/useReportActionsNewActionLiveTailTest.ts index 1264d0ba9eac..30824469f62b 100644 --- a/tests/unit/useReportActionsNewActionLiveTailTest.ts +++ b/tests/unit/useReportActionsNewActionLiveTailTest.ts @@ -5,9 +5,13 @@ import {FALLBACK_NAVIGATION_CONTEXT_VALUE} from '@components/withNavigationFallb import useReportActionsNewActionLiveTail from '@pages/inbox/report/useReportActionsNewActionLiveTail'; import CONST from '@src/CONST'; +import ONYXKEYS from '@src/ONYXKEYS'; import type {ReportAction} from '@src/types/onyx'; -import {getFakeReportAction} from '../utils/ReportTestUtils'; +import Onyx from 'react-native-onyx'; + +import {createMockReport, getFakeReportAction} from '../utils/ReportTestUtils'; +import waitForBatchedUpdates from '../utils/waitForBatchedUpdates'; const mockNavigationSetParams = jest.fn(); const mockGlobalSetParams = jest.fn(); @@ -35,6 +39,7 @@ let mockNavigation: Record = {setParams: mockNavigationSetParam let mockIsInSidePanel = false; jest.mock('@react-navigation/native', () => ({ + ...jest.requireActual>('@react-navigation/native'), useNavigation: () => mockNavigation, })); @@ -91,10 +96,7 @@ const reportScrollManager = { function buildParams(overrides: Partial = {}): HookParams { return { reportID: '1', - introSelected: undefined, - conciergeChat: undefined, - isSelfTourViewed: undefined, - hasCompletedGuidedSetupFlow: undefined, + policyID: undefined, isOffline: false, reportScrollManager, setIsFloatingMessageCounterVisible: jest.fn(), @@ -115,8 +117,9 @@ function buildParams(overrides: Partial = {}): HookParams { } describe('useReportActionsNewActionLiveTail', () => { - beforeEach(() => { + beforeEach(async () => { jest.clearAllMocks(); + await Onyx.clear(); newActionHandler = undefined; mockNavigation = {setParams: mockNavigationSetParams, getState: () => ({key: 'stack-report'})}; mockIsInSidePanel = false; @@ -135,35 +138,58 @@ describe('useReportActionsNewActionLiveTail', () => { expect(params.setTreatAsNoPaginationAnchor).toHaveBeenLastCalledWith(false); }); - it('threads the conciergeChat report through to the catch-up openReport call', () => { - const conciergeChat = {reportID: 'concierge-live-tail-1'}; - renderHook((props: HookParams) => useReportActionsNewActionLiveTail(props), {initialProps: buildParams({conciergeChat})}); - + it('reads the openReport inputs from Onyx for the catch-up openReport call', async () => { + // Given the Concierge chat, onboarding, intro, session and full policy snapshot in Onyx. The hook subscribes to none + // of them, so it must read them when the jump happens for the guided setup data openReport builds. + const conciergeChat = createMockReport({reportID: 'concierge-live-tail-1'}); + await Onyx.set(ONYXKEYS.CONCIERGE_REPORT_ID, conciergeChat.reportID); + await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${conciergeChat.reportID}`, conciergeChat); + await Onyx.set(ONYXKEYS.NVP_ONBOARDING, {selfTourViewed: true, hasCompletedGuidedSetupFlow: false}); + await Onyx.set(ONYXKEYS.NVP_INTRO_SELECTED, {choice: CONST.ONBOARDING_CHOICES.EMPLOYER}); + await Onyx.set(ONYXKEYS.SESSION, {accountID: 42}); + await Onyx.set(`${ONYXKEYS.COLLECTION.RAM_ONLY_FULL_POLICY_SNAPSHOT}policy-1`, {lastModified: 123}); + renderHook((props: HookParams) => useReportActionsNewActionLiveTail(props), {initialProps: buildParams({policyID: 'policy-1'})}); + + // When the current user sends a comment while the newest actions are not loaded act(() => { newActionHandler?.(true, getFakeReportAction(1, {actionName: CONST.REPORT.ACTIONS.TYPE.ADD_COMMENT})); }); - - expect(mockOpenReport).toHaveBeenCalledWith(expect.objectContaining({conciergeChat})); + await waitForBatchedUpdates(); + + // Then the catch-up openReport receives each value as it was in Onyx, with the selectors applied + expect(mockOpenReport).toHaveBeenCalledWith( + expect.objectContaining({ + conciergeChat: expect.objectContaining({reportID: conciergeChat.reportID}), + introSelected: expect.objectContaining({choice: CONST.ONBOARDING_CHOICES.EMPLOYER}), + isSelfTourViewed: true, + hasCompletedGuidedSetupFlow: false, + currentUserAccountID: 42, + fullPolicySnapshot: {policyID: 'policy-1', lastModified: 123}, + }), + ); }); - it('threads the onboarding status through to the catch-up openReport call', () => { - renderHook((props: HookParams) => useReportActionsNewActionLiveTail(props), {initialProps: buildParams({isSelfTourViewed: true, hasCompletedGuidedSetupFlow: false})}); + it('returns the openReport helper that the "Latest messages" pill reuses', async () => { + // Given the hook for report 1. The pill in useReportActionsScroll calls this helper instead of reading the inputs itself. + const {result} = renderHook((props: HookParams) => useReportActionsNewActionLiveTail(props), {initialProps: buildParams()}); - act(() => { - newActionHandler?.(true, getFakeReportAction(1, {actionName: CONST.REPORT.ACTIONS.TYPE.ADD_COMMENT})); + // When the pill calls the returned helper + await act(async () => { + await result.current.openReportAtLiveTail(); }); - // The onboarding flags are threaded straight through so guided-setup optimistic data is derived from real Onyx - // data supplied by the caller instead of the deprecated module-level fallback. - expect(mockOpenReport).toHaveBeenCalledWith(expect.objectContaining({isSelfTourViewed: true, hasCompletedGuidedSetupFlow: false})); + // Then openReport runs once, for this report + expect(mockOpenReport).toHaveBeenCalledTimes(1); + expect(mockOpenReport).toHaveBeenCalledWith(expect.objectContaining({reportID: '1'})); }); - it('clears the report screen param after loading the live tail without changing the focused route', () => { + it('clears the report screen param after loading the live tail without changing the focused route', async () => { const {rerender} = renderHook((props: HookParams) => useReportActionsNewActionLiveTail(props), {initialProps: buildParams()}); act(() => { newActionHandler?.(true, getFakeReportAction(1, {actionName: CONST.REPORT.ACTIONS.TYPE.ADD_COMMENT})); }); + await waitForBatchedUpdates(); expect(mockOpenReport).toHaveBeenCalledTimes(1); @@ -223,7 +249,7 @@ describe('useReportActionsNewActionLiveTail', () => { expect(setTreatAsNoPaginationAnchor).toHaveBeenCalledWith(true); }); - it('scrolls straight to the bottom when an unread marker is set but the newest actions are already loaded', () => { + it('scrolls straight to the bottom when an unread marker is set but the newest actions are already loaded', async () => { // Given a report scrolled up with an unread marker from another user's comment, and the newest actions already loaded const setIsFloatingMessageCounterVisible = jest.fn(); const {result} = renderHook((props: HookParams) => useReportActionsNewActionLiveTail(props), { @@ -234,6 +260,7 @@ describe('useReportActionsNewActionLiveTail', () => { act(() => { newActionHandler?.(true, getFakeReportAction(1, {actionName: CONST.REPORT.ACTIONS.TYPE.ADD_COMMENT})); }); + await waitForBatchedUpdates(); // Then the list scrolls to the bottom directly, without an openReport round trip expect(mockOpenReport).not.toHaveBeenCalled(); @@ -242,7 +269,7 @@ describe('useReportActionsNewActionLiveTail', () => { expect(result.current.isScrollToBottomEnabled).toBe(true); }); - it('still loads the live tail when an unread marker is set and the newest actions are not loaded', () => { + it('still loads the live tail when an unread marker is set and the newest actions are not loaded', async () => { // Given an unread marker and a report whose newest actions are not loaded yet renderHook((props: HookParams) => useReportActionsNewActionLiveTail(props), { initialProps: buildParams({unreadMarkerReportActionID: '2', hasNewerActions: false, hasNewestReportAction: false}), @@ -252,6 +279,7 @@ describe('useReportActionsNewActionLiveTail', () => { act(() => { newActionHandler?.(true, getFakeReportAction(1, {actionName: CONST.REPORT.ACTIONS.TYPE.ADD_COMMENT})); }); + await waitForBatchedUpdates(); // Then openReport fetches the newest actions before the list scrolls expect(mockOpenReport).toHaveBeenCalledTimes(1); diff --git a/tests/unit/useReportActionsScrollTest.tsx b/tests/unit/useReportActionsScrollTest.tsx index 2de3e2daa285..5da4c0baa803 100644 --- a/tests/unit/useReportActionsScrollTest.tsx +++ b/tests/unit/useReportActionsScrollTest.tsx @@ -70,6 +70,7 @@ jest.mock('@pages/inbox/report/useReportUnreadMessageScrollTracking', () => ({ // --- useReportActionsNewActionLiveTail --- const mockSetIsScrollToBottomEnabled = jest.fn(); const mockCompleteLiveTailPrune = jest.fn(); +const mockOpenReportAtLiveTail = jest.fn(); let mockIsScrollToBottomEnabled = false; jest.mock('@pages/inbox/report/useReportActionsNewActionLiveTail', () => ({ __esModule: true, @@ -77,6 +78,7 @@ jest.mock('@pages/inbox/report/useReportActionsNewActionLiveTail', () => ({ isScrollToBottomEnabled: mockIsScrollToBottomEnabled, setIsScrollToBottomEnabled: mockSetIsScrollToBottomEnabled, completeLiveTailPruneAfterScrollToBottom: mockCompleteLiveTailPrune, + openReportAtLiveTail: mockOpenReportAtLiveTail, }), })); @@ -115,15 +117,6 @@ jest.mock('@libs/Navigation/Navigation', () => ({ }, })); -// --- openReport --- -const mockOpenReport = jest.fn(); -jest.mock('@userActions/Report', () => ({ - __esModule: true, - openReport: (...args: unknown[]) => { - mockOpenReport(...args); - }, -})); - // --- react-navigation route --- let mockRouteParams: {reportActionID?: string; backTo?: string; shouldScrollToLatest?: string} = {}; jest.mock('@react-navigation/native', () => { @@ -183,7 +176,6 @@ function makeAction(reportActionID: string, overrides: Partial = { function buildParams(overrides: Partial = {}): ScrollParams { return { reportID: REPORT_ID, - conciergeChat: undefined, report: createMockReport({reportID: REPORT_ID}), transactionThreadReport: undefined, parentReportAction: undefined, @@ -376,7 +368,7 @@ describe('useReportActionsScroll', () => { expect(mockScrollToBottom).toHaveBeenCalledTimes(1); expect(mockMarkNewestActionAsRead).toHaveBeenCalledTimes(1); expect(mockNavigate).not.toHaveBeenCalled(); - expect(mockOpenReport).not.toHaveBeenCalled(); + expect(mockOpenReportAtLiveTail).not.toHaveBeenCalled(); }); it('navigates and opens the report when the newest action is not present', async () => { @@ -388,7 +380,7 @@ describe('useReportActionsScroll', () => { }); expect(mockNavigate).toHaveBeenCalledTimes(1); - expect(mockOpenReport).toHaveBeenCalledTimes(1); + expect(mockOpenReportAtLiveTail).toHaveBeenCalledTimes(1); expect(mockScrollToBottom).toHaveBeenCalledTimes(1); expect(mockMarkNewestActionAsRead).not.toHaveBeenCalled(); }); @@ -403,7 +395,7 @@ describe('useReportActionsScroll', () => { }); expect(mockNavigate).not.toHaveBeenCalled(); - expect(mockOpenReport).toHaveBeenCalledTimes(1); + expect(mockOpenReportAtLiveTail).toHaveBeenCalledTimes(1); }); }); diff --git a/tests/utils/mockUsePaymentContext.ts b/tests/utils/mockUsePaymentContext.ts index 9875e5e3dc67..7be173b5fb72 100644 --- a/tests/utils/mockUsePaymentContext.ts +++ b/tests/utils/mockUsePaymentContext.ts @@ -1,21 +1,20 @@ -type MockPaymentContextOverrides = Partial; +import type {PaymentContextValue} from '@hooks/usePaymentContext'; -const defaultMockPaymentContextValue = { +type MockPaymentContextOverrides = Partial; + +const defaultMockPaymentContextValue: PaymentContextValue = { currentUserAccountID: 1, currentUserLogin: 'test@example.com', email: 'test@example.com', localCurrencyCode: 'USD', - introSelected: undefined, isASAPSubmitBetaEnabled: false, - isSelfTourViewed: false, + isWiseReimbursementsBetaEnabled: false, activePolicyID: undefined, activePolicy: undefined, - conciergeReportID: undefined, defaultWorkspaceName: 'Test Workspace', - userBillingGracePeriodEnds: undefined, - amountOwed: undefined, - ownerBillingGracePeriodEnd: undefined, delegateEmail: undefined, + delegateAccountID: undefined, + readSearchActionInputs: () => Promise.resolve({conciergeChat: undefined, introSelected: undefined, isSelfTourViewed: false, amountOwed: undefined, bankAccountList: undefined}), }; function createMockUsePaymentContextModule(overrides: MockPaymentContextOverrides = {}) {