diff --git a/src/components/MoneyRequestConfirmationList.tsx b/src/components/MoneyRequestConfirmationList.tsx index df6eb06e1062..5c5bb0fab548 100644 --- a/src/components/MoneyRequestConfirmationList.tsx +++ b/src/components/MoneyRequestConfirmationList.tsx @@ -1,10 +1,11 @@ import {useFocusEffect, useIsFocused} from '@react-navigation/native'; -import React, {useCallback, useEffect, useRef, useState} from 'react'; +import React, {useCallback, useEffect, useMemo, useRef, useState} from 'react'; // eslint-disable-next-line no-restricted-imports import {InteractionManager, View} from 'react-native'; import type {OnyxEntry} from 'react-native-onyx'; import useCurrentUserPersonalDetails from '@hooks/useCurrentUserPersonalDetails'; import useIsInLandscapeMode from '@hooks/useIsInLandscapeMode'; +import useLocalize from '@hooks/useLocalize'; import {MouseProvider} from '@hooks/useMouseContext'; import usePermissions from '@hooks/usePermissions'; import usePolicyForMovingExpenses from '@hooks/usePolicyForMovingExpenses'; @@ -64,6 +65,9 @@ type MoneyRequestConfirmationListProps = { /** Callback to inform parent modal of success */ onConfirm?: (selectedParticipants: Participant[]) => void; + /** When set, used in the new manual expense flow to open the parent-owned participant picker instead of navigating away */ + onOpenParticipantPicker?: () => void; + /** Callback to parent modal to pay someone */ onSendMoney?: (paymentMethod: PaymentMethodType | undefined) => void; @@ -164,6 +168,7 @@ function MoneyRequestConfirmationList({ transaction, onSendMoney, onConfirm, + onOpenParticipantPicker, iouType = CONST.IOU.TYPE.SUBMIT, isOdometerDistanceRequest = false, isLoadingReceipt = false, @@ -204,6 +209,7 @@ function MoneyRequestConfirmationList({ const {isDelegateAccessRestricted} = useDelegateNoAccessState(); const {showDelegateNoAccessModal} = useDelegateNoAccessActions(); const isInLandscapeMode = useIsInLandscapeMode(); + const {translate} = useLocalize(); const {isTestReceipt, shouldShowProductTrainingTooltip, renderProductTrainingTooltip} = useReceiptTraining({ transaction, @@ -257,7 +263,6 @@ function MoneyRequestConfirmationList({ iouCurrencyCode, }); - // A flag for showing the categories field const shouldShowCategories = isTrackExpense ? !policy || shouldSelectPolicy || !!iouCategory || hasEnabledOptions(Object.values(policyCategories ?? {})) : (isPolicyExpenseChat || isTypeInvoice) && (!!iouCategory || hasEnabledOptions(Object.values(policyCategories ?? {}))); @@ -293,6 +298,9 @@ function MoneyRequestConfirmationList({ prevSubRates, }); + const isManualRequest = transaction?.iouRequestType === CONST.IOU.REQUEST_TYPE.MANUAL; + const shouldForceTopEmptySections = isNewManualExpenseFlowEnabled && (iouType === CONST.IOU.TYPE.CREATE || isManualRequest || isScanRequest); + const isFocused = useIsFocused(); const [didConfirm, setDidConfirm] = useState(isConfirmed); @@ -307,7 +315,7 @@ function MoneyRequestConfirmationList({ const isTypeSplit = iouType === CONST.IOU.TYPE.SPLIT; const shouldShowReadOnlySplits = isPolicyExpenseChat || isReadOnly || isScanRequest; - const {formError, setFormError, clearFormErrors, shouldDisplayFieldError, isMerchantEmpty, isMerchantRequired, errorMessage} = useFormErrorManagement({ + const {formError, setFormError, clearFormErrors, shouldDisplayFieldError, isMerchantEmpty, isMerchantFieldValid, isMerchantRequired, errorMessage} = useFormErrorManagement({ transaction, transactionReport, iouMerchant, @@ -360,6 +368,24 @@ function MoneyRequestConfirmationList({ const selectedParticipants = selectedParticipantsProp.filter((participant) => participant.selected); const payeePersonalDetails = payeePersonalDetailsProp ?? currentUserPersonalDetails; + const participantRowErrors = useMemo(() => { + if (formError !== 'iou.error.noParticipantSelected' && formError !== 'violations.missingAttendees') { + return undefined; + } + return {participants: translate(formError)}; + }, [formError, translate]); + + useEffect(() => { + if (selectedParticipants.length === 0) { + return; + } + clearFormErrors(['iou.error.noParticipantSelected']); + }, [selectedParticipants.length, clearFormErrors]); + + const dismissParticipantRowError = useCallback(() => { + clearFormErrors(['iou.error.noParticipantSelected', 'violations.missingAttendees']); + }, [clearFormErrors]); + const {splitParticipants, getSplitSectionHeader} = useSplitParticipants({ isTypeSplit, shouldShowReadOnlySplits, @@ -375,6 +401,8 @@ function MoneyRequestConfirmationList({ const sections = useConfirmationSections({ isTypeSplit, shouldHideToSection, + shouldForceTopEmptySections, + participantRowErrors, canEditParticipant, payeePersonalDetails, splitParticipants, @@ -390,8 +418,13 @@ function MoneyRequestConfirmationList({ return; } + if (isNewManualExpenseFlowEnabled) { + onOpenParticipantPicker?.(); + return; + } + const newIOUType = iouType === CONST.IOU.TYPE.SUBMIT || iouType === CONST.IOU.TYPE.TRACK ? CONST.IOU.TYPE.CREATE : iouType; - Navigation.navigate(ROUTES.MONEY_REQUEST_STEP_PARTICIPANTS.getRoute(newIOUType, transactionID, transaction.reportID, Navigation.getActiveRoute(), action)); + Navigation.navigate(ROUTES.MONEY_REQUEST_STEP_PARTICIPANTS.getRoute(newIOUType, transactionID, transaction?.reportID, Navigation.getActiveRoute(), action)); }; const {validate} = useConfirmationValidation({ @@ -412,6 +445,7 @@ function MoneyRequestConfirmationList({ currentUserPersonalDetails, isEditingSplitBill, isMerchantRequired, + isMerchantFieldValid, isMerchantEmpty, shouldDisplayFieldError, shouldShowTax, @@ -419,8 +453,8 @@ function MoneyRequestConfirmationList({ isDistanceRequestWithPendingRoute, isPerDiemRequest, isTimeRequest, - isNewManualExpenseFlowEnabled, routeError, + isNewManualExpenseFlowEnabled, }); const confirm = buildConfirmAction({ @@ -443,13 +477,17 @@ function MoneyRequestConfirmationList({ const focusTimeoutRef = useRef(null); useFocusEffect( useCallback(() => { + // Blurring the active element after transition fights AmountField focus in the new manual flow (RHP reopen). + if (isNewManualExpenseFlowEnabled) { + return undefined; + } focusTimeoutRef.current = setTimeout(() => { InteractionManager.runAfterInteractions(() => { blurActiveElement(); }); }, CONST.ANIMATED_TRANSITION); return () => focusTimeoutRef.current && clearTimeout(focusTimeoutRef.current); - }, []), + }, [isNewManualExpenseFlowEnabled]), ); const isCompactMode = !showMoreFields && isScanRequest && !isInLandscapeMode; @@ -489,6 +527,8 @@ function MoneyRequestConfirmationList({ formattedAmount={formattedAmount} formattedAmountPerAttendee={formattedAmountPerAttendee} formError={formError} + clearFormErrors={clearFormErrors} + setFormError={setFormError} hasRoute={hasRoute} iouType={iouType} isCategoryRequired={isCategoryRequired} @@ -532,6 +572,7 @@ function MoneyRequestConfirmationList({ isDescriptionRequired={isDescriptionRequired} showMoreFields={showMoreFields} setShowMoreFields={setShowMoreFields} + onSubmitForm={confirm} /> ); @@ -603,6 +644,7 @@ function MoneyRequestConfirmationList({ sections={sections} ListItem={BareUserListItem} onSelectRow={navigateToParticipantPage} + onDismissError={dismissParticipantRowError} shouldSingleExecuteRowSelect shouldPreventDefaultFocusOnSelectRow shouldShowListEmptyContent={false} diff --git a/src/components/MoneyRequestConfirmationList/confirmAction.ts b/src/components/MoneyRequestConfirmationList/confirmAction.ts index 7a7f9919b313..92813d16508b 100644 --- a/src/components/MoneyRequestConfirmationList/confirmAction.ts +++ b/src/components/MoneyRequestConfirmationList/confirmAction.ts @@ -79,7 +79,7 @@ function buildConfirmAction({ onConfirm, onSendMoney, }: BuildConfirmActionParams) { - return ({paymentType: paymentMethod}: PaymentActionParams) => { + return ({paymentType: paymentMethod}: PaymentActionParams = {}) => { // Routing short-circuit: invoices without company info go to the company info step before we validate anything. if (iouType === CONST.IOU.TYPE.INVOICE && !hasInvoicingDetails(policy) && transactionID && !routeError) { Navigation.navigate(ROUTES.MONEY_REQUEST_STEP_COMPANY_INFO.getRoute(iouType, transactionID, reportID, Navigation.getActiveRoute())); diff --git a/src/components/MoneyRequestConfirmationList/hooks/useConfirmationSections.ts b/src/components/MoneyRequestConfirmationList/hooks/useConfirmationSections.ts index 8dee6c1ee250..b611217aacc2 100644 --- a/src/components/MoneyRequestConfirmationList/hooks/useConfirmationSections.ts +++ b/src/components/MoneyRequestConfirmationList/hooks/useConfirmationSections.ts @@ -17,6 +17,14 @@ type UseConfirmationSectionsParams = { /** Whether the "to" section should be hidden (used when adding directly to a report) */ shouldHideToSection: boolean; + /** + * When true with `shouldHideToSection`, still render the "To" section (e.g. new manual flow so the user can open the participant picker). + */ + shouldForceTopEmptySections?: boolean; + + /** Row-level errors for the participant section (e.g. missing recipient / attendees), shown on the list row */ + participantRowErrors?: Record; + /** Whether participant rows should be interactive (allow editing the recipient) */ canEditParticipant: boolean; @@ -44,6 +52,8 @@ type UseConfirmationSectionsParams = { function useConfirmationSections({ isTypeSplit, shouldHideToSection, + shouldForceTopEmptySections = false, + participantRowErrors, canEditParticipant, payeePersonalDetails, splitParticipants, @@ -67,18 +77,31 @@ function useConfirmationSections({ }, ); // When adding an expense from within a report, hide the "To:" section since the destination is already the current report - } else if (!shouldHideToSection) { - const formattedSelectedParticipants = selectedParticipants.map((participant) => ({ - ...participant, - isSelected: false, - keyForList: `${participant.keyForList ?? participant.accountID ?? participant.reportID}`, - isInteractive: canEditParticipant, - shouldShowRightCaret: canEditParticipant, - })); + } else if (!shouldHideToSection || shouldForceTopEmptySections) { + const participantRows = + selectedParticipants.length > 0 + ? selectedParticipants.map((participant) => ({ + ...participant, + isSelected: false, + keyForList: `${participant.keyForList ?? participant.accountID ?? participant.reportID}`, + isInteractive: canEditParticipant, + shouldShowRightCaret: canEditParticipant, + ...(participantRowErrors ? {errors: participantRowErrors} : {}), + })) + : [ + { + keyForList: 'empty-participant-option', + text: translate('iou.chooseRecipient'), + isInteractive: canEditParticipant, + shouldShowRightCaret: canEditParticipant, + isBold: false, + ...(participantRowErrors ? {errors: participantRowErrors} : {}), + }, + ]; options.push({ - title: translate('common.to'), - data: formattedSelectedParticipants, + title: selectedParticipants.length > 0 ? translate('common.to') : undefined, + data: participantRows, sectionIndex: 0, }); } diff --git a/src/components/MoneyRequestConfirmationList/hooks/useConfirmationValidation.ts b/src/components/MoneyRequestConfirmationList/hooks/useConfirmationValidation.ts index cbe3ff2e30e6..8f1bfc756877 100644 --- a/src/components/MoneyRequestConfirmationList/hooks/useConfirmationValidation.ts +++ b/src/components/MoneyRequestConfirmationList/hooks/useConfirmationValidation.ts @@ -7,7 +7,7 @@ import type {getTagLists as getTagListsFn} from '@libs/PolicyUtils'; import {isAttendeeTrackingEnabled} from '@libs/PolicyUtils'; import {hasEnabledTags, hasMatchingTag} from '@libs/TagsOptionsListUtils'; import {isValidTimeExpenseAmount} from '@libs/TimeTrackingUtils'; -import {areRequiredFieldsEmpty, getTag, hasTaxRateWithMatchingValue, isMerchantMissing} from '@libs/TransactionUtils'; +import {areRequiredFieldsEmpty, getTag, hasTaxRateWithMatchingValue, isMerchantMissing, isScanRequest as isScanRequestUtil} from '@libs/TransactionUtils'; import {isValidInputLength} from '@libs/ValidationUtils'; import type {IOUType} from '@src/CONST'; import CONST from '@src/CONST'; @@ -71,10 +71,13 @@ type UseConfirmationValidationParams = { /** Whether the merchant field is required for this flow */ isMerchantRequired: boolean | undefined; - /** Whether the merchant field is currently empty / partial */ + /** Whether the merchant value passes full validation (length, required, disallowed values) */ + isMerchantFieldValid: boolean; + + /** Whether the merchant field is empty / partial (from {@link useFormErrorManagement}) */ isMerchantEmpty: boolean; - /** Whether per-field errors should be shown */ + /** When editing a split bill, whether per-field errors should be shown (SmartScan failure paths) */ shouldDisplayFieldError: boolean; /** Whether the tax section is enabled for this policy */ @@ -92,11 +95,11 @@ type UseConfirmationValidationParams = { /** Whether the transaction is a time-tracking request */ isTimeRequest: boolean; - /** Whether the new manual expense flow beta is enabled */ - isNewManualExpenseFlowEnabled: boolean; - /** Truthy when the route to the confirmation page has a known error */ routeError: string | null | undefined; + + /** Whether the new manual expense flow is enabled */ + isNewManualExpenseFlowEnabled: boolean; }; /** @@ -131,6 +134,7 @@ function useConfirmationValidation({ currentUserPersonalDetails, isEditingSplitBill, isMerchantRequired, + isMerchantFieldValid, isMerchantEmpty, shouldDisplayFieldError, shouldShowTax, @@ -138,8 +142,8 @@ function useConfirmationValidation({ isDistanceRequestWithPendingRoute, isPerDiemRequest, isTimeRequest, - isNewManualExpenseFlowEnabled, routeError, + isNewManualExpenseFlowEnabled, }: UseConfirmationValidationParams): {validate: (paymentType?: PaymentMethodType) => ValidationResult | null} { const {getCurrencyDecimals} = useCurrencyListActions(); const selectedParticipantsCount = selectedParticipants.length; @@ -152,21 +156,30 @@ function useConfirmationValidation({ return {errorKey: 'iou.error.noParticipantSelected'}; } - const amountForValidation = iouAmount; - const isAmountMissingForManualFlow = amountForValidation === null || amountForValidation === undefined; + const firstParticipant = transaction?.participants?.at(0); + const isP2P = !!(firstParticipant?.accountID && !firstParticipant?.isPolicyExpenseChat); - if (iouType !== CONST.IOU.TYPE.PAY && isNewManualExpenseFlowEnabled && isAmountMissingForManualFlow) { + // P2P manual submit: $0 is invalid unless scan/time/distance (same guard as legacy inline confirm). + if (iouType !== CONST.IOU.TYPE.PAY && !isScanRequestUtil(transaction) && !isTimeRequest && !isDistanceRequest && iouAmount === 0 && isP2P) { return {errorKey: 'common.error.invalidAmount'}; } - + if (isNewManualExpenseFlowEnabled && !transaction?.isAmountSet) { + return {errorKey: 'common.error.fieldRequired'}; + } const merchantValue = iouMerchant ?? ''; const {isValid: isMerchantLengthValid} = isValidInputLength(merchantValue, CONST.MERCHANT_NAME_MAX_BYTES); if (!isMerchantLengthValid) { return {errorKey: 'iou.error.invalidMerchant'}; } - - if (!isEditingSplitBill && isMerchantRequired && (isMerchantEmpty || (shouldDisplayFieldError && isMerchantMissing(transaction)))) { + if (isMerchantRequired) { + if (!isEditingSplitBill && !isMerchantFieldValid) { + return {errorKey: 'iou.error.invalidMerchant'}; + } + if (isEditingSplitBill && (isMerchantEmpty || (shouldDisplayFieldError && isMerchantMissing(transaction)))) { + return {errorKey: 'iou.error.invalidMerchant'}; + } + } else if (transaction?.isMerchantSet && !isMerchantFieldValid) { return {errorKey: 'iou.error.invalidMerchant'}; } @@ -252,4 +265,4 @@ function useConfirmationValidation({ } export default useConfirmationValidation; -export type {ValidationResult}; +export type {ValidationResult, UseConfirmationValidationParams}; diff --git a/src/components/MoneyRequestConfirmationList/sections/AmountField.tsx b/src/components/MoneyRequestConfirmationList/sections/AmountField.tsx index c59a392befca..edda76523b93 100644 --- a/src/components/MoneyRequestConfirmationList/sections/AmountField.tsx +++ b/src/components/MoneyRequestConfirmationList/sections/AmountField.tsx @@ -1,22 +1,28 @@ -import React, {useState} from 'react'; +import React, {useEffect, useRef, useState} from 'react'; import {View} from 'react-native'; import type {OnyxEntry} from 'react-native-onyx'; import MenuItemWithTopDescription from '@components/MenuItemWithTopDescription'; import NumberWithSymbolForm from '@components/NumberWithSymbolForm'; +import type {BaseTextInputRef} from '@components/TextInput/BaseTextInput/types'; import {useCurrencyListActions} from '@hooks/useCurrencyList'; +import useCurrentUserPersonalDetails from '@hooks/useCurrentUserPersonalDetails'; import useLocalize from '@hooks/useLocalize'; import useOnyx from '@hooks/useOnyx'; +import useScreenWrapperTransitionStatus from '@hooks/useScreenWrapperTransitionStatus'; import useThemeStyles from '@hooks/useThemeStyles'; -import {setMoneyRequestAmount} from '@libs/actions/IOU'; +import {clearMoneyRequestAmount, setMoneyRequestAmount} from '@libs/actions/IOU'; import {convertToBackendAmount, convertToFrontendAmountAsString, getLocalizedCurrencySymbol} from '@libs/CurrencyUtils'; import {calculateAmount} from '@libs/IOUUtils'; import Navigation from '@libs/Navigation/Navigation'; import {shouldEnableNegative} from '@libs/ReportUtils'; import {isAmountMissing} from '@libs/TransactionUtils'; +import {isParticipantP2P} from '@pages/iou/request/step/IOURequestStepAmount'; import IOURequestStepCurrencyModal from '@pages/iou/request/step/IOURequestStepCurrencyModal'; -import {resetSplitShares, setDraftSplitTransaction} from '@userActions/IOU/Split'; +import {getMoneyRequestParticipantsFromReport} from '@userActions/IOU'; +import {resetSplitShares, setDraftSplitTransaction, setSplitShares} from '@userActions/IOU/Split'; import CONST from '@src/CONST'; import type {IOUAction, IOUType} from '@src/CONST'; +import type {TranslationPaths} from '@src/languages/types'; import ONYXKEYS from '@src/ONYXKEYS'; import ROUTES from '@src/ROUTES'; import type * as OnyxTypes from '@src/types/onyx'; @@ -41,6 +47,9 @@ type AmountFieldProps = { reportActionID: string | undefined; isEditingSplitBill: boolean; policy: OnyxEntry; + clearFormErrors: (errors: string[]) => void; + setFormError: (error: TranslationPaths | '') => void; + autoFocus?: boolean; }; function AmountField({ @@ -63,6 +72,9 @@ function AmountField({ reportActionID, isEditingSplitBill, policy, + clearFormErrors, + setFormError, + autoFocus = false, }: AmountFieldProps) { const styles = useThemeStyles(); const {translate, preferredLocale} = useLocalize(); @@ -70,17 +82,46 @@ function AmountField({ const [report] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`); const [splitDraftTransaction] = useOnyx(`${ONYXKEYS.COLLECTION.SPLIT_TRANSACTION_DRAFT}${transactionID}`); const [currentUserAccountID] = useOnyx(ONYXKEYS.SESSION, {selector: (session) => session?.accountID}); + const currentUserPersonalDetails = useCurrentUserPersonalDetails(); + const amountInputRef = useRef(null); + const {didScreenTransitionEnd} = useScreenWrapperTransitionStatus(); const [isCurrencyPickerVisible, setIsCurrencyPickerVisible] = useState(false); const isAmountFieldDisabled = didConfirm || isReadOnly || shouldShowTimeRequestFields || isDistanceRequest; - const shouldShowAmountRequiredError = formError === 'common.error.invalidAmount'; + const firstParticipant = transaction?.participants?.at(0); + const isP2P = isNewManualExpenseFlowEnabled + ? isParticipantP2P(getMoneyRequestParticipantsFromReport(report, currentUserPersonalDetails.accountID).at(0)) + : !!(firstParticipant?.accountID && !firstParticipant?.isPolicyExpenseChat); + const shouldShowAmountRequiredError = formError === 'common.error.fieldRequired'; + const shouldShowAmountInvalidError = formError === 'common.error.invalidAmount'; + + let amountFieldErrorText = ''; + if (shouldShowAmountInvalidError) { + amountFieldErrorText = translate('common.error.invalidAmount'); + } else if (shouldShowAmountRequiredError) { + amountFieldErrorText = translate('common.error.fieldRequired'); + } const effectiveCurrency = isDistanceRequest ? distanceRateCurrency : (iouCurrencyCode ?? CONST.CURRENCY.USD); const decimals = getCurrencyDecimals(effectiveCurrency); - const transactionAmount = convertToFrontendAmountAsString(amount, decimals); + // In the new manual expense flow the amount field starts empty (transaction.amount defaults to 0 before the user + // touches it). Once the user explicitly sets an amount – including 0 – isAmountSet becomes true and we show the + // real value. This avoids showing "$0.00" as a pre-filled default. + const transactionAmount = isNewManualExpenseFlowEnabled && !transaction?.isAmountSet ? '' : convertToFrontendAmountAsString(amount, decimals); const allowNegative = shouldEnableNegative(report, policy, iouType, transaction?.participants); + // `autoFocus` on our TextInput only runs on mount. Closing and reopening the RHP often keeps the same mounted + // instance, so autofocus does not run again. After `ScreenWrapper` finishes its entry transition the field is + // reliably focusable. + useEffect(() => { + if (!didScreenTransitionEnd || !autoFocus || isAmountFieldDisabled || !isNewManualExpenseFlowEnabled) { + return; + } + + amountInputRef.current?.focus(); + }, [didScreenTransitionEnd, autoFocus, isAmountFieldDisabled, isNewManualExpenseFlowEnabled]); + const showCurrencyPicker = () => { setIsCurrencyPickerVisible(true); }; @@ -106,38 +147,68 @@ function AmountField({ return isNegative ? -absoluteBackendAmount : absoluteBackendAmount; }; + /** + * When the bill total or currency changes: + * - Editing an existing split bill: recompute shares on the split draft (`SPLIT_TRANSACTION_DRAFT`). + * - Creating a split (`iouType` split): `setSplitShares` on the transaction draft (or seed from `participants` if shares are missing). + * - Any other draft that already has `splitShares`: `resetSplitShares` so shares stay proportional to the new total. + */ const buildAndSaveSplitShares = (updatedAmount: number, updatedCurrency: string) => { - if (!transactionID) { - return; - } + if (isEditingSplitBill) { + if (!transactionID) { + return; + } + const splitShares = splitDraftTransaction?.splitShares ?? transaction?.splitShares; + const accountID = currentUserAccountID ?? CONST.DEFAULT_NUMBER_ID; + const newAccountIDs = Object.keys(splitShares ?? {}).map((key) => Number(key)); + const oldAccountIDs = Object.keys(transaction?.splitShares ?? {}).map((key) => Number(key)); + const accountIDs = [...new Set([accountID, ...newAccountIDs, ...oldAccountIDs])]; - const splitShares = splitDraftTransaction?.splitShares ?? transaction?.splitShares; - const accountID = currentUserAccountID ?? CONST.DEFAULT_NUMBER_ID; - const newAccountIDs = Object.keys(splitShares ?? {}).map((key) => Number(key)); - const oldAccountIDs = Object.keys(transaction?.splitShares ?? {}).map((key) => Number(key)); - const accountIDs = [...new Set([accountID, ...newAccountIDs, ...oldAccountIDs])]; + const participantsLength = newAccountIDs.includes(accountID) ? newAccountIDs.length - 1 : newAccountIDs.length; - const participantsLength = newAccountIDs.includes(accountID) ? newAccountIDs.length - 1 : newAccountIDs.length; + const updatedSplitShares = accountIDs.reduce>((acc, splitShareAccountID) => { + if (!newAccountIDs.includes(splitShareAccountID) && splitShareAccountID !== accountID) { + acc[splitShareAccountID] = null; + return acc; + } - const updatedSplitShares = accountIDs.reduce>((acc, splitShareAccountID) => { - if (!newAccountIDs.includes(splitShareAccountID) && splitShareAccountID !== accountID) { - acc[splitShareAccountID] = null; + const isPayer = splitShareAccountID === accountID; + acc[splitShareAccountID] = { + amount: calculateAmount(participantsLength, updatedAmount, updatedCurrency, isPayer), + isModified: false, + }; return acc; + }, {}); + + setDraftSplitTransaction(transactionID, splitDraftTransaction, { + amount: updatedAmount, + currency: updatedCurrency, + ...(accountIDs.length > 0 ? {splitShares: updatedSplitShares} : {}), + }); + return; + } + + if (iouType === CONST.IOU.TYPE.SPLIT && transaction) { + const shareAccountIDs = Object.keys(transaction.splitShares ?? {}).map(Number); + const participantAccountIDs = + shareAccountIDs.length > 0 ? shareAccountIDs : (transaction.participants ?? []).map((p) => p.accountID).filter((id): id is number => id !== undefined); + if (participantAccountIDs.length > 0) { + setSplitShares(transaction, updatedAmount, updatedCurrency, participantAccountIDs); } + return; + } - const isPayer = splitShareAccountID === accountID; - acc[splitShareAccountID] = { - amount: calculateAmount(participantsLength, updatedAmount, updatedCurrency, isPayer), - isModified: false, - }; - return acc; - }, {}); - - setDraftSplitTransaction(transactionID, splitDraftTransaction, { - amount: updatedAmount, - currency: updatedCurrency, - ...(accountIDs.length > 0 ? {splitShares: updatedSplitShares} : {}), - }); + if (transaction?.splitShares) { + resetSplitShares(transaction, updatedAmount, updatedCurrency); + } + }; + + /** Writes `amount` / `currency` to the main transaction draft unless we only touched the split-bill draft above. */ + const persistMainDraftTotal = (backendAmount: number, currency: string) => { + if (isEditingSplitBill || !transactionID) { + return; + } + setMoneyRequestAmount(transactionID, backendAmount, currency); }; const updateCurrency = (value: string) => { @@ -150,12 +221,8 @@ function AmountField({ const parsedAmount = getBackendAmountFromInput(transactionAmount); const updatedAmount = parsedAmount ?? amount; - if (isEditingSplitBill) { - buildAndSaveSplitShares(updatedAmount, value); - return; - } - - setMoneyRequestAmount(transactionID, updatedAmount, value); + buildAndSaveSplitShares(updatedAmount, value); + persistMainDraftTotal(updatedAmount, value); }; const handleAmountChange = (newAmount: string) => { @@ -165,19 +232,22 @@ function AmountField({ const parsedAmount = getBackendAmountFromInput(newAmount); if (parsedAmount === null) { + // User cleared the field — mark amount as unset so the field stays empty + // and submission is blocked until a value is re-entered. + clearMoneyRequestAmount(transactionID); return; } - // Edits to the amount from the splits page should reset the split shares. - if (transaction?.splitShares) { - resetSplitShares(transaction, parsedAmount); - } - if (isEditingSplitBill) { - buildAndSaveSplitShares(parsedAmount, effectiveCurrency); - return; + const isInlineAmountInvalid = parsedAmount === 0 && isP2P; + + if (isInlineAmountInvalid && shouldDisplayFieldError) { + setFormError('common.error.invalidAmount'); + } else if (!isInlineAmountInvalid) { + clearFormErrors(['common.error.invalidAmount', 'common.error.fieldRequired']); } - setMoneyRequestAmount(transactionID, parsedAmount, effectiveCurrency); + buildAndSaveSplitShares(parsedAmount, effectiveCurrency); + persistMainDraftTotal(parsedAmount, effectiveCurrency); }; return ( @@ -192,13 +262,15 @@ function AmountField({ {isNewManualExpenseFlowEnabled && !isAmountFieldDisabled ? ( ; transaction: OnyxEntry; isEditingSplitBill: boolean; + onSubmitForm?: () => void; }; function DescriptionField({ @@ -48,6 +49,7 @@ function DescriptionField({ policy, transaction, isEditingSplitBill, + onSubmitForm, }: DescriptionFieldProps) { const styles = useThemeStyles(); const {translate} = useLocalize(); @@ -102,6 +104,8 @@ function DescriptionField({ value={iouComment ?? ''} readOnly={didConfirm} onChangeText={handleDescriptionInputChange} + submitBehavior="blurAndSubmit" + onSubmitEditing={onSubmitForm} label={translate('common.description')} accessibilityLabel={translate('common.description')} autoGrowHeight diff --git a/src/components/MoneyRequestConfirmationList/sections/MerchantField.tsx b/src/components/MoneyRequestConfirmationList/sections/MerchantField.tsx index 633d5ef8f7fe..928bf9bb3b73 100644 --- a/src/components/MoneyRequestConfirmationList/sections/MerchantField.tsx +++ b/src/components/MoneyRequestConfirmationList/sections/MerchantField.tsx @@ -6,9 +6,9 @@ import TextInput from '@components/TextInput'; import useLocalize from '@hooks/useLocalize'; import useOnyx from '@hooks/useOnyx'; import useThemeStyles from '@hooks/useThemeStyles'; -import {setMoneyRequestMerchant} from '@libs/actions/IOU'; +import {clearMoneyRequestMerchant, setMoneyRequestMerchant} from '@libs/actions/IOU'; import Navigation from '@libs/Navigation/Navigation'; -import {getMerchant, hasReceipt, isMerchantMissing} from '@libs/TransactionUtils'; +import {getMerchant, hasReceipt} from '@libs/TransactionUtils'; import {isValidInputLength} from '@libs/ValidationUtils'; import {setDraftSplitTransaction} from '@userActions/IOU/Split'; import CONST from '@src/CONST'; @@ -53,19 +53,23 @@ function MerchantField({ const [splitDraftTransaction] = useOnyx(`${ONYXKEYS.COLLECTION.SPLIT_TRANSACTION_DRAFT}${transactionID}`); - const iouMerchant = getMerchant(transaction); - const isMerchantEmpty = !iouMerchant || isMerchantMissing(transaction); + const merchantValue = getMerchant(transaction); + const displayMerchantValue = !transaction?.isMerchantSet ? '' : merchantValue; + const isMerchantEmpty = !displayMerchantValue; // Determine if the merchant error should be displayed const merchantErrorText = (() => { - const merchantValue = iouMerchant ?? ''; const {isValid, byteLength} = isValidInputLength(merchantValue, CONST.MERCHANT_NAME_MAX_BYTES); if (!isValid) { return translate('common.error.characterLimitExceedCounter', byteLength, CONST.MERCHANT_NAME_MAX_BYTES); } - if ((shouldDisplayFieldError || formError === 'iou.error.invalidMerchant') && isMerchantRequired && isMerchantEmpty) { + if (formError === 'iou.error.invalidMerchant') { + return translate('iou.error.invalidMerchant'); + } + + if (shouldDisplayFieldError && isMerchantRequired && isMerchantEmpty) { return translate('common.error.fieldRequired'); } @@ -82,10 +86,19 @@ function MerchantField({ // When editing a split expense, persist directly to the split draft so that // SplitBillDetailsPage and completeSplitBill read the latest value. if (isEditingSplitBill) { + if (newMerchant.trim() === '') { + setDraftSplitTransaction(transactionID, splitDraftTransaction, {merchant: '', isMerchantSet: false}); + return; + } setDraftSplitTransaction(transactionID, splitDraftTransaction, {merchant: newMerchant}); return; } + if (newMerchant.trim() === '') { + clearMoneyRequestMerchant(transactionID); + return; + } + setMoneyRequestMerchant(transactionID, newMerchant, true, hasReceipt(transaction)); }; @@ -93,7 +106,7 @@ function MerchantField({ return ( void; + + /** Sets a form error message */ + setFormError: (error: TranslationPaths | '') => void; + /** Flag indicating if there is a route */ hasRoute: boolean; @@ -179,6 +186,9 @@ type MoneyRequestConfirmationListFooterProps = { /** Toggles compact mode by showing all fields */ setShowMoreFields?: (showMoreFields: boolean) => void; + + /** Triggers submit from inline inputs */ + onSubmitForm?: () => void; }; function MoneyRequestConfirmationListFooter({ @@ -190,6 +200,8 @@ function MoneyRequestConfirmationListFooter({ formattedAmount, formattedAmountPerAttendee, formError, + clearFormErrors, + setFormError, hasRoute, iouType, isCategoryRequired, @@ -233,6 +245,7 @@ function MoneyRequestConfirmationListFooter({ isDescriptionRequired = false, showMoreFields = false, setShowMoreFields = () => {}, + onSubmitForm, }: MoneyRequestConfirmationListFooterProps) { const styles = useThemeStyles(); const {windowWidth} = useWindowDimensions(); @@ -396,6 +409,8 @@ function MoneyRequestConfirmationListFooter({ isPerDiemRequest={isPerDiemRequest} shouldDisplayFieldError={shouldDisplayFieldError} formError={formError} + clearFormErrors={clearFormErrors} + setFormError={setFormError} iouCurrencyCode={flags.iouCurrencyCode} amount={amount} formattedAmount={formattedAmount} @@ -410,6 +425,7 @@ function MoneyRequestConfirmationListFooter({ onToggleBillable={onToggleBillable} setShowMoreFields={setShowMoreFields} isCompactMode={compact.isCompactMode} + onSubmitForm={onSubmitForm} /> ); diff --git a/src/components/MoneyRequestConfirmationListFooter/ConfirmationFieldList.tsx b/src/components/MoneyRequestConfirmationListFooter/ConfirmationFieldList.tsx index 804b9abdbfb0..3b97f7442ca8 100644 --- a/src/components/MoneyRequestConfirmationListFooter/ConfirmationFieldList.tsx +++ b/src/components/MoneyRequestConfirmationListFooter/ConfirmationFieldList.tsx @@ -12,6 +12,7 @@ import useThemeStyles from '@hooks/useThemeStyles'; import variables from '@styles/variables'; import type CONST from '@src/CONST'; import type {IOUAction, IOUType} from '@src/CONST'; +import type {TranslationPaths} from '@src/languages/types'; import type * as OnyxTypes from '@src/types/onyx'; import type {Participant} from '@src/types/onyx/IOU'; import type {Unit} from '@src/types/onyx/Policy'; @@ -148,6 +149,12 @@ type ConfirmationFieldListProps = { /** Form-level error message */ formError: string; + /** Clears specific form errors by key */ + clearFormErrors: (errors: string[]) => void; + + /** Sets a form error message */ + setFormError: (error: TranslationPaths | '') => void; + /** ISO currency code for the transaction */ iouCurrencyCode: string; @@ -189,6 +196,9 @@ type ConfirmationFieldListProps = { /** Whether the receipt area is using compact mode (drives the show-more split) */ isCompactMode: boolean; + + /** Triggers submit from inline inputs */ + onSubmitForm?: () => void; }; function ConfirmationFieldList({ @@ -232,6 +242,8 @@ function ConfirmationFieldList({ isPerDiemRequest, shouldDisplayFieldError, formError, + clearFormErrors, + setFormError, iouCurrencyCode, amount, formattedAmount, @@ -246,6 +258,7 @@ function ConfirmationFieldList({ onToggleBillable, setShowMoreFields, isCompactMode, + onSubmitForm, }: ConfirmationFieldListProps) { const styles = useThemeStyles(); const theme = useTheme(); @@ -305,6 +318,8 @@ function ConfirmationFieldList({ isDescriptionRequired={isDescriptionRequired} shouldDisplayFieldError={shouldDisplayFieldError} formError={formError} + clearFormErrors={clearFormErrors} + setFormError={setFormError} shouldNavigateToUpgradePath={shouldNavigateToUpgradePath} shouldSelectPolicy={shouldSelectPolicy} iouCurrencyCode={iouCurrencyCode} @@ -318,6 +333,7 @@ function ConfirmationFieldList({ distanceRateCurrency={distanceRateCurrency} isCompactMode={isCompactMode} fieldVisibility={fieldVisibility} + onSubmitForm={onSubmitForm} /> void; + + /** Sets a form error message */ + setFormError: (error: TranslationPaths | '') => void; + /** Whether navigating to upgrade is required to proceed past blocked workspaces */ shouldNavigateToUpgradePath: boolean; @@ -108,6 +116,9 @@ type TransactionDetailsFieldsProps = { /** When true, suppresses the below-show-more entries (Amount, Rate, Merchant, Time) */ isCompactMode: boolean; + + /** Triggers submit from inline inputs */ + onSubmitForm?: () => void; }; function TransactionDetailsFields({ @@ -130,6 +141,8 @@ function TransactionDetailsFields({ isDescriptionRequired, shouldDisplayFieldError, formError, + clearFormErrors, + setFormError, shouldNavigateToUpgradePath, shouldSelectPolicy, iouCurrencyCode, @@ -143,7 +156,10 @@ function TransactionDetailsFields({ distanceRateCurrency, isCompactMode, fieldVisibility, + onSubmitForm, }: TransactionDetailsFieldsProps) { + const shouldAutoFocusAmountField = !canUseTouchScreen(); + return ( <> {!isCompactMode && fieldVisibility.amount && ( @@ -167,6 +183,27 @@ function TransactionDetailsFields({ reportActionID={reportActionID} isEditingSplitBill={isEditingSplitBill} policy={policy} + clearFormErrors={clearFormErrors} + setFormError={setFormError} + autoFocus={shouldAutoFocusAmountField} + /> + )} + + {!isCompactMode && fieldVisibility.merchant && ( + )} @@ -183,6 +220,7 @@ function TransactionDetailsFields({ policy={policy} transaction={transaction} isEditingSplitBill={isEditingSplitBill} + onSubmitForm={onSubmitForm} /> {fieldVisibility.distance && ( @@ -225,24 +263,6 @@ function TransactionDetailsFields({ /> )} - {!isCompactMode && fieldVisibility.merchant && ( - - )} - {!isCompactMode && fieldVisibility.time && ( void; + + /** Callback fired when participant selection is completed */ + onFinish?: (value?: string, participants?: Participant[]) => void; + + /** Whether the picker modal is visible */ + isVisible?: boolean; + + /** Callback fired when picker should close */ + onClose?: () => void; +}; + +function ParticipantPicker({ + participants = CONST.EMPTY_ARRAY, + iouType, + action, + isPerDiemRequest = false, + isTimeRequest = false, + onParticipantsAdded, + onFinish, + isVisible = true, + onClose, +}: ParticipantPickerProps) { + const {translate} = useLocalize(); + + const pickerContent = ( + + ); + + if (!onClose) { + return pickerContent; + } + + return ( + + + + {pickerContent} + + + ); +} + +export default ParticipantPicker; diff --git a/src/libs/DebugUtils.ts b/src/libs/DebugUtils.ts index f4ad651a7d29..2640250c9aae 100644 --- a/src/libs/DebugUtils.ts +++ b/src/libs/DebugUtils.ts @@ -1091,6 +1091,7 @@ function validateTransactionDraftProperty(key: keyof Transaction, value: string) modifiedMerchant: CONST.RED_BRICK_ROAD_PENDING_ACTION, modifiedWaypoints: CONST.RED_BRICK_ROAD_PENDING_ACTION, participantsAutoAssigned: CONST.RED_BRICK_ROAD_PENDING_ACTION, + isMerchantSet: CONST.RED_BRICK_ROAD_PENDING_ACTION, participants: CONST.RED_BRICK_ROAD_PENDING_ACTION, receipt: CONST.RED_BRICK_ROAD_PENDING_ACTION, reportID: CONST.RED_BRICK_ROAD_PENDING_ACTION, @@ -1140,6 +1141,7 @@ function validateTransactionDraftProperty(key: keyof Transaction, value: string) splitsStartDate: CONST.RED_BRICK_ROAD_PENDING_ACTION, splitsEndDate: CONST.RED_BRICK_ROAD_PENDING_ACTION, withdrawalID: CONST.RED_BRICK_ROAD_PENDING_ACTION, + isAmountSet: CONST.RED_BRICK_ROAD_PENDING_ACTION, }, 'string', ); @@ -1304,6 +1306,9 @@ function validateTransactionDraftProperty(key: keyof Transaction, value: string) originalMessage: 'object', previousMessage: 'object', }); + case 'isAmountSet': + case 'isMerchantSet': + return validateBoolean(value); } } diff --git a/src/libs/IOUUtils.ts b/src/libs/IOUUtils.ts index 6eeb71e21d61..97b23f6392f4 100644 --- a/src/libs/IOUUtils.ts +++ b/src/libs/IOUUtils.ts @@ -315,7 +315,7 @@ function shouldShowReceiptEmptyState(iouType: IOUType, action: IOUAction, policy // - Hide for per diem requests // - Hide when submitting a track expense to a non-paid group policy (personal users) return ( - (iouType === CONST.IOU.TYPE.SUBMIT || iouType === CONST.IOU.TYPE.TRACK || iouType === CONST.IOU.TYPE.PAY) && + (iouType === CONST.IOU.TYPE.SUBMIT || iouType === CONST.IOU.TYPE.TRACK || iouType === CONST.IOU.TYPE.PAY || iouType === CONST.IOU.TYPE.CREATE) && !isPerDiemRequest && (!isMovingTransactionFromTrackExpense(action) || isPaidGroupPolicy(policy)) ); diff --git a/src/libs/actions/IOU/index.ts b/src/libs/actions/IOU/index.ts index 43d70d59b48c..63eae9e5f28a 100644 --- a/src/libs/actions/IOU/index.ts +++ b/src/libs/actions/IOU/index.ts @@ -292,10 +292,25 @@ function setMoneyRequestReceiptState(transactionID: string, isDraft: boolean, sh } function setMoneyRequestAmount(transactionID: string, amount: number, currency: string, shouldShowOriginalAmount = false, shouldStopSmartscan = false) { - Onyx.merge(`${ONYXKEYS.COLLECTION.TRANSACTION_DRAFT}${transactionID}`, {amount, currency, shouldShowOriginalAmount}); + // Mark that the user has explicitly set the amount. This is used by the new manual expense flow to distinguish + // a default amount of 0 (field empty) from a user-entered 0 (valid $0 expense). + Onyx.merge(`${ONYXKEYS.COLLECTION.TRANSACTION_DRAFT}${transactionID}`, {amount, currency, shouldShowOriginalAmount, isAmountSet: true}); setMoneyRequestReceiptState(transactionID, true, shouldStopSmartscan); } +/** + * Clears the amount field back to an empty/unset state in the new manual expense flow. + * Called when the user deletes all characters from the amount input so that the field + * shows as empty and submission is blocked until a value is entered again. + */ +function clearMoneyRequestAmount(transactionID: string) { + Onyx.merge(`${ONYXKEYS.COLLECTION.TRANSACTION_DRAFT}${transactionID}`, {amount: 0, isAmountSet: false}); +} + +function clearMoneyRequestMerchant(transactionID: string, isDraft = true) { + Onyx.merge(`${isDraft ? ONYXKEYS.COLLECTION.TRANSACTION_DRAFT : ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`, {merchant: '', isMerchantSet: false}); +} + function setMoneyRequestCreated(transactionID: string, created: string, isDraft: boolean, shouldStopSmartscan = false) { Onyx.merge(`${isDraft ? ONYXKEYS.COLLECTION.TRANSACTION_DRAFT : ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`, {created}); setMoneyRequestReceiptState(transactionID, isDraft, shouldStopSmartscan); @@ -311,15 +326,16 @@ function setMoneyRequestCurrency(transactionID: string, currency: string, isEdit } function setMoneyRequestDescription(transactionID: string, comment: string, isDraft: boolean, shouldStopSmartscan = false) { - Onyx.merge(`${isDraft ? ONYXKEYS.COLLECTION.TRANSACTION_DRAFT : ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`, {comment: {comment: comment.trim()}}); + // Trim only when persisting to the real transaction (not a draft) to avoid + // stripping trailing spaces/newlines while the user is still typing. + Onyx.merge(`${isDraft ? ONYXKEYS.COLLECTION.TRANSACTION_DRAFT : ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`, {comment: {comment: isDraft ? comment : comment.trim()}}); setMoneyRequestReceiptState(transactionID, isDraft, shouldStopSmartscan); } function setMoneyRequestMerchant(transactionID: string, merchant: string, isDraft: boolean, shouldStopSmartscan = false) { - Onyx.merge(`${isDraft ? ONYXKEYS.COLLECTION.TRANSACTION_DRAFT : ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`, {merchant}); + Onyx.merge(`${isDraft ? ONYXKEYS.COLLECTION.TRANSACTION_DRAFT : ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`, {merchant, isMerchantSet: true}); setMoneyRequestReceiptState(transactionID, isDraft, shouldStopSmartscan); } - function setMoneyRequestAttendees(transactionID: string, attendees: Attendee[], isDraft: boolean) { Onyx.merge(`${isDraft ? ONYXKEYS.COLLECTION.TRANSACTION_DRAFT : ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`, {comment: {attendees}}); } @@ -615,6 +631,8 @@ export { setGPSTransactionDraftData, setCustomUnitID, setMoneyRequestAmount, + clearMoneyRequestAmount, + clearMoneyRequestMerchant, setMoneyRequestAttendees, setMoneyRequestAccountant, setMoneyRequestBillable, diff --git a/src/pages/iou/request/IOURequestStartPage.tsx b/src/pages/iou/request/IOURequestStartPage.tsx index 648dfa317239..3fa23516fd86 100644 --- a/src/pages/iou/request/IOURequestStartPage.tsx +++ b/src/pages/iou/request/IOURequestStartPage.tsx @@ -1,4 +1,3 @@ -import {iouRequestPolicyCollectionSelector} from '@selectors/Policy'; import React, {useEffect, useMemo, useRef, useState} from 'react'; import {View} from 'react-native'; import DragAndDropProvider from '@components/DragAndDrop/Provider'; @@ -11,6 +10,7 @@ import useAndroidBackButtonHandler from '@hooks/useAndroidBackButtonHandler'; import useCurrentUserPersonalDetails from '@hooks/useCurrentUserPersonalDetails'; import useLocalize from '@hooks/useLocalize'; import useOnyx from '@hooks/useOnyx'; +import usePermissions from '@hooks/usePermissions'; import usePolicy from '@hooks/usePolicy'; import useResetIOUType from '@hooks/useResetIOUType'; import useThemeStyles from '@hooks/useThemeStyles'; @@ -31,10 +31,12 @@ import AccessOrNotFoundWrapper from '@pages/workspace/AccessOrNotFoundWrapper'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import type SCREENS from '@src/SCREENS'; +import {iouRequestPolicyCollectionSelector} from '@src/selectors/Policy'; import type {SelectedTabRequest} from '@src/types/onyx'; import {isEmptyObject} from '@src/types/utils/EmptyObject'; import isLoadingOnyxValue from '@src/types/utils/isLoadingOnyxValue'; import {IOURequestStepAmountWithTransactionOnly} from './step/IOURequestStepAmount'; +import IOURequestStepConfirmation from './step/IOURequestStepConfirmation'; import IOURequestStepDestination from './step/IOURequestStepDestination'; import IOURequestStepDistance from './step/IOURequestStepDistance'; import IOURequestStepHours from './step/IOURequestStepHours'; @@ -77,7 +79,6 @@ function IOURequestStartPage({ }); const perDiemInputRef = useRef(null); - const tabTitles = { [CONST.IOU.TYPE.REQUEST]: translate('iou.createExpense'), [CONST.IOU.TYPE.SUBMIT]: translate('iou.createExpense'), @@ -193,6 +194,9 @@ function IOURequestStartPage({ return [headerWithBackBtnContainerElement, tabBarContainerElement, activeTabContainerElement].filter((element) => !!element); }, [headerWithBackBtnContainerElement, tabBarContainerElement, activeTabContainerElement]); + const {isBetaEnabled} = usePermissions(); + const isNewManualExpenseFlowEnabled = isBetaEnabled(CONST.BETAS.NEW_MANUAL_EXPENSE_FLOW); + const onBackButtonPress = () => { navigateBack(); return true; @@ -211,13 +215,14 @@ function IOURequestStartPage({ allPolicies={iouType === CONST.IOU.TYPE.INVOICE ? allPolicies : undefined} > - + {/* If the new manual expense flow is enabled, the confirmation screen is shown on the start page, so we do not want to disable the drag and drop provider in that case */} + {() => ( - + {isNewManualExpenseFlowEnabled ? ( + + ) : ( + + )} )} diff --git a/src/pages/iou/request/ParticipantSearchResults.tsx b/src/pages/iou/request/ParticipantSearchResults.tsx index 119097dd08c9..499b4079185f 100644 --- a/src/pages/iou/request/ParticipantSearchResults.tsx +++ b/src/pages/iou/request/ParticipantSearchResults.tsx @@ -119,6 +119,7 @@ function ParticipantSearchResults({ initiallySelectedReportID, shouldMoveSelectedToTop = false, }: ParticipantSearchResultsProps) { + const getParticipantOptionKey = (option: Partial) => option.reportID ?? option.accountID?.toString() ?? option.login ?? option.phoneNumber ?? ''; const isIOUSplit = iouType === CONST.IOU.TYPE.SPLIT; const isCategorizeOrShareAction = action === CONST.IOU.ACTION.CATEGORIZE || action === CONST.IOU.ACTION.SHARE; const isAllowedToSplit = @@ -275,6 +276,7 @@ function ParticipantSearchResults({ const sections: Array> = []; let header = ''; if (areOptionsInitialized && didScreenTransitionEnd) { + const selectedParticipantKeys = new Set(participants.map((participant) => getParticipantOptionKey(participant)).filter(Boolean)); const formatResults = formatSectionsFromSearchTerm( searchTerm, participants.map((participant) => ({...participant, reportID: participant.reportID})) as OptionData[], @@ -293,7 +295,7 @@ function ParticipantSearchResults({ if ((availableOptions.workspaceChats ?? []).length > 0) { sections.push({ title: translate('workspace.common.workspace'), - data: availableOptions.workspaceChats ?? [], + data: (availableOptions.workspaceChats ?? []).filter((option) => !selectedParticipantKeys.has(getParticipantOptionKey(option))), sectionIndex: 1, }); } @@ -312,7 +314,7 @@ function ParticipantSearchResults({ if (recentReports.length > 0) { sections.push({ title: translate('common.recents'), - data: recentReports, + data: recentReports.filter((option) => !selectedParticipantKeys.has(getParticipantOptionKey(option))), sectionIndex: 3, }); } @@ -320,7 +322,7 @@ function ParticipantSearchResults({ if (availableOptions.personalDetails.length > 0 && !isPerDiemRequest && !isTimeRequest) { sections.push({ title: translate('common.contacts'), - data: availableOptions.personalDetails, + data: availableOptions.personalDetails.filter((option) => !selectedParticipantKeys.has(getParticipantOptionKey(option))), sectionIndex: 4, }); } diff --git a/src/pages/iou/request/step/IOURequestStepConfirmation.tsx b/src/pages/iou/request/step/IOURequestStepConfirmation.tsx index 999132f92873..85bf2a940419 100644 --- a/src/pages/iou/request/step/IOURequestStepConfirmation.tsx +++ b/src/pages/iou/request/step/IOURequestStepConfirmation.tsx @@ -1,4 +1,5 @@ import {validTransactionDraftIDsSelector} from '@selectors/TransactionDraft'; +import type {ComponentProps} from 'react'; import React, {useCallback, useEffect, useMemo, useRef, useState} from 'react'; import {View} from 'react-native'; import DragAndDropConsumer from '@components/DragAndDrop/Consumer'; @@ -10,10 +11,12 @@ import HeaderWithBackButton from '@components/HeaderWithBackButton'; import {ModalActions} from '@components/Modal/Global/ModalContext'; import MoneyRequestConfirmationList from '@components/MoneyRequestConfirmationList'; import {usePersonalDetails, usePolicyCategories} from '@components/OnyxListItemProvider'; +import ParticipantPicker from '@components/ParticipantPicker'; import PrevNextButtons from '@components/PrevNextButtons'; import ScreenWrapper from '@components/ScreenWrapper'; import useConfirmModal from '@hooks/useConfirmModal'; import useCurrentUserPersonalDetails from '@hooks/useCurrentUserPersonalDetails'; +import useDefaultExpensePolicy from '@hooks/useDefaultExpensePolicy'; import useFetchRoute from '@hooks/useFetchRoute'; import useFilesValidation from '@hooks/useFilesValidation'; import {useMemoizedLazyExpensifyIcons} from '@hooks/useLazyAsset'; @@ -21,11 +24,14 @@ import useLocalize from '@hooks/useLocalize'; import useNetwork from '@hooks/useNetwork'; import useOnyx from '@hooks/useOnyx'; import useOptimisticDraftTransactions from '@hooks/useOptimisticDraftTransactions'; +import usePermissions from '@hooks/usePermissions'; +import usePersonalPolicy from '@hooks/usePersonalPolicy'; import usePolicyForTransaction from '@hooks/usePolicyForTransaction'; import usePrivateIsArchivedMap from '@hooks/usePrivateIsArchivedMap'; import useReportAttributes from '@hooks/useReportAttributes'; import useReportOrReportDraft from '@hooks/useReportOrReportDraft'; import useRestartOnOdometerImagesFailure from '@hooks/useRestartOnOdometerImagesFailure'; +import useSelfDMReport from '@hooks/useSelfDMReport'; import useTheme from '@hooks/useTheme'; import useThemeStyles from '@hooks/useThemeStyles'; import {isMobileSafari} from '@libs/Browser'; @@ -43,9 +49,11 @@ import isReportOpenInRHP from '@libs/Navigation/helpers/isReportOpenInRHP'; import isReportTopmostSplitNavigator from '@libs/Navigation/helpers/isReportTopmostSplitNavigator'; import isSearchTopmostFullScreenRoute from '@libs/Navigation/helpers/isSearchTopmostFullScreenRoute'; import Navigation, {navigationRef} from '@libs/Navigation/Navigation'; +import type {MoneyRequestNavigatorParamList} from '@libs/Navigation/types'; import {getParticipantsOption, getReportOption} from '@libs/OptionsListUtils'; -import {getReportOrDraftReport, isMoneyRequestReport, isSelectedManagerMcTest} from '@libs/ReportUtils'; +import {getPolicyExpenseChat, getReportOrDraftReport, isMoneyRequestReport, isPolicyExpenseChat as isPolicyExpenseChatUtils, isSelectedManagerMcTest} from '@libs/ReportUtils'; import {buildCannedSearchQuery, getCurrentSearchQueryJSON} from '@libs/SearchQueryUtils'; +import shouldUseDefaultExpensePolicy from '@libs/shouldUseDefaultExpensePolicy'; import type {SkeletonSpanReasonAttributes} from '@libs/telemetry/useSkeletonSpan'; import { getRequestType, @@ -55,14 +63,23 @@ import { isOdometerDistanceRequest as isOdometerDistanceRequestTransactionUtils, isScanRequest, } from '@libs/TransactionUtils'; -import {getIOURequestPolicyID, setMoneyRequestBillable, setMoneyRequestParticipantsFromReport, setMoneyRequestReimbursable} from '@userActions/IOU'; +import { + getIOURequestPolicyID, + getMoneyRequestParticipantsFromReport, + setMoneyRequestBillable, + setMoneyRequestParticipants, + setMoneyRequestParticipantsFromReport, + setMoneyRequestReimbursable, +} from '@userActions/IOU'; import {setMoneyRequestReceipt} from '@userActions/IOU/Receipt'; import {removeDraftTransaction, replaceDefaultDraftTransaction} from '@userActions/TransactionEdit'; import CONST from '@src/CONST'; +import type {IOUType} from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import type {Route} from '@src/ROUTES'; import ROUTES from '@src/ROUTES'; -import type SCREENS from '@src/SCREENS'; +import SCREENS from '@src/SCREENS'; +import type {Participant} from '@src/types/onyx/IOU'; import type {Receipt} from '@src/types/onyx/Transaction'; import type {FileObject} from '@src/types/utils/Attachment'; import isLoadingOnyxValue from '@src/types/utils/isLoadingOnyxValue'; @@ -80,19 +97,31 @@ import withFullTransactionOrNotFound from './withFullTransactionOrNotFound'; import type {WithWritableReportOrNotFoundProps} from './withWritableReportOrNotFound'; import withWritableReportOrNotFound from './withWritableReportOrNotFound'; -type IOURequestStepConfirmationProps = WithWritableReportOrNotFoundProps & - WithFullTransactionOrNotFoundProps; +type IOURequestStepConfirmationIncomingRouteName = typeof SCREENS.MONEY_REQUEST.STEP_CONFIRMATION | typeof SCREENS.MONEY_REQUEST.CREATE; + +type StepConfirmationParams = MoneyRequestNavigatorParamList[typeof SCREENS.MONEY_REQUEST.STEP_CONFIRMATION]; + +type IOURequestStepConfirmationProps = WithWritableReportOrNotFoundProps & + WithFullTransactionOrNotFoundProps & { + shouldHideHeader?: boolean; + }; function IOURequestStepConfirmation({ report: reportReal, reportDraft, - route: { - params: {iouType, reportID, transactionID: initialTransactionID, action, participantsAutoAssigned: participantsAutoAssignedFromRoute, backToReport, backTo}, - }, + route, transaction: initialTransaction, isLoadingTransaction, + shouldHideHeader = false, }: IOURequestStepConfirmationProps) { + const params = route.params; + const {iouType, reportID, transactionID: initialTransactionID, action, backToReport, backTo} = params; + const participantsAutoAssignedFromRoute = route.name === SCREENS.MONEY_REQUEST.STEP_CONFIRMATION ? (params as StepConfirmationParams).participantsAutoAssigned : undefined; + const currentUserPersonalDetails = useCurrentUserPersonalDetails(); + const defaultExpensePolicy = useDefaultExpensePolicy(); + const personalPolicy = usePersonalPolicy(); + const selfDMReport = useSelfDMReport(); const personalDetails = usePersonalDetails(); const allPolicyCategories = usePolicyCategories(); @@ -123,6 +152,9 @@ function IOURequestStepConfirmation({ const [policyDraft] = useOnyx(`${ONYXKEYS.COLLECTION.POLICY_DRAFTS}${draftPolicyID}`); const [policyReal] = useOnyx(`${ONYXKEYS.COLLECTION.POLICY}${realPolicyID}`); const [conciergeReportID] = useOnyx(ONYXKEYS.CONCIERGE_REPORT_ID); + const [amountOwed] = useOnyx(ONYXKEYS.NVP_PRIVATE_AMOUNT_OWED); + const [userBillingGracePeriodEnds] = useOnyx(ONYXKEYS.COLLECTION.SHARED_NVP_PRIVATE_USER_BILLING_GRACE_PERIOD_END); + const [ownerBillingGracePeriodEnd] = useOnyx(ONYXKEYS.NVP_PRIVATE_OWNER_BILLING_GRACE_PERIOD_END); const expensifyIcons = useMemoizedLazyExpensifyIcons(['ReplaceReceipt', 'SmartScan']); @@ -171,6 +203,8 @@ function IOURequestStepConfirmation({ const styles = useThemeStyles(); const theme = useTheme(); const {translate} = useLocalize(); + const {isBetaEnabled} = usePermissions(); + const isNewManualExpenseFlowEnabled = isBetaEnabled(CONST.BETAS.NEW_MANUAL_EXPENSE_FLOW); const {isOffline} = useNetwork(); const {showConfirmModal} = useConfirmModal(); // isConfirming, selectedParticipantList, and startLocationPermissionFlow state @@ -179,6 +213,7 @@ function IOURequestStepConfirmation({ const [receiptFiles, setReceiptFiles] = useState>({}); const isDistanceRequest = isDistanceRequestTransactionUtils(transaction); const isManualDistanceRequest = isManualDistanceRequestTransactionUtils(transaction); + const isManualRequest = transaction?.iouRequestType === CONST.IOU.REQUEST_TYPE.MANUAL; const isOdometerDistanceRequest = isOdometerDistanceRequestTransactionUtils(transaction); const isTimeRequest = requestType === CONST.IOU.REQUEST_TYPE.TIME; const [lastLocationPermissionPrompt] = useOnyx(ONYXKEYS.NVP_LAST_LOCATION_PERMISSION_PROMPT); @@ -230,14 +265,136 @@ function IOURequestStepConfirmation({ // connection, so we don't need to subscribe to COLLECTION.REPORT_DRAFT here. [transaction?.participants, iouType, personalDetails, reportAttributesDerived, privateIsArchivedMap, policy, conciergeReportID], ); - const isPolicyExpenseChat = useMemo(() => participants?.some((participant) => participant.isPolicyExpenseChat), [participants]); + + const defaultParticipants = useMemo(() => { + const hasSelectedParticipants = (transaction?.participants ?? []).some((participant) => participant?.selected); + if (hasSelectedParticipants) { + return []; + } + + const sourceReportID = transaction?.reportID ?? reportID; + if (!sourceReportID) { + return []; + } + + const sourceReport = getReportOrDraftReport(sourceReportID); + let defaultParticipantsOptions = getMoneyRequestParticipantsFromReport(sourceReport, currentUserPersonalDetails.accountID).filter((participant) => participant.selected); + + const isGlobalCreateFlow = transaction?.isFromGlobalCreate ?? transaction?.isFromFloatingActionButton ?? iouType === CONST.IOU.TYPE.CREATE; + if (!defaultParticipantsOptions.length && isGlobalCreateFlow) { + const canUseDefaultPolicy = shouldUseDefaultExpensePolicy(iouType, defaultExpensePolicy, amountOwed, userBillingGracePeriodEnds, ownerBillingGracePeriodEnd); + + if (canUseDefaultPolicy) { + const shouldAutoReport = !!defaultExpensePolicy?.autoReporting || !!personalPolicy?.autoReporting; + const defaultTargetReport = shouldAutoReport ? getPolicyExpenseChat(currentUserPersonalDetails.accountID, defaultExpensePolicy?.id) : selfDMReport; + defaultParticipantsOptions = getMoneyRequestParticipantsFromReport(defaultTargetReport, currentUserPersonalDetails.accountID).filter((participant) => participant.selected); + } + } + + return defaultParticipantsOptions; + }, [ + transaction?.participants, + transaction?.reportID, + transaction?.isFromGlobalCreate, + transaction?.isFromFloatingActionButton, + reportID, + currentUserPersonalDetails.accountID, + iouType, + defaultExpensePolicy, + personalPolicy?.autoReporting, + selfDMReport, + amountOwed, + userBillingGracePeriodEnds, + ownerBillingGracePeriodEnd, + ]); + + const shouldAutoOpenParticipantPicker = useMemo(() => { + if (!transaction?.transactionID) { + return false; + } + const transactionParticipants = transaction?.participants ?? []; + const hasTransactionParticipants = transactionParticipants.length > 0; + const hasDefaultParticipants = defaultParticipants.length > 0; + return !hasTransactionParticipants && !hasDefaultParticipants && isNewManualExpenseFlowEnabled && isManualRequest; + }, [transaction?.transactionID, transaction?.participants, defaultParticipants.length, isNewManualExpenseFlowEnabled, isManualRequest]); + const activeTransactionID = transaction?.transactionID; + const [manuallyOpenedParticipantPickerForTransactionID, setManuallyOpenedParticipantPickerForTransactionID] = useState(); + const [dismissedAutoOpenParticipantPickerForTransactionID, setDismissedAutoOpenParticipantPickerForTransactionID] = useState(); + const participantPickerIOUType = iouType === CONST.IOU.TYPE.SUBMIT || iouType === CONST.IOU.TYPE.TRACK ? CONST.IOU.TYPE.CREATE : iouType; + const isParticipantPickerVisible = + !!activeTransactionID && + (manuallyOpenedParticipantPickerForTransactionID === activeTransactionID || + (shouldAutoOpenParticipantPicker && dismissedAutoOpenParticipantPickerForTransactionID !== activeTransactionID)); + + const closeParticipantPicker = useCallback(() => { + setManuallyOpenedParticipantPickerForTransactionID(undefined); + if (!activeTransactionID) { + return; + } + setDismissedAutoOpenParticipantPickerForTransactionID(activeTransactionID); + }, [activeTransactionID]); + + const handleParticipantsAdded = useCallback( + (participantsList: Participant[]) => { + if (!activeTransactionID) { + return; + } + setMoneyRequestParticipants(activeTransactionID, participantsList); + if (participantsList.length > 0) { + closeParticipantPicker(); + } + }, + [activeTransactionID, closeParticipantPicker], + ); + + useEffect(() => { + if (!transaction?.transactionID) { + return; + } + + const transactionParticipants = transaction?.participants ?? []; + const hasTransactionParticipants = transactionParticipants.length > 0; + const hasDefaultParticipants = defaultParticipants.length > 0; + + if (hasTransactionParticipants || !hasDefaultParticipants) { + return; + } + + setMoneyRequestParticipants(transaction.transactionID, defaultParticipants); + }, [transaction?.transactionID, transaction?.participants, defaultParticipants, isNewManualExpenseFlowEnabled, isManualRequest]); + + const isPolicyExpenseChat = useMemo(() => { + const hasPolicyExpenseChat = (participantList: typeof defaultParticipants) => + participantList.some((participant) => { + if (isPolicyExpenseChatUtils(participant)) { + return true; + } + + return !!participant?.reportID && isPolicyExpenseChatUtils(getReportOrDraftReport(participant.reportID)); + }); + + if (isPolicyExpenseChatUtils(report)) { + return true; + } + + const transactionParticipants = transaction?.participants ?? []; + if (hasPolicyExpenseChat(transactionParticipants)) { + return true; + } + + return hasPolicyExpenseChat(defaultParticipants); + }, [report, transaction?.participants, defaultParticipants]); + const isFromGlobalCreate = transaction?.isFromGlobalCreate === true || transaction?.isFromFloatingActionButton === true; useFetchRoute(transaction, transaction?.comment?.waypoints, action, shouldUseTransactionDraft(action, iouType) ? CONST.TRANSACTION.STATE.DRAFT : CONST.TRANSACTION.STATE.CURRENT); - const policyExpenseChatPolicyID = participants?.find((participant) => participant.isPolicyExpenseChat)?.policyID; + const policyExpenseChatPolicyID = + transaction?.participants?.find((participant) => participant?.isPolicyExpenseChat)?.policyID ?? + defaultParticipants.find((participant) => participant?.isPolicyExpenseChat)?.policyID ?? + (isPolicyExpenseChatUtils(report) ? report?.policyID : undefined); - const senderPolicyID = participants?.find((participant) => !!participant && 'isSender' in participant && participant.isSender)?.policyID; + const senderPolicyID = transaction?.participants?.find((participant) => !!participant && 'isSender' in participant && participant.isSender)?.policyID; const odometerStartImage = transaction?.comment?.odometerStartImage; const odometerEndImage = transaction?.comment?.odometerEndImage; @@ -329,10 +486,12 @@ function IOURequestStepConfirmation({ hasPreInsertFired.current = true; - const route: Route = shouldPreInsertSearch ? ROUTES.SEARCH_ROOT.getRoute({query: buildCannedSearchQuery({type: searchType})}) : ROUTES.REPORT_WITH_ID.getRoute(destinationReportID); + const preInsertFullscreenRoute: Route = shouldPreInsertSearch + ? ROUTES.SEARCH_ROOT.getRoute({query: buildCannedSearchQuery({type: searchType})}) + : ROUTES.REPORT_WITH_ID.getRoute(destinationReportID); const timer = setTimeout(() => { - Navigation.preInsertFullscreenUnderRHP(route); + Navigation.preInsertFullscreenUnderRHP(preInsertFullscreenRoute); }, CONST.PRE_INSERT_FULLSCREEN_DELAY); return () => { @@ -534,13 +693,19 @@ function IOURequestStepConfirmation({ isMovingTransactionFromTrackExpense={isMovingTransactionFromTrackExpense} isCreatingTrackExpense={isCreatingTrackExpense} /> - + {/* + * In this rollout, NEW_MANUAL_EXPENSE_FLOW means this screen is embedded on IOURequestStartPage. + * Skip MoneyRequestInitializer here to avoid duplicate initialization and navigation side effects. + */} + {!isNewManualExpenseFlowEnabled && ( + + )} - - {hasMultipleTransactions ? ( - - ) : null} - + {/* + * Keep a single header in embedded mode: IOURequestStartPage renders the parent header, + * so this inner header must be hidden to prevent duplicate back buttons and title layout issues. + */} + {!shouldHideHeader && ( + + {hasMultipleTransactions ? ( + + ) : null} + + )} {(isLoading || (isScanRequest(transaction) && !Object.values(receiptFiles).length)) && ( { + if (!activeTransactionID) { + return; + } + setManuallyOpenedParticipantPickerForTransactionID(activeTransactionID); + }} onToggleBillable={setBillable} onConfirm={onConfirm} onSendMoney={sendMoney} @@ -641,7 +818,7 @@ function IOURequestStepConfirmation({ }} receiptPath={receiptPath} receiptFilename={receiptFilename} - iouType={iouType} + iouType={iouType as Exclude} reportID={reportID} shouldDisplayReceipt={ !isMovingTransactionFromTrackExpense && (!isDistanceRequest || isManualDistanceRequest || isOdometerDistanceRequest) && !isPerDiemRequest @@ -663,6 +840,19 @@ function IOURequestStepConfirmation({ /> )} + {isNewManualExpenseFlowEnabled && ( + + )} @@ -672,4 +862,8 @@ function IOURequestStepConfirmation({ const IOURequestStepConfirmationWithFullTransactionOrNotFound = withFullTransactionOrNotFound(IOURequestStepConfirmation); const IOURequestStepConfirmationWithWritableReportOrNotFound = withWritableReportOrNotFound(IOURequestStepConfirmationWithFullTransactionOrNotFound); + +type IOURequestStepConfirmationPublicProps = ComponentProps; + export default IOURequestStepConfirmationWithWritableReportOrNotFound; +export type {IOURequestStepConfirmationPublicProps}; diff --git a/src/pages/iou/request/step/IOURequestStepParticipants.tsx b/src/pages/iou/request/step/IOURequestStepParticipants.tsx index 1624887bae8d..96dba30b5c2f 100644 --- a/src/pages/iou/request/step/IOURequestStepParticipants.tsx +++ b/src/pages/iou/request/step/IOURequestStepParticipants.tsx @@ -4,6 +4,7 @@ import FormHelpMessage from '@components/FormHelpMessage'; import useLocalize from '@hooks/useLocalize'; import useOnyx from '@hooks/useOnyx'; import useParticipantSubmission from '@hooks/useParticipantSubmission'; +import usePermissions from '@hooks/usePermissions'; import useThemeStyles from '@hooks/useThemeStyles'; import {isMovingTransactionFromTrackExpense as isMovingTransactionFromTrackExpenseIOUUtils, navigateToStartMoneyRequestStep} from '@libs/IOUUtils'; import Navigation from '@libs/Navigation/Navigation'; @@ -41,6 +42,8 @@ function IOURequestStepParticipants({ const isPerDiem = isPerDiemRequest(initialTransaction); const isTime = isTimeRequestUtil(initialTransaction); const isCorporateCard = isCorporateCardTransaction(initialTransaction); + const {isBetaEnabled} = usePermissions(); + const isNewManualExpenseFlowEnabled = isBetaEnabled(CONST.BETAS.NEW_MANUAL_EXPENSE_FLOW); let headerTitle = translate('iou.chooseRecipient'); if (action === CONST.IOU.ACTION.CATEGORIZE) { @@ -125,8 +128,14 @@ function IOURequestStepParticipants({ return false; } + // In new flow - the amount step is skipped, so we need to include the recents for all the cases. + if (isNewManualExpenseFlowEnabled) { + return false; + } + return initialTransaction?.amount !== undefined && initialTransaction?.amount !== null && initialTransaction?.amount <= 0; }; + const isWorkspacesOnly = getIsWorkspacesOnly(); const selectedParticipant = isSplitRequest ? undefined : participants?.find((participant) => participant.selected && !participant.isSender); // Participants with a reportID are found in the list and highlighted via initiallySelectedReportID. diff --git a/src/types/onyx/Transaction.ts b/src/types/onyx/Transaction.ts index 793ee852acc5..9a6654dd4d54 100644 --- a/src/types/onyx/Transaction.ts +++ b/src/types/onyx/Transaction.ts @@ -512,6 +512,17 @@ type Transaction = OnyxCommon.OnyxValueWithOfflineFeedback< /** Used during the creation flow before the transaction is saved to the server */ iouRequestType?: IOURequestType; + /** + * Tracks whether the user has explicitly set an amount in the new manual expense flow. + * A fresh draft transaction starts at amount=0 which is indistinguishable from an intentional $0 entry, + * so this flag is set to `true` the first time setMoneyRequestAmount is called, allowing the UI + * to show an empty field initially and the confirmation step to block submission until the field is empty. + */ + isAmountSet?: boolean; + + /** Whether the merchant has been explicitly set by the user */ + isMerchantSet?: boolean; + /** The original merchant name */ merchant: string; diff --git a/tests/actions/IOU/IOUSettersTest.ts b/tests/actions/IOU/IOUSettersTest.ts index b614fb9d0de7..532ed18b57b5 100644 --- a/tests/actions/IOU/IOUSettersTest.ts +++ b/tests/actions/IOU/IOUSettersTest.ts @@ -112,14 +112,6 @@ describe('IOU setter functions', () => { }); describe('setMoneyRequestDescription', () => { - it('should set trimmed comment on a draft transaction', async () => { - setMoneyRequestDescription(TRANSACTION_ID, ' Test description ', true); - await waitForBatchedUpdates(); - - const draft = await getOnyxValue(`${ONYXKEYS.COLLECTION.TRANSACTION_DRAFT}${TRANSACTION_ID}`); - expect(draft?.comment?.comment).toBe('Test description'); - }); - it('should set comment on a real transaction when isDraft is false', async () => { const transaction = createRandomTransaction(1); transaction.transactionID = TRANSACTION_ID; diff --git a/tests/actions/IOUTest.ts b/tests/actions/IOUTest.ts index c3b8ce6fda09..bb859343effb 100644 --- a/tests/actions/IOUTest.ts +++ b/tests/actions/IOUTest.ts @@ -14,7 +14,6 @@ import { setMoneyRequestCategory, setMoneyRequestCreated, setMoneyRequestDateAttribute, - setMoneyRequestDescription, setMoneyRequestDistanceRate, setMoneyRequestMerchant, setMoneyRequestTag, @@ -6734,13 +6733,6 @@ describe('actions/IOU', () => { expect(draft?.comment?.customUnit?.attributes?.dates?.end).toBe('2024-01-31'); }); - it('setMoneyRequestDescription should set comment on transaction draft', async () => { - setMoneyRequestDescription(transactionID, ' Lunch with team ', true); - await waitForBatchedUpdates(); - const draft = await getOnyxValue(`${ONYXKEYS.COLLECTION.TRANSACTION_DRAFT}${transactionID}`); - expect(draft?.comment?.comment).toBe('Lunch with team'); - }); - it('setMoneyRequestMerchant should set merchant on transaction draft', async () => { setMoneyRequestMerchant(transactionID, 'Coffee Shop', true); await waitForBatchedUpdates(); diff --git a/tests/ui/MoneyRequestReportFooter.tsx b/tests/ui/MoneyRequestReportFooter.tsx index 91e6489cc941..79e42d7f9f83 100644 --- a/tests/ui/MoneyRequestReportFooter.tsx +++ b/tests/ui/MoneyRequestReportFooter.tsx @@ -127,6 +127,8 @@ const renderMoneyRequestConfirmationListFooter = (transaction: Transaction) => { isTimeRequest: false, showMoreFields: false, setShowMoreFields: jest.fn(), + clearFormErrors: jest.fn(), + setFormError: jest.fn(), }; return render( diff --git a/tests/ui/TimeExpenseConfirmationTest.tsx b/tests/ui/TimeExpenseConfirmationTest.tsx index 5a60d18b69c5..872840f59108 100644 --- a/tests/ui/TimeExpenseConfirmationTest.tsx +++ b/tests/ui/TimeExpenseConfirmationTest.tsx @@ -85,10 +85,12 @@ jest.mock('@libs/Navigation/Navigation', () => { goBack: jest.fn(), dismissModal: jest.fn(), dismissModalWithReport: jest.fn(), + getActiveRoute: jest.fn(() => ''), getIsFullscreenPreInsertedUnderRHP: jest.fn(() => false), getPreInsertedFullscreenRouteName: jest.fn(() => undefined), clearFullscreenPreInsertedFlag: jest.fn(), revealRouteBeforeDismissingModal: jest.fn(), + isTopmostRouteModalScreen: jest.fn(() => false), navigationRef: mockRef, }; }); @@ -150,6 +152,7 @@ function createPolicyWithTimeTracking(): Policy { const DEFAULT_TIME_TRANSACTION: Transaction = { amount: 40000, // $400.00 (8 hours * $50/hr) + isAmountSet: true, billable: false, comment: { units: { diff --git a/tests/ui/components/IOURequestStepConfirmationPageTest.tsx b/tests/ui/components/IOURequestStepConfirmationPageTest.tsx index 5a950e3b5fd3..1aa0b51dedd9 100644 --- a/tests/ui/components/IOURequestStepConfirmationPageTest.tsx +++ b/tests/ui/components/IOURequestStepConfirmationPageTest.tsx @@ -125,6 +125,7 @@ jest.mock('@libs/Navigation/Navigation', () => { getTopmostReportId: jest.fn(() => undefined), preInsertFullscreenUnderRHP: jest.fn(), removePreInsertedFullscreenIfNeeded: jest.fn(), + isTopmostRouteModalScreen: jest.fn(() => false), navigationRef: mockRef, }; }); @@ -238,6 +239,7 @@ function createWaypoints(startAddress: string, endAddress: string): WaypointColl const DEFAULT_SPLIT_TRANSACTION: Transaction = { amount: 0, + isAmountSet: true, billable: false, comment: { attendees: [ @@ -983,6 +985,7 @@ describe('IOURequestStepConfirmationPageTest', () => { transactionID, reportID: transactionReportID, amount: 1000, + isAmountSet: true, currency: 'USD', merchant: 'Test', created: '2025-01-15', @@ -1049,6 +1052,7 @@ describe('IOURequestStepConfirmationPageTest', () => { transactionID, reportID: routeReportID, amount: 1000, + isAmountSet: true, currency: 'USD', merchant: 'Test', created: '2025-01-15', @@ -1124,6 +1128,7 @@ describe('IOURequestStepConfirmationPageTest', () => { transactionID, reportID: transactionReportID, amount: 1000, + isAmountSet: true, currency: 'USD', merchant: 'Test', created: '2025-01-15', @@ -1183,6 +1188,7 @@ describe('IOURequestStepConfirmationPageTest', () => { transactionID, reportID: CONST.REPORT.UNREPORTED_REPORT_ID, amount: 1000, + isAmountSet: true, currency: 'USD', merchant: 'Test Merchant', created: '2025-01-15', diff --git a/tests/unit/hooks/useConfirmationValidation.test.ts b/tests/unit/hooks/useConfirmationValidation.test.ts index a41fadf288ff..66bcb590ce82 100644 --- a/tests/unit/hooks/useConfirmationValidation.test.ts +++ b/tests/unit/hooks/useConfirmationValidation.test.ts @@ -1,4 +1,5 @@ import {renderHook} from '@testing-library/react-native'; +import type {UseConfirmationValidationParams} from '@components/MoneyRequestConfirmationList/hooks/useConfirmationValidation'; import useConfirmationValidation from '@components/MoneyRequestConfirmationList/hooks/useConfirmationValidation'; import CONST from '@src/CONST'; import type * as OnyxTypes from '@src/types/onyx'; @@ -11,9 +12,7 @@ jest.mock('@hooks/useCurrencyList', () => ({ }), })); -type Params = Parameters[0]; - -const baseParams: Params = { +const baseParams = { transaction: {transactionID: 'txn1', comment: {}, amount: 100} as unknown as OnyxTypes.Transaction, transactionReport: undefined, transactionID: 'txn1', @@ -31,6 +30,7 @@ const baseParams: Params = { currentUserPersonalDetails: {accountID: 1} as CurrentUserPersonalDetails, isEditingSplitBill: false, isMerchantRequired: false, + isMerchantFieldValid: true, isMerchantEmpty: false, shouldDisplayFieldError: false, shouldShowTax: false, @@ -38,9 +38,9 @@ const baseParams: Params = { isDistanceRequestWithPendingRoute: false, isPerDiemRequest: false, isTimeRequest: false, - isNewManualExpenseFlowEnabled: false, routeError: undefined, -}; + isNewManualExpenseFlowEnabled: false, +} satisfies UseConfirmationValidationParams; describe('useConfirmationValidation', () => { it('returns null when routeError is set', () => { @@ -65,7 +65,7 @@ describe('useConfirmationValidation', () => { }); it('returns invalidMerchant when merchant is required but empty', () => { - const {result} = renderHook(() => useConfirmationValidation({...baseParams, isMerchantRequired: true, isMerchantEmpty: true})); + const {result} = renderHook(() => useConfirmationValidation({...baseParams, isMerchantRequired: true, isMerchantEmpty: true, isMerchantFieldValid: false})); expect(result.current.validate()).toEqual({errorKey: 'iou.error.invalidMerchant'}); });