diff --git a/src/hooks/useMarkAsRead.ts b/src/hooks/useMarkAsRead.ts index f42db642c7f7..ee1a8c6d2902 100644 --- a/src/hooks/useMarkAsRead.ts +++ b/src/hooks/useMarkAsRead.ts @@ -23,6 +23,7 @@ import useAppFocusEvent from './useAppFocusEvent'; import useCurrentUserPersonalDetails from './useCurrentUserPersonalDetails'; import useIsAnonymousUser from './useIsAnonymousUser'; import useIsReportActionsLoaded from './useIsReportActionsLoaded'; +import {useDerivedIsEmptyReport} from './useReportAttributes'; import useReportIsArchived from './useReportIsArchived'; // useRef gets reset when the reportID changes (the list reuses the same instance per report), @@ -116,6 +117,7 @@ function useMarkAsRead({ const route = useRoute>(); const isFocused = useIsFocused(); const isReportArchived = useReportIsArchived(reportID); + const derivedIsEmptyReport = useDerivedIsEmptyReport(reportID); const isReportActionsLoaded = useIsReportActionsLoaded(reportID); const [isVisible, setIsVisible] = useState(Visibility.isVisible); @@ -137,7 +139,7 @@ function useMarkAsRead({ const didMarkReportAsReadInitially = useRef(false); const lastAction = sortedVisibleReportActions.at(0); - const isReportUnreadValue = isUnread(report, transactionThreadReport, isReportArchived) || (!!lastAction && isCurrentActionUnread(report, lastAction)); + const isReportUnreadValue = isUnread(report, transactionThreadReport, isReportArchived, derivedIsEmptyReport) || (!!lastAction && isCurrentActionUnread(report, lastAction)); const [instanceID] = useState(() => { lastInstanceID += 1; @@ -195,7 +197,7 @@ function useMarkAsRead({ } const isLastActionUnread = !!lastAction && isCurrentActionUnread(report, lastAction, sortedVisibleReportActions); - if (!isUnread(report, transactionThreadReport, isReportArchived) && !isLastActionUnread) { + if (!isUnread(report, transactionThreadReport, isReportArchived, derivedIsEmptyReport) && !isLastActionUnread) { return; } const isFromNotification = route?.params?.referrer === CONST.REFERRER.NOTIFICATION; diff --git a/src/hooks/useReportActionsListModel.ts b/src/hooks/useReportActionsListModel.ts index f9867c5d2a79..0b8e2db7bd39 100644 --- a/src/hooks/useReportActionsListModel.ts +++ b/src/hooks/useReportActionsListModel.ts @@ -18,6 +18,7 @@ import useOnyx from './useOnyx'; import useParentReportAction from './useParentReportAction'; import useReportActionsPagination from './useReportActionsPagination'; import useReportActionsVisibility from './useReportActionsVisibility'; +import {useDerivedIsEmptyReport} from './useReportAttributes'; import useReportIsArchived from './useReportIsArchived'; /** @@ -65,6 +66,7 @@ function useReportActionsListModel(reportID: string, isReportLoadPending: boolea const shouldBeAlignedToTop = shouldReportAlignToTop(report, parentReportAction); const isReportArchived = useReportIsArchived(reportID); + const derivedIsEmptyReport = useDerivedIsEmptyReport(reportID); const canPerformWriteAction = !!canUserPerformWriteAction(report, isReportArchived); const isAppLoadPending = useIsAppLoadPending(); @@ -138,6 +140,7 @@ function useReportActionsListModel(reportID: string, isReportLoadPending: boolea isConciergeMainDM, hasCachedReportActions, showConciergeSidePanelWelcome, + derivedIsEmptyReport, }; // The render state slice on `ReportActionsListStateContext`; this is what drives list re-renders. diff --git a/src/hooks/useReportAttributes.ts b/src/hooks/useReportAttributes.ts index 48622b540c5a..0f13893c4f99 100644 --- a/src/hooks/useReportAttributes.ts +++ b/src/hooks/useReportAttributes.ts @@ -3,7 +3,7 @@ import type {ReportAttributesDerivedValue} from '@src/types/onyx'; import type {OnyxEntry} from 'react-native-onyx'; -import {reportNameSelector} from '@selectors/ReportAttributes'; +import {reportIsEmptySelector, reportNameSelector} from '@selectors/ReportAttributes'; import useOnyx from './useOnyx'; @@ -68,5 +68,18 @@ function useDerivedReportNamesByReportIDs(reportIDs: Array) return reportNames; } +/** + * Returns a single report's cached `isEmpty` flag using a selector. + * + * The selector output is a primitive boolean, so its comparison is trivial and the component re-renders only when + * that specific report's emptiness changes — not on every global report attribute change. + */ +function useDerivedIsEmptyReport(reportID: string | undefined) { + const [isEmpty] = useOnyx(ONYXKEYS.DERIVED.REPORT_ATTRIBUTES, { + selector: (value: OnyxEntry) => reportIsEmptySelector(value, reportID), + }); + return isEmpty; +} + export default useReportAttributes; -export {useReportAttributesByID, useDerivedReportNameByReportID, useDerivedReportNamesByReportIDs}; +export {useReportAttributesByID, useDerivedReportNameByReportID, useDerivedReportNamesByReportIDs, useDerivedIsEmptyReport}; diff --git a/src/libs/DebugUtils.ts b/src/libs/DebugUtils.ts index 628863b3f90c..dcaa116465d4 100644 --- a/src/libs/DebugUtils.ts +++ b/src/libs/DebugUtils.ts @@ -1528,6 +1528,7 @@ function getReasonForShowingRowInLHN({ currentUserAccountID, conciergeReportID, hasGuidesEmails, + derivedIsEmptyReport, }: { report: OnyxEntry; chatReport: OnyxEntry; @@ -1541,6 +1542,7 @@ function getReasonForShowingRowInLHN({ currentUserAccountID?: number; hasGuidesEmails: boolean; conciergeReportID: string | undefined; + derivedIsEmptyReport: boolean | undefined; }): TranslationPaths | null { if (!report) { return null; @@ -1561,6 +1563,7 @@ function getReasonForShowingRowInLHN({ currentUserLogin, currentUserAccountID, conciergeReportID, + derivedIsEmptyReport, hasGuidesEmails, }); diff --git a/src/libs/Navigation/AppNavigator/KeyboardShortcutsHandler/MarkAllMessagesAsReadHandler.tsx b/src/libs/Navigation/AppNavigator/KeyboardShortcutsHandler/MarkAllMessagesAsReadHandler.tsx index 16f75378ab56..e6266700c4ee 100644 --- a/src/libs/Navigation/AppNavigator/KeyboardShortcutsHandler/MarkAllMessagesAsReadHandler.tsx +++ b/src/libs/Navigation/AppNavigator/KeyboardShortcutsHandler/MarkAllMessagesAsReadHandler.tsx @@ -1,4 +1,5 @@ import useOnyx from '@hooks/useOnyx'; +import useReportAttributes from '@hooks/useReportAttributes'; import markAllMessagesAsRead from '@libs/actions/Report/MarkAllMessageAsRead'; import KeyboardShortcut from '@libs/KeyboardShortcut'; @@ -11,19 +12,25 @@ import {useEffect, useRef} from 'react'; function MarkAllMessagesAsReadHandler() { const [reportNameValuePairs] = useOnyx(ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS, {selector: reportNameValuePairsArchivedSelector}); + const reportAttributesDerived = useReportAttributes(); // The keyboard-shortcut callback below is registered once on mount, so keep the latest archived state in a ref // for it to read at fire time instead of closing over a stale value. const reportNameValuePairsRef = useRef(reportNameValuePairs); + const reportAttributesDerivedRef = useRef(reportAttributesDerived); useEffect(() => { reportNameValuePairsRef.current = reportNameValuePairs; }, [reportNameValuePairs]); + useEffect(() => { + reportAttributesDerivedRef.current = reportAttributesDerived; + }, [reportAttributesDerived]); + useEffect(() => { const shortcutConfig = CONST.KEYBOARD_SHORTCUTS.MARK_ALL_MESSAGES_AS_READ; const unsubscribe = KeyboardShortcut.subscribe( shortcutConfig.shortcutKey, - () => markAllMessagesAsRead(reportNameValuePairsRef.current), + () => markAllMessagesAsRead(reportNameValuePairsRef.current, undefined, reportAttributesDerivedRef.current), shortcutConfig.descriptionKey, shortcutConfig.modifiers, true, diff --git a/src/libs/OptionsListUtils/index.ts b/src/libs/OptionsListUtils/index.ts index 4c899be61eaa..f96fcd2323ba 100644 --- a/src/libs/OptionsListUtils/index.ts +++ b/src/libs/OptionsListUtils/index.ts @@ -1829,6 +1829,7 @@ function isValidReport( draftComment: string | undefined, chatReport: OnyxEntry, hasGuidesEmails: boolean, + derivedIsEmptyReport: boolean | undefined, ): boolean { const { isDefaultRoomsBetaEnabled = false, @@ -1874,6 +1875,7 @@ function isValidReport( currentUserAccountID, conciergeReportID, hasGuidesEmails, + derivedIsEmptyReport, }); if (!shouldBeInOptionList) { @@ -2069,7 +2071,7 @@ function prepareReportOptionsForDisplay( : undefined; const oneTransactionThreadReport = oneTransactionThreadReportID ? allReports?.[`${ONYXKEYS.COLLECTION.REPORT}${oneTransactionThreadReportID}`] : undefined; - isOptionUnread = isUnread(report, oneTransactionThreadReport, option.private_isArchived) && !!report.lastActorAccountID; + isOptionUnread = isUnread(report, oneTransactionThreadReport, option.private_isArchived, reportAttributesDerived?.[report.reportID]?.isEmpty) && !!report.lastActorAccountID; } let lastIOUCreationDate; @@ -2284,6 +2286,7 @@ function getValidOptions( chatReport, // TODO: Pass guideAccountIDs once callers are fully migrated — PR 33 (https://github.com/Expensify/App/issues/66413); hasExpensifyGuidesEmails falls back to allPersonalDetails isDefaultRoom(report.item) ? hasExpensifyGuidesEmails(Object.keys(report.item?.participants ?? {}).map(Number), undefined) : false, + report.reportID ? reportAttributesDerived?.[report.reportID]?.isEmpty : undefined, ); }; diff --git a/src/libs/ReportUtils.ts b/src/libs/ReportUtils.ts index 9bbb1a2cab92..780f8cb17e15 100644 --- a/src/libs/ReportUtils.ts +++ b/src/libs/ReportUtils.ts @@ -1219,14 +1219,6 @@ Onyx.connect({ }, }); -let reportAttributesDerivedValue: ReportAttributesDerivedValue['reports']; -Onyx.connect({ - key: ONYXKEYS.DERIVED.REPORT_ATTRIBUTES, - callback: (value) => { - reportAttributesDerivedValue = value?.reports ?? {}; - }, -}); - let cachedSelfDMReportID: OnyxEntry; Onyx.connect({ key: ONYXKEYS.SELF_DM_REPORT_ID, @@ -9610,20 +9602,15 @@ function buildOptimisticMoneyRequestEntities({ /** * Check if the report is empty, meaning it has no visible messages (i.e. only a "created" report action). - * Added caching mechanism via derived values. + * + * @param derivedIsEmptyReport Always prefer passing this cached flag for this report from ONYXKEYS.DERIVED.REPORT_ATTRIBUTES, i.e. + * `reportAttributes?.[reportID]?.isEmpty`. */ -function isEmptyReport(report: OnyxEntry, isReportArchived: boolean | undefined): boolean { +function isEmptyReport(report: OnyxEntry, isReportArchived: boolean | undefined, derivedIsEmptyReport: boolean | undefined): boolean { if (!report) { return true; } - - // Get the `isEmpty` state from cached report attributes - const attributes = reportAttributesDerivedValue?.[report.reportID]; - if (attributes) { - return attributes.isEmpty; - } - - return generateIsEmptyReport(report, isReportArchived); + return derivedIsEmptyReport ?? generateIsEmptyReport(report, isReportArchived); } /** @@ -9723,12 +9710,12 @@ function generateIsEmptyReport(report: OnyxEntry, isReportArchived: bool } // We need oneTransactionThreadReport to get the correct last visible action created -function isUnread(report: OnyxEntry, oneTransactionThreadReport: OnyxEntry, isReportArchived: boolean | undefined): boolean { +function isUnread(report: OnyxEntry, oneTransactionThreadReport: OnyxEntry, isReportArchived: boolean | undefined, derivedIsEmptyReport: boolean | undefined): boolean { if (!report) { return false; } - if (isEmptyReport(report, isReportArchived)) { + if (isEmptyReport(report, isReportArchived, derivedIsEmptyReport)) { return false; } @@ -10270,6 +10257,8 @@ type ShouldReportBeInOptionListParams = { conciergeReportID: string | undefined; /** Pre-computed value from reportAttributes derived value. When provided, skips the expensive requiresAttentionFromCurrentUser recomputation. */ requiresAttention?: boolean; + /** Pre-computed isEmpty flag from reportAttributes derived value. When provided, skips the module-level reportAttributesDerivedValue read inside isEmptyReport. */ + derivedIsEmptyReport: boolean | undefined; hasGuidesEmails: boolean; }; @@ -10290,6 +10279,7 @@ function reasonForReportToBeInOptionList({ isReportArchived, conciergeReportID, requiresAttention, + derivedIsEmptyReport, hasGuidesEmails, }: ShouldReportBeInOptionListParams): ValueOf | null { const isInDefaultMode = !isInFocusMode; @@ -10338,7 +10328,7 @@ function reasonForReportToBeInOptionList({ // We used to use the system DM for A/B testing onboarding tasks, but now only create them in the Concierge chat. We // still need to allow existing users who have tasks in the system DM to see them, but otherwise we don't need to // show that chat - if (report?.participants?.[CONST.ACCOUNT_ID.NOTIFICATIONS] && isEmptyReport(report, isReportArchived)) { + if (report?.participants?.[CONST.ACCOUNT_ID.NOTIFICATIONS] && isEmptyReport(report, isReportArchived, derivedIsEmptyReport)) { return null; } @@ -10375,7 +10365,7 @@ function reasonForReportToBeInOptionList({ return CONST.REPORT_IN_LHN_REASONS.HAS_GBR; } - const isEmptyChat = isEmptyReport(report, isReportArchived); + const isEmptyChat = isEmptyReport(report, isReportArchived, derivedIsEmptyReport); const canHideReport = shouldHideReport(report, currentReportId, isReportArchived); // Drafts already return early above, so no draft check needed here @@ -10416,7 +10406,7 @@ function reasonForReportToBeInOptionList({ if (isInFocusMode) { const oneTransactionThreadReportID = getOneTransactionThreadReportID(report, chatReport, currentReportActions); const oneTransactionThreadReport = deprecatedAllReports?.[`${ONYXKEYS.COLLECTION.REPORT}${oneTransactionThreadReportID}`]; - return isUnread(report, oneTransactionThreadReport, isReportArchived) && getReportNotificationPreference(report) !== CONST.REPORT.NOTIFICATION_PREFERENCE.MUTE + return isUnread(report, oneTransactionThreadReport, isReportArchived, derivedIsEmptyReport) && getReportNotificationPreference(report) !== CONST.REPORT.NOTIFICATION_PREFERENCE.MUTE ? CONST.REPORT_IN_LHN_REASONS.IS_UNREAD : null; } @@ -14473,6 +14463,7 @@ export { isDefaultRoom, isDeprecatedGroupDM, generateIsEmptyReport, + isEmptyReport, isRootGroupChat, isExpenseReport, isExpenseRequest, diff --git a/src/libs/SidebarUtils.ts b/src/libs/SidebarUtils.ts index 7fb7ace13857..53a7566324a8 100644 --- a/src/libs/SidebarUtils.ts +++ b/src/libs/SidebarUtils.ts @@ -233,6 +233,7 @@ function shouldDisplayReportInLHN({ includeSelfDM: true, isReportArchived, requiresAttention, + derivedIsEmptyReport: reportAttributes?.[report?.reportID]?.isEmpty, currentUserLogin, currentUserAccountID, conciergeReportID, @@ -305,7 +306,7 @@ function getReportsToDisplayInLHN({ if (shouldDisplay) { const requiresAttention = reportAttributes?.[report?.reportID]?.requiresAttention ?? false; - const isUnreadReport = getIsUnreadReportForInboxTab(report, isReportArchived); + const isUnreadReport = getIsUnreadReportForInboxTab(report, isReportArchived, reportAttributes?.[report?.reportID]?.isEmpty); reportsToDisplay[reportID] = requiresAttention || hasErrorsOtherThanFailedReceipt || isUnreadReport ? {...report, requiresAttention, hasErrorsOtherThanFailedReceipt, isUnreadReport} : report; } @@ -394,7 +395,7 @@ function updateReportsToDisplayInLHN({ if (shouldDisplay) { const requiresAttention = reportAttributes?.[report?.reportID]?.requiresAttention ?? false; - const isUnreadReport = getIsUnreadReportForInboxTab(report, isReportArchived); + const isUnreadReport = getIsUnreadReportForInboxTab(report, isReportArchived, reportAttributes?.[report?.reportID]?.isEmpty); // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing const hasFlags = requiresAttention || hasErrorsOtherThanFailedReceipt || isUnreadReport; const existingEntry = displayedReports[reportID]; @@ -827,7 +828,7 @@ function getOptionData({ result.statusNum = report.statusNum; // When the only message of a report is deleted lastVisibleActionCreated is not reset leading to wrongly // setting it Unread so we add additional condition here to avoid empty chat LHN from being bold. - result.isUnread = isUnread(report, oneTransactionThreadReport, isReportArchived) && !!report.lastActorAccountID; + result.isUnread = isUnread(report, oneTransactionThreadReport, isReportArchived, reportAttributes?.isEmpty) && !!report.lastActorAccountID; result.isUnreadWithMention = isUnreadWithMention(report); result.isPinned = report.isPinned; result.iouReportID = report.iouReportID; @@ -975,10 +976,14 @@ function getOptionData({ * Whether a report should appear in the "Unread" Inbox tab: it has unread messages and is not muted. * Computed once while building the LHN report set (which is cached/incremental) so the tab filter only reads a flag. */ -function getIsUnreadReportForInboxTab(report: Report, isReportArchived: boolean): boolean { +function getIsUnreadReportForInboxTab(report: Report, isReportArchived: boolean, derivedIsEmptyReport: boolean | undefined): boolean { // The `lastActorAccountID` guard matches getOptionData: it keeps chats whose only visible message was // deleted out of the Unread tab even though isUnread() can still be true (lastVisibleActionCreated isn't reset). - return isUnread(report, undefined, isReportArchived) && !!report.lastActorAccountID && getReportNotificationPreference(report) !== CONST.REPORT.NOTIFICATION_PREFERENCE.MUTE; + return ( + isUnread(report, undefined, isReportArchived, derivedIsEmptyReport) && + !!report.lastActorAccountID && + getReportNotificationPreference(report) !== CONST.REPORT.NOTIFICATION_PREFERENCE.MUTE + ); } /** Whether a report belongs in the "To-do" Inbox tab: it has an outstanding GBR (requiresAttention) or RBR (errors). */ diff --git a/src/libs/UnreadIndicatorUpdater/index.ts b/src/libs/UnreadIndicatorUpdater/index.ts index eda976d04990..743ccbd470dc 100644 --- a/src/libs/UnreadIndicatorUpdater/index.ts +++ b/src/libs/UnreadIndicatorUpdater/index.ts @@ -8,7 +8,7 @@ import Navigation, {navigationRef} from '@navigation/Navigation'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; -import type {Report, ReportActions, ReportNameValuePairs, Session} from '@src/types/onyx'; +import type {Report, ReportActions, ReportAttributesDerivedValue, ReportNameValuePairs, Session} from '@src/types/onyx'; import type {OnyxCollection} from 'react-native-onyx'; @@ -65,6 +65,15 @@ Onyx.connectWithoutView({ }, }); +let reportAttributesDerived: ReportAttributesDerivedValue['reports'] | undefined; +// This subscription is used to update the unread indicators count which is not linked to UI and it does not update any UI state. +Onyx.connectWithoutView({ + key: ONYXKEYS.DERIVED.REPORT_ATTRIBUTES, + callback: (value) => { + reportAttributesDerived = value?.reports; + }, +}); + function getUnreadReportsForUnreadIndicator(reports: OnyxCollection, currentReportID: string | undefined, draftComment: string | undefined) { // Read the in-memory offline state directly since this is an imperative one-shot computation (reactivity is not needed here). const isOffline = getIsOffline(); @@ -91,7 +100,9 @@ function getUnreadReportsForUnreadIndicator(reports: OnyxCollection, cur const oneTransactionThreadReportID = getOneTransactionThreadReportID(report, chatReport, allReportActions?.[`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${report?.reportID}`], isOffline); const oneTransactionThreadReport = allReports?.[`${ONYXKEYS.COLLECTION.REPORT}${oneTransactionThreadReportID}`]; - if (!ReportUtils.isUnread(report, oneTransactionThreadReport, isReportArchived)) { + const derivedIsEmptyReport = report?.reportID ? reportAttributesDerived?.[report.reportID]?.isEmpty : undefined; + + if (!ReportUtils.isUnread(report, oneTransactionThreadReport, isReportArchived, derivedIsEmptyReport)) { return false; } @@ -112,6 +123,7 @@ function getUnreadReportsForUnreadIndicator(reports: OnyxCollection, cur // TODO: Pass guideAccountIDs once callers are fully migrated — PR 33 (https://github.com/Expensify/App/issues/66413); hasExpensifyGuidesEmails falls back to allPersonalDetails hasGuidesEmails: ReportUtils.isDefaultRoom(report) ? ReportUtils.hasExpensifyGuidesEmails(Object.keys(report?.participants ?? {}).map(Number), undefined) : false, conciergeReportID, + derivedIsEmptyReport, }); }); } diff --git a/src/libs/actions/Report/MarkAllMessageAsRead.tsx b/src/libs/actions/Report/MarkAllMessageAsRead.tsx index 544edd0511b9..2d766d52f1f8 100644 --- a/src/libs/actions/Report/MarkAllMessageAsRead.tsx +++ b/src/libs/actions/Report/MarkAllMessageAsRead.tsx @@ -7,7 +7,7 @@ import {getOneTransactionThreadReportID} from '@libs/ReportActionsUtils'; import {isArchivedReport, isUnread} from '@libs/ReportUtils'; import ONYXKEYS from '@src/ONYXKEYS'; -import type {Report, ReportActions} from '@src/types/onyx'; +import type {Report, ReportActions, ReportAttributesDerivedValue} from '@src/types/onyx'; import type {ReportNameValuePairsArchivedState} from '@selectors/ReportNameValuePairs'; import type {OnyxCollection} from 'react-native-onyx'; @@ -35,7 +35,11 @@ Onyx.connectWithoutView({ * Marks every unread report as read. Pass `reportIDs` to limit it to a subset, e.g. only the reports listed under one * Inbox tab; when omitted, every unread report is marked read. */ -function markAllMessagesAsRead(reportNameValuePairs: OnyxCollection, reportIDs?: string[]) { +function markAllMessagesAsRead( + reportNameValuePairs: OnyxCollection, + reportIDs: string[] | undefined, + reportAttributesDerived: ReportAttributesDerivedValue['reports'] | undefined, +) { if (isAnonymousUser()) { return; } @@ -60,7 +64,7 @@ function markAllMessagesAsRead(reportNameValuePairs: OnyxCollection(() => { if (!report) { @@ -131,6 +133,7 @@ function DebugReportPage({ currentUserAccountID, conciergeReportID, hasGuidesEmails, + derivedIsEmptyReport, }); return [ @@ -193,6 +196,7 @@ function DebugReportPage({ translate, conciergeReportID, hasGuidesEmails, + derivedIsEmptyReport, ]); const icons = useMemoizedLazyExpensifyIcons(['Eye']); diff --git a/src/pages/inbox/report/ContextMenu/BaseReportActionContextMenu.tsx b/src/pages/inbox/report/ContextMenu/BaseReportActionContextMenu.tsx index d67176425c8b..ab9072d90c2e 100755 --- a/src/pages/inbox/report/ContextMenu/BaseReportActionContextMenu.tsx +++ b/src/pages/inbox/report/ContextMenu/BaseReportActionContextMenu.tsx @@ -17,7 +17,7 @@ import useLocalize from '@hooks/useLocalize'; import useNetwork from '@hooks/useNetwork'; import useOnyx from '@hooks/useOnyx'; import usePaginatedReportActions from '@hooks/usePaginatedReportActions'; -import useReportAttributes, {useDerivedReportNameByReportID} from '@hooks/useReportAttributes'; +import useReportAttributes, {useDerivedIsEmptyReport, useDerivedReportNameByReportID} from '@hooks/useReportAttributes'; import useReportIsArchived from '@hooks/useReportIsArchived'; import useReportOrReportDraft from '@hooks/useReportOrReportDraft'; import useResponsiveLayout from '@hooks/useResponsiveLayout'; @@ -267,7 +267,8 @@ function BaseReportActionContextMenu({ const isArchivedRoom = isArchivedNonExpenseReport(originalReport, isOriginalReportArchived); const isChronosReport = chatIncludesChronosWithID(originalReportID); const isPinnedChat = !!report?.isPinned; - const isUnreadChat = isUnread(report, lhnOneTransactionThreadReport, isOriginalReportArchived); + const derivedIsEmptyReport = useDerivedIsEmptyReport(reportID); + const isUnreadChat = isUnread(report, lhnOneTransactionThreadReport, isOriginalReportArchived, derivedIsEmptyReport); const shouldEnableArrowNavigation = !isMini && (isVisible || shouldKeepOpen); const isHarvestReport = isHarvestCreatedExpenseReport(reportNameValuePairs?.origin, reportNameValuePairs?.originalID); const memberChangeLogReportActionMessage = isMemberChangeAction(reportAction) ? getOriginalMessage(reportAction) : undefined; diff --git a/src/pages/inbox/report/ReportActionsListContext.tsx b/src/pages/inbox/report/ReportActionsListContext.tsx index 0e5e876212ae..4910aa0793e7 100644 --- a/src/pages/inbox/report/ReportActionsListContext.tsx +++ b/src/pages/inbox/report/ReportActionsListContext.tsx @@ -63,9 +63,10 @@ function computeReportActionsSkeletonState(readinessSignals: ReportActionsReadin isConciergeMainDM, hasCachedReportActions, showConciergeSidePanelWelcome, + derivedIsEmptyReport, } = readinessSignals; - const isReportUnread = isUnread(report, transactionThreadReport, isReportArchived); + const isReportUnread = isUnread(report, transactionThreadReport, isReportArchived, derivedIsEmptyReport); // Before the first successful load, a missing loading-state entry means ReportFetchHandler has not // enqueued OpenReport yet. Once a terminal failure writes false, the stored state releases the gate. diff --git a/src/pages/inbox/sidebar/InboxTabSelector.tsx b/src/pages/inbox/sidebar/InboxTabSelector.tsx index d0bab5d8f7d1..cc6273506bbc 100644 --- a/src/pages/inbox/sidebar/InboxTabSelector.tsx +++ b/src/pages/inbox/sidebar/InboxTabSelector.tsx @@ -11,6 +11,7 @@ import {useMemoizedLazyExpensifyIcons} from '@hooks/useLazyAsset'; import useLocalize from '@hooks/useLocalize'; import useOnyx from '@hooks/useOnyx'; import usePopoverPosition from '@hooks/usePopoverPosition'; +import useReportAttributes from '@hooks/useReportAttributes'; import useResponsiveLayout from '@hooks/useResponsiveLayout'; import {useSidebarOrderedReportsActions, useSidebarOrderedReportsState} from '@hooks/useSidebarOrderedReports'; import useThemeStyles from '@hooks/useThemeStyles'; @@ -43,6 +44,7 @@ function InboxTabSelector() { const {activeTab, inboxTabCounts, hasStaleUnreadReport} = useSidebarOrderedReportsState(); const {setActiveTab, getReportIDsForTab} = useSidebarOrderedReportsActions(); const [reportNameValuePairs] = useOnyx(ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS, {selector: reportNameValuePairsArchivedSelector}); + const reportAttributesDerived = useReportAttributes(); const icons = useMemoizedLazyExpensifyIcons(['Checkmark', 'Feed', 'ChatBubbleUnread', 'Task']); const {showConfirmModal} = useConfirmModal(); // Only show the tooltip if we have unread message > 3 months old. @@ -96,7 +98,7 @@ function InboxTabSelector() { } // From the To-dos tab only the chats listed there are marked read. The All and Unread tabs both cover every // unread chat, so they mark all of them. - markAllMessagesAsRead(reportNameValuePairs, isTodoTab ? getReportIDsForTab(CONST.INBOX_TAB.TODO) : undefined); + markAllMessagesAsRead(reportNameValuePairs, isTodoTab ? getReportIDsForTab(CONST.INBOX_TAB.TODO) : undefined, reportAttributesDerived); }); }; diff --git a/src/selectors/ReportAttributes.ts b/src/selectors/ReportAttributes.ts index b56086ca52e0..3c6fb8789673 100644 --- a/src/selectors/ReportAttributes.ts +++ b/src/selectors/ReportAttributes.ts @@ -17,5 +17,7 @@ const reportByIDsSelector = (reportIDs: string[]) => (attributes: OnyxEntry, reportID: string | undefined) => (reportID ? attributes?.reports?.[reportID]?.reportName : undefined); -export {reportNameSelector}; +const reportIsEmptySelector = (attributes: OnyxEntry, reportID: string | undefined) => (reportID ? attributes?.reports?.[reportID]?.isEmpty : undefined); + +export {reportNameSelector, reportIsEmptySelector}; export default reportByIDsSelector; diff --git a/tests/actions/ReportTest.ts b/tests/actions/ReportTest.ts index 4d4889bf4944..f78aec793352 100644 --- a/tests/actions/ReportTest.ts +++ b/tests/actions/ReportTest.ts @@ -736,7 +736,7 @@ describe('actions/Report', () => { }) .then(() => { // Then the report will be unread - expect(ReportUtils.isUnread(report, undefined, undefined)).toBe(true); + expect(ReportUtils.isUnread(report, undefined, undefined, undefined)).toBe(true); // And show a green dot for unread mentions in the LHN expect(ReportUtils.isUnreadWithMention(report)).toBe(true); @@ -758,7 +758,7 @@ describe('actions/Report', () => { }) .then(() => { // The report will be read - expect(ReportUtils.isUnread(report, undefined, undefined)).toBe(false); + expect(ReportUtils.isUnread(report, undefined, undefined, undefined)).toBe(false); expect(toZonedTime(report?.lastReadTime ?? '', UTC).getTime()).toBeGreaterThanOrEqual(toZonedTime(currentTime, UTC).getTime()); // And no longer show the green dot for unread mentions in the LHN @@ -770,7 +770,7 @@ describe('actions/Report', () => { }) .then(() => { // Then the report will be unread and show the green dot for unread mentions in LHN - expect(ReportUtils.isUnread(report, undefined, undefined)).toBe(true); + expect(ReportUtils.isUnread(report, undefined, undefined, undefined)).toBe(true); expect(ReportUtils.isUnreadWithMention(report)).toBe(true); expect(report?.lastReadTime).toBe(DateUtils.subtractMillisecondsFromDateTime(reportActionCreatedDate, 1)); @@ -791,7 +791,7 @@ describe('actions/Report', () => { }) .then(() => { // The report will be read, the green dot for unread mentions will go away, and the lastReadTime updated - expect(ReportUtils.isUnread(report, undefined, undefined)).toBe(false); + expect(ReportUtils.isUnread(report, undefined, undefined, undefined)).toBe(false); expect(ReportUtils.isUnreadWithMention(report)).toBe(false); expect(toZonedTime(report?.lastReadTime ?? '', UTC).getTime()).toBeGreaterThanOrEqual(toZonedTime(currentTime, UTC).getTime()); expect(report?.lastMessageText).toBe('Current User Comment 1'); @@ -812,7 +812,7 @@ describe('actions/Report', () => { }) .then(() => { // The report will be read and the lastReadTime updated - expect(ReportUtils.isUnread(report, undefined, undefined)).toBe(false); + expect(ReportUtils.isUnread(report, undefined, undefined, undefined)).toBe(false); expect(toZonedTime(report?.lastReadTime ?? '', UTC).getTime()).toBeGreaterThanOrEqual(toZonedTime(currentTime, UTC).getTime()); expect(report?.lastMessageText).toBe('Current User Comment 2'); @@ -832,7 +832,7 @@ describe('actions/Report', () => { }) .then(() => { // The report will be read and the lastReadTime updated - expect(ReportUtils.isUnread(report, undefined, undefined)).toBe(false); + expect(ReportUtils.isUnread(report, undefined, undefined, undefined)).toBe(false); expect(toZonedTime(report?.lastReadTime ?? '', UTC).getTime()).toBeGreaterThanOrEqual(toZonedTime(currentTime, UTC).getTime()); expect(report?.lastMessageText).toBe('Current User Comment 3'); @@ -914,7 +914,7 @@ describe('actions/Report', () => { .then(() => { // Then no change will occur expect(report?.lastReadTime).toBe(reportActionCreatedDate); - expect(ReportUtils.isUnread(report, undefined, undefined)).toBe(false); + expect(ReportUtils.isUnread(report, undefined, undefined, undefined)).toBe(false); // When the user manually marks a message as "unread" Report.markCommentAsUnread(REPORT_ID, reportActions, reportActions[400], USER_1_ACCOUNT_ID, false); @@ -922,7 +922,7 @@ describe('actions/Report', () => { }) .then(() => { // Then we should expect the report to be to be unread - expect(ReportUtils.isUnread(report, undefined, undefined)).toBe(true); + expect(ReportUtils.isUnread(report, undefined, undefined, undefined)).toBe(true); expect(report?.lastReadTime).toBe(DateUtils.subtractMillisecondsFromDateTime(reportActions[400].created, 1)); rerender(report); @@ -932,7 +932,7 @@ describe('actions/Report', () => { }) .then(() => getOnyxValue(`${ONYXKEYS.COLLECTION.REPORT}${REPORT_ID}` as const)) .then((updatedReport) => { - expect(ReportUtils.isUnread(updatedReport, undefined, undefined)).toBe(false); + expect(ReportUtils.isUnread(updatedReport, undefined, undefined, undefined)).toBe(false); expect(updatedReport?.lastMessageText).toBe('Current User Comment 2'); }); waitForBatchedUpdates(); // flushing onyx.set as it will be batched @@ -3498,7 +3498,7 @@ describe('actions/Report', () => { await Onyx.mergeCollection(ONYXKEYS.COLLECTION.REPORT, reportCollections); // When mark all reports as read - markAllMessagesAsRead(undefined); + markAllMessagesAsRead(undefined, undefined, undefined); await waitForBatchedUpdates(); @@ -3510,7 +3510,7 @@ describe('actions/Report', () => { key: `${ONYXKEYS.COLLECTION.REPORT}${report.reportID}`, callback: (reportVal) => { Onyx.disconnect(connection); - resolve(ReportUtils.isUnread(reportVal, undefined, undefined)); + resolve(ReportUtils.isUnread(reportVal, undefined, undefined, undefined)); }, }); }); diff --git a/tests/perf-test/ReportUtils.perf-test.ts b/tests/perf-test/ReportUtils.perf-test.ts index ea89ce284104..94c673114221 100644 --- a/tests/perf-test/ReportUtils.perf-test.ts +++ b/tests/perf-test/ReportUtils.perf-test.ts @@ -198,6 +198,7 @@ describe('ReportUtils', () => { isReportArchived: false, hasGuidesEmails: false, conciergeReportID: undefined, + derivedIsEmptyReport: undefined, }), ); }); diff --git a/tests/unit/DebugUtilsTest.ts b/tests/unit/DebugUtilsTest.ts index 1ec5e7c8c7af..621f061c92a1 100644 --- a/tests/unit/DebugUtilsTest.ts +++ b/tests/unit/DebugUtilsTest.ts @@ -801,6 +801,7 @@ describe('DebugUtils', () => { isReportArchived: undefined, hasGuidesEmails: false, conciergeReportID: undefined, + derivedIsEmptyReport: undefined, }); expect(reason).toBeNull(); }); @@ -814,6 +815,7 @@ describe('DebugUtils', () => { isReportArchived: undefined, hasGuidesEmails: false, conciergeReportID: undefined, + derivedIsEmptyReport: undefined, }); expect(reason).toBe('debug.reasonVisibleInLHN.hasDraftComment'); }); @@ -830,6 +832,7 @@ describe('DebugUtils', () => { isReportArchived: undefined, hasGuidesEmails: false, conciergeReportID: undefined, + derivedIsEmptyReport: undefined, }); expect(reason).toBe('debug.reasonVisibleInLHN.hasGBR'); }); @@ -845,6 +848,7 @@ describe('DebugUtils', () => { isReportArchived: undefined, hasGuidesEmails: false, conciergeReportID: undefined, + derivedIsEmptyReport: undefined, }); expect(reason).toBe('debug.reasonVisibleInLHN.pinnedByUser'); }); @@ -864,6 +868,7 @@ describe('DebugUtils', () => { isReportArchived: undefined, hasGuidesEmails: false, conciergeReportID: undefined, + derivedIsEmptyReport: undefined, }); expect(reason).toBe('debug.reasonVisibleInLHN.hasAddWorkspaceRoomErrors'); }); @@ -891,6 +896,7 @@ describe('DebugUtils', () => { isReportArchived: undefined, hasGuidesEmails: false, conciergeReportID: undefined, + derivedIsEmptyReport: undefined, }); expect(reason).toBe('debug.reasonVisibleInLHN.isUnread'); }); @@ -911,6 +917,7 @@ describe('DebugUtils', () => { draftComment: '', hasGuidesEmails: false, conciergeReportID: undefined, + derivedIsEmptyReport: undefined, }); expect(reason).toBe('debug.reasonVisibleInLHN.isArchived'); }); @@ -926,6 +933,7 @@ describe('DebugUtils', () => { isReportArchived: undefined, hasGuidesEmails: false, conciergeReportID: undefined, + derivedIsEmptyReport: undefined, }); expect(reason).toBe('debug.reasonVisibleInLHN.isSelfDM'); }); @@ -938,6 +946,7 @@ describe('DebugUtils', () => { isReportArchived: undefined, hasGuidesEmails: false, conciergeReportID: undefined, + derivedIsEmptyReport: undefined, }); expect(reason).toBe('debug.reasonVisibleInLHN.isFocused'); }); @@ -999,6 +1008,7 @@ describe('DebugUtils', () => { isReportArchived: undefined, hasGuidesEmails: false, conciergeReportID: undefined, + derivedIsEmptyReport: undefined, }); expect(reason).toBe('debug.reasonVisibleInLHN.hasRBR'); }); @@ -1060,6 +1070,7 @@ describe('DebugUtils', () => { isReportArchived: undefined, hasGuidesEmails: false, conciergeReportID: undefined, + derivedIsEmptyReport: undefined, }); expect(reason).toBe('debug.reasonVisibleInLHN.hasRBR'); }); @@ -1073,6 +1084,7 @@ describe('DebugUtils', () => { isReportArchived: undefined, hasGuidesEmails: false, conciergeReportID: undefined, + derivedIsEmptyReport: undefined, }); expect(reason).toBe('debug.reasonVisibleInLHN.hasRBR'); }); diff --git a/tests/unit/ReportActionsListContextTest.ts b/tests/unit/ReportActionsListContextTest.ts index 6bfa0ddbbd1f..d23ca6dc7830 100644 --- a/tests/unit/ReportActionsListContextTest.ts +++ b/tests/unit/ReportActionsListContextTest.ts @@ -53,6 +53,7 @@ function createReadinessSignals(overrides: Partial { isReportArchived: undefined, hasGuidesEmails: false, conciergeReportID: undefined, + derivedIsEmptyReport: undefined, }), ).toBeTruthy(); }); @@ -8144,6 +8146,7 @@ describe('ReportUtils', () => { isReportArchived: undefined, hasGuidesEmails: false, conciergeReportID: undefined, + derivedIsEmptyReport: undefined, }), ).toBeTruthy(); }); @@ -8174,6 +8177,7 @@ describe('ReportUtils', () => { isReportArchived: undefined, hasGuidesEmails: false, conciergeReportID: undefined, + derivedIsEmptyReport: undefined, }), ).toBeFalsy(); }); @@ -8239,6 +8243,7 @@ describe('ReportUtils', () => { isReportArchived: undefined, hasGuidesEmails: false, conciergeReportID: undefined, + derivedIsEmptyReport: undefined, }), ).toBeTruthy(); }); @@ -8263,6 +8268,7 @@ describe('ReportUtils', () => { isReportArchived: undefined, hasGuidesEmails: false, conciergeReportID: undefined, + derivedIsEmptyReport: undefined, }), ).toBeTruthy(); }); @@ -8287,6 +8293,7 @@ describe('ReportUtils', () => { isReportArchived: undefined, hasGuidesEmails: false, conciergeReportID: undefined, + derivedIsEmptyReport: undefined, }), ).toBeTruthy(); }); @@ -8311,6 +8318,7 @@ describe('ReportUtils', () => { isReportArchived: undefined, hasGuidesEmails: false, conciergeReportID: undefined, + derivedIsEmptyReport: undefined, }), ).toBeTruthy(); }); @@ -8348,6 +8356,7 @@ describe('ReportUtils', () => { isReportArchived: undefined, hasGuidesEmails: false, conciergeReportID: undefined, + derivedIsEmptyReport: undefined, }), ).toBeTruthy(); }); @@ -8380,6 +8389,7 @@ describe('ReportUtils', () => { draftComment: '', hasGuidesEmails: false, conciergeReportID: undefined, + derivedIsEmptyReport: undefined, }), ).toBeTruthy(); }); @@ -8412,6 +8422,7 @@ describe('ReportUtils', () => { draftComment: '', hasGuidesEmails: false, conciergeReportID: undefined, + derivedIsEmptyReport: undefined, }), ).toBeFalsy(); }); @@ -8438,6 +8449,7 @@ describe('ReportUtils', () => { isReportArchived: undefined, hasGuidesEmails: false, conciergeReportID: undefined, + derivedIsEmptyReport: undefined, }), ).toBeTruthy(); }); @@ -8466,6 +8478,7 @@ describe('ReportUtils', () => { isReportArchived: undefined, hasGuidesEmails: false, conciergeReportID: undefined, + derivedIsEmptyReport: undefined, }), ).toBeFalsy(); }); @@ -8487,6 +8500,7 @@ describe('ReportUtils', () => { isReportArchived: undefined, hasGuidesEmails: false, conciergeReportID: undefined, + derivedIsEmptyReport: undefined, }), ).toBeFalsy(); }); @@ -8511,6 +8525,7 @@ describe('ReportUtils', () => { isReportArchived: undefined, hasGuidesEmails: false, conciergeReportID: undefined, + derivedIsEmptyReport: undefined, }), ).toBeFalsy(); }); @@ -8565,6 +8580,7 @@ describe('ReportUtils', () => { isReportArchived: undefined, hasGuidesEmails: false, conciergeReportID: undefined, + derivedIsEmptyReport: undefined, }), ).toBeFalsy(); }); @@ -8586,6 +8602,7 @@ describe('ReportUtils', () => { isReportArchived: undefined, hasGuidesEmails: false, conciergeReportID: undefined, + derivedIsEmptyReport: undefined, }), ).toBeFalsy(); }); @@ -8615,6 +8632,7 @@ describe('ReportUtils', () => { isReportArchived: undefined, hasGuidesEmails: false, conciergeReportID, + derivedIsEmptyReport: undefined, }), ).toBe(CONST.REPORT_IN_LHN_REASONS.DEFAULT); }); @@ -8643,6 +8661,7 @@ describe('ReportUtils', () => { isReportArchived: undefined, conciergeReportID, hasGuidesEmails: false, + derivedIsEmptyReport: undefined, }), ).toBe(CONST.REPORT_IN_LHN_REASONS.DEFAULT); }); @@ -8670,6 +8689,7 @@ describe('ReportUtils', () => { isReportArchived: undefined, conciergeReportID: 'some-other-report-id', hasGuidesEmails: false, + derivedIsEmptyReport: undefined, }), ).toBeNull(); }); @@ -8698,6 +8718,7 @@ describe('ReportUtils', () => { isReportArchived: undefined, isDefaultRoomsBetaEnabled: false, hasGuidesEmails: false, + derivedIsEmptyReport: undefined, }; // When the param identifies this report as Concierge, the empty chat is kept in the option list... @@ -8725,6 +8746,7 @@ describe('ReportUtils', () => { isReportArchived: undefined, hasGuidesEmails: false, conciergeReportID: undefined, + derivedIsEmptyReport: undefined, }), ).toBeFalsy(); }); @@ -8772,6 +8794,7 @@ describe('ReportUtils', () => { isReportArchived: undefined, hasGuidesEmails: false, conciergeReportID: undefined, + derivedIsEmptyReport: undefined, }), ).toBeFalsy(); }); @@ -8793,6 +8816,7 @@ describe('ReportUtils', () => { isReportArchived: undefined, hasGuidesEmails: false, conciergeReportID: undefined, + derivedIsEmptyReport: undefined, }), ).toBeFalsy(); }); @@ -8829,6 +8853,7 @@ describe('ReportUtils', () => { isReportArchived: undefined, hasGuidesEmails: false, conciergeReportID: undefined, + derivedIsEmptyReport: undefined, }), ).toBeFalsy(); }); @@ -8862,6 +8887,7 @@ describe('ReportUtils', () => { isReportArchived: undefined, hasGuidesEmails: false, conciergeReportID: undefined, + derivedIsEmptyReport: undefined, }), ).toBe(CONST.REPORT_IN_LHN_REASONS.IS_UNREAD); }); @@ -8893,6 +8919,7 @@ describe('ReportUtils', () => { isReportArchived: undefined, hasGuidesEmails: false, conciergeReportID: undefined, + derivedIsEmptyReport: undefined, }), ).toBeFalsy(); }); @@ -8917,6 +8944,7 @@ describe('ReportUtils', () => { isReportArchived: undefined, hasGuidesEmails: false, conciergeReportID: undefined, + derivedIsEmptyReport: undefined, }), ).toBe(CONST.REPORT_IN_LHN_REASONS.HAS_ADD_WORKSPACE_ROOM_ERRORS); }); @@ -8963,6 +8991,7 @@ describe('ReportUtils', () => { isReportArchived: undefined, hasGuidesEmails: false, conciergeReportID: undefined, + derivedIsEmptyReport: undefined, }), ).toBeFalsy(); }); @@ -9016,6 +9045,7 @@ describe('ReportUtils', () => { isReportArchived: undefined, hasGuidesEmails: false, conciergeReportID: undefined, + derivedIsEmptyReport: undefined, }), ).toBe(CONST.REPORT_IN_LHN_REASONS.PINNED_BY_USER); }); @@ -9040,6 +9070,7 @@ describe('ReportUtils', () => { isReportArchived: undefined, hasGuidesEmails: false, conciergeReportID: undefined, + derivedIsEmptyReport: undefined, }), ).toBeNull(); }); @@ -9063,6 +9094,7 @@ describe('ReportUtils', () => { isReportArchived: undefined, hasGuidesEmails: false, conciergeReportID: undefined, + derivedIsEmptyReport: undefined, }), ).toBeTruthy(); }); @@ -9086,6 +9118,7 @@ describe('ReportUtils', () => { isReportArchived: undefined, hasGuidesEmails: false, conciergeReportID: undefined, + derivedIsEmptyReport: undefined, }), ).toBeFalsy(); }); @@ -9109,6 +9142,7 @@ describe('ReportUtils', () => { isReportArchived: undefined, hasGuidesEmails: false, conciergeReportID: undefined, + derivedIsEmptyReport: undefined, }), ).toBeFalsy(); }); @@ -9132,6 +9166,7 @@ describe('ReportUtils', () => { isReportArchived: undefined, hasGuidesEmails: false, conciergeReportID: undefined, + derivedIsEmptyReport: undefined, }), ).toBeFalsy(); }); @@ -9151,6 +9186,7 @@ describe('ReportUtils', () => { isReportArchived: undefined, hasGuidesEmails: false, conciergeReportID: undefined, + derivedIsEmptyReport: undefined, }), ).toBeFalsy(); }); @@ -9220,6 +9256,7 @@ describe('ReportUtils', () => { isReportArchived: undefined, hasGuidesEmails: false, conciergeReportID: undefined, + derivedIsEmptyReport: undefined, }); expect(reason).not.toBe(CONST.REPORT_IN_LHN_REASONS.HAS_IOU_VIOLATIONS); @@ -9989,7 +10026,74 @@ describe('ReportUtils', () => { lastVisibleActionCreated: '2024-03-01 12:00:00.000', }; - expect(isUnread(report, transactionThreadReport, false)).toBe(false); + expect(isUnread(report, transactionThreadReport, false, undefined)).toBe(false); + }); + + it('returns false when derivedIsEmptyReport is true (empty report is never unread)', () => { + const report = { + ...LHNTestUtils.getFakeReport(), + reportID: '1', + lastReadTime: '2024-03-01 12:00:00.000', + lastVisibleActionCreated: '2024-03-01 12:00:01.000', + lastMessageText: 'Hello', + }; + + expect(isUnread(report, undefined, false, true)).toBe(false); + }); + + it('does not short-circuit when derivedIsEmptyReport is false', () => { + const report = { + ...LHNTestUtils.getFakeReport(), + reportID: '1', + lastReadTime: '2024-03-01 12:00:00.000', + lastVisibleActionCreated: '2024-03-01 12:00:01.000', + lastMessageText: 'Hello', + }; + + // derivedIsEmptyReport=false means report is not empty, so isUnread proceeds to check lastReadTime + expect(isUnread(report, undefined, false, false)).toBe(true); + }); + + it('falls through to generateIsEmptyReport when derivedIsEmptyReport is undefined', () => { + const report = { + ...LHNTestUtils.getFakeReport(), + reportID: '1', + lastReadTime: '2024-03-01 12:00:00.000', + lastVisibleActionCreated: '2024-03-01 12:00:01.000', + lastMessageText: 'Hello', + }; + + // report has lastMessageText so generateIsEmptyReport returns false, isUnread proceeds + expect(isUnread(report, undefined, false, undefined)).toBe(true); + expect(isUnread(report, undefined, false, undefined)).toBe(true); + }); + }); + + describe('isEmptyReport', () => { + const report = { + ...LHNTestUtils.getFakeReport(), + reportID: '1', + lastMessageText: 'Hello', + }; + + it('returns the passed value when derivedIsEmptyReport is true', () => { + expect(isEmptyReport(report, false, true)).toBe(true); + }); + + it('returns the passed value when derivedIsEmptyReport is false', () => { + // Verifies ?? (not ||) — false is a valid cache hit, must NOT fall through + expect(isEmptyReport(report, false, false)).toBe(false); + }); + + it('falls through to generateIsEmptyReport when derivedIsEmptyReport is undefined', () => { + // report has lastMessageText so generateIsEmptyReport returns false + expect(isEmptyReport(report, false, undefined)).toBe(false); + expect(isEmptyReport(report, false, undefined)).toBe(false); + }); + + it('returns true when report is undefined', () => { + expect(isEmptyReport(undefined, false, false)).toBe(true); + expect(isEmptyReport(undefined, false, true)).toBe(true); }); }); @@ -17051,6 +17155,7 @@ describe('ReportUtils', () => { hasGuidesEmails: false, conciergeReportID: undefined, + derivedIsEmptyReport: undefined, }); expect(reason).toBe(CONST.REPORT_IN_LHN_REASONS.HAS_GBR); @@ -17112,6 +17217,7 @@ describe('ReportUtils', () => { hasGuidesEmails: false, conciergeReportID: undefined, + derivedIsEmptyReport: undefined, }); expect(reason).toBe(CONST.REPORT_IN_LHN_REASONS.DEFAULT); @@ -17306,6 +17412,7 @@ describe('ReportUtils', () => { hasGuidesEmails: false, conciergeReportID: undefined, + derivedIsEmptyReport: undefined, }); expect(reasonForOptionList).toBe(CONST.REPORT_IN_LHN_REASONS.HAS_GBR); @@ -17352,6 +17459,7 @@ describe('ReportUtils', () => { hasGuidesEmails: false, conciergeReportID: undefined, + derivedIsEmptyReport: undefined, }); expect(reasonForOptionList).toBe(null); @@ -18475,6 +18583,7 @@ describe('ReportUtils', () => { hasGuidesEmails: false, conciergeReportID: undefined, + derivedIsEmptyReport: undefined, currentUserAccountID: adminAccountID, }); @@ -18659,6 +18768,7 @@ describe('ReportUtils', () => { isReportArchived: undefined, hasGuidesEmails: false, conciergeReportID: undefined, + derivedIsEmptyReport: undefined, }); expect(reason).toBe(CONST.REPORT_IN_LHN_REASONS.DEFAULT); @@ -18855,6 +18965,7 @@ describe('ReportUtils', () => { isReportArchived: archiveState.current, hasGuidesEmails: false, conciergeReportID: undefined, + derivedIsEmptyReport: undefined, }); expect(reasonBeforeDelete).toBe(CONST.REPORT_IN_LHN_REASONS.HAS_GBR); @@ -18879,6 +18990,7 @@ describe('ReportUtils', () => { isReportArchived: archiveState.current, hasGuidesEmails: false, conciergeReportID: undefined, + derivedIsEmptyReport: undefined, }); expect(reasonAfterDelete).toBe(CONST.REPORT_IN_LHN_REASONS.IS_ARCHIVED); @@ -18981,6 +19093,7 @@ describe('ReportUtils', () => { isReportArchived: isReportArchivedBefore.current, hasGuidesEmails: false, conciergeReportID: undefined, + derivedIsEmptyReport: undefined, }); expect(reasonBeforeRemoval).toBe(CONST.REPORT_IN_LHN_REASONS.HAS_GBR); @@ -19023,6 +19136,7 @@ describe('ReportUtils', () => { isReportArchived: isReportArchivedAfter.current, hasGuidesEmails: false, conciergeReportID: undefined, + derivedIsEmptyReport: undefined, }); expect(reasonAfterRemoval).toBe(CONST.REPORT_IN_LHN_REASONS.HAS_GBR); @@ -20203,6 +20317,7 @@ describe('ReportUtils', () => { draftComment: '', hasGuidesEmails: false, conciergeReportID: undefined, + derivedIsEmptyReport: undefined, }); expect(reason).toBe(CONST.REPORT_IN_LHN_REASONS.HAS_GBR); @@ -20258,6 +20373,7 @@ describe('ReportUtils', () => { draftComment: '', hasGuidesEmails: false, conciergeReportID: undefined, + derivedIsEmptyReport: undefined, }); expect(reason).toBe(CONST.REPORT_IN_LHN_REASONS.DEFAULT); @@ -22589,6 +22705,7 @@ describe('ReportUtils', () => { hasGuidesEmails: false, conciergeReportID: undefined, + derivedIsEmptyReport: undefined, }); expect(reason).toBe(CONST.REPORT_IN_LHN_REASONS.HAS_GBR); @@ -22661,6 +22778,7 @@ describe('ReportUtils', () => { hasGuidesEmails: false, conciergeReportID: undefined, + derivedIsEmptyReport: undefined, }); expect(reason).toBe(CONST.REPORT_IN_LHN_REASONS.HAS_GBR); diff --git a/tests/unit/useReportAttributesTest.ts b/tests/unit/useReportAttributesTest.ts index 07e8f86d6c3d..c9e4fbc6b98e 100644 --- a/tests/unit/useReportAttributesTest.ts +++ b/tests/unit/useReportAttributesTest.ts @@ -1,12 +1,13 @@ import {renderHook} from '@testing-library/react-native'; -import useReportAttributes, {useDerivedReportNameByReportID, useDerivedReportNamesByReportIDs} from '@hooks/useReportAttributes'; +import useReportAttributes, {useDerivedIsEmptyReport, useDerivedReportNameByReportID, useDerivedReportNamesByReportIDs} from '@hooks/useReportAttributes'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import type {ReportAttributesDerivedValue} from '@src/types/onyx'; import type {ReportAttributes} from '@src/types/onyx/DerivedValues'; +import {reportIsEmptySelector} from '@selectors/ReportAttributes'; import Onyx from 'react-native-onyx'; import waitForBatchedUpdates from '../utils/waitForBatchedUpdates'; @@ -268,3 +269,102 @@ describe('useDerivedReportNamesByReportIDs', () => { expect(result.current?.[REPORT_ID_2]).toBe('Report 2'); }); }); + +describe('useDerivedIsEmptyReport', () => { + beforeAll(() => { + Onyx.init({keys: ONYXKEYS}); + }); + + beforeEach(async () => { + await Onyx.clear(); + }); + + it('should return undefined when the derived value is not set', async () => { + await waitForBatchedUpdates(); + + const {result} = renderHook(() => useDerivedIsEmptyReport(REPORT_ID_1)); + + expect(result.current).toBeUndefined(); + }); + + it('should return false for a non-empty report', async () => { + await Onyx.set(ONYXKEYS.DERIVED.REPORT_ATTRIBUTES, createDerivedValue(MOCK_REPORTS)); + + await waitForBatchedUpdates(); + + const {result} = renderHook(() => useDerivedIsEmptyReport(REPORT_ID_1)); + + expect(result.current).toBe(false); + }); + + it('should return true for an empty report', async () => { + await Onyx.set(ONYXKEYS.DERIVED.REPORT_ATTRIBUTES, createDerivedValue(MOCK_REPORTS)); + + await waitForBatchedUpdates(); + + const {result} = renderHook(() => useDerivedIsEmptyReport(REPORT_ID_2)); + + expect(result.current).toBe(true); + }); + + it('should return undefined when reportID is undefined', async () => { + await Onyx.set(ONYXKEYS.DERIVED.REPORT_ATTRIBUTES, createDerivedValue(MOCK_REPORTS)); + + await waitForBatchedUpdates(); + + const {result} = renderHook(() => useDerivedIsEmptyReport(undefined)); + + expect(result.current).toBeUndefined(); + }); + + it('should return undefined when the reportID does not exist', async () => { + await Onyx.set(ONYXKEYS.DERIVED.REPORT_ATTRIBUTES, createDerivedValue(MOCK_REPORTS)); + + await waitForBatchedUpdates(); + + const {result} = renderHook(() => useDerivedIsEmptyReport('nonExistentReportID')); + + expect(result.current).toBeUndefined(); + }); + + it('should update when the isEmpty flag changes', async () => { + await Onyx.set(ONYXKEYS.DERIVED.REPORT_ATTRIBUTES, createDerivedValue(MOCK_REPORTS)); + + await waitForBatchedUpdates(); + + const {result, rerender} = renderHook(() => useDerivedIsEmptyReport(REPORT_ID_1)); + + expect(result.current).toBe(false); + + await Onyx.set(ONYXKEYS.DERIVED.REPORT_ATTRIBUTES, createDerivedValue({[REPORT_ID_1]: createMockReport({isEmpty: true})})); + + await waitForBatchedUpdates(); + rerender(undefined); + + expect(result.current).toBe(true); + }); +}); + +describe('reportIsEmptySelector', () => { + const derivedValue = createDerivedValue(MOCK_REPORTS); + + it('should return false for a non-empty report', () => { + expect(reportIsEmptySelector(derivedValue, REPORT_ID_1)).toBe(false); + }); + + it('should return true for an empty report', () => { + expect(reportIsEmptySelector(derivedValue, REPORT_ID_2)).toBe(true); + }); + + it('should return undefined when reportID is undefined', () => { + expect(reportIsEmptySelector(derivedValue, undefined)).toBeUndefined(); + }); + + it('should return undefined when reportID does not exist', () => { + expect(reportIsEmptySelector(derivedValue, 'nonExistentReportID')).toBeUndefined(); + }); + + it('should return undefined when attributes is undefined', () => { + expect(reportIsEmptySelector(undefined, REPORT_ID_1)).toBeUndefined(); + }); +});