diff --git a/src/components/Search/index.tsx b/src/components/Search/index.tsx index 56a7b28277e4..890e7c34e844 100644 --- a/src/components/Search/index.tsx +++ b/src/components/Search/index.tsx @@ -23,6 +23,7 @@ import useNetwork from '@hooks/useNetwork'; import useOnyx from '@hooks/useOnyx'; import usePolicyForMovingExpenses from '@hooks/usePolicyForMovingExpenses'; import usePrevious from '@hooks/usePrevious'; +import useReportAttributes from '@hooks/useReportAttributes'; import useResponsiveLayout from '@hooks/useResponsiveLayout'; import useSaveSortedReportIDs from '@hooks/useSaveSortedReportIDs'; import useSearchHighlightAndScroll from '@hooks/useSearchHighlightAndScroll'; @@ -317,6 +318,7 @@ function Search({ const [customCardNames] = useOnyx(ONYXKEYS.NVP_EXPENSIFY_COMPANY_CARDS_CUSTOM_NAMES); const [nonPersonalAndWorkspaceCards] = useOnyx(ONYXKEYS.DERIVED.NON_PERSONAL_AND_WORKSPACE_CARD_LIST); const [conciergeReportID] = useOnyx(ONYXKEYS.CONCIERGE_REPORT_ID); + const reportAttributesDerivedValue = useReportAttributes(); const { showPendingExpensePlaceholder, @@ -576,6 +578,7 @@ function Search({ onyxPersonalDetailsList, policyForMovingExpenses, convertToDisplayString, + reportAttributesDerivedValue, optimisticTransactionID: optimisticTrackingState.optimisticWatchKey?.toString().replace(ONYXKEYS.COLLECTION.TRANSACTION, ''), }); return { @@ -611,6 +614,7 @@ function Search({ onyxPersonalDetailsList, policyForMovingExpenses, convertToDisplayString, + reportAttributesDerivedValue, optimisticTrackingState.optimisticWatchKey, ]); diff --git a/src/hooks/useSearchSections.ts b/src/hooks/useSearchSections.ts index fd331bef0c3e..3a9461f23dd5 100644 --- a/src/hooks/useSearchSections.ts +++ b/src/hooks/useSearchSections.ts @@ -9,6 +9,7 @@ import useCurrentUserPersonalDetails from './useCurrentUserPersonalDetails'; import useFilterPendingDeleteReports from './useFilterPendingDeleteReports'; import useLocalize from './useLocalize'; import useOnyx from './useOnyx'; +import useReportAttributes from './useReportAttributes'; type UseSearchSectionsResult = { allReports: Array; @@ -30,6 +31,7 @@ function useSearchSections(): UseSearchSectionsResult { const archivedReportsIdSet = useArchivedReportsIdSet(); const [conciergeReportID] = useOnyx(ONYXKEYS.CONCIERGE_REPORT_ID); + const reportAttributesDerivedValue = useReportAttributes(); const {type, status, sortBy, sortOrder, groupBy} = lastSearchQuery?.queryJSON ?? {}; const searchResultsData = currentSearchResults?.data; @@ -56,6 +58,7 @@ function useSearchSections(): UseSearchSectionsResult { cardList: nonPersonalAndWorkspaceCards, conciergeReportID, convertToDisplayString, + reportAttributesDerivedValue, }); results = getSortedSections(type, status ?? '', searchData, localeCompare, translate, sortBy, sortOrder, groupBy).map((value) => value.reportID); } diff --git a/src/libs/ModifiedExpenseMessage.ts b/src/libs/ModifiedExpenseMessage.ts index e962a2b98673..61d0b20ebf17 100644 --- a/src/libs/ModifiedExpenseMessage.ts +++ b/src/libs/ModifiedExpenseMessage.ts @@ -22,7 +22,6 @@ import {getOriginalMessage, isModifiedExpenseAction} from './ReportActionsUtils' // ReportNameUtils imports helper functions from ReportUtils, and ReportUtils imports name generation functions from ReportNameUtils. // eslint-disable-next-line import/no-cycle import {buildReportNameFromParticipantNames, getPolicyExpenseChatName, getReportName} from './ReportNameUtils'; -// eslint-disable-next-line import/no-cycle import {getPolicyName, getRootParentReport, isPolicyExpenseChat, isSelfDM} from './ReportUtils'; import {getFormattedAttendees, getTagArrayFromName} from './TransactionUtils'; import {isInvalidMerchantValue} from './ValidationUtils'; diff --git a/src/libs/ReportActionsUtils.ts b/src/libs/ReportActionsUtils.ts index c97a5b6267ea..df0cde3c3e1e 100644 --- a/src/libs/ReportActionsUtils.ts +++ b/src/libs/ReportActionsUtils.ts @@ -174,8 +174,6 @@ const QBO_EXPENSES_URL = 'https://qbo.intuit.com/app/expenses'; const POLICY_CHANGE_LOG_ARRAY = new Set(Object.values(CONST.REPORT.ACTIONS.TYPE.POLICY_CHANGE_LOG)); -const ROOM_CHANGE_LOG_ARRAY = new Set(Object.values(CONST.REPORT.ACTIONS.TYPE.ROOM_CHANGE_LOG)); - const MEMBER_CHANGE_ARRAY = new Set([ CONST.REPORT.ACTIONS.TYPE.ROOM_CHANGE_LOG.INVITE_TO_ROOM, CONST.REPORT.ACTIONS.TYPE.ROOM_CHANGE_LOG.REMOVE_FROM_ROOM, @@ -698,10 +696,6 @@ function isRejectedAction(reportAction: OnyxInputOrEntry): boolean return isActionOfType(reportAction, CONST.REPORT.ACTIONS.TYPE.REJECTED) || isActionOfType(reportAction, CONST.REPORT.ACTIONS.TYPE.REJECTED_TO_SUBMITTER); } -function isRoomChangeLogAction(reportAction: OnyxEntry): reportAction is ReportAction> { - return reportAction?.actionName ? ROOM_CHANGE_LOG_ARRAY.has(reportAction.actionName) : false; -} - function isInviteOrRemovedAction( reportAction: OnyxInputOrEntry, ): reportAction is ReportAction> { @@ -4740,7 +4734,6 @@ export { isPayAction, isPendingRemove, getModerationFlagState, - isPolicyChangeLogAction, isReimbursementDeQueuedOrCanceledAction, isReimbursementQueuedAction, isRenamedAction, @@ -4748,7 +4741,6 @@ export { isReportPreviewAction, isReversedTransaction, getMentionedAccountIDsFromAction, - isRoomChangeLogAction, isSentMoneyReportAction, isSplitBillAction, isTaskAction, diff --git a/src/libs/ReportNameUtils.ts b/src/libs/ReportNameUtils.ts index 587bba7b9d1e..86d3ff9c8f32 100644 --- a/src/libs/ReportNameUtils.ts +++ b/src/libs/ReportNameUtils.ts @@ -1057,7 +1057,6 @@ function getReportName(report?: Report, reportAttributesDerivedValue?: ReportAtt export { computeReportName, getReportName, - generateArchivedReportName, getInvoiceReportName, getMoneyRequestReportName, buildReportNameFromParticipantNames, @@ -1065,5 +1064,4 @@ export { getGroupChatName, getPolicyExpenseChatName, getInvoicesChatName, - computeReportNameBasedOnReportAction, }; diff --git a/src/libs/ReportUtils.ts b/src/libs/ReportUtils.ts index b3bcbae3d67d..3de7c834d6ad 100644 --- a/src/libs/ReportUtils.ts +++ b/src/libs/ReportUtils.ts @@ -67,7 +67,6 @@ import type {OriginalMessageExportedToIntegration} from '@src/types/onyx/OldDotA import type Onboarding from '@src/types/onyx/Onboarding'; import type {ErrorFields, Errors, Icon, PendingAction} from '@src/types/onyx/OnyxCommon'; import type { - OriginalMessageChangeLog, OriginalMessageChangePolicy, OriginalMessageExportIntegration, OriginalMessageModifiedExpense, @@ -82,8 +81,8 @@ import type {PendingChatMember} from '@src/types/onyx/ReportMetadata'; import type {OnyxData} from '@src/types/onyx/Request'; import type {Comment, TransactionChanges, WaypointCollection} from '@src/types/onyx/Transaction'; import type {FileObject} from '@src/types/utils/Attachment'; -import {isEmptyObject, isEmptyValueObject} from '@src/types/utils/EmptyObject'; import type {EmptyObject} from '@src/types/utils/EmptyObject'; +import {isEmptyObject, isEmptyValueObject} from '@src/types/utils/EmptyObject'; import type IconAsset from '@src/types/utils/IconAsset'; import {getBankAccountFromID} from './actions/BankAccounts'; import {unholdRequest} from './actions/IOU/Hold'; @@ -98,12 +97,12 @@ import { import {canApproveIOU, canIOUBePaid, canSubmitReport, getBadgeFromIOUReport, getIOUReportActionWithBadge} from './actions/IOU/ReportWorkflow'; import {createDraftWorkspace} from './actions/Policy/Policy'; import hasCreditBankAccount from './actions/ReimbursementAccount/hasCreditBankAccount'; -import {openUnreportedExpense} from './actions/Report'; import type {GuidedSetupData, TaskForParameters} from './actions/Report'; +import {openUnreportedExpense} from './actions/Report'; import {isAnonymousUser as isAnonymousUserSession} from './actions/Session'; import {removeDraftTransactionsByIDs} from './actions/TransactionEdit'; -import {getOnboardingMessages} from './actions/Welcome/OnboardingFlow'; import type {OnboardingCompanySize, OnboardingMessage, OnboardingPurpose, OnboardingTaskLinks} from './actions/Welcome/OnboardingFlow'; +import {getOnboardingMessages} from './actions/Welcome/OnboardingFlow'; import type {AddCommentOrAttachmentParams} from './API/parameters'; import {getCategoryGLCode} from './CategoryUtils'; import {convertToDisplayString} from './CurrencyUtils'; @@ -119,8 +118,6 @@ import {formatPhoneNumber as formatPhoneNumberPhoneUtils} from './LocalePhoneNum import {translateLocal} from './Localize'; import Log from './Log'; import {isEmailPublicDomain} from './LoginUtils'; -// eslint-disable-next-line import/no-cycle -import {getForReportAction, getMovedReportID} from './ModifiedExpenseMessage'; import createDynamicRoute from './Navigation/helpers/dynamicRoutesUtils/createDynamicRoute'; import getReportURLForCurrentContext from './Navigation/helpers/getReportURLForCurrentContext'; import getStateFromPath from './Navigation/helpers/getStateFromPath'; @@ -129,22 +126,13 @@ import isSearchTopmostFullScreenRoute from './Navigation/helpers/isSearchTopmost import {linkingConfig} from './Navigation/linkingConfig'; import Navigation, {navigationRef} from './Navigation/Navigation'; import type {MoneyRequestNavigatorParamList, ReportsSplitNavigatorParamList} from './Navigation/types'; -import {getCurrentUserEmail} from './Network/NetworkStore'; import {getDBTimeWithSkew} from './NetworkState'; import {rand64} from './NumberUtils'; import Parser from './Parser'; import {getParsedMessageWithShortMentions} from './ParsingUtils'; import {getBankAccountLastFourDigits} from './PaymentUtils'; import Permissions from './Permissions'; -import { - getAccountIDsByLogins, - getDisplayNameOrDefault, - getEffectiveDisplayName, - getLoginsByAccountIDs, - getPersonalDetailByEmail, - getPersonalDetailsByIDs, - getShortMentionIfFound, -} from './PersonalDetailsUtils'; +import {getAccountIDsByLogins, getDisplayNameOrDefault, getLoginsByAccountIDs, getPersonalDetailByEmail, getShortMentionIfFound} from './PersonalDetailsUtils'; import { canSendInvoiceFromWorkspace, getActivePolicies, @@ -173,11 +161,11 @@ import { isSubmitAndClose, shouldShowPolicy, } from './PolicyUtils'; +import type {LastVisibleMessage} from './ReportActionsUtils'; import { formatLastMessageText, getActionableJoinRequestPendingReportAction, getAllReportActions, - getCreatedReportForUnapprovedTransactionsMessage, getIOUActionForTransactionID, getIOUReportIDFromReportActionPreview, getLastVisibleAction, @@ -209,20 +197,16 @@ import { isExportIntegrationAction, isForwardedAction, isIntegrationMessageAction, - isModifiedExpenseAction, isMoneyRequestAction, isMovedAction, isOlderReportAction, isPendingRemove, - isPolicyChangeLogAction, isReimbursementQueuedAction, isReopenedAction, - isReportActionAttachment, isReportActionVisible, isReportPreviewAction, isRetractedAction, isReversedTransaction, - isRoomChangeLogAction, isSentMoneyReportAction, isSplitBillAction as isSplitBillReportAction, isSubmittedAction, @@ -233,25 +217,11 @@ import { isWhisperAction, wasActionTakenByCurrentUser, } from './ReportActionsUtils'; -import type {LastVisibleMessage} from './ReportActionsUtils'; // This cycle import is safe because ReportNameUtils was extracted from ReportUtils to separate report name computation logic. // The functions imported here are pure utility functions that don't create initialization-time dependencies. // ReportNameUtils imports helper functions from ReportUtils, and ReportUtils imports name generation functions from ReportNameUtils. // eslint-disable-next-line import/no-cycle -import { - buildReportNameFromParticipantNames, - // eslint-disable-next-line no-restricted-imports -- We plan to refactor this file to remove dependency on computeReportName - computeReportName, - computeReportNameBasedOnReportAction, - generateArchivedReportName, - getGroupChatName, - getInvoicePayerName, - getInvoiceReportName, - getInvoicesChatName, - getMoneyRequestReportName, - getPolicyExpenseChatName, - getReportName as getReportNameFromNameUtils, -} from './ReportNameUtils'; +import {getGroupChatName, getInvoicePayerName, getInvoiceReportName, getReportName} from './ReportNameUtils'; import type {ArchivedReportsIDSet} from './SearchUIUtils'; import {shouldRestrictUserBillableActions} from './SubscriptionUtils'; import {isTaskCompleted} from './TaskUtils'; @@ -972,22 +942,6 @@ type GetPolicyNameParams = { reports?: Report[]; }; -type GetReportNameParams = { - report: OnyxEntry; - policy?: OnyxEntry; - parentReportActionParam?: OnyxInputOrEntry; - personalDetails?: Partial; - invoiceReceiverPolicy?: OnyxEntry; - /** Report attributes used to return a precomputed report name */ - reportAttributes?: ReportAttributesDerivedValue['reports']; - transactions?: Transaction[]; - reports?: Report[]; - isReportArchived?: boolean; - // TODO: Make this required when https://github.com/Expensify/App/issues/66411 is done - /** Used to identify the Concierge chat so its name can be set to the Concierge display name */ - conciergeReportID?: string; -}; - type GetReportStatusParams = { stateNum?: number; statusNum?: number; @@ -5379,19 +5333,17 @@ type GetReportPreviewMessageBaseParams = { /** * Get expense message for an IOU report. - * - * `conciergeReportID` is only consumed (and required) when `isCopyAction: true`. */ function getReportPreviewMessage(params: GetReportPreviewMessageBaseParams & {isCopyAction?: false}): string; -function getReportPreviewMessage(params: GetReportPreviewMessageBaseParams & {isCopyAction: true; conciergeReportID: string | undefined}): string; -function getReportPreviewMessage(params: GetReportPreviewMessageBaseParams & {isCopyAction?: boolean; conciergeReportID?: string | undefined}): string { +function getReportPreviewMessage(params: GetReportPreviewMessageBaseParams & {isCopyAction: true; reportAttributes?: ReportAttributesDerivedValue['reports']}): string; +function getReportPreviewMessage(params: GetReportPreviewMessageBaseParams & {isCopyAction?: boolean; reportAttributes?: ReportAttributesDerivedValue['reports']}): string { const {reportOrID, iouReportAction = null, shouldConsiderScanningReceiptOrPendingRoute = false, isPreviewMessageForParentChatReport = false, policy, isForListPreview = false} = params; const originalReportAction = params.originalReportAction ?? iouReportAction; const report = typeof reportOrID === 'string' ? getReport(reportOrID, deprecatedAllReports) : reportOrID; const reportActionMessage = getReportActionHtml(iouReportAction); if (params.isCopyAction) { if (report) { - return computeReportName({report, currentUserLogin: '', conciergeReportID: params.conciergeReportID}) || (originalReportAction?.childReportName ?? ''); + return getReportName(report, params.reportAttributes ?? reportAttributesDerivedValue) || (originalReportAction?.childReportName ?? ''); } return originalReportAction?.childReportName ?? ''; } @@ -5697,60 +5649,6 @@ function getModifiedExpenseOriginalMessage( return originalMessage; } -/** - * Check if original message is an object and can be used as a ChangeLog type - * @param originalMessage - */ -function isChangeLogObject(originalMessage?: OriginalMessageChangeLog): OriginalMessageChangeLog | undefined { - if (originalMessage && typeof originalMessage === 'object') { - return originalMessage; - } - return undefined; -} - -/** - * Build invited usernames for admin chat threads - * @param parentReportAction - * @param parentReportActionMessage - */ -function getAdminRoomInvitedParticipants(translate: LocalizedTranslate, parentReportAction: OnyxEntry, parentReportActionMessage: string) { - if (isEmptyObject(parentReportAction)) { - return parentReportActionMessage || translate('parentReportAction.deletedMessage'); - } - if (!getOriginalMessage(parentReportAction)) { - return parentReportActionMessage || translate('parentReportAction.deletedMessage'); - } - if (!isPolicyChangeLogAction(parentReportAction) && !isRoomChangeLogAction(parentReportAction)) { - return parentReportActionMessage || translate('parentReportAction.deletedMessage'); - } - - const originalMessage = isChangeLogObject(getOriginalMessage(parentReportAction) as OriginalMessageChangeLog); - const personalDetails = getPersonalDetailsByIDs({accountIDs: originalMessage?.targetAccountIDs ?? [], currentUserAccountID: 0}); - - const participants = personalDetails.map((personalDetail) => { - const name = getEffectiveDisplayName(formatPhoneNumberPhoneUtils, personalDetail); - if (name && name?.length > 0) { - return name; - } - return translate('common.hidden'); - }); - const users = participants.length > 1 ? participants.join(` ${translate('common.and')} `) : participants.at(0); - if (!users) { - return parentReportActionMessage; - } - const actionType = parentReportAction.actionName; - const isInviteAction = actionType === CONST.REPORT.ACTIONS.TYPE.ROOM_CHANGE_LOG.INVITE_TO_ROOM || actionType === CONST.REPORT.ACTIONS.TYPE.POLICY_CHANGE_LOG.INVITE_TO_ROOM; - - const verbKey = isInviteAction ? 'workspace.invite.invited' : 'workspace.invite.removed'; - const prepositionKey = isInviteAction ? 'workspace.invite.to' : 'workspace.invite.from'; - const verb = translate(verbKey); - const preposition = translate(prepositionKey); - - const roomName = originalMessage?.roomName ?? ''; - - return roomName ? `${verb} ${users} ${preposition} ${roomName}` : `${verb} ${users}`; -} - /** * Parse html of reportAction into text */ @@ -5776,7 +5674,7 @@ function parseReportActionHtmlToText(reportAction: OnyxEntry, repo const reportIDToName: Record = {}; for (const match of matches) { if (match[1] !== childReportID) { - reportIDToName[match[1]] = getReportNameFromNameUtils(getReportOrDraftReport(match[1]), reportAttributesDerivedValue) ?? ''; + reportIDToName[match[1]] = getReportName(getReportOrDraftReport(match[1]), reportAttributesDerivedValue) ?? ''; } } @@ -5797,232 +5695,6 @@ function parseReportActionHtmlToText(reportAction: OnyxEntry, repo return textMessage; } -/** - * Get the title for a report. - * @deprecated Moved to src/libs/ReportNameUtils.ts. - */ -function getReportName(reportNameInformation: GetReportNameParams): string { - const {report, policy, parentReportActionParam, personalDetails, invoiceReceiverPolicy, reportAttributes, transactions, isReportArchived, reports, conciergeReportID} = - reportNameInformation; - // Check if we can use report name in derived values - only when we have report but no other params - const canUseDerivedValue = - report && policy === undefined && parentReportActionParam === undefined && personalDetails === undefined && invoiceReceiverPolicy === undefined && isReportArchived === undefined; - const attributes = reportAttributes ?? reportAttributesDerivedValue; - const derivedNameExists = report && !!attributes?.[report.reportID]?.reportName; - if (canUseDerivedValue && derivedNameExists) { - return attributes[report.reportID].reportName; - } - - let formattedName: string | undefined; - let parentReportAction: OnyxEntry; - const parentReport = deprecatedAllReports?.[`${ONYXKEYS.COLLECTION.REPORT}${report?.parentReportID}`]; - if (parentReportActionParam) { - parentReportAction = parentReportActionParam; - } else { - parentReportAction = isThread(report) ? allReportActions?.[`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${report?.parentReportID}`]?.[report.parentReportActionID] : undefined; - } - const parentReportActionMessage = getReportActionMessageReportUtils(parentReportAction); - const isArchivedNonExpense = isArchivedNonExpenseReport(report, isReportArchived); - - const reportPolicy = policy ?? allPolicies?.[`${ONYXKEYS.COLLECTION.POLICY}${report?.policyID}`]; - - const parentReportActionBasedName = computeReportNameBasedOnReportAction( - translateLocal, - formatPhoneNumberPhoneUtils, - parentReportAction, - report, - reportPolicy, - parentReport, - personalDetails as PersonalDetailsList, - attributes, - ); - - if (parentReportActionBasedName) { - return parentReportActionBasedName; - } - - if (isActionOfType(parentReportAction, CONST.REPORT.ACTIONS.TYPE.CREATED_REPORT_FOR_UNAPPROVED_TRANSACTIONS)) { - const {originalID} = getOriginalMessage(parentReportAction) ?? {}; - const originalReport = deprecatedAllReports?.[`${ONYXKEYS.COLLECTION.REPORT}${originalID}`]; - const reportName = getReportName({report: originalReport}); - return getCreatedReportForUnapprovedTransactionsMessage(originalID, reportName, !!parentReportAction.isOriginalReportDeleted, translateLocal); - } - - if (isTaskReport(report)) { - const taskName = report?.reportName ?? ''; - return Parser.isHTML(taskName) ? Parser.htmlToText(taskName).trim() : taskName.trim(); - } - - if (isChatThread(report)) { - if (!isEmptyObject(parentReportAction) && isTransactionThread(parentReportAction)) { - formattedName = getTransactionReportName({translate: translateLocal, reportAction: parentReportAction, transactions, reports}); - - if (isArchivedNonExpense) { - formattedName = generateArchivedReportName(formattedName); - } - return formatReportLastMessageText(formattedName); - } - - if (parentReportActionMessage?.isDeletedParentAction) { - return translateLocal('parentReportAction.deletedMessage'); - } - - const isAttachment = isReportActionAttachment(!isEmptyObject(parentReportAction) ? parentReportAction : undefined); - const reportActionMessage = parseReportActionHtmlToText(parentReportAction, report?.parentReportID, conciergeReportID, report?.reportID).replaceAll(/(\n+|\r\n|\n|\r)/gm, ' '); - if (isAttachment && reportActionMessage) { - return `[${translateLocal('common.attachment')}]`; - } - if ( - parentReportActionMessage?.moderationDecision?.decision === CONST.MODERATION.MODERATOR_DECISION_PENDING_HIDE || - parentReportActionMessage?.moderationDecision?.decision === CONST.MODERATION.MODERATOR_DECISION_HIDDEN || - parentReportActionMessage?.moderationDecision?.decision === CONST.MODERATION.MODERATOR_DECISION_PENDING_REMOVE - ) { - return translateLocal('parentReportAction.hiddenMessage'); - } - if (isAdminRoom(report) || isUserCreatedPolicyRoom(report)) { - return getAdminRoomInvitedParticipants(translateLocal, parentReportAction, reportActionMessage); - } - - if (reportActionMessage && isArchivedNonExpense) { - return generateArchivedReportName(reportActionMessage); - } - if (!isEmptyObject(parentReportAction) && isModifiedExpenseAction(parentReportAction)) { - const movedFromReport = deprecatedAllReports?.[`${ONYXKEYS.COLLECTION.REPORT}${getMovedReportID(parentReportAction, CONST.REPORT.MOVE_TYPE.FROM)}`]; - const movedToReport = deprecatedAllReports?.[`${ONYXKEYS.COLLECTION.REPORT}${getMovedReportID(parentReportAction, CONST.REPORT.MOVE_TYPE.TO)}`]; - const modifiedMessageWithHTML = getForReportAction({ - translate: translateLocal, - reportAction: parentReportAction, - policy, - movedFromReport, - movedToReport, - // Temporarily retrieves current user email from getCurrentUserEmail, since getReportName is deprecated and no longer requires this parameter to be passed explicitly. - currentUserLogin: getCurrentUserEmail() ?? '', - }); - // Strip HTML tags for plain text display in report last message - const modifiedMessage = Parser.htmlToText(modifiedMessageWithHTML); - return formatReportLastMessageText(modifiedMessage); - } - if (isTripRoom(report) && report?.reportName !== CONST.REPORT.DEFAULT_REPORT_NAME) { - return report?.reportName ?? ''; - } - return reportActionMessage; - } - - if (isClosedExpenseReportWithNoExpenses(report, transactions)) { - return translateLocal('parentReportAction.deletedReport'); - } - - if (isGroupChat(report)) { - return getGroupChatName(formatPhoneNumberPhoneUtils, undefined, true, report) ?? ''; - } - - if (isChatRoom(report)) { - formattedName = report?.reportName; - } - - if (isPolicyExpenseChat(report)) { - formattedName = getPolicyExpenseChatName({report, personalDetailsList: personalDetails}); - } - - if (isMoneyRequestReport(report)) { - formattedName = getMoneyRequestReportName({report, policy}); - } - - if (isInvoiceReport(report)) { - formattedName = getInvoiceReportName(report, policy, invoiceReceiverPolicy); - } - - if (isInvoiceRoom(report)) { - const invoiceReceiverPolicyID = getInvoiceReceiverPolicyID(report); - formattedName = getInvoicesChatName({ - report, - // This will be fixed as part of https://github.com/Expensify/Expensify/issues/507850 - receiverPolicy: invoiceReceiverPolicy ?? getPolicy(invoiceReceiverPolicyID), - personalDetails, - policy, - currentUserAccountID: deprecatedCurrentUserAccountID, - }); - } - - if (isSelfDM(report)) { - formattedName = getDisplayNameForParticipant({ - accountID: deprecatedCurrentUserAccountID, - shouldAddCurrentUserPostfix: true, - personalDetailsData: personalDetails, - formatPhoneNumber: formatPhoneNumberPhoneUtils, - }); - } - - if (isConciergeChatReport(report, conciergeReportID)) { - formattedName = CONST.CONCIERGE_DISPLAY_NAME; - } - - if (formattedName) { - return formatReportLastMessageText(isArchivedNonExpense ? generateArchivedReportName(formattedName) : formattedName); - } - - // Not a room or PolicyExpenseChat, generate title from first 5 other participants - formattedName = buildReportNameFromParticipantNames({report, personalDetailsList: personalDetails, currentUserAccountID: deprecatedCurrentUserAccountID}); - - const finalName = formattedName || (report?.reportName ?? ''); - - return isArchivedNonExpense ? generateArchivedReportName(finalName) : finalName; -} - -/** - * @deprecated Moved to src/libs/ReportNameUtils.ts. - * Use ReportNameUtils.computeReportName(...) in search contexts instead. - * @param props - */ -function getSearchReportName(props: GetReportNameParams): string { - const {report, policy} = props; - if (isChatThread(report) && policy?.name) { - // Traverse up the parent chain to find the first expense report - // If found, return the expense report name instead of workspace name - let currentParent = getParentReport(report); - const visitedReportIDs = new Set(); - - while (currentParent) { - if (!currentParent.reportID) { - break; - } - if (visitedReportIDs.has(currentParent.reportID)) { - break; - } - visitedReportIDs.add(currentParent.reportID); - - if (isExpenseReport(currentParent)) { - return getReportName({ - report: currentParent, - policy, - parentReportActionParam: props.parentReportActionParam, - personalDetails: props.personalDetails, - invoiceReceiverPolicy: props.invoiceReceiverPolicy, - transactions: props.transactions, - isReportArchived: props.isReportArchived, - reports: props.reports, - }); - } - - // Continue traversing up the parent chain - currentParent = getParentReport(currentParent); - } - - return policy.name; - } - // This will be fixed as follow up https://github.com/Expensify/App/pull/75357 - return getReportName({ - report, - policy, - parentReportActionParam: props.parentReportActionParam, - personalDetails: props.personalDetails, - invoiceReceiverPolicy: props.invoiceReceiverPolicy, - transactions: props.transactions, - isReportArchived: props.isReportArchived, - reports: props.reports, - }); -} - /** * Get the payee name given a report. */ @@ -6169,7 +5841,7 @@ function getParentNavigationSubtitle( } return { - reportName: getReportNameFromNameUtils(parentReport, reportAttributes ?? reportAttributesDerivedValue), + reportName: getReportName(parentReport, reportAttributes ?? reportAttributesDerivedValue), workspaceName: getPolicyName({report: parentReport, policy, returnEmptyIfNotFound: true}), }; } @@ -6951,7 +6623,7 @@ function getMovedTransactionMessage(translate: LocalizedTranslate, action: Repor const report = fromReport ?? toReport; - const reportName = Parser.htmlToText(getReportNameFromNameUtils(report, reportAttributes) ?? report?.reportName ?? ''); + const reportName = Parser.htmlToText(getReportName(report, reportAttributes) ?? report?.reportName ?? ''); const reportUrl = getReportURLForCurrentContext(report?.reportID); if (typeof fromReportID === 'undefined') { return reportName ? translate('iou.movedTransactionTo', reportUrl, reportName) : translate('iou.movedTransactionToAnotherReport'); @@ -6965,7 +6637,7 @@ function getUnreportedTransactionMessage(translate: LocalizedTranslate, action: const fromReport = deprecatedAllReports?.[`${ONYXKEYS.COLLECTION.REPORT}${fromReportID}`]; - const reportName = Parser.htmlToText(getReportNameFromNameUtils(fromReport, reportAttributes) ?? fromReport?.reportName ?? ''); + const reportName = Parser.htmlToText(getReportName(fromReport, reportAttributes) ?? fromReport?.reportName ?? ''); let reportUrl = getReportURLForCurrentContext(fromReportID); @@ -12736,10 +12408,10 @@ function getChatListItemReportName(action: ReportAction & {reportName?: string}, } if (report?.reportID) { - return getReportNameFromNameUtils(getReport(report?.reportID, deprecatedAllReports), reportAttributesDerivedValue); + return getReportName(getReport(report?.reportID, deprecatedAllReports), reportAttributesDerivedValue); } - return getReportNameFromNameUtils(report, reportAttributesDerivedValue); + return getReportName(report, reportAttributesDerivedValue); } /** @@ -13418,8 +13090,6 @@ export { getReportFieldKey, getReportFieldMaps, getReportIDFromLink, - // This will be fixed as follow up https://github.com/Expensify/App/pull/75357 - getSearchReportName, getReportTransactions, getReportNotificationPreference, getReportOfflinePendingActionAndErrors, diff --git a/src/libs/SearchUIUtils.ts b/src/libs/SearchUIUtils.ts index ca422097f8a7..2b695604008c 100644 --- a/src/libs/SearchUIUtils.ts +++ b/src/libs/SearchUIUtils.ts @@ -139,13 +139,11 @@ import { findSelfDMReportID, generateReportID, getIcons, - getInvoiceReceiverPolicyID, getMoneyRequestSpendBreakdown, getPersonalDetailsForAccountID, getPolicyName, getReportOrDraftReport, getReportStatusTranslation, - getSearchReportName, hasHeldExpenses, hasInvoiceReports, hasOnlyNonReimbursableTransactions, @@ -612,6 +610,7 @@ type GetSectionsParams = { onyxPersonalDetailsList?: OnyxTypes.PersonalDetailsList; policyForMovingExpenses?: OnyxTypes.Policy; optimisticTransactionID?: string; + reportAttributesDerivedValue?: OnyxTypes.ReportAttributesDerivedValue['reports']; }; /** @@ -2508,6 +2507,7 @@ function getTaskSections( formatPhoneNumber: LocaleContextProps['formatPhoneNumber'], conciergeReportID: string | undefined, archivedReportsIDList?: ArchivedReportsIDSet, + reportAttributesDerivedValue?: OnyxTypes.ReportAttributesDerivedValue['reports'], ): [TaskListItemType[], number] { const {shouldShowYearCreated} = shouldShowYear(data); const tasks = Object.keys(data) @@ -2545,7 +2545,7 @@ function getTaskSections( if (parentReport && personalDetails) { const policy = data[`${ONYXKEYS.COLLECTION.POLICY}${parentReport.policyID}`]; const isParentReportArchived = archivedReportsIDList?.has(`${ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS}${parentReport?.reportID}`); - const parentReportName = getReportName(parentReport); + const parentReportName = getReportName(parentReport, reportAttributesDerivedValue); const icons = getIcons(parentReport, formatPhoneNumber, personalDetails, null, '', -1, policy, undefined, isParentReportArchived); const parentReportIcon = icons?.at(0); @@ -2673,17 +2673,13 @@ function createAndOpenSearchTransactionThread({ * * Do not use directly, use only via `getSections()` facade. */ -function getReportActionsSections(data: OnyxTypes.SearchResults['data'], visibleReportActionsData?: OnyxTypes.VisibleReportActionsDerivedValue): [ReportActionListItemType[], number] { +function getReportActionsSections( + data: OnyxTypes.SearchResults['data'], + visibleReportActionsData?: OnyxTypes.VisibleReportActionsDerivedValue, + reportAttributesDerivedValue?: OnyxTypes.ReportAttributesDerivedValue['reports'], +): [ReportActionListItemType[], number] { const reportActionItems: ReportActionListItemType[] = []; - const transactions = Object.keys(data) - .filter(isTransactionEntry) - .map((key) => data[key]); - - const reports = Object.keys(data) - .filter(isReportEntry) - .map((key) => data[key]); - let n = 0; for (const key in data) { @@ -2701,12 +2697,9 @@ function getReportActionsSections(data: OnyxTypes.SearchResults['data'], visible data[`${ONYXKEYS.COLLECTION.REPORT}${reportID}`] ?? data[`${ONYXKEYS.COLLECTION.REPORT}${reportAction.reportID}`] ?? {}; - const policy = data[`${ONYXKEYS.COLLECTION.POLICY}${report.policyID}`] ?? {}; const originalMessage = isMoneyRequestAction(reportAction) ? getOriginalMessage(reportAction) : undefined; const isSendingMoney = isMoneyRequestAction(reportAction) && originalMessage?.type === CONST.IOU.REPORT_ACTION_TYPE.PAY && originalMessage?.IOUDetails; const isReportArchived = isArchivedReport(data[`${ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS}${report.reportID}`]); - const invoiceReceiverPolicyID = getInvoiceReceiverPolicyID(report); - const invoiceReceiverPolicy: OnyxTypes.Policy | undefined = invoiceReceiverPolicyID ? data[`${ONYXKEYS.COLLECTION.POLICY}${invoiceReceiverPolicyID}`] : undefined; if ( !reportID || !isReportActionVisible(reportAction, reportID, canUserPerformWriteAction(report, isReportArchived), visibleReportActionsData) || @@ -2724,7 +2717,7 @@ function getReportActionsSections(data: OnyxTypes.SearchResults['data'], visible ...reportAction, reportID, from, - reportName: getSearchReportName({report, policy, personalDetails: data.personalDetailsList, transactions, invoiceReceiverPolicy, reports, isReportArchived}), + reportName: getReportName(report, reportAttributesDerivedValue), formattedFrom: from?.displayName ?? from?.login ?? '', date: reportAction.created, keyForList: reportAction.reportActionID, @@ -3604,12 +3597,13 @@ function getSections({ policyForMovingExpenses, convertToDisplayString, optimisticTransactionID, + reportAttributesDerivedValue, }: GetSectionsParams): GetSectionsResult { if (type === CONST.SEARCH.DATA_TYPES.CHAT) { - return [...getReportActionsSections(data, visibleReportActionsData), false]; + return [...getReportActionsSections(data, visibleReportActionsData, reportAttributesDerivedValue), false]; } if (type === CONST.SEARCH.DATA_TYPES.TASK) { - return [...getTaskSections(data, formatPhoneNumber, conciergeReportID, archivedReportsIDList), false]; + return [...getTaskSections(data, formatPhoneNumber, conciergeReportID, archivedReportsIDList, reportAttributesDerivedValue), false]; } if (type === CONST.SEARCH.DATA_TYPES.EXPENSE_REPORT) { diff --git a/src/pages/inbox/report/ContextMenu/ContextMenuActions.tsx b/src/pages/inbox/report/ContextMenu/ContextMenuActions.tsx index 74b5d87bba6f..ddd027c1c78a 100644 --- a/src/pages/inbox/report/ContextMenu/ContextMenuActions.tsx +++ b/src/pages/inbox/report/ContextMenu/ContextMenuActions.tsx @@ -885,7 +885,6 @@ const ContextMenuActions: ContextMenuAction[] = [ harvestReportOriginalID, currentUserPersonalDetails, bankAccountList, - conciergeReportID, reportAttributes, originalReportOfUnapprovedTransaction, }, @@ -903,7 +902,7 @@ const ContextMenuActions: ContextMenuAction[] = [ reportOrID: iouReportID, iouReportAction: reportAction, isCopyAction: true, - conciergeReportID, + reportAttributes, }); Clipboard.setString(displayMessage); } else if (isTaskActionReportActionsUtils(reportAction)) { diff --git a/tests/unit/ReportUtilsTest.ts b/tests/unit/ReportUtilsTest.ts index 9e36e95891b3..28d58c208b9b 100644 --- a/tests/unit/ReportUtilsTest.ts +++ b/tests/unit/ReportUtilsTest.ts @@ -186,6 +186,7 @@ import type { Report, ReportAction, ReportActions, + ReportAttributesDerivedValue, ReportMetadata, ReportNameValuePairs, Transaction, @@ -14388,34 +14389,40 @@ describe('ReportUtils', () => { }; // When we call getReportPreviewMessage with isCopyAction = true - const result = getReportPreviewMessage({reportOrID: report, iouReportAction: reportAction, originalReportAction: reportAction, isCopyAction: true, conciergeReportID: undefined}); + const result = getReportPreviewMessage({reportOrID: report, iouReportAction: reportAction, originalReportAction: reportAction, isCopyAction: true}); // Then it should return the childReportName instead of "payer owes $0" expect(result).toBe('Expense Report 2025-01-15'); }); - it('should pass conciergeReportID through to computeReportName when isCopyAction is true', async () => { + it('should use the report name from the reportAttributes param when isCopyAction is true', async () => { const report = LHNTestUtils.getFakeReport(); + report.reportName = 'Stale Report Name'; const reportAction: ReportAction = { ...LHNTestUtils.getFakeReportAction(), actionName: CONST.REPORT.ACTIONS.TYPE.REPORT_PREVIEW, - childReportName: 'Expense Report', + childReportName: 'Child Report Name', childMoneyRequestCount: 0, }; + const reportAttributes: ReportAttributesDerivedValue['reports'] = { + [report.reportID]: { + reportName: 'Computed Report Name', + isEmpty: false, + brickRoadStatus: undefined, + requiresAttention: false, + reportErrors: {}, + }, + }; - // When called with conciergeReportID undefined, the function should not throw - const result1 = getReportPreviewMessage({ + // When called with reportAttributes that provide a report name, it should be preferred over the report's own name + const result = getReportPreviewMessage({ reportOrID: report, iouReportAction: reportAction, originalReportAction: reportAction, isCopyAction: true, - conciergeReportID: undefined, + reportAttributes, }); - expect(typeof result1).toBe('string'); - - // When called with a specific conciergeReportID, the function should not throw - const result2 = getReportPreviewMessage({reportOrID: report, iouReportAction: reportAction, originalReportAction: reportAction, isCopyAction: true, conciergeReportID: '12345'}); - expect(typeof result2).toBe('string'); + expect(result).toBe('Computed Report Name'); }); });