diff --git a/src/CONST.ts b/src/CONST.ts index 0f01edb87cde..01857b763cba 100755 --- a/src/CONST.ts +++ b/src/CONST.ts @@ -1318,6 +1318,9 @@ const CONST = { }, }, THREAD_DISABLED: ['CREATED'], + // Used when displaying reportActions list to handle of unread messages icon/button + SCROLL_VERTICAL_OFFSET_THRESHOLD: 200, + ACTION_VISIBLE_THRESHOLD: 250, }, TRANSACTION_LIST: { COLUMNS: { @@ -6434,6 +6437,10 @@ const CONST = { GROUP_BY: { REPORTS: 'reports', }, + TABLE_COLUMN_SIZES: { + NORMAL: 'normal', + WIDE: 'wide', + }, STATUS: { EXPENSE: { ALL: 'all', diff --git a/src/components/MoneyRequestHeader.tsx b/src/components/MoneyRequestHeader.tsx index af909c3f9c6a..b8eb591fac50 100644 --- a/src/components/MoneyRequestHeader.tsx +++ b/src/components/MoneyRequestHeader.tsx @@ -39,6 +39,7 @@ import * as Expensicons from './Icon/Expensicons'; import LoadingBar from './LoadingBar'; import type {MoneyRequestHeaderStatusBarProps} from './MoneyRequestHeaderStatusBar'; import MoneyRequestHeaderStatusBar from './MoneyRequestHeaderStatusBar'; +import MoneyRequestReportTransactionsNavigation from './MoneyRequestReportView/MoneyRequestReportTransactionsNavigation'; type MoneyRequestHeaderProps = { /** The report currently being looked at */ @@ -79,6 +80,7 @@ function MoneyRequestHeader({report, parentReportAction, policy, onBackButtonPre const isReportInRHP = route.name === SCREENS.SEARCH.REPORT_RHP; const shouldDisplaySearchRouter = !isReportInRHP || isSmallScreenWidth; + const shouldDisplayTransactionNavigation = !!(reportID && isReportInRHP); const hasPendingRTERViolation = hasPendingRTERViolationTransactionUtils(transactionViolations); @@ -184,6 +186,7 @@ function MoneyRequestHeader({report, parentReportAction, policy, onBackButtonPre }} /> )} + {shouldDisplayTransactionNavigation && } {shouldShowMarkAsCashButton && shouldUseNarrowLayout && ( diff --git a/src/components/MoneyRequestReportView/MoneyRequestReportActionsList.tsx b/src/components/MoneyRequestReportView/MoneyRequestReportActionsList.tsx index 7ecf424d633c..d1eae9ee8f02 100644 --- a/src/components/MoneyRequestReportView/MoneyRequestReportActionsList.tsx +++ b/src/components/MoneyRequestReportView/MoneyRequestReportActionsList.tsx @@ -1,14 +1,20 @@ import type {ListRenderItemInfo} from '@react-native/virtualized-lists/Lists/VirtualizedList'; import isEmpty from 'lodash/isEmpty'; -import React, {useCallback, useMemo} from 'react'; +import React, {useCallback, useEffect, useMemo, useRef, useState} from 'react'; import {InteractionManager, View} from 'react-native'; +import type {NativeScrollEvent, NativeSyntheticEvent} from 'react-native'; import type {OnyxCollection, OnyxEntry} from 'react-native-onyx'; import {useOnyx} from 'react-native-onyx'; import FlatList from '@components/FlatList'; +import {AUTOSCROLL_TO_TOP_THRESHOLD} from '@components/InvertedFlatList/BaseInvertedFlatList'; import useLoadReportActions from '@hooks/useLoadReportActions'; -import useNetwork from '@hooks/useNetwork'; +import useLocalize from '@hooks/useLocalize'; +import useNetworkWithOfflineStatus from '@hooks/useNetworkWithOfflineStatus'; +import usePrevious from '@hooks/usePrevious'; +import useReportScrollManager from '@hooks/useReportScrollManager'; import useThemeStyles from '@hooks/useThemeStyles'; import getNonEmptyStringOnyxID from '@libs/getNonEmptyStringOnyxID'; +import {isActionVisibleOnMoneyRequestReport} from '@libs/MoneyRequestReportUtils'; import { getFirstVisibleReportActionID, getMostRecentIOURequestActionID, @@ -16,15 +22,21 @@ import { hasNextActionMadeBySameActor, isConsecutiveChronosAutomaticTimerAction, isDeletedParentAction, - isReversedTransaction, - isTransactionThread, + isReportActionUnread, + isReportPreviewAction, + shouldHideNewMarker, shouldReportActionBeVisible, + wasMessageReceivedWhileOffline, } from '@libs/ReportActionsUtils'; -import {canUserPerformWriteAction, chatIncludesChronosWithID, isCanceledTaskReport, isExpenseReport, isInvoiceReport, isIOUReport, isTaskReport} from '@libs/ReportUtils'; +import {canUserPerformWriteAction, chatIncludesChronosWithID, getReportLastVisibleActionCreated} from '@libs/ReportUtils'; import isSearchTopmostFullScreenRoute from '@navigation/helpers/isSearchTopmostFullScreenRoute'; +import Navigation from '@navigation/Navigation'; +import FloatingMessageCounter from '@pages/home/report/FloatingMessageCounter'; import ReportActionsListItemRenderer from '@pages/home/report/ReportActionsListItemRenderer'; +import {openReport, readNewestAction} from '@userActions/Report'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; +import ROUTES from '@src/ROUTES'; import type * as OnyxTypes from '@src/types/onyx'; import type Transaction from '@src/types/onyx/Transaction'; import MoneyRequestReportTransactionList from './MoneyRequestReportTransactionList'; @@ -35,6 +47,8 @@ import SearchMoneyRequestReportEmptyState from './SearchMoneyRequestReportEmptyS */ const EmptyParentReportActionForTransactionThread = undefined; +const INITIAL_NUM_TO_RENDER = 20; + type MoneyRequestReportListProps = { /** The report */ report: OnyxTypes.Report; @@ -56,11 +70,7 @@ function getParentReportAction(parentReportActions: OnyxEntry, reportID: string) { +function selectTransactionsForReportID(transactions: OnyxCollection, reportID: string) { return Object.values(transactions ?? {}).filter((transaction): transaction is Transaction => { return transaction?.reportID === reportID; }); @@ -68,16 +78,13 @@ function getTransactionsForReportID(transactions: OnyxCollection getFirstVisibleReportActionID(reportActions, isOffline), [reportActions, isOffline]); const [transactions = []] = useOnyx(ONYXKEYS.COLLECTION.TRANSACTION, { - selector: (allTransactions): OnyxTypes.Transaction[] => getTransactionsForReportID(allTransactions, reportID), + selector: (allTransactions): OnyxTypes.Transaction[] => selectTransactionsForReportID(allTransactions, reportID), }); const [transactionThreadReport] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${transactionThreadReportID ?? CONST.DEFAULT_NUMBER_ID}`); + const [currentUserAccountID] = useOnyx(ONYXKEYS.SESSION, {selector: (session) => session?.accountID}); const canPerformWriteAction = canUserPerformWriteAction(report); + const [isFloatingMessageCounterVisible, setIsFloatingMessageCounterVisible] = useState(false); + + const reportScrollManager = useReportScrollManager(); // We are reversing actions because in this View we are starting at the top and don't use Inverted list const visibleReportActions = useMemo(() => { const filteredActions = reportActions.filter((reportAction) => { - const isChatAction = isChatOnlyReportAction(reportAction); + const isActionVisibleOnMoneyReport = isActionVisibleOnMoneyRequestReport(reportAction); return ( - isChatAction && + isActionVisibleOnMoneyReport && (isOffline || isDeletedParentAction(reportAction) || reportAction.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE || reportAction.errors) && shouldReportActionBeVisible(reportAction, reportAction.reportActionID, canPerformWriteAction) ); @@ -137,23 +148,137 @@ function MoneyRequestReportActionsList({report, reportActions = [], hasNewerActi loadOlderChats(false); }, [loadOlderChats]); - const shouldUseThreadDividerLine = useMemo(() => { - const topReport = reportActions.length > 0 ? reportActions.at(reportActions.length - 1) : null; + const reportActionSize = useRef(visibleReportActions.length); + const lastAction = visibleReportActions.at(-1); + const lastActionIndex = lastAction?.reportActionID; + const previousLastIndex = useRef(lastActionIndex); - if (topReport && topReport.actionName !== CONST.REPORT.ACTIONS.TYPE.CREATED) { - return false; - } + const scrollingVerticalOffset = useRef(0); + const readActionSkipped = useRef(false); + const lastVisibleActionCreated = getReportLastVisibleActionCreated(report, transactionThreadReport); + const hasNewestReportAction = lastAction?.created === lastVisibleActionCreated; + const hasNewestReportActionRef = useRef(hasNewestReportAction); - if (isTransactionThread(parentReportAction)) { - return !isDeletedParentAction(parentReportAction) && !isReversedTransaction(parentReportAction); + useEffect(() => { + if ( + scrollingVerticalOffset.current < AUTOSCROLL_TO_TOP_THRESHOLD && + previousLastIndex.current !== lastActionIndex && + reportActionSize.current > reportActions.length && + hasNewestReportAction + ) { + setIsFloatingMessageCounterVisible(false); + reportScrollManager.scrollToEnd(); } - if (isTaskReport(report)) { - return !isCanceledTaskReport(report, parentReportAction); + previousLastIndex.current = lastActionIndex; + reportActionSize.current = visibleReportActions.length; + hasNewestReportActionRef.current = hasNewestReportAction; + }, [lastActionIndex, reportActions, reportScrollManager, hasNewestReportAction, visibleReportActions.length]); + + const prevUnreadMarkerReportActionID = useRef(null); + + const visibleActionsMap = useMemo(() => { + return visibleReportActions.reduce((actionsMap, reportAction) => { + Object.assign(actionsMap, {[reportAction.reportActionID]: reportAction}); + return actionsMap; + }, {} as OnyxTypes.ReportActions); + }, [visibleReportActions]); + const prevVisibleActionsMap = usePrevious(visibleActionsMap); + + /** + * The timestamp for the unread marker. + * + * This should ONLY be updated when the user + * - switches reports + * - marks a message as read/unread + * - reads a new message as it is received + */ + const [unreadMarkerTime, setUnreadMarkerTime] = useState(report.lastReadTime); + useEffect(() => { + setUnreadMarkerTime(report.lastReadTime); + + // eslint-disable-next-line react-compiler/react-compiler, react-hooks/exhaustive-deps + }, [report.reportID]); + + /** + * The index of the earliest message that was received while offline + */ + const earliestReceivedOfflineMessageIndex = useMemo(() => { + const lastIndex = reportActions.findLastIndex((action) => { + return wasMessageReceivedWhileOffline(action, isOffline, lastOfflineAt.current, lastOnlineAt.current, preferredLocale); + }); + + // The last index in the list is the earliest message that was received while offline + return lastIndex > -1 ? lastIndex : undefined; + }, [isOffline, lastOfflineAt, lastOnlineAt, preferredLocale, reportActions]); + + /** + * TODO extract as reusable logic from ReportActionsList - https://github.com/Expensify/App/issues/58891 + */ + const unreadMarkerReportActionID = useMemo(() => { + const shouldDisplayNewMarker = (message: OnyxTypes.ReportAction, index: number): boolean => { + const nextMessage = visibleReportActions.at(index + 1); + const isNextMessageUnread = !!nextMessage && isReportActionUnread(nextMessage, unreadMarkerTime); + + // If the current message is the earliest message received while offline, we want to display the unread marker above this message. + const isEarliestReceivedOfflineMessage = index === earliestReceivedOfflineMessageIndex; + if (isEarliestReceivedOfflineMessage && !isNextMessageUnread) { + return true; + } + + // If the unread marker should be hidden or is not within the visible area, don't show the unread marker. + if (shouldHideNewMarker(message)) { + return false; + } + + const isCurrentMessageUnread = isReportActionUnread(message, unreadMarkerTime); + + // If the current message is read or the next message is unread, don't show the unread marker. + if (!isCurrentMessageUnread || isNextMessageUnread) { + return false; + } + + const isPendingAdd = (action: OnyxTypes.ReportAction) => { + return action?.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD; + }; + + // If no unread marker exists, don't set an unread marker for newly added messages from the current user. + const isFromCurrentUser = currentUserAccountID === (isReportPreviewAction(message) ? message.childLastActorAccountID : message.actorAccountID); + const isNewMessage = !prevVisibleActionsMap[message.reportActionID]; + + // The unread marker will show if the action's `created` time is later than `unreadMarkerTime`. + // The `unreadMarkerTime` has already been updated to match the optimistic action created time, + // but once the new action is saved on the backend, the actual created time will be later than the optimistic one. + // Therefore, we also need to prevent the unread marker from appearing for previously optimistic actions. + const isPreviouslyOptimistic = + (isPendingAdd(prevVisibleActionsMap[message.reportActionID]) && !isPendingAdd(message)) || + (!!prevVisibleActionsMap[message.reportActionID]?.isOptimisticAction && !message.isOptimisticAction); + const shouldIgnoreUnreadForCurrentUserMessage = !prevUnreadMarkerReportActionID.current && isFromCurrentUser && (isNewMessage || isPreviouslyOptimistic); + + if (isFromCurrentUser) { + return !shouldIgnoreUnreadForCurrentUserMessage; + } + + return !isNewMessage || scrollingVerticalOffset.current >= CONST.REPORT.ACTIONS.ACTION_VISIBLE_THRESHOLD; + }; + + // If there are message that were recevied while offline, + // we can skip checking all messages later than the earliest recevied offline message. + const startIndex = earliestReceivedOfflineMessageIndex ?? 0; + + // Scan through each visible report action until we find the appropriate action to show the unread marker + for (let index = startIndex; index < visibleReportActions.length; index++) { + const reportAction = visibleReportActions.at(index); + + // eslint-disable-next-line react-compiler/react-compiler + if (reportAction && shouldDisplayNewMarker(reportAction, index)) { + return reportAction.reportActionID; + } } - return isExpenseReport(report) || isIOUReport(report) || isInvoiceReport(report); - }, [parentReportAction, report, reportActions]); + return null; + }, [currentUserAccountID, earliestReceivedOfflineMessageIndex, prevVisibleActionsMap, visibleReportActions, unreadMarkerTime]); + prevUnreadMarkerReportActionID.current = unreadMarkerReportActionID; const renderItem = useCallback( ({item: reportAction, index}: ListRenderItemInfo) => { @@ -172,38 +297,91 @@ function MoneyRequestReportActionsList({report, reportActions = [], hasNewerActi transactionThreadReport={transactionThreadReport} displayAsGroup={displayAsGroup} mostRecentIOUReportActionID={mostRecentIOUReportActionID} - shouldDisplayNewMarker={false} - shouldHideThreadDividerLine - shouldUseThreadDividerLine={shouldUseThreadDividerLine} + shouldDisplayNewMarker={reportAction.reportActionID === unreadMarkerReportActionID} shouldDisplayReplyDivider={visibleReportActions.length > 1} isFirstVisibleReportAction={firstVisibleReportActionID === reportAction.reportActionID} + shouldHideThreadDividerLine /> ); }, - [visibleReportActions, reportActions, parentReportAction, report, transactionThreadReport, mostRecentIOUReportActionID, shouldUseThreadDividerLine, firstVisibleReportActionID], + [visibleReportActions, reportActions, parentReportAction, report, transactionThreadReport, mostRecentIOUReportActionID, unreadMarkerReportActionID, firstVisibleReportActionID], ); + const scrollToBottomAndMarkReportAsRead = useCallback(() => { + setIsFloatingMessageCounterVisible(false); + + if (!hasNewestReportAction) { + Navigation.navigate(ROUTES.REPORT_WITH_ID.getRoute(report.reportID)); + openReport(report.reportID); + reportScrollManager.scrollToEnd(); + return; + } + + reportScrollManager.scrollToEnd(); + readActionSkipped.current = false; + readNewestAction(report.reportID); + }, [report.reportID, reportScrollManager, hasNewestReportAction]); + + /** + * Todo - extract to reusable logic - https://github.com/Expensify/App/issues/58891 + * Show/hide the new floating message counter when user is scrolling back/forth in the history of messages. + */ + const handleUnreadFloatingButton = () => { + if (scrollingVerticalOffset.current > CONST.REPORT.ACTIONS.SCROLL_VERTICAL_OFFSET_THRESHOLD && !isFloatingMessageCounterVisible && !!unreadMarkerReportActionID) { + setIsFloatingMessageCounterVisible(true); + } + + if (scrollingVerticalOffset.current < CONST.REPORT.ACTIONS.SCROLL_VERTICAL_OFFSET_THRESHOLD && isFloatingMessageCounterVisible) { + if (readActionSkipped.current) { + readActionSkipped.current = false; + readNewestAction(report.reportID); + } + setIsFloatingMessageCounterVisible(false); + } + }; + + const reportHasComments = visibleReportActions.length > 0; + const trackVerticalScrolling = (event: NativeSyntheticEvent) => { + scrollingVerticalOffset.current = event.nativeEvent.contentOffset.y; + handleUnreadFloatingButton(); + }; + return ( - - {isEmpty(visibleReportActions) && isEmpty(transactions) ? ( - - ) : ( - item.reportActionID} - initialNumToRender={10} - onEndReached={onEndReached} - onEndReachedThreshold={0.75} - onStartReached={onStartReached} - onStartReachedThreshold={0.75} - ListHeaderComponent={} - keyboardShouldPersistTaps="handled" + + + - )} + {isEmpty(visibleReportActions) && isEmpty(transactions) ? ( + + ) : ( + item.reportActionID} + onEndReached={onEndReached} + onEndReachedThreshold={0.75} + onStartReached={onStartReached} + onStartReachedThreshold={0.75} + ListHeaderComponent={ + + } + keyboardShouldPersistTaps="handled" + onScroll={trackVerticalScrolling} + ref={reportScrollManager.ref} + /> + )} + ); } diff --git a/src/components/MoneyRequestReportView/MoneyRequestReportTableHeader.tsx b/src/components/MoneyRequestReportView/MoneyRequestReportTableHeader.tsx index dda1b20ae29d..68b7073501e9 100644 --- a/src/components/MoneyRequestReportView/MoneyRequestReportTableHeader.tsx +++ b/src/components/MoneyRequestReportView/MoneyRequestReportTableHeader.tsx @@ -1,11 +1,9 @@ import React from 'react'; import {View} from 'react-native'; -import type {SortOrder} from '@components/Search/types'; +import type {SortOrder, TableColumnSize} from '@components/Search/types'; import SortableTableHeader from '@components/SelectionList/SortableTableHeader'; import type {SortableColumnName} from '@components/SelectionList/types'; -import useStyleUtils from '@hooks/useStyleUtils'; import useThemeStyles from '@hooks/useThemeStyles'; -import variables from '@styles/variables'; import CONST from '@src/CONST'; import type {TranslationPaths} from '@src/languages/types'; @@ -57,22 +55,22 @@ type SearchTableHeaderProps = { sortBy?: SortableColumnName; sortOrder?: SortOrder; onSortPress: (column: SortableColumnName, order: SortOrder) => void; + dateColumnSize: TableColumnSize; shouldShowSorting: boolean; }; // At this moment with new Report View we have no extra logic for displaying columns const shouldShowColumn = () => true; -function MoneyRequestReportTableHeader({sortBy, sortOrder, onSortPress, shouldShowSorting}: SearchTableHeaderProps) { +function MoneyRequestReportTableHeader({sortBy, sortOrder, onSortPress, dateColumnSize, shouldShowSorting}: SearchTableHeaderProps) { const styles = useThemeStyles(); - const StyleUtils = useStyleUtils(); return ( - + transaction[getTransactionKey(transaction, key)] === firstValidTransaction[keyOfFirstValidTransaction]); }; -function MoneyRequestReportTransactionList({transactions}: MoneyRequestReportTransactionListProps) { +function MoneyRequestReportTransactionList({report, transactions, reportActions, hasComments}: MoneyRequestReportTransactionListProps) { const styles = useThemeStyles(); + const {translate} = useLocalize(); const {shouldUseNarrowLayout, isMediumScreenWidth} = useResponsiveLayout(); const displayNarrowVersion = isMediumScreenWidth || shouldUseNarrowLayout; + const {totalDisplaySpend, nonReimbursableSpend, reimbursableSpend} = getMoneyRequestSpendBreakdown(report); + const formattedOutOfPocketAmount = convertToDisplayString(reimbursableSpend, report?.currency); + const formattedCompanySpendAmount = convertToDisplayString(nonReimbursableSpend, report?.currency); + const shouldShowBreakdown = !!nonReimbursableSpend && !!reimbursableSpend; + + const {bind} = useHover(); + const {isMouseDownOnInput, setMouseUp} = useMouseContext(); + + const handleMouseLeave = (e: React.MouseEvent) => { + bind.onMouseLeave(); + e.stopPropagation(); + setMouseUp(); + }; + const [sortedData, setSortedData] = useState({ transactions, sortBy: CONST.SEARCH.TABLE_COLUMNS.DATE, - sortOrder: CONST.SEARCH.SORT_ORDER.DESC, + sortOrder: CONST.SEARCH.SORT_ORDER.ASC, }); const {sortBy, sortOrder} = sortedData; @@ -74,6 +111,35 @@ function MoneyRequestReportTransactionList({transactions}: MoneyRequestReportTra })); }, [sortBy, sortOrder, transactions]); + const navigateToTransaction = useCallback( + (activeTransaction: OnyxTypes.Transaction) => { + const iouAction = getIOUActionForTransactionID(reportActions, activeTransaction.transactionID); + const reportIDToNavigate = iouAction?.childReportID; + if (!reportIDToNavigate) { + return; + } + + const backTo = Navigation.getActiveRoute(); + + // Single transaction report will open in RHP, and we need to find every other report ID for the rest of transactions + // to display prev/next arrows in RHP for navigating between transactions + const sortedSiblingTransactionReportIDs = getThreadReportIDsForTransactions(reportActions, sortedData.transactions); + setActiveTransactionReportIDs(sortedSiblingTransactionReportIDs); + + Navigation.navigate(ROUTES.SEARCH_REPORT.getRoute({reportID: reportIDToNavigate, backTo})); + }, + [reportActions, sortedData.transactions], + ); + + const dateColumnSize = useMemo(() => { + const shouldShowYearForSomeTransaction = transactions.some((transaction) => shouldShowTransactionYear(transaction)); + return shouldShowYearForSomeTransaction ? CONST.SEARCH.TABLE_COLUMN_SIZES.WIDE : CONST.SEARCH.TABLE_COLUMN_SIZES.NORMAL; + }, [transactions]); + + const pressableStyle = [styles.overflowHidden]; + + const listHorizontalPadding = styles.ph5; + return !isEmpty(transactions) ? ( <> {!displayNarrowVersion && ( @@ -81,6 +147,7 @@ function MoneyRequestReportTransactionList({transactions}: MoneyRequestReportTra shouldShowSorting sortBy={sortBy} sortOrder={sortOrder} + dateColumnSize={dateColumnSize} onSortPress={(selectedSortBy, selectedSortOrder) => { if (!isSortableColumnName(selectedSortBy)) { return; @@ -90,21 +157,71 @@ function MoneyRequestReportTransactionList({transactions}: MoneyRequestReportTra }} /> )} - + {sortedData.transactions.map((transaction) => { return ( - + { + if (isMouseDownOnInput) { + e?.stopPropagation(); + return; + } + + navigateToTransaction(transaction); + }} + accessibilityLabel={translate('iou.viewDetails')} + role={getButtonRole(true)} + isNested + hoverDimmingValue={1} + onMouseDown={(e) => e.preventDefault()} + id={transaction.transactionID} + style={[pressableStyle]} + onMouseLeave={handleMouseLeave} + > - + ); })} + {shouldShowBreakdown && ( + + {[ + {text: translate('cardTransactions.outOfPocket'), value: formattedOutOfPocketAmount}, + {text: translate('cardTransactions.companySpend'), value: formattedCompanySpendAmount}, + ].map(({text, value}) => ( + + + {text} + + + {value} + + + ))} + + )} + + {hasComments ? translate('common.comments') : ''} + + {translate('common.total')} + + {convertToDisplayString(totalDisplaySpend, report?.currency)} + + + ) : ( diff --git a/src/components/MoneyRequestReportView/MoneyRequestReportTransactionsNavigation.tsx b/src/components/MoneyRequestReportView/MoneyRequestReportTransactionsNavigation.tsx new file mode 100644 index 000000000000..f5dcc9536a47 --- /dev/null +++ b/src/components/MoneyRequestReportView/MoneyRequestReportTransactionsNavigation.tsx @@ -0,0 +1,116 @@ +import {findFocusedRoute} from '@react-navigation/native'; +import React, {useMemo} from 'react'; +import Icon from '@components/Icon'; +import * as Expensicons from '@components/Icon/Expensicons'; +import PressableWithFeedback from '@components/Pressable/PressableWithFeedback'; +import useTheme from '@hooks/useTheme'; +import useThemeStyles from '@hooks/useThemeStyles'; +import {isFullScreenName} from '@navigation/helpers/isNavigatorName'; +import Navigation from '@navigation/Navigation'; +import navigationRef from '@navigation/navigationRef'; +import type {RootNavigatorParamList, State} from '@navigation/types'; +import CONST from '@src/CONST'; +import ROUTES from '@src/ROUTES'; +import SCREENS from '@src/SCREENS'; +import {getActiveTransactionReportIDs} from './TransactionReportIDRepository'; + +type MoneyRequestReportRHPNavigationButtonsProps = { + currentReportID: string; +}; + +/** + * We only want to show the extra navigation for switching between transactions + * If a transaction was opened from MoneyRequestReportView + */ +function shouldShowTransactionNavigation(rootState?: State) { + const lastFullscreenNavigator = rootState?.routes.findLast((route) => isFullScreenName(route.name)); + if (lastFullscreenNavigator?.state) { + const focusedRoute = findFocusedRoute(lastFullscreenNavigator.state); + return focusedRoute?.name === SCREENS.SEARCH.MONEY_REQUEST_REPORT; + } +} + +function MoneyRequestReportTransactionsNavigation({currentReportID}: MoneyRequestReportRHPNavigationButtonsProps) { + const styles = useThemeStyles(); + const theme = useTheme(); + + const rootState = navigationRef.getRootState() as State; + const shouldShow = shouldShowTransactionNavigation(rootState); + + const reportIDsList = getActiveTransactionReportIDs(); + const {prevReportID, nextReportID} = useMemo(() => { + if (!reportIDsList) { + return {prevReportID: undefined, nextReportID: undefined}; + } + + const currentReportIndex = reportIDsList.findIndex((id) => id === currentReportID); + + const prevID = currentReportIndex > 0 ? reportIDsList.at(currentReportIndex - 1) : undefined; + const nextID = currentReportIndex <= reportIDsList.length - 1 ? reportIDsList.at(currentReportIndex + 1) : undefined; + + return {prevReportID: prevID, nextReportID: nextID}; + }, [currentReportID, reportIDsList]); + + const backTo = Navigation.getActiveRoute(); + + if (!shouldShow || reportIDsList.length < 2) { + return; + } + + const pressableStyle = [ + styles.ml1, + styles.alignItemsCenter, + styles.justifyContentCenter, + { + borderRadius: 50, + width: 28, + height: 28, + backgroundColor: theme.borderLighter, + }, + ]; + + return ( + <> + { + e?.preventDefault(); + Navigation.navigate(ROUTES.SEARCH_REPORT.getRoute({reportID: prevReportID, backTo}), {forceReplace: true}); + }} + > + + + { + e?.preventDefault(); + Navigation.navigate(ROUTES.SEARCH_REPORT.getRoute({reportID: nextReportID, backTo}), {forceReplace: true}); + }} + > + + + + ); +} + +MoneyRequestReportTransactionsNavigation.displayName = 'MoneyRequestReportTransactionsNavigation'; + +export default MoneyRequestReportTransactionsNavigation; diff --git a/src/components/MoneyRequestReportView/MoneyRequestReportView.tsx b/src/components/MoneyRequestReportView/MoneyRequestReportView.tsx index dcf75ce9ea1d..f53fa8f19e89 100644 --- a/src/components/MoneyRequestReportView/MoneyRequestReportView.tsx +++ b/src/components/MoneyRequestReportView/MoneyRequestReportView.tsx @@ -4,6 +4,9 @@ import type {OnyxEntry} from 'react-native-onyx'; import {useOnyx} from 'react-native-onyx'; import HeaderGap from '@components/HeaderGap'; import MoneyReportHeader from '@components/MoneyReportHeader'; +import ReportActionsSkeletonView from '@components/ReportActionsSkeletonView'; +import ReportHeaderSkeletonView from '@components/ReportHeaderSkeletonView'; +import useNetwork from '@hooks/useNetwork'; import usePaginatedReportActions from '@hooks/usePaginatedReportActions'; import useThemeStyles from '@hooks/useThemeStyles'; import getNonEmptyStringOnyxID from '@libs/getNonEmptyStringOnyxID'; @@ -12,6 +15,8 @@ import {canEditReportAction, getReportOfflinePendingActionAndErrors} from '@libs import Navigation from '@navigation/Navigation'; import ReportFooter from '@pages/home/report/ReportFooter'; import ONYXKEYS from '@src/ONYXKEYS'; +import type {Route} from '@src/ROUTES'; +import type {ThemeStyles} from '@src/styles'; import type * as OnyxTypes from '@src/types/onyx'; import MoneyRequestReportActionsList from './MoneyRequestReportActionsList'; @@ -27,8 +32,22 @@ type MoneyRequestReportViewProps = { /** Whether Report footer (that includes Composer) should be displayed */ shouldDisplayReportFooter: boolean; + + /** The `backTo` route that should be used when clicking back button */ + backToRoute: Route | undefined; }; +function InitialLoadingSkeleton({styles}: {styles: ThemeStyles}) { + return ( + + + {}} /> + + + + ); +} + function getParentReportAction(parentReportActions: OnyxEntry, parentReportActionID: string | undefined): OnyxEntry { if (!parentReportActions || !parentReportActionID) { return; @@ -36,21 +55,16 @@ function getParentReportAction(parentReportActions: OnyxEntry {}; - -function MoneyRequestReportView({report, policy, reportMetadata, shouldDisplayReportFooter}: MoneyRequestReportViewProps) { +function MoneyRequestReportView({report, policy, reportMetadata, shouldDisplayReportFooter, backToRoute}: MoneyRequestReportViewProps) { const styles = useThemeStyles(); + const {isOffline} = useNetwork(); const reportID = report?.reportID; + const [isLoadingApp] = useOnyx(ONYXKEYS.IS_LOADING_APP); const [isComposerFullSize] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT_IS_COMPOSER_FULL_SIZE}${reportID}`, {initialValue: false}); const {reportPendingAction} = getReportOfflinePendingActionAndErrors(report); - const { - reportActions, - hasNewerActions, - hasOlderActions, - // sortedAllReportActions, - } = usePaginatedReportActions(reportID); + const {reportActions, hasNewerActions, hasOlderActions} = usePaginatedReportActions(reportID); const [parentReportAction] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${getNonEmptyStringOnyxID(report?.parentReportID)}`, { canEvict: false, @@ -58,6 +72,15 @@ function MoneyRequestReportView({report, policy, reportMetadata, shouldDisplayRe }); const lastReportAction = [...reportActions, parentReportAction].find((action) => canEditReportAction(action) && !isMoneyRequestAction(action)); + const isLoadingInitialReportActions = reportMetadata?.isLoadingInitialReportActions; + + if (isLoadingInitialReportActions && reportActions.length === 0 && !isOffline) { + return ; + } + + if (reportActions.length === 0) { + return ; + } if (!report) { return; @@ -66,26 +89,32 @@ function MoneyRequestReportView({report, policy, reportMetadata, shouldDisplayRe return ( - { - Navigation.goBack(); - }} - /> - + {!isLoadingApp ? ( + { + Navigation.goBack(backToRoute); + }} + /> + ) : ( + + )} + {!isLoadingApp ? ( + + ) : ( + + )} {shouldDisplayReportFooter ? ( ); diff --git a/src/components/MoneyRequestReportView/TransactionReportIDRepository.ts b/src/components/MoneyRequestReportView/TransactionReportIDRepository.ts new file mode 100644 index 000000000000..1e8469d81f24 --- /dev/null +++ b/src/components/MoneyRequestReportView/TransactionReportIDRepository.ts @@ -0,0 +1,20 @@ +const transactionReportIDs: string[] = []; +/** + * When single transaction report is displayed in RHP it may need extra context when user navigated to it from MoneyRequestReportView + * This context are the list of "sibling" report ids. + * These "siblings" are child report IDs of every transaction connected to the same parent Report that the original transaction. + * + * This is a super simple storage to keep these ids. It's implemented as a singleton because we can only ever have 1 RHP opened with report screen. + */ + +function setActiveTransactionReportIDs(ids: string[]) { + // Cleaning previously saved keys because + transactionReportIDs.splice(0, Infinity); + transactionReportIDs.push(...ids); +} + +function getActiveTransactionReportIDs() { + return transactionReportIDs; +} + +export {setActiveTransactionReportIDs, getActiveTransactionReportIDs}; diff --git a/src/components/Search/SearchList.tsx b/src/components/Search/SearchList.tsx index 0ff09ffac782..7658dfd4a745 100644 --- a/src/components/Search/SearchList.tsx +++ b/src/components/Search/SearchList.tsx @@ -299,7 +299,7 @@ function SearchList( return ( {canSelectMultiple && ( - + ; type ChatSearchStatus = ValueOf; type SearchStatus = ExpenseSearchStatus | InvoiceSearchStatus | TripSearchStatus | ChatSearchStatus | Array; type SearchGroupBy = ValueOf; +type TableColumnSize = ValueOf; type SearchContext = { currentSearchHash: number; @@ -162,4 +163,5 @@ export type { SearchAutocompleteResult, PaymentData, SearchAutocompleteQueryRange, + TableColumnSize, }; diff --git a/src/components/SelectionList/SearchTableHeader.tsx b/src/components/SelectionList/SearchTableHeader.tsx index 14166ddf1fdb..a722f012adf6 100644 --- a/src/components/SelectionList/SearchTableHeader.tsx +++ b/src/components/SelectionList/SearchTableHeader.tsx @@ -134,7 +134,7 @@ function SearchTableHeader({data, metadata, sortBy, sortOrder, onSortPress, shou ; shouldShowColumn: (columnName: SortableColumnName) => boolean; onSortPress: (column: SortableColumnName, order: SortOrder) => void; @@ -46,12 +46,12 @@ function SortableTableHeader({columns, sortBy, sortOrder, shouldShowColumn, date return ( onSortPress(columnName, order)} /> diff --git a/src/components/TransactionItemRow/DataCells/TypeCell.tsx b/src/components/TransactionItemRow/DataCells/TypeCell.tsx index 6da5f339e0ee..46d517984bcc 100644 --- a/src/components/TransactionItemRow/DataCells/TypeCell.tsx +++ b/src/components/TransactionItemRow/DataCells/TypeCell.tsx @@ -2,9 +2,11 @@ import React from 'react'; import Icon from '@components/Icon'; import * as Expensicons from '@components/Icon/Expensicons'; import TextWithTooltip from '@components/TextWithTooltip'; +import useLocalize from '@hooks/useLocalize'; import useTheme from '@hooks/useTheme'; import useThemeStyles from '@hooks/useThemeStyles'; import CONST from '@src/CONST'; +import type {TranslationPaths} from '@src/languages/types'; import type TransactionDataCellProps from './TransactionDataCellProps'; // If the transaction is cash, it has the type CONST.EXPENSE.TYPE.CASH_CARD_NAME. @@ -23,18 +25,19 @@ const getTypeIcon = (type?: string) => { } }; -const getTypeText = (type?: string) => { +const getTypeText = (type?: string): TranslationPaths => { switch (type) { case CONST.EXPENSE.TYPE.CASH_CARD_NAME: - return 'Cash'; + return 'iou.cash'; case undefined: - return 'Cash'; + return 'iou.cash'; default: - return 'CreditCard'; + return 'iou.card'; } }; function TypeCell({transactionItem, shouldUseNarrowLayout, shouldShowTooltip}: TransactionDataCellProps) { + const {translate} = useLocalize(); const theme = useTheme(); const typeIcon = getTypeIcon(transactionItem.cardName); const typeText = getTypeText(transactionItem.cardName); @@ -43,7 +46,7 @@ function TypeCell({transactionItem, shouldUseNarrowLayout, shouldShowTooltip}: T return shouldUseNarrowLayout ? ( ) : ( diff --git a/src/components/TransactionItemRow/index.tsx b/src/components/TransactionItemRow/index.tsx index 3ba1b8ead2f6..b29fbaa9a274 100644 --- a/src/components/TransactionItemRow/index.tsx +++ b/src/components/TransactionItemRow/index.tsx @@ -1,6 +1,7 @@ import React from 'react'; import {View} from 'react-native'; import Hoverable from '@components/Hoverable'; +import type {TableColumnSize} from '@components/Search/types'; import Text from '@components/Text'; import useStyleUtils from '@hooks/useStyleUtils'; import useThemeStyles from '@hooks/useThemeStyles'; @@ -21,12 +22,14 @@ function TransactionItemRow({ shouldUseNarrowLayout, isSelected, shouldShowTooltip, + dateColumnSize, shouldShowChatBubbleComponent = false, }: { transactionItem: Transaction; shouldUseNarrowLayout: boolean; isSelected: boolean; shouldShowTooltip: boolean; + dateColumnSize: TableColumnSize; shouldShowChatBubbleComponent?: boolean; }) { const styles = useThemeStyles(); @@ -35,6 +38,8 @@ function TransactionItemRow({ const backgroundColor = isSelected ? styles.buttonDefaultBG : styles.highlightBG; const hasCategoryOrTag = !!transactionItem.category || !!transactionItem.tag; + const isDateColumnWide = dateColumnSize === CONST.SEARCH.TABLE_COLUMN_SIZES.WIDE; + return ( {shouldUseNarrowLayout ? ( @@ -102,7 +107,7 @@ function TransactionItemRow({ ) : ( {(hovered) => ( - + - + { if (!flatListRef?.current) { @@ -32,7 +33,18 @@ function useReportScrollManager(): ReportScrollManagerData { flatListRef.current?.scrollToOffset({animated: false, offset: 0}); }, [flatListRef, setScrollPosition]); - return {ref: flatListRef, scrollToIndex, scrollToBottom}; + /** + * Scroll to the end of the FlatList. + */ + const scrollToEnd = useCallback(() => { + if (!flatListRef?.current) { + return; + } + + flatListRef.current.scrollToEnd({animated: false}); + }, [flatListRef]); + + return {ref: flatListRef, scrollToIndex, scrollToBottom, scrollToEnd}; } export default useReportScrollManager; diff --git a/src/hooks/useReportScrollManager/index.ts b/src/hooks/useReportScrollManager/index.ts index eb68f52fc760..b8e6798e75ee 100644 --- a/src/hooks/useReportScrollManager/index.ts +++ b/src/hooks/useReportScrollManager/index.ts @@ -20,7 +20,8 @@ function useReportScrollManager(): ReportScrollManagerData { ); /** - * Scroll to the bottom of the flatlist. + * Scroll to the bottom of the inverted FlatList. + * When FlatList is inverted it's "bottom" is really it's top */ const scrollToBottom = useCallback(() => { if (!flatListRef?.current) { @@ -30,7 +31,18 @@ function useReportScrollManager(): ReportScrollManagerData { flatListRef.current.scrollToOffset({animated: false, offset: 0}); }, [flatListRef]); - return {ref: flatListRef, scrollToIndex, scrollToBottom}; + /** + * Scroll to the end of the FlatList. + */ + const scrollToEnd = useCallback(() => { + if (!flatListRef?.current) { + return; + } + + flatListRef.current.scrollToEnd({animated: false}); + }, [flatListRef]); + + return {ref: flatListRef, scrollToIndex, scrollToBottom, scrollToEnd}; } export default useReportScrollManager; diff --git a/src/hooks/useReportScrollManager/types.ts b/src/hooks/useReportScrollManager/types.ts index 5182f7269a9c..7d6d096de16d 100644 --- a/src/hooks/useReportScrollManager/types.ts +++ b/src/hooks/useReportScrollManager/types.ts @@ -4,6 +4,7 @@ type ReportScrollManagerData = { ref: FlatListRefType; scrollToIndex: (index: number, isEditing?: boolean) => void; scrollToBottom: () => void; + scrollToEnd: () => void; }; export default ReportScrollManagerData; diff --git a/src/languages/en.ts b/src/languages/en.ts index 48a9842a7cd9..bc236a3630f7 100755 --- a/src/languages/en.ts +++ b/src/languages/en.ts @@ -530,6 +530,7 @@ const translations = { help: 'Help', expenseReports: 'Expense Reports', rateOutOfPolicy: 'Rate out of policy', + comments: 'Comments', }, supportalNoAccess: { title: 'Not so fast', diff --git a/src/languages/es.ts b/src/languages/es.ts index 47ac36ce01bf..29b0a38a4525 100644 --- a/src/languages/es.ts +++ b/src/languages/es.ts @@ -521,6 +521,7 @@ const translations = { help: 'Ayuda', expenseReports: 'Informes de Gastos', rateOutOfPolicy: 'Tasa fuera de póliza', + comments: 'Comentarios', }, supportalNoAccess: { title: 'No tan rápido', diff --git a/src/libs/API/parameters/OpenReportParams.ts b/src/libs/API/parameters/OpenReportParams.ts index a665313580e8..bf5105128794 100644 --- a/src/libs/API/parameters/OpenReportParams.ts +++ b/src/libs/API/parameters/OpenReportParams.ts @@ -15,6 +15,12 @@ type OpenReportParams = { optimisticAccountIDList?: string; file?: File | CustomRNImageManipulatorResult; guidedSetupData?: string; + /** + * This flag decides in what order should the api return report actions, and it's used by MoneyRequestReportView + * By default api returns report actions newest-first, and then older ones on subsequent pagination calls. + * If this flag is set to true, api will return oldest first starting from the beginning of report. + */ + useTableReportView?: boolean; }; export default OpenReportParams; diff --git a/src/libs/MoneyRequestReportUtils.ts b/src/libs/MoneyRequestReportUtils.ts new file mode 100644 index 000000000000..27105202ca06 --- /dev/null +++ b/src/libs/MoneyRequestReportUtils.ts @@ -0,0 +1,42 @@ +import CONST from '@src/CONST'; +import type {OriginalMessageIOU, ReportAction, Transaction} from '@src/types/onyx'; +import {getIOUActionForTransactionID, getOriginalMessage, isMoneyRequestAction} from './ReportActionsUtils'; + +/** + * In MoneyRequestReport we filter out some IOU action types, because expense/transaction data is displayed in a separate list + * at the top + */ +const IOU_ACTIONS_TO_FILTER_OUT: Array = [CONST.IOU.REPORT_ACTION_TYPE.CREATE, CONST.IOU.REPORT_ACTION_TYPE.TRACK]; + +/** + * Returns whether a specific action should be displayed in the feed/message list on MoneyRequestReportView. + * + * In MoneyRequestReport we filter out some action types, because expense/transaction data is displayed in a separate list + * at the top the report, instead of in-between the rest of messages like in normal chat. + * Because of that several action types are not relevant to this ReportView and should not be shown. + */ +function isActionVisibleOnMoneyRequestReport(action: ReportAction) { + if (isMoneyRequestAction(action)) { + const originalMessage = getOriginalMessage(action); + return originalMessage ? !IOU_ACTIONS_TO_FILTER_OUT.includes(originalMessage.type) : false; + } + + return action.actionName !== CONST.REPORT.ACTIONS.TYPE.CREATED; +} + +/** + * Give a list of report actions and a list of transactions, + * function will return a list of reportIDs for the threads for the IOU parent action of every transaction. + * It is used in UI to allow for navigation to "sibling" transactions when opening a single transaction (report) view. + */ + +function getThreadReportIDsForTransactions(reportActions: ReportAction[], transactions: Transaction[]) { + return transactions + .map((transaction) => { + const action = getIOUActionForTransactionID(reportActions, transaction.transactionID); + return action?.childReportID; + }) + .filter((reportID): reportID is string => !!reportID); +} + +export {isActionVisibleOnMoneyRequestReport, getThreadReportIDsForTransactions}; diff --git a/src/libs/Navigation/AppNavigator/ModalStackNavigators/index.tsx b/src/libs/Navigation/AppNavigator/ModalStackNavigators/index.tsx index be40fb1e3774..5406a6e39cf8 100644 --- a/src/libs/Navigation/AppNavigator/ModalStackNavigators/index.tsx +++ b/src/libs/Navigation/AppNavigator/ModalStackNavigators/index.tsx @@ -1,6 +1,7 @@ import type {ParamListBase} from '@react-navigation/routers'; import React from 'react'; import createPlatformStackNavigator from '@libs/Navigation/PlatformStackNavigation/createPlatformStackNavigator'; +import Animations from '@libs/Navigation/PlatformStackNavigation/navigationOptions/animation'; import type { AddPersonalBankAccountNavigatorParamList, ConsoleNavigatorParamList, @@ -695,10 +696,15 @@ const TransactionDuplicateStackNavigator = createModalStackNavigator require('../../../../pages/TransactionDuplicate/Confirmation').default, }); -const SearchReportModalStackNavigator = createModalStackNavigator({ - [SCREENS.SEARCH.REPORT_RHP]: () => require('../../../../pages/home/ReportScreen').default, - [SCREENS.SEARCH.TRANSACTION_HOLD_REASON_RHP]: () => require('../../../../pages/Search/SearchHoldReasonPage').default, -}); +const SearchReportModalStackNavigator = createModalStackNavigator( + { + [SCREENS.SEARCH.REPORT_RHP]: () => require('../../../../pages/home/ReportScreen').default, + [SCREENS.SEARCH.TRANSACTION_HOLD_REASON_RHP]: () => require('../../../../pages/Search/SearchHoldReasonPage').default, + }, + () => ({ + animation: Animations.NONE, + }), +); const SearchAdvancedFiltersModalStackNavigator = createModalStackNavigator({ [SCREENS.SEARCH.ADVANCED_FILTERS_RHP]: () => require('../../../../pages/Search/SearchAdvancedFiltersPage').default, diff --git a/src/libs/Navigation/AppNavigator/ModalStackNavigators/useModalStackScreenOptions.ts b/src/libs/Navigation/AppNavigator/ModalStackNavigators/useModalStackScreenOptions.ts index 57809588b2cd..a7499cf5f7dd 100644 --- a/src/libs/Navigation/AppNavigator/ModalStackNavigators/useModalStackScreenOptions.ts +++ b/src/libs/Navigation/AppNavigator/ModalStackNavigators/useModalStackScreenOptions.ts @@ -36,7 +36,11 @@ function useModalStackScreenOptions(getScreenOptions?: GetModalStackScreenOption [cardStyleInterpolator, styles.navigationScreenCardStyle], ); - return getScreenOptions?.(styles) ?? defaultSubRouteOptions; + if (!getScreenOptions) { + return defaultSubRouteOptions; + } + + return {...defaultSubRouteOptions, ...getScreenOptions(styles)}; } export default useModalStackScreenOptions; diff --git a/src/libs/Navigation/types.ts b/src/libs/Navigation/types.ts index b6521a75b998..cc21866e55d3 100644 --- a/src/libs/Navigation/types.ts +++ b/src/libs/Navigation/types.ts @@ -1900,6 +1900,7 @@ type SearchFullscreenNavigatorParamList = { }; [SCREENS.SEARCH.MONEY_REQUEST_REPORT]: { reportID: string; + backTo?: Routes; }; }; diff --git a/src/libs/ReportActionsUtils.ts b/src/libs/ReportActionsUtils.ts index 9bfdfafb0c46..d94313b92375 100644 --- a/src/libs/ReportActionsUtils.ts +++ b/src/libs/ReportActionsUtils.ts @@ -1667,11 +1667,18 @@ function getIOUActionForReportID(reportID: string | undefined, transactionID: st } const report = allReports?.[`${ONYXKEYS.COLLECTION.REPORT}${reportID}`]; const reportActions = getAllReportActions(report?.reportID); - const action = Object.values(reportActions ?? {})?.find((reportAction) => { + + return getIOUActionForTransactionID(Object.values(reportActions ?? {}), transactionID); +} + +/** + * Get the IOU action for a transactionID from given reportActions + */ +function getIOUActionForTransactionID(reportActions: ReportAction[], transactionID: string): OnyxEntry { + return reportActions.find((reportAction) => { const IOUTransactionID = isMoneyRequestAction(reportAction) ? getOriginalMessage(reportAction)?.IOUTransactionID : undefined; return IOUTransactionID === transactionID; }); - return action; } /** @@ -2261,6 +2268,9 @@ function getReportActions(report: Report) { return allReportActions?.[`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${report.reportID}`]; } +/** + * @private + */ function wasActionCreatedWhileOffline(action: ReportAction, isOffline: boolean, lastOfflineAt: Date | undefined, lastOnlineAt: Date | undefined, locale: Locale): boolean { // The user has never gone offline or never come back online if (!lastOfflineAt || !lastOnlineAt) { @@ -2283,6 +2293,16 @@ function wasActionCreatedWhileOffline(action: ReportAction, isOffline: boolean, return false; } +/** + * Whether a message is NOT from the active user, and it was received while the user was offline. + */ +function wasMessageReceivedWhileOffline(action: ReportAction, isOffline: boolean, lastOfflineAt: Date | undefined, lastOnlineAt: Date | undefined, locale: Locale) { + const wasByCurrentUser = wasActionTakenByCurrentUser(action); + const wasCreatedOffline = wasActionCreatedWhileOffline(action, isOffline, lastOfflineAt, lastOnlineAt, locale); + + return !wasByCurrentUser && wasCreatedOffline && !(action.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD || action.isOptimisticAction); +} + export { doesReportHaveVisibleActions, extractLinksFromMessageHtml, @@ -2294,6 +2314,7 @@ export { getDismissedViolationMessageText, getFirstVisibleReportActionID, getIOUActionForReportID, + getIOUActionForTransactionID, getIOUReportIDFromReportActionPreview, getLastClosedReportAction, getLastVisibleAction, @@ -2396,7 +2417,7 @@ export { getRemovedConnectionMessage, getActionableJoinRequestPendingReportAction, getReportActionsLength, - wasActionCreatedWhileOffline, + wasMessageReceivedWhileOffline, shouldShowAddMissingDetails, getWorkspaceCategoryUpdateMessage, getWorkspaceUpdateFieldMessage, diff --git a/src/libs/SearchUIUtils.ts b/src/libs/SearchUIUtils.ts index c1f2c48ca9af..6e81cf1e618f 100644 --- a/src/libs/SearchUIUtils.ts +++ b/src/libs/SearchUIUtils.ts @@ -51,6 +51,7 @@ import { } from './ReportUtils'; import {buildCannedSearchQuery} from './SearchQueryUtils'; import {getAmount as getTransactionAmount, getCreated as getTransactionCreatedDate, getMerchant as getTransactionMerchant, isPendingCardOrScanningTransaction} from './TransactionUtils'; +import shouldShowTransactionYear from './TransactionUtils/shouldShowTransactionYear'; const columnNamesToSortingProperty = { [CONST.SEARCH.TABLE_COLUMNS.TO]: 'formattedTo' as const, @@ -226,9 +227,7 @@ function shouldShowYear(data: TransactionListItemType[] | ReportListItemType[] | for (const key in data) { if (isTransactionEntry(key)) { const item = data[key]; - const date = getTransactionCreatedDate(item); - - if (DateUtils.doesDateBelongToAPastYear(date)) { + if (shouldShowTransactionYear(item)) { return true; } } else if (isReportActionEntry(key)) { @@ -778,14 +777,14 @@ function createTypeMenuItems(allPolicies: OnyxCollection | nul return typeMenuItems; } -function createBaseSavedSearchMenuItem(item: SaveSearchItem, key: string, index: number, title: string, hash: number): SavedSearchMenuItem { +function createBaseSavedSearchMenuItem(item: SaveSearchItem, key: string, index: number, title: string, isFocused: boolean): SavedSearchMenuItem { return { key, title, hash: key, query: item.query, shouldShowRightComponent: true, - focused: Number(key) === hash, + focused: isFocused, pendingAction: item.pendingAction, disabled: item.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE, shouldIconUseAutoWidthStyle: true, diff --git a/src/libs/TransactionUtils/shouldShowTransactionYear.ts b/src/libs/TransactionUtils/shouldShowTransactionYear.ts new file mode 100644 index 000000000000..18dcd4f76c9b --- /dev/null +++ b/src/libs/TransactionUtils/shouldShowTransactionYear.ts @@ -0,0 +1,10 @@ +import DateUtils from '@libs/DateUtils'; +import type {OnyxInputOrEntry, Transaction} from '@src/types/onyx'; +import {getCreated as getTransactionCreatedDate} from './index'; + +function shouldShowTransactionYear(transaction: OnyxInputOrEntry) { + const date = getTransactionCreatedDate(transaction); + return DateUtils.doesDateBelongToAPastYear(date); +} + +export default shouldShowTransactionYear; diff --git a/src/libs/actions/Report.ts b/src/libs/actions/Report.ts index 7bdabcf4b4e2..4c150902f0e5 100644 --- a/src/libs/actions/Report.ts +++ b/src/libs/actions/Report.ts @@ -875,6 +875,7 @@ function clearAvatarErrors(reportID: string) { * @param parentReportActionID The parent report action that a thread was created from (only passed for new threads) * @param isFromDeepLink Whether or not this report is being opened from a deep link * @param participantAccountIDList The list of accountIDs that are included in a new chat, not including the user creating it + * @param temporaryShouldUseTableReportView For now MoneyRequestReportView is only supported on Search pages. Once the view is handled on ReportScreens as well we will remove this flag */ function openReport( reportID: string | undefined, @@ -885,6 +886,7 @@ function openReport( isFromDeepLink = false, participantAccountIDList: number[] = [], avatar?: File | CustomRNImageManipulatorResult, + temporaryShouldUseTableReportView = false, ) { if (!reportID) { return; @@ -954,6 +956,11 @@ function openReport( parentReportActionID, }; + // temporary flag will be removed once ReportScreen supports MoneyRequestReportView - https://github.com/Expensify/App/issues/57509 + if (temporaryShouldUseTableReportView) { + parameters.useTableReportView = true; + } + const isInviteOnboardingComplete = introSelected?.isInviteOnboardingComplete ?? false; const isOnboardingCompleted = onboarding?.hasCompletedGuidedSetupFlow ?? false; diff --git a/src/pages/Search/SearchMoneyRequestReportPage.tsx b/src/pages/Search/SearchMoneyRequestReportPage.tsx index 57ff2a38dcff..d6aa2f25b841 100644 --- a/src/pages/Search/SearchMoneyRequestReportPage.tsx +++ b/src/pages/Search/SearchMoneyRequestReportPage.tsx @@ -1,7 +1,9 @@ import {PortalHost} from '@gorhom/portal'; -import React, {useEffect} from 'react'; +import React, {useEffect, useMemo, useRef, useState} from 'react'; +import type {FlatList} from 'react-native'; import {View} from 'react-native'; import {useOnyx} from 'react-native-onyx'; +import FullPageNotFoundView from '@components/BlockingViews/FullPageNotFoundView'; import DragAndDropProvider from '@components/DragAndDrop/Provider'; import HeaderGap from '@components/HeaderGap'; import MoneyRequestReportView from '@components/MoneyRequestReportView/MoneyRequestReportView'; @@ -9,23 +11,23 @@ import BottomTabBar from '@components/Navigation/BottomTabBar'; import BOTTOM_TABS from '@components/Navigation/BottomTabBar/BOTTOM_TABS'; import TopBar from '@components/Navigation/TopBar'; import ScreenWrapper from '@components/ScreenWrapper'; -import type {SearchQueryJSON} from '@components/Search/types'; import useIsReportReadyToDisplay from '@hooks/useIsReportReadyToDisplay'; import useLocalize from '@hooks/useLocalize'; import useResponsiveLayout from '@hooks/useResponsiveLayout'; import useThemeStyles from '@hooks/useThemeStyles'; +import getNonEmptyStringOnyxID from '@libs/getNonEmptyStringOnyxID'; import type {PlatformStackScreenProps} from '@libs/Navigation/PlatformStackNavigation/types'; import type {SearchFullscreenNavigatorParamList} from '@libs/Navigation/types'; -import {buildSearchQueryJSON} from '@libs/SearchQueryUtils'; +import {isValidReportIDFromPath} from '@libs/ReportUtils'; +import Navigation from '@navigation/Navigation'; import {openReport} from '@userActions/Report'; import ONYXKEYS from '@src/ONYXKEYS'; +import {ActionListContext, ReactionListContext} from '@src/pages/home/ReportScreenContext'; +import type {ActionListContextType, ReactionListRef, ScrollPosition} from '@src/pages/home/ReportScreenContext'; import type SCREENS from '@src/SCREENS'; import SearchTypeMenu from './SearchTypeMenu'; -// We will figure out later, when this view is actually being finalized, how to pass down an actual query -const tempJSONQuery = buildSearchQueryJSON('') as unknown as SearchQueryJSON; - -type SearchPageProps = PlatformStackScreenProps; +type SearchMoneyRequestPageProps = PlatformStackScreenProps; const defaultReportMetadata = { isLoadingInitialReportActions: true, @@ -36,23 +38,49 @@ const defaultReportMetadata = { isOptimisticReport: false, }; -function SearchMoneyRequestReportPage({route}: SearchPageProps) { +function SearchMoneyRequestReportPage({route}: SearchMoneyRequestPageProps) { const {translate} = useLocalize(); const {shouldUseNarrowLayout} = useResponsiveLayout(); const styles = useThemeStyles(); - const {reportID} = route.params; - - const [report] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`, {allowStaleData: true}); - const [reportMetadata = defaultReportMetadata] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT_METADATA}${reportID}`); + const reportIDFromRoute = getNonEmptyStringOnyxID(route.params?.reportID); + const [report] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${reportIDFromRoute}`, {allowStaleData: true}); + const [reportMetadata = defaultReportMetadata] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT_METADATA}${reportIDFromRoute}`); const [policies] = useOnyx(ONYXKEYS.COLLECTION.POLICY, {allowStaleData: true, initialValue: {}}); const policy = policies?.[`${ONYXKEYS.COLLECTION.POLICY}${report?.policyID}`]; + const [isLoadingApp] = useOnyx(ONYXKEYS.IS_LOADING_APP); + + const {isEditingDisabled, isCurrentReportLoadedFromOnyx} = useIsReportReadyToDisplay(report, reportIDFromRoute); - const {isEditingDisabled, isCurrentReportLoadedFromOnyx} = useIsReportReadyToDisplay(report, reportID); + const [scrollPosition, setScrollPosition] = useState({}); + const flatListRef = useRef(null); + const reactionListRef = useRef(null); + const actionListValue = useMemo((): ActionListContextType => ({flatListRef, scrollPosition, setScrollPosition}), [flatListRef, scrollPosition, setScrollPosition]); + + const reportID = report?.reportID; useEffect(() => { - openReport(reportID); - }, [reportID]); + openReport(reportIDFromRoute, '', [], undefined, undefined, false, [], undefined, true); + }, [reportIDFromRoute]); + + // eslint-disable-next-line rulesdir/no-negated-variables + const shouldShowNotFoundPage = useMemo( + (): boolean => { + if (isLoadingApp !== false) { + return false; + } + + // eslint-disable-next-line react-compiler/react-compiler + if (!reportID && !reportMetadata?.isLoadingInitialReportActions) { + // eslint-disable-next-line react-compiler/react-compiler + return true; + } + + return !!reportID && !isValidReportIDFromPath(reportID); + }, + // eslint-disable-next-line react-compiler/react-compiler, react-hooks/exhaustive-deps + [reportID, reportMetadata?.isLoadingInitialReportActions], + ); if (shouldUseNarrowLayout) { return ( @@ -62,50 +90,76 @@ function SearchMoneyRequestReportPage({route}: SearchPageProps) { offlineIndicatorStyle={styles.mtAuto} headerGapStyles={styles.searchHeaderGap} > - + + + ); } return ( - - - - - - - - - - - - - - + + + + + + + + + + + - - - - - + + + + + + + + + + + + + + ); } diff --git a/src/pages/Search/SearchTypeMenu.tsx b/src/pages/Search/SearchTypeMenu.tsx index fed2da78092d..1cfede643771 100644 --- a/src/pages/Search/SearchTypeMenu.tsx +++ b/src/pages/Search/SearchTypeMenu.tsx @@ -36,11 +36,11 @@ import type {SaveSearchItem} from '@src/types/onyx/SaveSearch'; import SavedSearchItemThreeDotMenu from './SavedSearchItemThreeDotMenu'; type SearchTypeMenuProps = { - queryJSON: SearchQueryJSON; + queryJSON: SearchQueryJSON | undefined; }; function SearchTypeMenu({queryJSON}: SearchTypeMenuProps) { - const {type, hash} = queryJSON; + const {type, groupBy, hash} = queryJSON ?? {}; const styles = useThemeStyles(); const {singleExecution} = useSingleExecution(); const {translate} = useLocalize(); @@ -77,7 +77,9 @@ function SearchTypeMenu({queryJSON}: SearchTypeMenuProps) { title = buildUserReadableQueryString(jsonQuery, personalDetails, reports, taxRates, allCards, cardFeedNamesWithType); } - const baseMenuItem: SavedSearchMenuItem = createBaseSavedSearchMenuItem(item, key, index, title, hash); + const isItemFocused = Number(key) === hash; + const baseMenuItem: SavedSearchMenuItem = createBaseSavedSearchMenuItem(item, key, index, title, isItemFocused); + return { ...baseMenuItem, onPress: () => { @@ -168,10 +170,10 @@ function SearchTypeMenu({queryJSON}: SearchTypeMenuProps) { [styles], ); - const isCannedQuery = isCannedSearchQuery(queryJSON); + const isCannedQuery = queryJSON ? isCannedSearchQuery(queryJSON) : false; const activeItemIndex = isCannedQuery ? typeMenuItems.findIndex((item) => { - if (queryJSON.groupBy === CONST.SEARCH.GROUP_BY.REPORTS) { + if (groupBy === CONST.SEARCH.GROUP_BY.REPORTS) { return item.translationPath === 'common.expenseReports' && item.type === type; } return item.type === type; @@ -189,7 +191,7 @@ function SearchTypeMenu({queryJSON}: SearchTypeMenuProps) { const onPress = singleExecution(() => { clearAllFilters(); clearSelectedTransactions(); - Navigation.navigate(item.getRoute(queryJSON.policyID)); + Navigation.navigate(item.getRoute(queryJSON?.policyID)); }); return ( diff --git a/src/pages/home/report/ReportActionsList.tsx b/src/pages/home/report/ReportActionsList.tsx index 3f9493ef6fd5..873fe587f389 100644 --- a/src/pages/home/report/ReportActionsList.tsx +++ b/src/pages/home/report/ReportActionsList.tsx @@ -36,8 +36,7 @@ import { isReversedTransaction, isTransactionThread, shouldHideNewMarker, - wasActionCreatedWhileOffline, - wasActionTakenByCurrentUser, + wasMessageReceivedWhileOffline, } from '@libs/ReportActionsUtils'; import { canShowReportRecipientLocalTime, @@ -113,8 +112,6 @@ type ReportActionsListProps = { shouldEnableAutoScrollToTopThreshold?: boolean; }; -const VERTICAL_OFFSET_THRESHOLD = 200; -const MSG_VISIBLE_THRESHOLD = 250; const IS_CLOSE_TO_NEWEST_THRESHOLD = 15; // In the component we are subscribing to the arrival of new actions. @@ -218,16 +215,6 @@ function ReportActionsList({ }, [report.reportID]); const prevUnreadMarkerReportActionID = useRef(null); - /** - * Whether a message is NOT from the active user and it was received while the user was offline. - */ - const wasMessageReceivedWhileOffline = useCallback( - (message: OnyxTypes.ReportAction) => - !wasActionTakenByCurrentUser(message) && - wasActionCreatedWhileOffline(message, isOffline, lastOfflineAt.current, lastOnlineAt.current, preferredLocale) && - !(message.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD || message.isOptimisticAction), - [isOffline, lastOfflineAt, lastOnlineAt, preferredLocale], - ); /** * The index of the earliest message that was received while offline @@ -235,7 +222,7 @@ function ReportActionsList({ const earliestReceivedOfflineMessageIndex = useMemo(() => { // Create a list of (sorted) indices of message that were received while offline const receivedOfflineMessages = sortedReportActions.reduce((acc, message, index) => { - if (wasMessageReceivedWhileOffline(message)) { + if (wasMessageReceivedWhileOffline(message, isOffline, lastOfflineAt.current, lastOnlineAt.current, preferredLocale)) { acc[index] = index; } @@ -244,7 +231,7 @@ function ReportActionsList({ // The last index in the list is the earliest message that was received while offline return receivedOfflineMessages.at(-1); - }, [sortedReportActions, wasMessageReceivedWhileOffline]); + }, [isOffline, lastOfflineAt, lastOnlineAt, preferredLocale, sortedReportActions]); /** * The reportActionID the unread marker should display above @@ -293,7 +280,7 @@ function ReportActionsList({ return !shouldIgnoreUnreadForCurrentUserMessage; } - return !isNewMessage || scrollingVerticalOffset.current >= MSG_VISIBLE_THRESHOLD; + return !isNewMessage || scrollingVerticalOffset.current >= CONST.REPORT.ACTIONS.ACTION_VISIBLE_THRESHOLD; }; // If there are message that were recevied while offline, @@ -404,7 +391,7 @@ function ReportActionsList({ // Currently, there's no programmatic way to dismiss the notification center panel. // To handle this, we use the 'referrer' parameter to check if the current navigation is triggered from a notification. const isFromNotification = route?.params?.referrer === CONST.REFERRER.NOTIFICATION; - if ((isVisible || isFromNotification) && scrollingVerticalOffset.current < MSG_VISIBLE_THRESHOLD) { + if ((isVisible || isFromNotification) && scrollingVerticalOffset.current < CONST.REPORT.ACTIONS.ACTION_VISIBLE_THRESHOLD) { readNewestAction(report.reportID); if (isFromNotification) { Navigation.setParams({referrer: undefined}); @@ -517,11 +504,11 @@ function ReportActionsList({ * Show/hide the new floating message counter when user is scrolling back/forth in the history of messages. */ const handleUnreadFloatingButton = () => { - if (scrollingVerticalOffset.current > VERTICAL_OFFSET_THRESHOLD && !isFloatingMessageCounterVisible && !!unreadMarkerReportActionID) { + if (scrollingVerticalOffset.current > CONST.REPORT.ACTIONS.SCROLL_VERTICAL_OFFSET_THRESHOLD && !isFloatingMessageCounterVisible && !!unreadMarkerReportActionID) { setIsFloatingMessageCounterVisible(true); } - if (scrollingVerticalOffset.current < VERTICAL_OFFSET_THRESHOLD && isFloatingMessageCounterVisible) { + if (scrollingVerticalOffset.current < CONST.REPORT.ACTIONS.SCROLL_VERTICAL_OFFSET_THRESHOLD && isFloatingMessageCounterVisible) { if (readActionSkipped.current) { readActionSkipped.current = false; readNewestAction(report.reportID); @@ -611,7 +598,7 @@ function ReportActionsList({ lastMessageTime.current = null; const isArchivedReport = isArchivedNonExpenseReport(report, reportNameValuePairs); - const hasNewMessagesInView = scrollingVerticalOffset.current < MSG_VISIBLE_THRESHOLD; + const hasNewMessagesInView = scrollingVerticalOffset.current < CONST.REPORT.ACTIONS.ACTION_VISIBLE_THRESHOLD; const hasUnreadReportAction = sortedVisibleReportActions.some( (reportAction) => newMessageTimeReference && diff --git a/src/pages/home/report/ReportFooter.tsx b/src/pages/home/report/ReportFooter.tsx index 693b5bd0edbd..6220a2aec214 100644 --- a/src/pages/home/report/ReportFooter.tsx +++ b/src/pages/home/report/ReportFooter.tsx @@ -62,10 +62,10 @@ type ReportFooterProps = { isComposerFullSize?: boolean; /** A method to call when the input is focus */ - onComposerFocus: () => void; + onComposerFocus?: () => void; /** A method to call when the input is blur */ - onComposerBlur: () => void; + onComposerBlur?: () => void; }; function ReportFooter({ diff --git a/src/stories/TransactionItemRow.stories.tsx b/src/stories/TransactionItemRow.stories.tsx index 3d2965770b7f..4b7da0d0441d 100644 --- a/src/stories/TransactionItemRow.stories.tsx +++ b/src/stories/TransactionItemRow.stories.tsx @@ -56,6 +56,7 @@ function Template({transactionItem, shouldUseNarrowLayout, isSelected, shouldSho isSelected={isSelected} shouldShowTooltip={shouldShowTooltip} shouldShowChatBubbleComponent + dateColumnSize={CONST.SEARCH.TABLE_COLUMN_SIZES.NORMAL} /> diff --git a/src/stories/mockData/transactions.ts b/src/stories/mockData/transactions.ts index d0184d7e1409..5e7730a4726a 100644 --- a/src/stories/mockData/transactions.ts +++ b/src/stories/mockData/transactions.ts @@ -1,10 +1,13 @@ +/* eslint-disable @typescript-eslint/naming-convention */ import CONST from '@src/CONST'; import type {OriginalMessageIOU, PersonalDetailsList, Report, ReportAction, Transaction, TransactionViolations} from '@src/types/onyx'; const amount = 1000; const currency = 'USD'; -/* eslint-disable @typescript-eslint/naming-convention */ +const REPORT_ID_456 = 'R98765'; +const REPORT_ID_111 = '1111111111111111'; + const personalDetails: PersonalDetailsList = { 11111111: { accountID: 11111111, @@ -69,7 +72,7 @@ const personalDetails: PersonalDetailsList = { }; const iouReport: Report = { - chatReportID: '1111111111111111', + chatReportID: REPORT_ID_111, chatType: CONST.REPORT.CHAT_TYPE.POLICY_EXPENSE_CHAT, currency, description: '', @@ -156,7 +159,7 @@ const chatReport: Report = { }, permissions: ['read', 'write'], policyID: CONST.POLICY.ID_FAKE, - reportID: '1111111111111111', + reportID: REPORT_ID_111, reportName: 'Chat Report', stateNum: 0, statusNum: 0, @@ -166,7 +169,7 @@ const chatReport: Report = { unheldTotal: 0, welcomeMessage: '', writeCapability: CONST.REPORT.WRITE_CAPABILITIES.ALL, - iouReportID: '1111111111111111', + iouReportID: REPORT_ID_111, managerID: 0, }; @@ -205,6 +208,38 @@ const transaction: Transaction = { hasEReceipt: true, }; +const fakeTransaction456: Transaction = { + amount, + transactionID: 'trsx456', + bank: '', + billable: false, + cardID: 0, + cardName: 'Cash Expense', + cardNumber: '', + category: '', + comment: {}, + created: '2025-02-14', + currency, + filename: '', + inserted: '2025-02-14 08:12:19', + managedCard: false, + merchant: 'Acme', + modifiedAmount: 0, + modifiedCreated: '', + modifiedCurrency: '', + modifiedMerchant: '', + originalAmount: 0, + originalCurrency: '', + parentTransactionID: '', + posted: '', + reimbursable: true, + reportID: '111111111111111', + status: CONST.TRANSACTION.STATUS.POSTED, + tag: '', + + hasEReceipt: true, +}; + const violations: TransactionViolations = [ { name: CONST.VIOLATIONS.DUPLICATED_TRANSACTION, @@ -234,6 +269,17 @@ const originalMessage: OriginalMessageIOU = { type: 'create', }; +const fakeOriginalMessage456: OriginalMessageIOU = { + IOUReportID: 'rep456', + IOUTransactionID: 'trsx456', + amount, + comment: '', + currency, + lastModified: '2025-02-20 08:10:05.165', + participantAccountIDs: [11111111, 22222222], + type: 'create', +}; + const action: ReportAction = { reportActionID: '1111111111111111111', message: [ @@ -249,7 +295,7 @@ const action: ReportAction = { ], actionName: 'IOU', originalMessage, - childReportID: '1111111111111111', + childReportID: REPORT_ID_111, created: '2025-02-14 08:12:05.165', actorAccountID: 11111111, childType: 'chat', @@ -262,6 +308,32 @@ const action: ReportAction = { ], }; -/* eslint-enable @typescript-eslint/naming-convention */ +const fakeAction456: ReportAction = { + reportActionID: 'ra456', + message: [ + { + type: CONST.REPORT.MESSAGE.TYPE.COMMENT, + html: '$0.01 expense', + text: '$0.01 expense', + isEdited: false, + whisperedTo: [], + isDeletedParentAction: false, + deleted: '', + }, + ], + actionName: 'IOU', + originalMessage: fakeOriginalMessage456, + childReportID: REPORT_ID_456, + created: '2025-02-14 08:12:05.165', + actorAccountID: 11111111, + childType: 'chat', + person: [ + { + type: 'TEXT', + style: 'strong', + text: 'John Smith', + }, + ], +}; -export {personalDetails, iouReport, chatReport, transaction, violations, action}; +export {personalDetails, iouReport, chatReport, transaction, violations, action, fakeAction456, fakeTransaction456}; diff --git a/src/styles/index.ts b/src/styles/index.ts index f7e06e6fe484..8c806f44d4a9 100644 --- a/src/styles/index.ts +++ b/src/styles/index.ts @@ -3781,8 +3781,6 @@ const styles = (theme: ThemeColors) => alignItems: 'center', ...userSelect.userSelectNone, paddingBottom: 12, - paddingHorizontal: 32, - paddingTop: 12, backgroundColor: theme.appBG, justifyContent: 'flex-start', }, @@ -4894,6 +4892,11 @@ const styles = (theme: ThemeColors) => borderRadius: 8, }, + listTableHeader: { + paddingVertical: 12, + paddingHorizontal: 32, + }, + cardItemSecondaryIconStyle: { position: 'absolute', bottom: -4, diff --git a/src/styles/utils/sizing.ts b/src/styles/utils/sizing.ts index ee7c04b57b13..3b901ada96a4 100644 --- a/src/styles/utils/sizing.ts +++ b/src/styles/utils/sizing.ts @@ -83,6 +83,13 @@ export default { mnw100: { minWidth: '100%', }, + mnw64p: { + minWidth: 64, + }, + + mnw100p: { + minWidth: 100, + }, mnw120: { minWidth: 120, diff --git a/tests/unit/libs/MoneyRequestReportUtils.ts b/tests/unit/libs/MoneyRequestReportUtils.ts new file mode 100644 index 000000000000..b2ad6b80c476 --- /dev/null +++ b/tests/unit/libs/MoneyRequestReportUtils.ts @@ -0,0 +1,32 @@ +import {getThreadReportIDsForTransactions} from '@libs/MoneyRequestReportUtils'; +import {fakeAction456, action as fakeReportAction, transaction as fakeTransaction, fakeTransaction456} from '@src/stories/mockData/transactions'; +import type {ReportAction, Transaction} from '@src/types/onyx'; + +describe('getThreadReportIDsForTransactions', () => { + test('returns empty list for no transactions', () => { + const result = getThreadReportIDsForTransactions([fakeReportAction], []); + expect(result).toEqual([]); + }); + + test('returns empty list for transactions but no reportActions', () => { + const result = getThreadReportIDsForTransactions([], [fakeTransaction]); + expect(result).toEqual([]); + }); + + test('returns list of reportIDs for transactions which have matching reportActions', () => { + const reportActions = [fakeReportAction, fakeAction456] satisfies ReportAction[]; + const transactions = [{...fakeTransaction, transactionID: '590639150582440369'}, {...fakeTransaction456}] satisfies Transaction[]; + + const result = getThreadReportIDsForTransactions(reportActions, transactions); + expect(result).toEqual(['1111111111111111', 'R98765']); + }); + + test('returns empty list for transactions which have no matching reportActions', () => { + // fakeAction456 has originalMessage with undefined id, so cannot be mapped + const reportActions = [{...fakeAction456, originalMessage: {}}] satisfies ReportAction[]; + const transactions = [{...fakeTransaction, transactionID: '590639150582440369'}, {...fakeTransaction456}] satisfies Transaction[]; + + const result = getThreadReportIDsForTransactions(reportActions, transactions); + expect(result).toEqual([]); + }); +});