From 0a90b854196a3eef9b569a58c1fdcc61cd8d60a0 Mon Sep 17 00:00:00 2001 From: Mateusz Titz Date: Fri, 21 Mar 2025 10:42:59 +0100 Subject: [PATCH 01/19] Improve MoneyRequestReportView - fix date column size - add basic scrolling to bottom functionality --- src/CONST.ts | 3 + .../MoneyRequestReportActionsList.tsx | 256 +++++++++++++++--- .../MoneyRequestReportTableHeader.tsx | 5 +- .../MoneyRequestReportTransactionList.tsx | 10 +- .../MoneyRequestReportView.tsx | 4 - src/components/TransactionItemRow/index.tsx | 6 +- src/hooks/useReportScrollManager/index.ts | 16 +- src/hooks/useReportScrollManager/types.ts | 1 + src/libs/API/parameters/OpenReportParams.ts | 6 + src/libs/ReportActionsUtils.ts | 15 +- src/libs/SearchUIUtils.ts | 5 +- .../shouldShowTransactionYear.ts | 10 + src/libs/actions/Report.ts | 5 +- .../Search/SearchMoneyRequestReportPage.tsx | 81 +++--- src/pages/home/report/ReportActionsList.tsx | 29 +- src/pages/home/report/ReportFooter.tsx | 4 +- 16 files changed, 342 insertions(+), 114 deletions(-) create mode 100644 src/libs/TransactionUtils/shouldShowTransactionYear.ts diff --git a/src/CONST.ts b/src/CONST.ts index d0a7223897f8..92c72a4e7b08 100755 --- a/src/CONST.ts +++ b/src/CONST.ts @@ -1314,6 +1314,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: { diff --git a/src/components/MoneyRequestReportView/MoneyRequestReportActionsList.tsx b/src/components/MoneyRequestReportView/MoneyRequestReportActionsList.tsx index 16aa6244c6aa..e1140f08652a 100644 --- a/src/components/MoneyRequestReportView/MoneyRequestReportActionsList.tsx +++ b/src/components/MoneyRequestReportView/MoneyRequestReportActionsList.tsx @@ -1,12 +1,17 @@ import type {ListRenderItemInfo} from '@react-native/virtualized-lists/Lists/VirtualizedList'; -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 ReportActionsSkeletonView from '@components/ReportActionsSkeletonView'; 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 { @@ -16,15 +21,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'; @@ -34,6 +45,8 @@ import MoneyRequestReportTransactionList from './MoneyRequestReportTransactionLi */ const EmptyParentReportActionForTransactionThread = undefined; +const INITIAL_NUM_TO_RENDER = 20; + type MoneyRequestReportListProps = { /** The report */ report: OnyxTypes.Report; @@ -67,16 +80,14 @@ function getTransactionsForReportID(transactions: OnyxCollection getTransactionsForReportID(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(() => { @@ -136,23 +151,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) => { @@ -171,35 +300,80 @@ 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 trackVerticalScrolling = (event: NativeSyntheticEvent) => { + scrollingVerticalOffset.current = event.nativeEvent.contentOffset.y; + handleUnreadFloatingButton(); + }; + return ( - + {report ? ( - item.reportActionID} - initialNumToRender={10} - onEndReached={onEndReached} - onEndReachedThreshold={0.75} - onStartReached={onStartReached} - onStartReachedThreshold={0.75} - ListHeaderComponent={} - keyboardShouldPersistTaps="handled" - /> + + + 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..7b3a358d98c5 100644 --- a/src/components/MoneyRequestReportView/MoneyRequestReportTableHeader.tsx +++ b/src/components/MoneyRequestReportView/MoneyRequestReportTableHeader.tsx @@ -57,13 +57,14 @@ type SearchTableHeaderProps = { sortBy?: SortableColumnName; sortOrder?: SortOrder; onSortPress: (column: SortableColumnName, order: SortOrder) => void; + dateColumnSize: 'normal' | 'wide'; 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(); @@ -72,7 +73,7 @@ function MoneyRequestReportTableHeader({sortBy, sortOrder, onSortPress, shouldSh { + const shouldShowYearForSomeTransaction = transactions.some((transaction) => shouldShowTransactionYear(transaction)); + return shouldShowYearForSomeTransaction ? 'wide' : 'normal'; + }, [transactions]); + return ( <> {!displayNarrowVersion && ( @@ -79,6 +85,7 @@ function MoneyRequestReportTransactionList({transactions}: MoneyRequestReportTra shouldShowSorting sortBy={sortBy} sortOrder={sortOrder} + dateColumnSize={dateColumnSize} onSortPress={(selectedSortBy, selectedSortOrder) => { if (!isSortableColumnName(selectedSortBy)) { return; @@ -96,6 +103,7 @@ function MoneyRequestReportTransactionList({transactions}: MoneyRequestReportTra transactionItem={transaction} isSelected={false} shouldShowTooltip + dateColumnSize={dateColumnSize} shouldUseNarrowLayout={displayNarrowVersion} shouldShowChatBubbleComponent /> diff --git a/src/components/MoneyRequestReportView/MoneyRequestReportView.tsx b/src/components/MoneyRequestReportView/MoneyRequestReportView.tsx index dcf75ce9ea1d..d182d6e01222 100644 --- a/src/components/MoneyRequestReportView/MoneyRequestReportView.tsx +++ b/src/components/MoneyRequestReportView/MoneyRequestReportView.tsx @@ -36,8 +36,6 @@ function getParentReportAction(parentReportActions: OnyxEntry {}; - function MoneyRequestReportView({report, policy, reportMetadata, shouldDisplayReportFooter}: MoneyRequestReportViewProps) { const styles = useThemeStyles(); @@ -84,8 +82,6 @@ function MoneyRequestReportView({report, policy, reportMetadata, shouldDisplayRe /> {shouldDisplayReportFooter ? ( {shouldUseNarrowLayout ? ( @@ -117,7 +121,7 @@ function TransactionItemRow({ shouldUseNarrowLayout={shouldUseNarrowLayout} /> - + { 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/libs/API/parameters/OpenReportParams.ts b/src/libs/API/parameters/OpenReportParams.ts index a665313580e8..7e500d1b8c82 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/ReportActionsUtils.ts b/src/libs/ReportActionsUtils.ts index d884b38b8fbd..69257698f48b 100644 --- a/src/libs/ReportActionsUtils.ts +++ b/src/libs/ReportActionsUtils.ts @@ -2262,6 +2262,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) { @@ -2284,6 +2287,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, @@ -2397,7 +2410,7 @@ export { getRemovedConnectionMessage, getActionableJoinRequestPendingReportAction, getReportActionsLength, - wasActionCreatedWhileOffline, + wasMessageReceivedWhileOffline, shouldShowAddMissingDetails, getWorkspaceCategoryUpdateMessage, getWorkspaceUpdateFieldMessage, diff --git a/src/libs/SearchUIUtils.ts b/src/libs/SearchUIUtils.ts index 4bb34bfe3126..5f4093459ac1 100644 --- a/src/libs/SearchUIUtils.ts +++ b/src/libs/SearchUIUtils.ts @@ -8,6 +8,7 @@ import ChatListItem from '@components/SelectionList/ChatListItem'; import ReportListItem from '@components/SelectionList/Search/ReportListItem'; import TransactionListItem from '@components/SelectionList/Search/TransactionListItem'; import type {ListItem, ReportActionListItemType, ReportListItemType, TransactionListItemType} from '@components/SelectionList/types'; +import shouldShowTransactionYear from '@libs/TransactionUtils/shouldShowTransactionYear'; import * as Expensicons from '@src/components/Icon/Expensicons'; import CONST from '@src/CONST'; import type {TranslationPaths} from '@src/languages/types'; @@ -236,9 +237,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)) { 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 68fdae4d6831..8de9d379742a 100644 --- a/src/libs/actions/Report.ts +++ b/src/libs/actions/Report.ts @@ -865,6 +865,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 useTableReportView Flag deciding how api returns reportActions - if set to true, api will return oldest first starting from the beginning of report. */ function openReport( reportID: string | undefined, @@ -874,6 +875,7 @@ function openReport( parentReportActionID?: string, isFromDeepLink = false, participantAccountIDList: number[] = [], + useTableReportView = false, avatar?: File | CustomRNImageManipulatorResult, ) { if (!reportID) { @@ -942,6 +944,7 @@ function openReport( emailList: participantLoginList ? participantLoginList.join(',') : '', accountIDList: participantAccountIDList ? participantAccountIDList.join(',') : '', parentReportActionID, + useTableReportView, }; const isInviteOnboardingComplete = introSelected?.isInviteOnboardingComplete ?? false; @@ -1199,7 +1202,7 @@ function navigateToAndOpenReport( const report = isEmptyObject(chat) ? newChat : chat; // We want to pass newChat here because if anything is passed in that param (even an existing chat), we will try to create a chat on the server - openReport(report?.reportID, '', userLogins, newChat, undefined, undefined, undefined, avatarFile); + openReport(report?.reportID, '', userLogins, newChat, undefined, undefined, undefined, false, avatarFile); if (shouldDismissModal) { if (getIsNarrowLayout()) { Navigation.dismissModalWithReport({report}); diff --git a/src/pages/Search/SearchMoneyRequestReportPage.tsx b/src/pages/Search/SearchMoneyRequestReportPage.tsx index 57ff2a38dcff..68f461d860f1 100644 --- a/src/pages/Search/SearchMoneyRequestReportPage.tsx +++ b/src/pages/Search/SearchMoneyRequestReportPage.tsx @@ -1,5 +1,6 @@ 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 DragAndDropProvider from '@components/DragAndDrop/Provider'; @@ -19,6 +20,8 @@ import type {SearchFullscreenNavigatorParamList} from '@libs/Navigation/types'; import {buildSearchQueryJSON} from '@libs/SearchQueryUtils'; 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'; @@ -42,7 +45,6 @@ function SearchMoneyRequestReportPage({route}: SearchPageProps) { 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 [policies] = useOnyx(ONYXKEYS.COLLECTION.POLICY, {allowStaleData: true, initialValue: {}}); @@ -50,8 +52,13 @@ function SearchMoneyRequestReportPage({route}: SearchPageProps) { 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]); + useEffect(() => { - openReport(reportID); + openReport(reportID, '', [], undefined, undefined, false, [], true); }, [reportID]); if (shouldUseNarrowLayout) { @@ -73,39 +80,43 @@ function SearchMoneyRequestReportPage({route}: SearchPageProps) { } return ( - - - - - - - - - - - - - - + + + + + + + + + + + - - - - - + + + + + + + + + + + + ); } diff --git a/src/pages/home/report/ReportActionsList.tsx b/src/pages/home/report/ReportActionsList.tsx index e9f8fd355642..b1a526544872 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}); @@ -501,11 +488,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); @@ -595,7 +582,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({ From 022d3a3c8d7cc7faf884d704d731d1759f0919bb Mon Sep 17 00:00:00 2001 From: Mateusz Titz Date: Fri, 21 Mar 2025 15:12:50 +0100 Subject: [PATCH 02/19] Make SearchTypeMenu look correct with undefined Search query --- src/libs/SearchUIUtils.ts | 4 ++-- src/pages/Search/SearchMoneyRequestReportPage.tsx | 7 +------ src/pages/Search/SearchTypeMenu.tsx | 14 ++++++++------ 3 files changed, 11 insertions(+), 14 deletions(-) diff --git a/src/libs/SearchUIUtils.ts b/src/libs/SearchUIUtils.ts index 5f4093459ac1..44706e3af020 100644 --- a/src/libs/SearchUIUtils.ts +++ b/src/libs/SearchUIUtils.ts @@ -786,14 +786,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/pages/Search/SearchMoneyRequestReportPage.tsx b/src/pages/Search/SearchMoneyRequestReportPage.tsx index 68f461d860f1..9f4641e7b919 100644 --- a/src/pages/Search/SearchMoneyRequestReportPage.tsx +++ b/src/pages/Search/SearchMoneyRequestReportPage.tsx @@ -10,14 +10,12 @@ 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 type {PlatformStackScreenProps} from '@libs/Navigation/PlatformStackNavigation/types'; import type {SearchFullscreenNavigatorParamList} from '@libs/Navigation/types'; -import {buildSearchQueryJSON} from '@libs/SearchQueryUtils'; import {openReport} from '@userActions/Report'; import ONYXKEYS from '@src/ONYXKEYS'; import {ActionListContext, ReactionListContext} from '@src/pages/home/ReportScreenContext'; @@ -25,9 +23,6 @@ import type {ActionListContextType, ReactionListRef, ScrollPosition} from '@src/ 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; const defaultReportMetadata = { @@ -96,7 +91,7 @@ function SearchMoneyRequestReportPage({route}: SearchPageProps) { breadcrumbLabel={translate('common.reports')} shouldDisplaySearch={false} /> - + diff --git a/src/pages/Search/SearchTypeMenu.tsx b/src/pages/Search/SearchTypeMenu.tsx index 0f85d2984a36..0a0720355fd2 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 ( From 0512fc9d2af3bca934ef8776e1308acc6426266b Mon Sep 17 00:00:00 2001 From: Mateusz Titz Date: Fri, 21 Mar 2025 17:25:11 +0100 Subject: [PATCH 03/19] Improve SearchMoneyRequestReportPage loading and not found page --- .../MoneyRequestReportActionsList.tsx | 50 +++++----- .../MoneyRequestReportView.tsx | 29 ++++-- src/libs/SearchUIUtils.ts | 2 +- .../Search/SearchMoneyRequestReportPage.tsx | 96 ++++++++++++++----- 4 files changed, 120 insertions(+), 57 deletions(-) diff --git a/src/components/MoneyRequestReportView/MoneyRequestReportActionsList.tsx b/src/components/MoneyRequestReportView/MoneyRequestReportActionsList.tsx index e1140f08652a..1b7a507d0648 100644 --- a/src/components/MoneyRequestReportView/MoneyRequestReportActionsList.tsx +++ b/src/components/MoneyRequestReportView/MoneyRequestReportActionsList.tsx @@ -350,33 +350,29 @@ function MoneyRequestReportActionsList({report, reportActions = [], hasNewerActi return ( - {report ? ( - - - item.reportActionID} - onEndReached={onEndReached} - onEndReachedThreshold={0.75} - onStartReached={onStartReached} - onStartReachedThreshold={0.75} - ListHeaderComponent={} - keyboardShouldPersistTaps="handled" - onScroll={trackVerticalScrolling} - ref={reportScrollManager.ref} - /> - - ) : ( - - )} + + + 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/MoneyRequestReportView.tsx b/src/components/MoneyRequestReportView/MoneyRequestReportView.tsx index d182d6e01222..1b02fbb59c13 100644 --- a/src/components/MoneyRequestReportView/MoneyRequestReportView.tsx +++ b/src/components/MoneyRequestReportView/MoneyRequestReportView.tsx @@ -4,6 +4,8 @@ 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 useNetwork from '@hooks/useNetwork'; import usePaginatedReportActions from '@hooks/usePaginatedReportActions'; import useThemeStyles from '@hooks/useThemeStyles'; import getNonEmptyStringOnyxID from '@libs/getNonEmptyStringOnyxID'; @@ -38,8 +40,10 @@ function getParentReportAction(parentReportActions: OnyxEntry canEditReportAction(action) && !isMoneyRequestAction(action)); + const isLoadingInitialReportActions = reportMetadata?.isLoadingInitialReportActions; + + if (isLoadingInitialReportActions && reportActions.length === 0 && !isOffline) { + return ; + } + + if (reportActions.length === 0) { + return ; + } if (!report) { return; @@ -74,12 +87,16 @@ function MoneyRequestReportView({report, policy, reportMetadata, shouldDisplayRe Navigation.goBack(); }} /> - + {report && !isLoadingApp ? ( + + ) : ( + + )} {shouldDisplayReportFooter ? ( ({}); 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, '', [], undefined, undefined, false, [], true); - }, [reportID]); + openReport(reportIDFromRoute, '', [], undefined, undefined, false, [], 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 ( @@ -64,12 +90,24 @@ function SearchMoneyRequestReportPage({route}: SearchPageProps) { offlineIndicatorStyle={styles.mtAuto} headerGapStyles={styles.searchHeaderGap} > - + + + ); } @@ -96,17 +134,29 @@ function SearchMoneyRequestReportPage({route}: SearchPageProps) { - - - - - - + + + + + + + + From 228e7ab3dcbf7ffaf8b68e8e6f474e239f7faa76 Mon Sep 17 00:00:00 2001 From: Mateusz Titz Date: Mon, 24 Mar 2025 13:52:19 +0100 Subject: [PATCH 04/19] Add navigating to transaction reportID --- .../MoneyRequestReportActionsList.tsx | 9 +- .../MoneyRequestReportTransactionList.tsx | 95 ++++++++++++++++--- .../MoneyRequestReportView.tsx | 8 +- .../SelectionList/SortableTableHeader.tsx | 2 +- src/libs/Navigation/types.ts | 1 + src/libs/ReportActionsUtils.ts | 12 ++- .../Search/SearchMoneyRequestReportPage.tsx | 10 +- 7 files changed, 109 insertions(+), 28 deletions(-) diff --git a/src/components/MoneyRequestReportView/MoneyRequestReportActionsList.tsx b/src/components/MoneyRequestReportView/MoneyRequestReportActionsList.tsx index 1b7a507d0648..4b597b7dd2cd 100644 --- a/src/components/MoneyRequestReportView/MoneyRequestReportActionsList.tsx +++ b/src/components/MoneyRequestReportView/MoneyRequestReportActionsList.tsx @@ -6,7 +6,6 @@ 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 ReportActionsSkeletonView from '@components/ReportActionsSkeletonView'; import useLoadReportActions from '@hooks/useLoadReportActions'; import useLocalize from '@hooks/useLocalize'; import useNetworkWithOfflineStatus from '@hooks/useNetworkWithOfflineStatus'; @@ -80,7 +79,6 @@ function getTransactionsForReportID(transactions: OnyxCollection} + ListHeaderComponent={ + + } keyboardShouldPersistTaps="handled" onScroll={trackVerticalScrolling} ref={reportScrollManager.ref} diff --git a/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx b/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx index 6531438398ea..589c6944e443 100644 --- a/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx +++ b/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx @@ -1,19 +1,30 @@ -import React, {useEffect, useState, useMemo} from 'react'; +import React, {useCallback, useEffect, useMemo, useState} from 'react'; import {View} from 'react-native'; import type {TupleToUnion} from 'type-fest'; +import {getButtonRole} from '@components/Button/utils'; +import PressableWithFeedback from '@components/Pressable/PressableWithFeedback'; import type {SortOrder} from '@components/Search/types'; import TransactionItemRow from '@components/TransactionItemRow'; +import useHover from '@hooks/useHover'; +import useLocalize from '@hooks/useLocalize'; +import {useMouseContext} from '@hooks/useMouseContext'; import useResponsiveLayout from '@hooks/useResponsiveLayout'; import useThemeStyles from '@hooks/useThemeStyles'; -import shouldShowTransactionYear from '@libs/TransactionUtils/shouldShowTransactionYear'; +import {getIOUActionForReportIDPure} from '@libs/ReportActionsUtils'; import {compareValues} from '@libs/SearchUIUtils'; +import shouldShowTransactionYear from '@libs/TransactionUtils/shouldShowTransactionYear'; +import Navigation from '@navigation/Navigation'; import CONST from '@src/CONST'; +import ROUTES from '@src/ROUTES'; import type * as OnyxTypes from '@src/types/onyx'; import MoneyRequestReportTableHeader from './MoneyRequestReportTableHeader'; type MoneyRequestReportTransactionListProps = { /** List of transactions belonging to one report */ transactions: OnyxTypes.Transaction[]; + + /** Array of report actions for the report that these transactions belong to */ + reportActions: OnyxTypes.ReportAction[]; }; const sortableColumnNames = [ @@ -49,15 +60,25 @@ const areTransactionValuesEqual = (transactions: OnyxTypes.Transaction[], key: S return transactions.every((transaction) => transaction[getTransactionKey(transaction, key)] === firstValidTransaction[keyOfFirstValidTransaction]); }; -function MoneyRequestReportTransactionList({transactions}: MoneyRequestReportTransactionListProps) { +function MoneyRequestReportTransactionList({transactions, reportActions}: MoneyRequestReportTransactionListProps) { const styles = useThemeStyles(); + const {translate} = useLocalize(); const {shouldUseNarrowLayout, isMediumScreenWidth} = useResponsiveLayout(); const displayNarrowVersion = isMediumScreenWidth || shouldUseNarrowLayout; + 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; @@ -73,11 +94,35 @@ function MoneyRequestReportTransactionList({transactions}: MoneyRequestReportTra })); }, [sortBy, sortOrder, transactions]); + const navigateToTransaction = useCallback( + (transaction: OnyxTypes.Transaction) => { + const backTo = Navigation.getActiveRoute(); + + const iouAction = getIOUActionForReportIDPure(reportActions, transaction.transactionID); + const reportIDToNavigate = iouAction?.childReportID; + if (!reportIDToNavigate) { + return; + } + + Navigation.navigate(ROUTES.SEARCH_REPORT.getRoute({reportID: reportIDToNavigate, backTo})); + }, + [reportActions], + ); + const dateColumnSize = useMemo(() => { const shouldShowYearForSomeTransaction = transactions.some((transaction) => shouldShowTransactionYear(transaction)); return shouldShowYearForSomeTransaction ? 'wide' : 'normal'; }, [transactions]); + if (sortedData.transactions.length === 0) { + return; + } + + const pressableStyle = [ + styles.overflowHidden, + // item.isSelected && styles.activeComponentBG, + ]; + return ( <> {!displayNarrowVersion && ( @@ -98,16 +143,38 @@ 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} + // pressDimmingValue={item.isInteractive === false ? 1 : variables.pressDimValue} + // hoverStyle={item.isSelected && styles.activeComponentBG} + onMouseDown={(e) => e.preventDefault()} + id={transaction.transactionID} + style={[pressableStyle]} + onMouseLeave={handleMouseLeave} + wrapperStyle={[]} + > + + + + ); })} diff --git a/src/components/MoneyRequestReportView/MoneyRequestReportView.tsx b/src/components/MoneyRequestReportView/MoneyRequestReportView.tsx index 1b02fbb59c13..1e8b90d27acf 100644 --- a/src/components/MoneyRequestReportView/MoneyRequestReportView.tsx +++ b/src/components/MoneyRequestReportView/MoneyRequestReportView.tsx @@ -14,6 +14,7 @@ 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 * as OnyxTypes from '@src/types/onyx'; import MoneyRequestReportActionsList from './MoneyRequestReportActionsList'; @@ -29,6 +30,9 @@ 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 getParentReportAction(parentReportActions: OnyxEntry, parentReportActionID: string | undefined): OnyxEntry { @@ -38,7 +42,7 @@ function getParentReportAction(parentReportActions: OnyxEntry { - Navigation.goBack(); + Navigation.goBack(backToRoute); }} /> {report && !isLoadingApp ? ( diff --git a/src/components/SelectionList/SortableTableHeader.tsx b/src/components/SelectionList/SortableTableHeader.tsx index ff6009bb1224..9d01dc17eaa1 100644 --- a/src/components/SelectionList/SortableTableHeader.tsx +++ b/src/components/SelectionList/SortableTableHeader.tsx @@ -46,7 +46,7 @@ function SortableTableHeader({columns, sortBy, sortOrder, shouldShowColumn, date return ( { + + return getIOUActionForReportIDPure(Object.values(reportActions ?? {}), transactionID); +} + +/** + * Get IOU action for a reportID and transactionID + */ +function getIOUActionForReportIDPure(reportActions: ReportAction[], transactionID: string): OnyxEntry { + return reportActions.find((reportAction) => { const IOUTransactionID = isMoneyRequestAction(reportAction) ? getOriginalMessage(reportAction)?.IOUTransactionID : undefined; return IOUTransactionID === transactionID; }); - return action; } /** @@ -2308,6 +2315,7 @@ export { getDismissedViolationMessageText, getFirstVisibleReportActionID, getIOUActionForReportID, + getIOUActionForReportIDPure, getIOUReportIDFromReportActionPreview, getLastClosedReportAction, getLastVisibleAction, diff --git a/src/pages/Search/SearchMoneyRequestReportPage.tsx b/src/pages/Search/SearchMoneyRequestReportPage.tsx index 8986409f6bb8..c52e50427144 100644 --- a/src/pages/Search/SearchMoneyRequestReportPage.tsx +++ b/src/pages/Search/SearchMoneyRequestReportPage.tsx @@ -27,7 +27,7 @@ import type {ActionListContextType, ReactionListRef, ScrollPosition} from '@src/ import type SCREENS from '@src/SCREENS'; import SearchTypeMenu from './SearchTypeMenu'; -type SearchPageProps = PlatformStackScreenProps; +type SearchMoneyRequestPageProps = PlatformStackScreenProps; const defaultReportMetadata = { isLoadingInitialReportActions: true, @@ -38,7 +38,7 @@ const defaultReportMetadata = { isOptimisticReport: false, }; -function SearchMoneyRequestReportPage({route}: SearchPageProps) { +function SearchMoneyRequestReportPage({route}: SearchMoneyRequestPageProps) { const {translate} = useLocalize(); const {shouldUseNarrowLayout} = useResponsiveLayout(); const styles = useThemeStyles(); @@ -97,15 +97,14 @@ function SearchMoneyRequestReportPage({route}: SearchPageProps) { shouldDisplaySearchRouter shouldShowBackButton={shouldUseNarrowLayout} onBackButtonPress={Navigation.goBack} - // shouldShowLink={shouldShowNotFoundLinkedAction} linkKey="notFound.noAccess" - // onLinkPress={navigateToEndOfReport} > @@ -141,9 +140,7 @@ function SearchMoneyRequestReportPage({route}: SearchPageProps) { shouldDisplaySearchRouter shouldShowBackButton={shouldUseNarrowLayout} onBackButtonPress={Navigation.goBack} - // shouldShowLink={shouldShowNotFoundLinkedAction} linkKey="notFound.noAccess" - // onLinkPress={navigateToEndOfReport} > @@ -152,6 +149,7 @@ function SearchMoneyRequestReportPage({route}: SearchPageProps) { reportMetadata={reportMetadata} policy={policy} shouldDisplayReportFooter={isCurrentReportLoadedFromOnyx} + backToRoute={route.params.backTo} /> From 1378cef3557e3f0a604df9f484f45542d58e2d46 Mon Sep 17 00:00:00 2001 From: Jan Nowakowski <56261019+jnowakow@users.noreply.github.com> Date: Mon, 24 Mar 2025 15:19:01 +0100 Subject: [PATCH 05/19] Add totals under table (#213) * Add totals under table * Move summary row to TransactionList --- .../MoneyRequestReportActionsList.tsx | 1 + .../MoneyRequestReportTransactionList.tsx | 44 ++++++++++++++++++- src/languages/en.ts | 1 + src/languages/es.ts | 1 + src/styles/utils/sizing.ts | 7 +++ 5 files changed, 53 insertions(+), 1 deletion(-) diff --git a/src/components/MoneyRequestReportView/MoneyRequestReportActionsList.tsx b/src/components/MoneyRequestReportView/MoneyRequestReportActionsList.tsx index 4b597b7dd2cd..09fba96529f9 100644 --- a/src/components/MoneyRequestReportView/MoneyRequestReportActionsList.tsx +++ b/src/components/MoneyRequestReportView/MoneyRequestReportActionsList.tsx @@ -367,6 +367,7 @@ function MoneyRequestReportActionsList({report, reportActions = [], hasNewerActi onStartReachedThreshold={0.75} ListHeaderComponent={ diff --git a/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx b/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx index 589c6944e443..2b7c10bb6df6 100644 --- a/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx +++ b/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx @@ -4,13 +4,16 @@ import type {TupleToUnion} from 'type-fest'; import {getButtonRole} from '@components/Button/utils'; import PressableWithFeedback from '@components/Pressable/PressableWithFeedback'; import type {SortOrder} from '@components/Search/types'; +import Text from '@components/Text'; import TransactionItemRow from '@components/TransactionItemRow'; import useHover from '@hooks/useHover'; import useLocalize from '@hooks/useLocalize'; import {useMouseContext} from '@hooks/useMouseContext'; import useResponsiveLayout from '@hooks/useResponsiveLayout'; import useThemeStyles from '@hooks/useThemeStyles'; +import {convertToDisplayString} from '@libs/CurrencyUtils'; import {getIOUActionForReportIDPure} from '@libs/ReportActionsUtils'; +import {getMoneyRequestSpendBreakdown} from '@libs/ReportUtils'; import {compareValues} from '@libs/SearchUIUtils'; import shouldShowTransactionYear from '@libs/TransactionUtils/shouldShowTransactionYear'; import Navigation from '@navigation/Navigation'; @@ -20,6 +23,8 @@ import type * as OnyxTypes from '@src/types/onyx'; import MoneyRequestReportTableHeader from './MoneyRequestReportTableHeader'; type MoneyRequestReportTransactionListProps = { + report: OnyxTypes.Report; + /** List of transactions belonging to one report */ transactions: OnyxTypes.Transaction[]; @@ -60,12 +65,17 @@ const areTransactionValuesEqual = (transactions: OnyxTypes.Transaction[], key: S return transactions.every((transaction) => transaction[getTransactionKey(transaction, key)] === firstValidTransaction[keyOfFirstValidTransaction]); }; -function MoneyRequestReportTransactionList({transactions, reportActions}: MoneyRequestReportTransactionListProps) { +function MoneyRequestReportTransactionList({report, transactions, reportActions}: 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(); @@ -178,6 +188,38 @@ function MoneyRequestReportTransactionList({transactions, reportActions}: MoneyR ); })} + {shouldShowBreakdown && ( + + {[ + {text: translate('cardTransactions.outOfPocket'), value: formattedOutOfPocketAmount}, + {text: translate('cardTransactions.companySpend'), value: formattedCompanySpendAmount}, + ].map(({text, value}) => ( + + + {text} + + + {value} + + + ))} + + )} + + {translate('common.comments')} + + {translate('common.total')} + + {convertToDisplayString(totalDisplaySpend, report?.currency)} + + + ); } diff --git a/src/languages/en.ts b/src/languages/en.ts index 05cfddb64dc2..c27eddc0ae50 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 885d6cec1f57..0ea44fd8600e 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/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, From 20e5c22b285640f1eb4cfeb9aefb3ebba655c0b8 Mon Sep 17 00:00:00 2001 From: Mateusz Titz Date: Tue, 25 Mar 2025 10:45:30 +0100 Subject: [PATCH 06/19] Add navigation when clicking on Transaction row --- src/components/MoneyRequestHeader.tsx | 3 + .../MoneyRequestReportTransactionList.tsx | 22 ++++- ...neyRequestReportTransactionsNavigation.tsx | 91 +++++++++++++++++++ .../TransactionReportIDRepository.ts | 30 ++++++ 4 files changed, 141 insertions(+), 5 deletions(-) create mode 100644 src/components/MoneyRequestReportView/MoneyRequestReportTransactionsNavigation.tsx create mode 100644 src/components/MoneyRequestReportView/TransactionReportIDRepository.ts diff --git a/src/components/MoneyRequestHeader.tsx b/src/components/MoneyRequestHeader.tsx index 6d7ca116a782..1322818c39d1 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); @@ -180,6 +182,7 @@ function MoneyRequestHeader({report, parentReportAction, policy, onBackButtonPre }} /> )} + {shouldDisplayTransactionNavigation && } {shouldShowMarkAsCashButton && shouldUseNarrowLayout && ( diff --git a/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx b/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx index 2b7c10bb6df6..930cbde0626f 100644 --- a/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx +++ b/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx @@ -21,6 +21,7 @@ import CONST from '@src/CONST'; import ROUTES from '@src/ROUTES'; import type * as OnyxTypes from '@src/types/onyx'; import MoneyRequestReportTableHeader from './MoneyRequestReportTableHeader'; +import {setActiveTransactionReportIDs} from './TransactionReportIDRepository'; type MoneyRequestReportTransactionListProps = { report: OnyxTypes.Report; @@ -105,18 +106,29 @@ function MoneyRequestReportTransactionList({report, transactions, reportActions} }, [sortBy, sortOrder, transactions]); const navigateToTransaction = useCallback( - (transaction: OnyxTypes.Transaction) => { - const backTo = Navigation.getActiveRoute(); - - const iouAction = getIOUActionForReportIDPure(reportActions, transaction.transactionID); + (activeTransaction: OnyxTypes.Transaction) => { + const iouAction = getIOUActionForReportIDPure(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 every sibling to `activeTransaction` + // we use this data to display prev/next arrows in RHP for navigating between transactions + const sortedSiblingTransactionReportIDs = sortedData.transactions + .map((transaction) => { + const action = getIOUActionForReportIDPure(reportActions, transaction.transactionID); + return action?.childReportID; + }) + .filter((reportID): reportID is string => !!reportID); + + setActiveTransactionReportIDs(sortedSiblingTransactionReportIDs); + Navigation.navigate(ROUTES.SEARCH_REPORT.getRoute({reportID: reportIDToNavigate, backTo})); }, - [reportActions], + [reportActions, sortedData.transactions], ); const dateColumnSize = useMemo(() => { diff --git a/src/components/MoneyRequestReportView/MoneyRequestReportTransactionsNavigation.tsx b/src/components/MoneyRequestReportView/MoneyRequestReportTransactionsNavigation.tsx new file mode 100644 index 000000000000..3d9cfa0c8db5 --- /dev/null +++ b/src/components/MoneyRequestReportView/MoneyRequestReportTransactionsNavigation.tsx @@ -0,0 +1,91 @@ +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 Navigation from '@navigation/Navigation'; +import ROUTES from '@src/ROUTES'; +import {getActiveTransactionReportIDs} from './TransactionReportIDRepository'; + +type MoneyRequestReportRHPNavigationButtonsProps = { + currentReportID: string; +}; + +function MoneyRequestReportTransactionsNavigation({currentReportID}: MoneyRequestReportRHPNavigationButtonsProps) { + const styles = useThemeStyles(); + const theme = useTheme(); + + 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(); + + 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/TransactionReportIDRepository.ts b/src/components/MoneyRequestReportView/TransactionReportIDRepository.ts new file mode 100644 index 000000000000..66c80a2cbc90 --- /dev/null +++ b/src/components/MoneyRequestReportView/TransactionReportIDRepository.ts @@ -0,0 +1,30 @@ +/** + * 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 getTransactionReportIDRepository() { + const transactionReportIDs: string[] = []; + + function setActiveTransactionReportIDs(ids: string[]) { + // Cleaning previously saved keys because + transactionReportIDs.splice(0, Infinity); + transactionReportIDs.push(...ids); + } + + function getActiveTransactionReportIDs() { + return transactionReportIDs; + } + + return { + setActiveTransactionReportIDs, + getActiveTransactionReportIDs, + }; +} + +// Initialize singleton instance, because we only ever need 1 state for this function +const {setActiveTransactionReportIDs, getActiveTransactionReportIDs} = getTransactionReportIDRepository(); + +export {setActiveTransactionReportIDs, getActiveTransactionReportIDs}; From 22606bcd685bfb47451afc5c0c172d9a17b0aafd Mon Sep 17 00:00:00 2001 From: Mateusz Titz Date: Tue, 25 Mar 2025 15:29:31 +0100 Subject: [PATCH 07/19] Improve styling and types in MoneyRequestReportView --- src/CONST.ts | 4 +++ .../MoneyRequestReportActionsList.tsx | 2 +- .../MoneyRequestReportTableHeader.tsx | 9 ++---- .../MoneyRequestReportTransactionList.tsx | 32 +++++++++---------- .../SearchTypeMenuPopover.tsx | 4 +-- src/components/Search/index.tsx | 2 +- src/components/Search/types.ts | 2 ++ .../SelectionList/SearchTableHeader.tsx | 2 +- .../SelectionList/SortableTableHeader.tsx | 6 ++-- .../TransactionItemRow/DataCells/TypeCell.tsx | 13 +++++--- src/components/TransactionItemRow/index.tsx | 7 ++-- .../useReportScrollManager/index.native.ts | 16 ++++++++-- src/libs/API/parameters/OpenReportParams.ts | 2 +- .../ModalStackNavigators/index.tsx | 14 +++++--- .../useModalStackScreenOptions.ts | 6 +++- src/stories/TransactionItemRow.stories.tsx | 1 + src/styles/index.ts | 5 +++ 17 files changed, 81 insertions(+), 46 deletions(-) diff --git a/src/CONST.ts b/src/CONST.ts index 92c72a4e7b08..bb13c814709e 100755 --- a/src/CONST.ts +++ b/src/CONST.ts @@ -6339,6 +6339,10 @@ const CONST = { GROUP_BY: { REPORTS: 'reports', }, + TABLE_COLUMN_SIZES: { + NORMAL: 'normal', + WIDE: 'wide', + }, STATUS: { EXPENSE: { ALL: 'all', diff --git a/src/components/MoneyRequestReportView/MoneyRequestReportActionsList.tsx b/src/components/MoneyRequestReportView/MoneyRequestReportActionsList.tsx index 09fba96529f9..f7fdebc5f0ec 100644 --- a/src/components/MoneyRequestReportView/MoneyRequestReportActionsList.tsx +++ b/src/components/MoneyRequestReportView/MoneyRequestReportActionsList.tsx @@ -168,7 +168,7 @@ function MoneyRequestReportActionsList({report, reportActions = [], hasNewerActi hasNewestReportAction ) { setIsFloatingMessageCounterVisible(false); - // reportScrollManager.scrollToEnd(); + reportScrollManager.scrollToEnd(); } previousLastIndex.current = lastActionIndex; diff --git a/src/components/MoneyRequestReportView/MoneyRequestReportTableHeader.tsx b/src/components/MoneyRequestReportView/MoneyRequestReportTableHeader.tsx index 7b3a358d98c5..dd045bdf82d4 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,7 +55,7 @@ type SearchTableHeaderProps = { sortBy?: SortableColumnName; sortOrder?: SortOrder; onSortPress: (column: SortableColumnName, order: SortOrder) => void; - dateColumnSize: 'normal' | 'wide'; + dateColumnSize: TableColumnSize; shouldShowSorting: boolean; }; @@ -66,10 +64,9 @@ const shouldShowColumn = () => true; function MoneyRequestReportTableHeader({sortBy, sortOrder, onSortPress, dateColumnSize, shouldShowSorting}: SearchTableHeaderProps) { const styles = useThemeStyles(); - const StyleUtils = useStyleUtils(); return ( - + { const shouldShowYearForSomeTransaction = transactions.some((transaction) => shouldShowTransactionYear(transaction)); - return shouldShowYearForSomeTransaction ? 'wide' : 'normal'; + return shouldShowYearForSomeTransaction ? CONST.SEARCH.TABLE_COLUMN_SIZES.WIDE : CONST.SEARCH.TABLE_COLUMN_SIZES.NORMAL; }, [transactions]); if (sortedData.transactions.length === 0) { @@ -145,8 +145,10 @@ function MoneyRequestReportTransactionList({report, transactions, reportActions} // item.isSelected && styles.activeComponentBG, ]; + const listHorizontalPadding = styles.ph5; + return ( - <> + {!displayNarrowVersion && ( )} - + {sortedData.transactions.map((transaction) => { return ( - - - + ); })} {shouldShowBreakdown && ( - + {[ {text: translate('cardTransactions.outOfPocket'), value: formattedOutOfPocketAmount}, {text: translate('cardTransactions.companySpend'), value: formattedCompanySpendAmount}, @@ -223,7 +223,7 @@ function MoneyRequestReportTransactionList({report, transactions, reportActions} ))} )} - + {translate('common.comments')} {translate('common.total')} @@ -232,7 +232,7 @@ function MoneyRequestReportTransactionList({report, transactions, reportActions} - + ); } diff --git a/src/components/Search/SearchPageHeader/SearchTypeMenuPopover.tsx b/src/components/Search/SearchPageHeader/SearchTypeMenuPopover.tsx index 8eac3505f1af..b55a993afdd6 100644 --- a/src/components/Search/SearchPageHeader/SearchTypeMenuPopover.tsx +++ b/src/components/Search/SearchPageHeader/SearchTypeMenuPopover.tsx @@ -95,8 +95,8 @@ function SearchTypeMenuPopover({queryJSON, searchName}: SearchTypeMenuNarrowProp const jsonQuery = buildSearchQueryJSON(item.query) ?? ({} as SearchQueryJSON); savedSearchTitle = buildUserReadableQueryString(jsonQuery, personalDetails, reports, taxRates, allCards, cardFeedNamesWithType); } - - const baseMenuItem: SavedSearchMenuItem = createBaseSavedSearchMenuItem(item, key, index, savedSearchTitle, hash); + const isItemFocused = Number(key) === hash; + const baseMenuItem: SavedSearchMenuItem = createBaseSavedSearchMenuItem(item, key, index, savedSearchTitle, isItemFocused); return { ...baseMenuItem, diff --git a/src/components/Search/index.tsx b/src/components/Search/index.tsx index c5a10c43e76c..f1ad636201bc 100644 --- a/src/components/Search/index.tsx +++ b/src/components/Search/index.tsx @@ -517,7 +517,7 @@ function Search({queryJSON, currentSearchResults, lastNonEmptySearchResults, onS shouldSingleExecuteRowSelect shouldPreventDefaultFocusOnSelectRow={!canUseTouchScreen()} shouldPreventDefault={false} - listHeaderWrapperStyle={[styles.ph8, styles.pt3]} + listHeaderWrapperStyle={styles.listTableHeader} containerStyle={[styles.pv0, type === CONST.SEARCH.DATA_TYPES.CHAT && !isSmallScreenWidth && styles.pt3]} showScrollIndicator={false} onEndReachedThreshold={0.75} diff --git a/src/components/Search/types.ts b/src/components/Search/types.ts index d5be6bb83cf4..04151ee4c7e3 100644 --- a/src/components/Search/types.ts +++ b/src/components/Search/types.ts @@ -59,6 +59,7 @@ type TripSearchStatus = ValueOf; 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; @@ -51,7 +51,7 @@ function SortableTableHeader({columns, sortBy, sortOrder, shouldShowColumn, date textStyle={textStyle} sortOrder={sortOrder ?? CONST.SEARCH.SORT_ORDER.ASC} isActive={isActive} - containerStyle={[StyleUtils.getReportTableColumnStyles(columnName, dateColumnSize === 'wide')]} + containerStyle={[StyleUtils.getReportTableColumnStyles(columnName, dateColumnSize === CONST.SEARCH.TABLE_COLUMN_SIZES.WIDE)]} isSortable={isSortable} onPress={(order: SortOrder) => 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 eaf0b56612f8..f3cfbb027a2b 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 {TableColumnSize} from '@components/Search/types'; import Text from '@components/Text'; import useStyleUtils from '@hooks/useStyleUtils'; import useThemeStyles from '@hooks/useThemeStyles'; @@ -28,7 +29,7 @@ function TransactionItemRow({ shouldUseNarrowLayout: boolean; isSelected: boolean; shouldShowTooltip: boolean; - dateColumnSize: 'normal' | 'wide'; + dateColumnSize: TableColumnSize; shouldShowChatBubbleComponent?: boolean; }) { const styles = useThemeStyles(); @@ -37,7 +38,7 @@ function TransactionItemRow({ const backgroundColor = isSelected ? styles.buttonDefaultBG : styles.highlightBG; const hasCategoryOrTag = !!transactionItem.category || !!transactionItem.tag; - const isDateColumnWide = dateColumnSize === 'wide'; + const isDateColumnWide = dateColumnSize === CONST.SEARCH.TABLE_COLUMN_SIZES.WIDE; return ( @@ -106,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/libs/API/parameters/OpenReportParams.ts b/src/libs/API/parameters/OpenReportParams.ts index 7e500d1b8c82..bf5105128794 100644 --- a/src/libs/API/parameters/OpenReportParams.ts +++ b/src/libs/API/parameters/OpenReportParams.ts @@ -20,7 +20,7 @@ type OpenReportParams = { * 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; + useTableReportView?: boolean; }; export default OpenReportParams; diff --git a/src/libs/Navigation/AppNavigator/ModalStackNavigators/index.tsx b/src/libs/Navigation/AppNavigator/ModalStackNavigators/index.tsx index 1b5c28549835..fd9b10637bf9 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, @@ -694,10 +695,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/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/styles/index.ts b/src/styles/index.ts index 6fdb05ce835f..00d2b9ad2cad 100644 --- a/src/styles/index.ts +++ b/src/styles/index.ts @@ -4869,6 +4869,11 @@ const styles = (theme: ThemeColors) => borderRadius: 8, }, + listTableHeader: { + paddingVertical: 12, + paddingHorizontal: 32, + }, + cardItemSecondaryIconStyle: { position: 'absolute', bottom: -4, From 276b51c899a726f012a64565dd5a668b27c5e672 Mon Sep 17 00:00:00 2001 From: Mateusz Titz Date: Wed, 26 Mar 2025 14:10:54 +0100 Subject: [PATCH 08/19] Add styling tweaks --- .../MoneyRequestReportActionsList.tsx | 2 ++ .../MoneyRequestReportTableHeader.tsx | 2 +- .../MoneyRequestReportTransactionList.tsx | 18 +++++++++++------- ...oneyRequestReportTransactionsNavigation.tsx | 4 ++++ 4 files changed, 18 insertions(+), 8 deletions(-) diff --git a/src/components/MoneyRequestReportView/MoneyRequestReportActionsList.tsx b/src/components/MoneyRequestReportView/MoneyRequestReportActionsList.tsx index f7fdebc5f0ec..4b5e3901a88c 100644 --- a/src/components/MoneyRequestReportView/MoneyRequestReportActionsList.tsx +++ b/src/components/MoneyRequestReportView/MoneyRequestReportActionsList.tsx @@ -341,6 +341,7 @@ function MoneyRequestReportActionsList({report, reportActions = [], hasNewerActi } }; + const reportHasComments = visibleReportActions.length > 0; const trackVerticalScrolling = (event: NativeSyntheticEvent) => { scrollingVerticalOffset.current = event.nativeEvent.contentOffset.y; handleUnreadFloatingButton(); @@ -370,6 +371,7 @@ function MoneyRequestReportActionsList({report, reportActions = [], hasNewerActi report={report} transactions={transactions} reportActions={reportActions} + hasComments={reportHasComments} /> } keyboardShouldPersistTaps="handled" diff --git a/src/components/MoneyRequestReportView/MoneyRequestReportTableHeader.tsx b/src/components/MoneyRequestReportView/MoneyRequestReportTableHeader.tsx index dd045bdf82d4..68b7073501e9 100644 --- a/src/components/MoneyRequestReportView/MoneyRequestReportTableHeader.tsx +++ b/src/components/MoneyRequestReportView/MoneyRequestReportTableHeader.tsx @@ -66,7 +66,7 @@ function MoneyRequestReportTableHeader({sortBy, sortOrder, onSortPress, dateColu const styles = useThemeStyles(); return ( - + transaction[getTransactionKey(transaction, key)] === firstValidTransaction[keyOfFirstValidTransaction]); }; -function MoneyRequestReportTransactionList({report, transactions, reportActions}: MoneyRequestReportTransactionListProps) { +function MoneyRequestReportTransactionList({report, transactions, reportActions, hasComments}: MoneyRequestReportTransactionListProps) { const styles = useThemeStyles(); const {translate} = useLocalize(); const {shouldUseNarrowLayout, isMediumScreenWidth} = useResponsiveLayout(); @@ -75,7 +78,8 @@ function MoneyRequestReportTransactionList({report, transactions, reportActions} const {totalDisplaySpend, nonReimbursableSpend, reimbursableSpend} = getMoneyRequestSpendBreakdown(report); const formattedOutOfPocketAmount = convertToDisplayString(reimbursableSpend, report?.currency); const formattedCompanySpendAmount = convertToDisplayString(nonReimbursableSpend, report?.currency); - const shouldShowBreakdown = !!nonReimbursableSpend && !!reimbursableSpend; + // const shouldShowBreakdown = !!nonReimbursableSpend && !!reimbursableSpend; + const shouldShowBreakdown = true; const {bind} = useHover(); const {isMouseDownOnInput, setMouseUp} = useMouseContext(); @@ -164,7 +168,7 @@ function MoneyRequestReportTransactionList({report, transactions, reportActions} }} /> )} - + {sortedData.transactions.map((transaction) => { return ( {shouldShowBreakdown && ( - + {[ {text: translate('cardTransactions.outOfPocket'), value: formattedOutOfPocketAmount}, {text: translate('cardTransactions.companySpend'), value: formattedCompanySpendAmount}, ].map(({text, value}) => ( - + )} - {translate('common.comments')} - + {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 index 3d9cfa0c8db5..188b1eb91d09 100644 --- a/src/components/MoneyRequestReportView/MoneyRequestReportTransactionsNavigation.tsx +++ b/src/components/MoneyRequestReportView/MoneyRequestReportTransactionsNavigation.tsx @@ -32,6 +32,10 @@ function MoneyRequestReportTransactionsNavigation({currentReportID}: MoneyReques const backTo = Navigation.getActiveRoute(); + if (reportIDsList.length < 2) { + return; + } + const pressableStyle = [ styles.ml1, styles.alignItemsCenter, From b2df980a2997bec1a6e67683e49909e216ca91ab Mon Sep 17 00:00:00 2001 From: Mateusz Titz Date: Thu, 27 Mar 2025 10:34:57 +0100 Subject: [PATCH 09/19] Improve filtering out actions for MoneyRequestReportActionsList --- .../MoneyRequestReportActionsList.tsx | 13 ++++----- src/libs/MoneyRequestReportUtils.ts | 28 +++++++++++++++++++ src/libs/Permissions.ts | 1 + 3 files changed, 34 insertions(+), 8 deletions(-) create mode 100644 src/libs/MoneyRequestReportUtils.ts diff --git a/src/components/MoneyRequestReportView/MoneyRequestReportActionsList.tsx b/src/components/MoneyRequestReportView/MoneyRequestReportActionsList.tsx index 4b5e3901a88c..c4db835f2f4e 100644 --- a/src/components/MoneyRequestReportView/MoneyRequestReportActionsList.tsx +++ b/src/components/MoneyRequestReportView/MoneyRequestReportActionsList.tsx @@ -13,6 +13,7 @@ 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, @@ -67,11 +68,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; }); @@ -98,7 +95,7 @@ function MoneyRequestReportActionsList({report, reportActions = [], hasNewerActi const transactionThreadReportID = getOneTransactionThreadReportID(reportID, reportActions ?? [], false); const firstVisibleReportActionID = useMemo(() => 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}); @@ -111,10 +108,10 @@ function MoneyRequestReportActionsList({report, reportActions = [], hasNewerActi // 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) ); diff --git a/src/libs/MoneyRequestReportUtils.ts b/src/libs/MoneyRequestReportUtils.ts new file mode 100644 index 000000000000..9de74a0e7252 --- /dev/null +++ b/src/libs/MoneyRequestReportUtils.ts @@ -0,0 +1,28 @@ +import CONST from '@src/CONST'; +import type * as OnyxTypes from '@src/types/onyx'; +import {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: OnyxTypes.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; +} + +// eslint-disable-next-line import/prefer-default-export +export {isActionVisibleOnMoneyRequestReport}; diff --git a/src/libs/Permissions.ts b/src/libs/Permissions.ts index c708518d584d..8ce2e6a772f1 100644 --- a/src/libs/Permissions.ts +++ b/src/libs/Permissions.ts @@ -55,6 +55,7 @@ function canUseCustomRules(betas: OnyxEntry): boolean { } function canUseTableReportView(betas: OnyxEntry): boolean { + return true; return !!betas?.includes(CONST.BETAS.TABLE_REPORT_VIEW) || canUseAllBetas(betas); } From fb78db244421c063909faafcf08160f41b0d8e70 Mon Sep 17 00:00:00 2001 From: Mateusz Titz Date: Thu, 27 Mar 2025 10:50:43 +0100 Subject: [PATCH 10/19] Update styling of table headers --- src/components/Search/SearchList.tsx | 2 +- src/components/TransactionItemRow/index.tsx | 2 +- src/libs/Permissions.ts | 1 - src/styles/index.ts | 2 -- 4 files changed, 2 insertions(+), 5 deletions(-) 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 && ( - + ): boolean { } function canUseTableReportView(betas: OnyxEntry): boolean { - return true; return !!betas?.includes(CONST.BETAS.TABLE_REPORT_VIEW) || canUseAllBetas(betas); } diff --git a/src/styles/index.ts b/src/styles/index.ts index 954b77bff064..88a34d6493e5 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', }, From 7267ab2c63c043e70c2f10e86ec5d97e7698a1b2 Mon Sep 17 00:00:00 2001 From: Mateusz Titz Date: Fri, 28 Mar 2025 10:21:56 +0100 Subject: [PATCH 11/19] Update styling and skeleton loader of MoneyRequestReportView --- .../MoneyRequestReportActionsList.tsx | 2 +- .../MoneyRequestReportTransactionList.tsx | 9 ++-- ...neyRequestReportTransactionsNavigation.tsx | 9 ++-- .../MoneyRequestReportView.tsx | 51 ++++++++++++------- src/libs/ReportActionsUtils.ts | 8 +-- 5 files changed, 46 insertions(+), 33 deletions(-) diff --git a/src/components/MoneyRequestReportView/MoneyRequestReportActionsList.tsx b/src/components/MoneyRequestReportView/MoneyRequestReportActionsList.tsx index c4db835f2f4e..b331d95e4dd9 100644 --- a/src/components/MoneyRequestReportView/MoneyRequestReportActionsList.tsx +++ b/src/components/MoneyRequestReportView/MoneyRequestReportActionsList.tsx @@ -346,7 +346,7 @@ function MoneyRequestReportActionsList({report, reportActions = [], hasNewerActi return ( - + { - const iouAction = getIOUActionForReportIDPure(reportActions, activeTransaction.transactionID); + const iouAction = getIOUActionForTransactionID(reportActions, activeTransaction.transactionID); const reportIDToNavigate = iouAction?.childReportID; if (!reportIDToNavigate) { return; @@ -123,7 +122,7 @@ function MoneyRequestReportTransactionList({report, transactions, reportActions, // we use this data to display prev/next arrows in RHP for navigating between transactions const sortedSiblingTransactionReportIDs = sortedData.transactions .map((transaction) => { - const action = getIOUActionForReportIDPure(reportActions, transaction.transactionID); + const action = getIOUActionForTransactionID(reportActions, transaction.transactionID); return action?.childReportID; }) .filter((reportID): reportID is string => !!reportID); diff --git a/src/components/MoneyRequestReportView/MoneyRequestReportTransactionsNavigation.tsx b/src/components/MoneyRequestReportView/MoneyRequestReportTransactionsNavigation.tsx index 188b1eb91d09..1df209a7d2e7 100644 --- a/src/components/MoneyRequestReportView/MoneyRequestReportTransactionsNavigation.tsx +++ b/src/components/MoneyRequestReportView/MoneyRequestReportTransactionsNavigation.tsx @@ -5,6 +5,7 @@ import PressableWithFeedback from '@components/Pressable/PressableWithFeedback'; import useTheme from '@hooks/useTheme'; import useThemeStyles from '@hooks/useThemeStyles'; import Navigation from '@navigation/Navigation'; +import CONST from '@src/CONST'; import ROUTES from '@src/ROUTES'; import {getActiveTransactionReportIDs} from './TransactionReportIDRepository'; @@ -51,9 +52,9 @@ function MoneyRequestReportTransactionsNavigation({currentReportID}: MoneyReques return ( <> { @@ -69,9 +70,9 @@ function MoneyRequestReportTransactionsNavigation({currentReportID}: MoneyReques /> { diff --git a/src/components/MoneyRequestReportView/MoneyRequestReportView.tsx b/src/components/MoneyRequestReportView/MoneyRequestReportView.tsx index 1e8b90d27acf..965699beab01 100644 --- a/src/components/MoneyRequestReportView/MoneyRequestReportView.tsx +++ b/src/components/MoneyRequestReportView/MoneyRequestReportView.tsx @@ -5,6 +5,7 @@ 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'; @@ -15,6 +16,7 @@ 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'; @@ -35,6 +37,17 @@ type MoneyRequestReportViewProps = { backToRoute: Route | undefined; }; +function InitialLoadingSkeleton({styles}: {styles: ThemeStyles}) { + return ( + + + {}} /> + + + + ); +} + function getParentReportAction(parentReportActions: OnyxEntry, parentReportActionID: string | undefined): OnyxEntry { if (!parentReportActions || !parentReportActionID) { return; @@ -51,12 +64,7 @@ function MoneyRequestReportView({report, policy, reportMetadata, shouldDisplayRe 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, @@ -64,10 +72,11 @@ function MoneyRequestReportView({report, policy, reportMetadata, shouldDisplayRe }); const lastReportAction = [...reportActions, parentReportAction].find((action) => canEditReportAction(action) && !isMoneyRequestAction(action)); - const isLoadingInitialReportActions = reportMetadata?.isLoadingInitialReportActions; + // const isLoadingInitialReportActions = reportMetadata?.isLoadingInitialReportActions; + const isLoadingInitialReportActions = true; if (isLoadingInitialReportActions && reportActions.length === 0 && !isOffline) { - return ; + return ; } if (reportActions.length === 0) { @@ -81,17 +90,21 @@ function MoneyRequestReportView({report, policy, reportMetadata, shouldDisplayRe return ( - { - Navigation.goBack(backToRoute); - }} - /> - {report && !isLoadingApp ? ( + {!isLoadingApp ? ( + { + Navigation.goBack(backToRoute); + }} + /> + ) : ( + + )} + {!isLoadingApp ? ( { +function getIOUActionForTransactionID(reportActions: ReportAction[], transactionID: string): OnyxEntry { return reportActions.find((reportAction) => { const IOUTransactionID = isMoneyRequestAction(reportAction) ? getOriginalMessage(reportAction)?.IOUTransactionID : undefined; return IOUTransactionID === transactionID; @@ -2313,7 +2313,7 @@ export { getDismissedViolationMessageText, getFirstVisibleReportActionID, getIOUActionForReportID, - getIOUActionForReportIDPure, + getIOUActionForTransactionID, getIOUReportIDFromReportActionPreview, getLastClosedReportAction, getLastVisibleAction, From aa7619280187951e825187961d30317e6d8cca9d Mon Sep 17 00:00:00 2001 From: Mateusz Titz Date: Fri, 28 Mar 2025 11:27:15 +0100 Subject: [PATCH 12/19] Add fixes after PR review --- .../MoneyRequestReportTransactionList.tsx | 8 +----- ...neyRequestReportTransactionsNavigation.tsx | 22 +++++++++++++++- .../TransactionReportIDRepository.ts | 26 ++++++------------- src/libs/actions/Report.ts | 16 +++++++++--- 4 files changed, 43 insertions(+), 29 deletions(-) diff --git a/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx b/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx index 1b2cfcb51ae5..f99ef2bac224 100644 --- a/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx +++ b/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx @@ -143,10 +143,7 @@ function MoneyRequestReportTransactionList({report, transactions, reportActions, return; } - const pressableStyle = [ - styles.overflowHidden, - // item.isSelected && styles.activeComponentBG, - ]; + const pressableStyle = [styles.overflowHidden]; const listHorizontalPadding = styles.ph5; @@ -183,13 +180,10 @@ function MoneyRequestReportTransactionList({report, transactions, reportActions, role={getButtonRole(true)} isNested hoverDimmingValue={1} - // pressDimmingValue={item.isInteractive === false ? 1 : variables.pressDimValue} - // hoverStyle={item.isSelected && styles.activeComponentBG} onMouseDown={(e) => e.preventDefault()} id={transaction.transactionID} style={[pressableStyle]} onMouseLeave={handleMouseLeave} - wrapperStyle={[]} > ) { + 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) { @@ -33,7 +53,7 @@ function MoneyRequestReportTransactionsNavigation({currentReportID}: MoneyReques const backTo = Navigation.getActiveRoute(); - if (reportIDsList.length < 2) { + if (!shouldShow || reportIDsList.length < 2) { return; } diff --git a/src/components/MoneyRequestReportView/TransactionReportIDRepository.ts b/src/components/MoneyRequestReportView/TransactionReportIDRepository.ts index 66c80a2cbc90..1e8469d81f24 100644 --- a/src/components/MoneyRequestReportView/TransactionReportIDRepository.ts +++ b/src/components/MoneyRequestReportView/TransactionReportIDRepository.ts @@ -1,3 +1,4 @@ +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. @@ -5,26 +6,15 @@ * * 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 getTransactionReportIDRepository() { - const transactionReportIDs: string[] = []; - function setActiveTransactionReportIDs(ids: string[]) { - // Cleaning previously saved keys because - transactionReportIDs.splice(0, Infinity); - transactionReportIDs.push(...ids); - } - - function getActiveTransactionReportIDs() { - return transactionReportIDs; - } - - return { - setActiveTransactionReportIDs, - getActiveTransactionReportIDs, - }; +function setActiveTransactionReportIDs(ids: string[]) { + // Cleaning previously saved keys because + transactionReportIDs.splice(0, Infinity); + transactionReportIDs.push(...ids); } -// Initialize singleton instance, because we only ever need 1 state for this function -const {setActiveTransactionReportIDs, getActiveTransactionReportIDs} = getTransactionReportIDRepository(); +function getActiveTransactionReportIDs() { + return transactionReportIDs; +} export {setActiveTransactionReportIDs, getActiveTransactionReportIDs}; diff --git a/src/libs/actions/Report.ts b/src/libs/actions/Report.ts index db48087344fe..a70c95c33764 100644 --- a/src/libs/actions/Report.ts +++ b/src/libs/actions/Report.ts @@ -155,6 +155,7 @@ import type {Route} from '@src/ROUTES'; import ROUTES from '@src/ROUTES'; import INPUT_IDS from '@src/types/form/NewRoomForm'; import type { + Beta, DismissedProductTraining, IntroSelected, InvitedEmailsToAccountIDs, @@ -178,6 +179,7 @@ import type {ConnectionName} from '@src/types/onyx/Policy'; import type {NotificationPreference, Participants, Participant as ReportParticipant, RoomVisibility, WriteCapability} from '@src/types/onyx/Report'; import type {Message, ReportActions} from '@src/types/onyx/ReportAction'; import {isEmptyObject} from '@src/types/utils/EmptyObject'; +import Permissions from '../Permissions'; import {clearByKey} from './CachedPDFPaths'; import {setDownload} from './Download'; import {close} from './Modal'; @@ -193,6 +195,12 @@ import {canAnonymousUserAccessRoute, hasAuthToken, isAnonymousUser, signOutAndRe import {isOnboardingFlowCompleted, onServerDataReady, setOnboardingErrorMessage} from './Welcome'; import {startOnboardingFlow} from './Welcome/OnboardingFlow'; +let allBetas: OnyxEntry; +Onyx.connect({ + key: ONYXKEYS.BETAS, + callback: (value) => (allBetas = value), +}); + type SubscriberCallback = (isFromCurrentUser: boolean, reportActionID: string | undefined) => void; type ActionSubscriber = { @@ -881,7 +889,6 @@ function openReport( parentReportActionID?: string, isFromDeepLink = false, participantAccountIDList: number[] = [], - useTableReportView = false, avatar?: File | CustomRNImageManipulatorResult, ) { if (!reportID) { @@ -950,9 +957,12 @@ function openReport( emailList: participantLoginList ? participantLoginList.join(',') : '', accountIDList: participantAccountIDList ? participantAccountIDList.join(',') : '', parentReportActionID, - useTableReportView, }; + if (Permissions.canUseTableReportView(allBetas)) { + parameters.useTableReportView = true; + } + const isInviteOnboardingComplete = introSelected?.isInviteOnboardingComplete ?? false; const isOnboardingCompleted = onboarding?.hasCompletedGuidedSetupFlow ?? false; @@ -1219,7 +1229,7 @@ function navigateToAndOpenReport( const report = isEmptyObject(chat) ? newChat : chat; // We want to pass newChat here because if anything is passed in that param (even an existing chat), we will try to create a chat on the server - openReport(report?.reportID, '', userLogins, newChat, undefined, undefined, undefined, false, avatarFile); + openReport(report?.reportID, '', userLogins, newChat, undefined, undefined, undefined, avatarFile); if (shouldDismissModal) { if (getIsNarrowLayout()) { Navigation.dismissModalWithReport({report}); From fec3a797f63108d5273c833fe3dcd58382715206 Mon Sep 17 00:00:00 2001 From: Mateusz Titz Date: Fri, 28 Mar 2025 11:30:31 +0100 Subject: [PATCH 13/19] Fix linting and TS for MoneyRequestReportPage --- src/libs/actions/Report.ts | 3 +-- src/pages/Search/SearchMoneyRequestReportPage.tsx | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/src/libs/actions/Report.ts b/src/libs/actions/Report.ts index a70c95c33764..b223b5b7dceb 100644 --- a/src/libs/actions/Report.ts +++ b/src/libs/actions/Report.ts @@ -83,6 +83,7 @@ import type {NetworkStatus} from '@libs/NetworkConnection'; import LocalNotification from '@libs/Notification/LocalNotification'; import {rand64} from '@libs/NumberUtils'; import Parser from '@libs/Parser'; +import Permissions from '@libs/Permissions'; import * as PersonalDetailsUtils from '@libs/PersonalDetailsUtils'; import * as PhoneNumber from '@libs/PhoneNumber'; import {extractPolicyIDFromPath, getPolicy} from '@libs/PolicyUtils'; @@ -179,7 +180,6 @@ import type {ConnectionName} from '@src/types/onyx/Policy'; import type {NotificationPreference, Participants, Participant as ReportParticipant, RoomVisibility, WriteCapability} from '@src/types/onyx/Report'; import type {Message, ReportActions} from '@src/types/onyx/ReportAction'; import {isEmptyObject} from '@src/types/utils/EmptyObject'; -import Permissions from '../Permissions'; import {clearByKey} from './CachedPDFPaths'; import {setDownload} from './Download'; import {close} from './Modal'; @@ -879,7 +879,6 @@ 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 useTableReportView Flag deciding how api returns reportActions - if set to true, api will return oldest first starting from the beginning of report. */ function openReport( reportID: string | undefined, diff --git a/src/pages/Search/SearchMoneyRequestReportPage.tsx b/src/pages/Search/SearchMoneyRequestReportPage.tsx index c52e50427144..7472f342bdb7 100644 --- a/src/pages/Search/SearchMoneyRequestReportPage.tsx +++ b/src/pages/Search/SearchMoneyRequestReportPage.tsx @@ -60,7 +60,7 @@ function SearchMoneyRequestReportPage({route}: SearchMoneyRequestPageProps) { const reportID = report?.reportID; useEffect(() => { - openReport(reportIDFromRoute, '', [], undefined, undefined, false, [], true); + openReport(reportIDFromRoute, '', [], undefined, undefined, false, []); }, [reportIDFromRoute]); // eslint-disable-next-line rulesdir/no-negated-variables From eaf93795b9411e1abbd2472c44505a78656548e4 Mon Sep 17 00:00:00 2001 From: Mateusz Titz Date: Fri, 28 Mar 2025 12:08:25 +0100 Subject: [PATCH 14/19] Fix undefined routes and openReport call --- .../MoneyRequestReportTransactionsNavigation.tsx | 4 ++-- src/libs/actions/Report.ts | 4 +++- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/src/components/MoneyRequestReportView/MoneyRequestReportTransactionsNavigation.tsx b/src/components/MoneyRequestReportView/MoneyRequestReportTransactionsNavigation.tsx index 68a760e19b60..f5dcc9536a47 100644 --- a/src/components/MoneyRequestReportView/MoneyRequestReportTransactionsNavigation.tsx +++ b/src/components/MoneyRequestReportView/MoneyRequestReportTransactionsNavigation.tsx @@ -22,8 +22,8 @@ type MoneyRequestReportRHPNavigationButtonsProps = { * 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)); +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; diff --git a/src/libs/actions/Report.ts b/src/libs/actions/Report.ts index b223b5b7dceb..720c3e582d81 100644 --- a/src/libs/actions/Report.ts +++ b/src/libs/actions/Report.ts @@ -879,6 +879,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, @@ -889,6 +890,7 @@ function openReport( isFromDeepLink = false, participantAccountIDList: number[] = [], avatar?: File | CustomRNImageManipulatorResult, + temporaryShouldUseTableReportView = false, ) { if (!reportID) { return; @@ -958,7 +960,7 @@ function openReport( parentReportActionID, }; - if (Permissions.canUseTableReportView(allBetas)) { + if (temporaryShouldUseTableReportView && Permissions.canUseTableReportView(allBetas)) { parameters.useTableReportView = true; } From 36290e1eeb12b629ad8db5292326bff932ad794e Mon Sep 17 00:00:00 2001 From: Mateusz Titz Date: Fri, 28 Mar 2025 12:21:59 +0100 Subject: [PATCH 15/19] Improve comments around openReport calling new flag --- src/libs/actions/Report.ts | 2 ++ src/pages/Search/SearchMoneyRequestReportPage.tsx | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/libs/actions/Report.ts b/src/libs/actions/Report.ts index 720c3e582d81..99599780b58d 100644 --- a/src/libs/actions/Report.ts +++ b/src/libs/actions/Report.ts @@ -960,6 +960,8 @@ function openReport( parentReportActionID, }; + // temporary flag will be removed once ReportScreen supports MoneyRequestReportView - https://github.com/Expensify/App/issues/57509 + // Permission will be removed before the end of the project if (temporaryShouldUseTableReportView && Permissions.canUseTableReportView(allBetas)) { parameters.useTableReportView = true; } diff --git a/src/pages/Search/SearchMoneyRequestReportPage.tsx b/src/pages/Search/SearchMoneyRequestReportPage.tsx index 7472f342bdb7..d6aa2f25b841 100644 --- a/src/pages/Search/SearchMoneyRequestReportPage.tsx +++ b/src/pages/Search/SearchMoneyRequestReportPage.tsx @@ -60,7 +60,7 @@ function SearchMoneyRequestReportPage({route}: SearchMoneyRequestPageProps) { const reportID = report?.reportID; useEffect(() => { - openReport(reportIDFromRoute, '', [], undefined, undefined, false, []); + openReport(reportIDFromRoute, '', [], undefined, undefined, false, [], undefined, true); }, [reportIDFromRoute]); // eslint-disable-next-line rulesdir/no-negated-variables From fca16572784f8c8583cde70c95ae2ed1c6843a84 Mon Sep 17 00:00:00 2001 From: Mateusz Titz Date: Mon, 31 Mar 2025 10:15:57 +0200 Subject: [PATCH 16/19] Fix code style --- .../MoneyRequestReportView/MoneyRequestReportView.tsx | 3 +-- src/libs/actions/Report.ts | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/src/components/MoneyRequestReportView/MoneyRequestReportView.tsx b/src/components/MoneyRequestReportView/MoneyRequestReportView.tsx index 965699beab01..f53fa8f19e89 100644 --- a/src/components/MoneyRequestReportView/MoneyRequestReportView.tsx +++ b/src/components/MoneyRequestReportView/MoneyRequestReportView.tsx @@ -72,8 +72,7 @@ function MoneyRequestReportView({report, policy, reportMetadata, shouldDisplayRe }); const lastReportAction = [...reportActions, parentReportAction].find((action) => canEditReportAction(action) && !isMoneyRequestAction(action)); - // const isLoadingInitialReportActions = reportMetadata?.isLoadingInitialReportActions; - const isLoadingInitialReportActions = true; + const isLoadingInitialReportActions = reportMetadata?.isLoadingInitialReportActions; if (isLoadingInitialReportActions && reportActions.length === 0 && !isOffline) { return ; diff --git a/src/libs/actions/Report.ts b/src/libs/actions/Report.ts index 99599780b58d..a89ad7386d9a 100644 --- a/src/libs/actions/Report.ts +++ b/src/libs/actions/Report.ts @@ -879,7 +879,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 + * @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, From 91f6b5c641f0991d5253e50f36400e1e8d9d22de Mon Sep 17 00:00:00 2001 From: Mateusz Titz Date: Mon, 31 Mar 2025 11:46:06 +0200 Subject: [PATCH 17/19] Handle EmptyState in MoneyRequestReportActionsList after merge conflicts --- .../MoneyRequestReportActionsList.tsx | 57 +++++++++---------- .../MoneyRequestReportTransactionList.tsx | 7 +-- .../SearchMoneyRequestReportEmptyState.tsx | 1 + 3 files changed, 31 insertions(+), 34 deletions(-) diff --git a/src/components/MoneyRequestReportView/MoneyRequestReportActionsList.tsx b/src/components/MoneyRequestReportView/MoneyRequestReportActionsList.tsx index 26a3b6f8b24d..d1eae9ee8f02 100644 --- a/src/components/MoneyRequestReportView/MoneyRequestReportActionsList.tsx +++ b/src/components/MoneyRequestReportView/MoneyRequestReportActionsList.tsx @@ -353,36 +353,35 @@ function MoneyRequestReportActionsList({report, reportActions = [], hasNewerActi isActive={isFloatingMessageCounterVisible} onClick={scrollToBottomAndMarkReportAsRead} /> - - {isEmpty(visibleReportActions) && isEmpty(transactions) ? ( - - ) : ( - item.reportActionID} - onEndReached={onEndReached} - onEndReachedThreshold={0.75} - onStartReached={onStartReached} - onStartReachedThreshold={0.75} - ListHeaderComponent={ - - } - keyboardShouldPersistTaps="handled" - onScroll={trackVerticalScrolling} - ref={reportScrollManager.ref} - /> + {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/MoneyRequestReportTransactionList.tsx b/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx index b4d567ed9742..f12d202a7dae 100644 --- a/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx +++ b/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx @@ -22,8 +22,8 @@ import CONST from '@src/CONST'; import ROUTES from '@src/ROUTES'; import type * as OnyxTypes from '@src/types/onyx'; import MoneyRequestReportTableHeader from './MoneyRequestReportTableHeader'; -import {setActiveTransactionReportIDs} from './TransactionReportIDRepository'; import SearchMoneyRequestReportEmptyState from './SearchMoneyRequestReportEmptyState'; +import {setActiveTransactionReportIDs} from './TransactionReportIDRepository'; type MoneyRequestReportTransactionListProps = { report: OnyxTypes.Report; @@ -141,10 +141,6 @@ function MoneyRequestReportTransactionList({report, transactions, reportActions, return shouldShowYearForSomeTransaction ? CONST.SEARCH.TABLE_COLUMN_SIZES.WIDE : CONST.SEARCH.TABLE_COLUMN_SIZES.NORMAL; }, [transactions]); - if (sortedData.transactions.length === 0) { - return; - } - const pressableStyle = [styles.overflowHidden]; const listHorizontalPadding = styles.ph5; @@ -231,6 +227,7 @@ function MoneyRequestReportTransactionList({report, transactions, reportActions, + ) : ( ); diff --git a/src/components/MoneyRequestReportView/SearchMoneyRequestReportEmptyState.tsx b/src/components/MoneyRequestReportView/SearchMoneyRequestReportEmptyState.tsx index 679d6cf7fbf6..eba4b7d3695e 100644 --- a/src/components/MoneyRequestReportView/SearchMoneyRequestReportEmptyState.tsx +++ b/src/components/MoneyRequestReportView/SearchMoneyRequestReportEmptyState.tsx @@ -22,6 +22,7 @@ function SearchMoneyRequestReportEmptyState() { headerStyles={[styles.emptyStateMoneyRequestReport]} lottieWebViewStyles={styles.emptyStateFolderWebStyles} headerContentStyles={styles.emptyStateFolderWebStyles} + minModalHeight={380} /> ); From 8d628feef87b05c5c66a5aefa0e79315df56b9d8 Mon Sep 17 00:00:00 2001 From: Mateusz Titz Date: Mon, 31 Mar 2025 16:51:24 +0200 Subject: [PATCH 18/19] Add tests for MoneyRequestReportTransactionList --- .../MoneyRequestReportTransactionList.tsx | 13 +-- .../SearchMoneyRequestReportEmptyState.tsx | 4 +- src/libs/MoneyRequestReportUtils.ts | 26 ++++-- src/libs/actions/Report.ts | 4 +- src/stories/mockData/transactions.ts | 86 +++++++++++++++++-- tests/unit/libs/MoneyRequestReportUtils.ts | 32 +++++++ 6 files changed, 139 insertions(+), 26 deletions(-) create mode 100644 tests/unit/libs/MoneyRequestReportUtils.ts diff --git a/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx b/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx index f12d202a7dae..676a4bfb28b9 100644 --- a/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx +++ b/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx @@ -13,6 +13,7 @@ import {useMouseContext} from '@hooks/useMouseContext'; import useResponsiveLayout from '@hooks/useResponsiveLayout'; import useThemeStyles from '@hooks/useThemeStyles'; import {convertToDisplayString} from '@libs/CurrencyUtils'; +import {getThreadReportIDsForTransactions} from '@libs/MoneyRequestReportUtils'; import {getIOUActionForTransactionID} from '@libs/ReportActionsUtils'; import {getMoneyRequestSpendBreakdown} from '@libs/ReportUtils'; import {compareValues} from '@libs/SearchUIUtils'; @@ -120,15 +121,9 @@ function MoneyRequestReportTransactionList({report, transactions, reportActions, const backTo = Navigation.getActiveRoute(); - // Single transaction report will open in RHP, and we need to find every other report ID for every sibling to `activeTransaction` - // we use this data to display prev/next arrows in RHP for navigating between transactions - const sortedSiblingTransactionReportIDs = sortedData.transactions - .map((transaction) => { - const action = getIOUActionForTransactionID(reportActions, transaction.transactionID); - return action?.childReportID; - }) - .filter((reportID): reportID is string => !!reportID); - + // 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})); diff --git a/src/components/MoneyRequestReportView/SearchMoneyRequestReportEmptyState.tsx b/src/components/MoneyRequestReportView/SearchMoneyRequestReportEmptyState.tsx index eba4b7d3695e..5b4591760f07 100644 --- a/src/components/MoneyRequestReportView/SearchMoneyRequestReportEmptyState.tsx +++ b/src/components/MoneyRequestReportView/SearchMoneyRequestReportEmptyState.tsx @@ -6,6 +6,8 @@ import useLocalize from '@hooks/useLocalize'; import useThemeStyles from '@hooks/useThemeStyles'; import CONST from '@src/CONST'; +const minModalHeight = 380; + function SearchMoneyRequestReportEmptyState() { const {translate} = useLocalize(); const styles = useThemeStyles(); @@ -22,7 +24,7 @@ function SearchMoneyRequestReportEmptyState() { headerStyles={[styles.emptyStateMoneyRequestReport]} lottieWebViewStyles={styles.emptyStateFolderWebStyles} headerContentStyles={styles.emptyStateFolderWebStyles} - minModalHeight={380} + minModalHeight={minModalHeight} /> ); diff --git a/src/libs/MoneyRequestReportUtils.ts b/src/libs/MoneyRequestReportUtils.ts index 9de74a0e7252..27105202ca06 100644 --- a/src/libs/MoneyRequestReportUtils.ts +++ b/src/libs/MoneyRequestReportUtils.ts @@ -1,12 +1,12 @@ import CONST from '@src/CONST'; -import type * as OnyxTypes from '@src/types/onyx'; -import {getOriginalMessage, isMoneyRequestAction} from './ReportActionsUtils'; +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]; +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. @@ -15,7 +15,7 @@ const IOU_ACTIONS_TO_FILTER_OUT: Array = [ * 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: OnyxTypes.ReportAction) { +function isActionVisibleOnMoneyRequestReport(action: ReportAction) { if (isMoneyRequestAction(action)) { const originalMessage = getOriginalMessage(action); return originalMessage ? !IOU_ACTIONS_TO_FILTER_OUT.includes(originalMessage.type) : false; @@ -24,5 +24,19 @@ function isActionVisibleOnMoneyRequestReport(action: OnyxTypes.ReportAction) { return action.actionName !== CONST.REPORT.ACTIONS.TYPE.CREATED; } -// eslint-disable-next-line import/prefer-default-export -export {isActionVisibleOnMoneyRequestReport}; +/** + * 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/actions/Report.ts b/src/libs/actions/Report.ts index 098d25a2916d..c0a89495b249 100644 --- a/src/libs/actions/Report.ts +++ b/src/libs/actions/Report.ts @@ -84,7 +84,6 @@ import {buildNextStep} from '@libs/NextStepUtils'; import LocalNotification from '@libs/Notification/LocalNotification'; import {rand64} from '@libs/NumberUtils'; import Parser from '@libs/Parser'; -import Permissions from '@libs/Permissions'; import * as PersonalDetailsUtils from '@libs/PersonalDetailsUtils'; import * as PhoneNumber from '@libs/PhoneNumber'; import {extractPolicyIDFromPath, getPolicy} from '@libs/PolicyUtils'; @@ -965,8 +964,7 @@ function openReport( }; // temporary flag will be removed once ReportScreen supports MoneyRequestReportView - https://github.com/Expensify/App/issues/57509 - // Permission will be removed before the end of the project - if (temporaryShouldUseTableReportView && Permissions.canUseTableReportView(allBetas)) { + if (temporaryShouldUseTableReportView) { parameters.useTableReportView = true; } 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/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([]); + }); +}); From 739e58d6af01df5bc6399874a6d9f76ce5c94b63 Mon Sep 17 00:00:00 2001 From: Mateusz Titz Date: Mon, 31 Mar 2025 16:56:01 +0200 Subject: [PATCH 19/19] Fix lint --- src/libs/actions/Report.ts | 7 ------- 1 file changed, 7 deletions(-) diff --git a/src/libs/actions/Report.ts b/src/libs/actions/Report.ts index c0a89495b249..4c150902f0e5 100644 --- a/src/libs/actions/Report.ts +++ b/src/libs/actions/Report.ts @@ -159,7 +159,6 @@ import type {Route} from '@src/ROUTES'; import ROUTES from '@src/ROUTES'; import INPUT_IDS from '@src/types/form/NewRoomForm'; import type { - Beta, DismissedProductTraining, IntroSelected, InvitedEmailsToAccountIDs, @@ -198,12 +197,6 @@ import {canAnonymousUserAccessRoute, hasAuthToken, isAnonymousUser, signOutAndRe import {isOnboardingFlowCompleted, onServerDataReady, setOnboardingErrorMessage} from './Welcome'; import {startOnboardingFlow} from './Welcome/OnboardingFlow'; -let allBetas: OnyxEntry; -Onyx.connect({ - key: ONYXKEYS.BETAS, - callback: (value) => (allBetas = value), -}); - type SubscriberCallback = (isFromCurrentUser: boolean, reportActionID: string | undefined) => void; type ActionSubscriber = {