diff --git a/src/components/DropZone/DualDropZone.tsx b/src/components/DropZone/DualDropZone.tsx index 84d99dcfd395..04e22b76042b 100644 --- a/src/components/DropZone/DualDropZone.tsx +++ b/src/components/DropZone/DualDropZone.tsx @@ -1,6 +1,11 @@ import React from 'react'; -import {View} from 'react-native'; +// We use Animated for all functionality related to wide RHP to make it easier +// to interact with react-navigation components (e.g., CardContainer, interpolator), which also use Animated. +// eslint-disable-next-line no-restricted-imports +import {Animated, View} from 'react-native'; +import type {ViewStyle} from 'react-native'; import DragAndDropConsumer from '@components/DragAndDrop/Consumer'; +import {useWideRHPState} from '@components/WideRHPContextProvider'; import {useMemoizedLazyExpensifyIcons} from '@hooks/useLazyAsset'; import useLocalize from '@hooks/useLocalize'; import useResponsiveLayout from '@hooks/useResponsiveLayout'; @@ -30,12 +35,20 @@ function DualDropZone({isEditing, onAttachmentDrop, onReceiptDrop, shouldAcceptS const theme = useTheme(); const icons = useMemoizedLazyExpensifyIcons(['MessageInABottle', 'SmartScan', 'ReplaceReceipt']); - const shouldStackVertically = shouldUseNarrowLayout || isMediumScreenWidth; + const {isWideRHPFocused} = useWideRHPState(); + const shouldStackVertically = (shouldUseNarrowLayout || isMediumScreenWidth) && !isWideRHPFocused; const scanReceiptsText = shouldAcceptSingleReceipt ? 'dropzone.addReceipt' : 'dropzone.scanReceipts'; + const shouldStackRevertHorizontally = isWideRHPFocused; + let flexStyle: ViewStyle = styles.flexRow; + if (shouldStackVertically) { + flexStyle = styles.flexColumn; + } else if (shouldStackRevertHorizontally) { + flexStyle = styles.flexRowReverse; + } return ( {}}> - + {({isDraggingOver}) => ( )} - - {({isDraggingOver}) => ( - - )} - + + + {({isDraggingOver}) => ( + + )} + + ); diff --git a/src/components/ReceiptEmptyState.tsx b/src/components/ReceiptEmptyState.tsx index 2af8959c9a59..c0892c7e6b04 100644 --- a/src/components/ReceiptEmptyState.tsx +++ b/src/components/ReceiptEmptyState.tsx @@ -1,11 +1,15 @@ import React, {useEffect, useRef} from 'react'; import {View} from 'react-native'; import type {StyleProp, ViewStyle} from 'react-native'; +import useFilesValidation from '@hooks/useFilesValidation'; import {useMemoizedLazyExpensifyIcons} from '@hooks/useLazyAsset'; import useLocalize from '@hooks/useLocalize'; import useTheme from '@hooks/useTheme'; import useThemeStyles from '@hooks/useThemeStyles'; import variables from '@styles/variables'; +import CONST from '@src/CONST'; +import type {FileObject} from '@src/types/utils/Attachment'; +import AttachmentPicker from './AttachmentPicker'; import Icon from './Icon'; import PressableWithoutFeedback from './Pressable/PressableWithoutFeedback'; import ReceiptAlternativeMethods from './ReceiptAlternativeMethods'; @@ -34,6 +38,9 @@ type ReceiptEmptyStateProps = { /** Whether it's displayed in Wide RHP */ isDisplayedInWideRHP?: boolean; + + /** Callback to be called when a receipt is selected */ + setReceiptFile?: (files: FileObject[]) => void; }; // Returns an SVG icon indicating that the user should attach a receipt @@ -46,12 +53,14 @@ function ReceiptEmptyState({ style, onLoad, isDisplayedInWideRHP = false, + setReceiptFile = () => {}, }: ReceiptEmptyStateProps) { const styles = useThemeStyles(); const {translate} = useLocalize(); const theme = useTheme(); const isLoadedRef = useRef(false); const icons = useMemoizedLazyExpensifyIcons(['ReceiptPlaceholderPlus', 'Receipt']); + const {validateFiles, PDFValidationComponent, ErrorModal} = useFilesValidation(setReceiptFile); const Wrapper = onPress ? PressableWithoutFeedback : View; const containerStyle = [ @@ -73,42 +82,56 @@ function ReceiptEmptyState({ }, [onLoad]); return ( - - - - - - {!isThumbnail && ( - - )} + + {({openPicker}) => ( + { + if (isDisplayedInWideRHP) { + openPicker({ + onPicked: validateFiles, + }); + return; + } + onPress?.(); + }} + disabled={disabled} + disabledStyle={styles.cursorDefault} + style={containerStyle} + > + {PDFValidationComponent} + {ErrorModal} + + + + + {!isThumbnail && ( + + )} + + {!isThumbnail && isDisplayedInWideRHP && ( + <> + {translate('receipt.addAReceipt.phrase1')} + {translate('receipt.addAReceipt.phrase2')} + + )} + - {!isThumbnail && isDisplayedInWideRHP && ( - <> - {translate('receipt.addAReceipt.phrase1')} - {translate('receipt.addAReceipt.phrase2')} - - )} - - - {isDisplayedInWideRHP && !disabled && } - + {isDisplayedInWideRHP && !disabled && } + + )} + ); } diff --git a/src/components/ReportActionItem/MoneyRequestReceiptView.tsx b/src/components/ReportActionItem/MoneyRequestReceiptView.tsx index e77ff216c5f5..9b46c521546c 100644 --- a/src/components/ReportActionItem/MoneyRequestReceiptView.tsx +++ b/src/components/ReportActionItem/MoneyRequestReceiptView.tsx @@ -46,7 +46,7 @@ import { } from '@libs/TransactionUtils'; import ViolationsUtils, {filterReceiptViolations} from '@libs/Violations/ViolationsUtils'; import Navigation from '@navigation/Navigation'; -import {cleanUpMoneyRequest} from '@userActions/IOU'; +import {cleanUpMoneyRequest, replaceReceipt} from '@userActions/IOU'; import {navigateToConciergeChatAndDeleteReport} from '@userActions/Report'; import {clearAllRelatedReportActionErrors} from '@userActions/ReportActions'; import {clearError, getLastModifiedExpense, revert} from '@userActions/Transaction'; @@ -55,6 +55,7 @@ import ONYXKEYS from '@src/ONYXKEYS'; import ROUTES from '@src/ROUTES'; import type * as OnyxTypes from '@src/types/onyx'; import type {TransactionPendingFieldsKey} from '@src/types/onyx/Transaction'; +import type {FileObject} from '@src/types/utils/Attachment'; import {isEmptyObject} from '@src/types/utils/EmptyObject'; import ReportActionItemImage from './ReportActionItemImage'; @@ -123,6 +124,7 @@ function MoneyRequestReceiptView({report, readonly = false, updatedTransaction, const [policy] = useOnyx(`${ONYXKEYS.COLLECTION.POLICY}${moneyRequestReport?.policyID}`); const [cardList] = useOnyx(ONYXKEYS.CARD_LIST); const transactionViolations = useTransactionViolations(transaction?.transactionID); + const [policyCategories] = useOnyx(`${ONYXKEYS.COLLECTION.POLICY_CATEGORIES}${moneyRequestReport?.policyID}`); const isDistanceRequest = isDistanceRequestTransactionUtils(transaction); const hasReceipt = hasReceiptTransactionUtils(updatedTransaction ?? transaction); @@ -327,6 +329,20 @@ function MoneyRequestReceiptView({report, readonly = false, updatedTransaction, ); + const setReceiptFile = (files: FileObject[]) => { + if (files.length === 0) { + return; + } + + const file = files.at(0); + + if (!file || !linkedTransactionID) { + return; + } + const source = URL.createObjectURL(file as Blob); + replaceReceipt({transactionID: linkedTransactionID, file: file as File, source, transactionPolicy: policy, transactionPolicyCategories: policyCategories}); + }; + // For empty receipt should be fullHeight // For the rest, expand to match the content return ( @@ -359,6 +375,7 @@ function MoneyRequestReceiptView({report, readonly = false, updatedTransaction, isInMoneyRequestView style={receiptStyle} isDisplayedInWideRHP={isDisplayedInWideRHP} + setReceiptFile={setReceiptFile} /> )} diff --git a/src/styles/index.ts b/src/styles/index.ts index 0ab688145bbf..154fc7b34d3d 100644 --- a/src/styles/index.ts +++ b/src/styles/index.ts @@ -5631,6 +5631,11 @@ const staticStyles = (theme: ThemeColors) => borderColor: theme.border, }, + wideRHPDropZoneContainer: { + width: animatedReceiptPaneRHPWidth, + height: '100%', + }, + wideRHPMoneyRequestReceiptViewScrollViewContainer: { ...spacing.pt3, ...spacing.pb2, diff --git a/tests/ui/components/MoneyRequestReceiptViewTest.tsx b/tests/ui/components/MoneyRequestReceiptViewTest.tsx new file mode 100644 index 000000000000..e4e81de60e4e --- /dev/null +++ b/tests/ui/components/MoneyRequestReceiptViewTest.tsx @@ -0,0 +1,178 @@ +import {act, fireEvent, render, screen} from '@testing-library/react-native'; +import React from 'react'; +import Onyx from 'react-native-onyx'; +import ComposeProviders from '@components/ComposeProviders'; +import {LocaleContextProvider} from '@components/LocaleContextProvider'; +import OnyxListItemProvider from '@components/OnyxListItemProvider'; +import MoneyRequestReceiptView from '@components/ReportActionItem/MoneyRequestReceiptView'; +import CONST from '@src/CONST'; +import ONYXKEYS from '@src/ONYXKEYS'; +import type {Report, Transaction} from '@src/types/onyx'; +import type {FileObject} from '@src/types/utils/Attachment'; +import {translateLocal} from '../../utils/TestHelper'; +import waitForBatchedUpdatesWithAct from '../../utils/waitForBatchedUpdatesWithAct'; + +const mockOpenPicker = jest.fn(); + +jest.mock('@components/AttachmentPicker', () => { + function MockAttachmentPicker({children}: {children: (props: {openPicker: (opts: {onPicked: (files: unknown[]) => void}) => void}) => React.ReactNode}) { + return <>{children({openPicker: mockOpenPicker})}; + } + return MockAttachmentPicker; +}); + +jest.mock('@hooks/useFilesValidation', () => (onFilesValidated: (files: FileObject[]) => void) => ({ + validateFiles: onFilesValidated, + PDFValidationComponent: null, + ErrorModal: null, +})); + +jest.mock( + '@components/ReceiptAlternativeMethods', + () => + function MockReceiptAlternativeMethods() { + return null; + }, +); + +// Override IDs so we control Onyx keys and can use evictableKeys for REPORT_ACTIONS +const TEST_PARENT_REPORT_ID = 'testParentReportID'; +const TEST_REPORT_ID = 'testReportID'; +const TEST_ACTION_ID = 'testActionID'; +const TEST_TRANSACTION_ID = 'testTransactionID'; +const TEST_POLICY_ID = 'testPolicyID'; + +const testReport: Report = { + reportID: TEST_REPORT_ID, + parentReportID: TEST_PARENT_REPORT_ID, + parentReportActionID: TEST_ACTION_ID, + policyID: TEST_POLICY_ID, + type: CONST.REPORT.TYPE.EXPENSE, + chatType: CONST.REPORT.CHAT_TYPE.POLICY_EXPENSE_CHAT, + participants: {}, + reportName: '', + lastReadTime: '', + lastVisibleActionCreated: '', + lastMessageText: '', + lastActorAccountID: 1, + ownerAccountID: 1, + managerID: 1, + total: 0, + unheldTotal: 0, + permissions: [CONST.REPORT.PERMISSIONS.READ, CONST.REPORT.PERMISSIONS.WRITE], + writeCapability: CONST.REPORT.WRITE_CAPABILITIES.ALL, + lastActionType: CONST.REPORT.ACTIONS.TYPE.ADD_COMMENT, + stateNum: 0, + statusNum: 0, + hasOutstandingChildRequest: false, + hasOutstandingChildTask: false, + isPinned: false, + isWaitingOnBankAccount: false, + lastReadSequenceNumber: 0, + unheldNonReimbursableTotal: 0, + nonReimbursableTotal: 0, + errorFields: {}, + currency: CONST.CURRENCY.USD, + oldPolicyName: '', + welcomeMessage: '', + description: '', +}; + +const testParentReportAction = { + reportActionID: TEST_ACTION_ID, + actionName: CONST.REPORT.ACTIONS.TYPE.IOU, + originalMessage: { + IOUTransactionID: TEST_TRANSACTION_ID, + type: CONST.IOU.REPORT_ACTION_TYPE.CREATE, + }, + created: '2025-02-14 08:12:05.165', + actorAccountID: 1, + person: [{type: 'TEXT', style: 'strong', text: 'Test'}], + message: [{type: 'COMMENT', html: '', text: '', isEdited: false, whisperedTo: [], isDeletedParentAction: false}], +}; + +const transactionWithoutReceipt: Transaction = { + transactionID: TEST_TRANSACTION_ID, + reportID: TEST_REPORT_ID, + amount: 100, + currency: CONST.CURRENCY.USD, + cardName: CONST.EXPENSE.TYPE.CASH_CARD_NAME, + status: CONST.TRANSACTION.STATUS.POSTED, + created: '2025-02-14', + inserted: '2025-02-14 08:12:19', + merchant: 'Test', + billable: false, + managedCard: false, + reimbursable: true, + receipt: undefined, + comment: {}, + bank: '', + cardNumber: '', + category: '', + modifiedAmount: '', + originalAmount: 0, + parentTransactionID: '', + posted: '', + tag: '', + hasEReceipt: false, + cardID: 0, + modifiedCreated: '', + modifiedCurrency: '', + modifiedMerchant: '', + originalCurrency: '', +}; + +function Wrapper({children}: {children: React.ReactNode}) { + return {children}; +} + +describe('MoneyRequestReceiptView', () => { + beforeAll(() => { + Onyx.init({ + keys: ONYXKEYS, + evictableKeys: [ONYXKEYS.COLLECTION.REPORT_ACTIONS], + }); + }); + + beforeEach(async () => { + jest.clearAllMocks(); + await act(async () => { + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${TEST_PARENT_REPORT_ID}`, { + [TEST_ACTION_ID]: testParentReportAction, + }); + await Onyx.merge(`${ONYXKEYS.COLLECTION.TRANSACTION}${TEST_TRANSACTION_ID}`, transactionWithoutReceipt); + await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}${TEST_POLICY_ID}`, {id: TEST_POLICY_ID}); + await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY_CATEGORIES}${TEST_POLICY_ID}`, {}); + }); + await waitForBatchedUpdatesWithAct(); + }); + + afterEach(async () => { + await act(async () => { + await Onyx.clear(); + }); + }); + + describe('wide RHP setReceiptFile flow', () => { + it('calls setReceiptFile with the picked file when onPicked is invoked (replaceReceipt called)', async () => { + render( + + + , + ); + await waitForBatchedUpdatesWithAct(); + + const uploadButton = screen.getByLabelText(translateLocal('receipt.upload')); + fireEvent.press(uploadButton); + expect(mockOpenPicker).toHaveBeenCalledTimes(1); + + const firstCall = (mockOpenPicker.mock.calls as Array<[{onPicked: (files: FileObject[]) => void}]>).at(0); + const onPicked = firstCall?.at(0)?.onPicked; + expect(onPicked).toBeDefined(); + }); + }); +}); diff --git a/tests/ui/components/ReceiptEmptyStateTest.tsx b/tests/ui/components/ReceiptEmptyStateTest.tsx new file mode 100644 index 000000000000..6b83fde95d12 --- /dev/null +++ b/tests/ui/components/ReceiptEmptyStateTest.tsx @@ -0,0 +1,107 @@ +import {fireEvent, render, screen} from '@testing-library/react-native'; +import React from 'react'; +import {LocaleContextProvider} from '@components/LocaleContextProvider'; +import ReceiptEmptyState from '@components/ReceiptEmptyState'; +import type {FileObject} from '@src/types/utils/Attachment'; +import {translateLocal} from '../../utils/TestHelper'; + +const mockOpenPicker = jest.fn(); + +jest.mock('@components/AttachmentPicker', () => { + function MockAttachmentPicker({children}: {children: (props: {openPicker: (opts: {onPicked: (files: unknown[]) => void}) => void}) => React.ReactNode}) { + return <>{children({openPicker: mockOpenPicker})}; + } + return MockAttachmentPicker; +}); + +jest.mock('@hooks/useFilesValidation', () => (onFilesValidated: (files: FileObject[]) => void) => ({ + validateFiles: onFilesValidated, + PDFValidationComponent: null, + ErrorModal: null, +})); + +// ReceiptAlternativeMethods uses RenderHTML which requires TRenderEngineProvider (buildTTree). Mock to avoid the error. +jest.mock( + '@components/ReceiptAlternativeMethods', + () => + function MockReceiptAlternativeMethods() { + return null; + }, +); + +function Wrapper({children}: {children: React.ReactNode}) { + return {children}; +} + +describe('ReceiptEmptyState', () => { + beforeEach(() => { + jest.clearAllMocks(); + }); + + describe('wide RHP attachment picker flow', () => { + it('calls openPicker when pressed and isDisplayedInWideRHP is true', () => { + render( + + + , + ); + + const uploadButton = screen.getByLabelText(translateLocal('receipt.upload')); + fireEvent.press(uploadButton); + + expect(mockOpenPicker).toHaveBeenCalledTimes(1); + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- Jest matcher for callback + expect(mockOpenPicker).toHaveBeenCalledWith({onPicked: expect.any(Function)}); + }); + + it('does not call openPicker when isDisplayedInWideRHP is false and calls onPress instead', () => { + const onPress = jest.fn(); + render( + + + , + ); + + const uploadButton = screen.getByLabelText(translateLocal('receipt.upload')); + fireEvent.press(uploadButton); + + expect(mockOpenPicker).not.toHaveBeenCalled(); + expect(onPress).toHaveBeenCalledTimes(1); + }); + + it('shows "Add a receipt" text when isDisplayedInWideRHP is true and not thumbnail', () => { + render( + + + , + ); + + expect(screen.getByText(translateLocal('receipt.addAReceipt.phrase1'))).toBeOnTheScreen(); + expect(screen.getByText(translateLocal('receipt.addAReceipt.phrase2'))).toBeOnTheScreen(); + }); + + it('does not show "Add a receipt" text when isDisplayedInWideRHP is false', () => { + render( + + + , + ); + + expect(screen.queryByText(translateLocal('receipt.addAReceipt.phrase1'))).not.toBeOnTheScreen(); + expect(screen.queryByText(translateLocal('receipt.addAReceipt.phrase2'))).not.toBeOnTheScreen(); + }); + }); +});