From 537d90690fc9f1754fe2773a30078a2f25961350 Mon Sep 17 00:00:00 2001 From: Carlos Alvarez Date: Thu, 5 Nov 2026 13:56:14 -0500 Subject: [PATCH 01/17] Open and approve bills behind the newDotBillPay beta --- src/CONST/index.ts | 2 +- .../useConfirmApproval.ts | 9 +- src/components/ParentNavigationSubtitle.tsx | 2 +- src/hooks/useLifecycleActions.tsx | 8 +- src/hooks/useSearchBulkActions.ts | 4 +- src/libs/BillPayReportActionUtils.ts | 4 +- src/libs/BillUtils.ts | 4 +- src/libs/DebugUtils.ts | 2 + src/libs/Formula.ts | 2 +- src/libs/NextStepUtils.ts | 2 +- src/libs/ReportActionsUtils.ts | 13 + src/libs/ReportNameUtils.ts | 4 +- src/libs/ReportPreviewActionUtils.ts | 6 + src/libs/ReportPrimaryActionUtils.ts | 58 +-- src/libs/ReportSecondaryActionUtils.ts | 28 +- src/libs/ReportUtils.ts | 158 ++++++-- src/libs/SearchUIUtils.ts | 3 +- src/libs/actions/IOU/MoneyRequestBuilder.ts | 6 + .../configs/visibleReportActions.ts | 37 +- src/selectors/Report.ts | 1 + src/types/onyx/Report.ts | 3 + src/types/utils/whitelistedReportKeys.ts | 1 + tests/ui/ParentNavigationSubtitleTest.tsx | 2 +- tests/ui/ReportActionItemTest.tsx | 6 +- tests/ui/SearchMoneyRequestReportPageTest.tsx | 2 +- .../MoneyReportHeaderNextStepTest.tsx | 4 +- tests/unit/BillPayAttentionTest.ts | 127 +++++++ tests/unit/BillPayTest.ts | 351 ++++++++++++++++++ tests/unit/BillUtilsTest.ts | 6 +- tests/unit/NextStepUtilsTest.ts | 2 +- .../OnyxDerived/visibleReportActionsTest.ts | 38 +- tests/unit/ReportActionsUtilsTest.ts | 30 +- tests/unit/ReportAlternateTextUtilsTest.ts | 56 +++ tests/unit/ReportNameUtilsTest.ts | 62 ++++ tests/unit/ReportNotFoundGuardTest.tsx | 4 +- tests/unit/ReportUtilsTest.ts | 41 +- tests/unit/Search/SearchUIUtilsTest.ts | 4 +- tests/unit/SidebarFilterTest.ts | 4 +- tests/unit/SidebarUtilsTest.ts | 4 +- tests/unit/hooks/useConfirmApprovalTest.ts | 96 +++++ tests/unit/hooks/useLifecycleActionsTest.ts | 124 +++++++ tests/unit/useReportActionAvatarsTest.tsx | 2 +- 42 files changed, 1193 insertions(+), 129 deletions(-) create mode 100644 tests/unit/BillPayAttentionTest.ts create mode 100644 tests/unit/BillPayTest.ts create mode 100644 tests/unit/hooks/useConfirmApprovalTest.ts create mode 100644 tests/unit/hooks/useLifecycleActionsTest.ts diff --git a/src/CONST/index.ts b/src/CONST/index.ts index bace3189d795..ddaa453325f3 100644 --- a/src/CONST/index.ts +++ b/src/CONST/index.ts @@ -2465,6 +2465,7 @@ const CONST = { TYPE: { CHAT: 'chat', EXPENSE: 'expense', + BILL: 'bill', IOU: 'iou', TASK: 'task', SUPPORT_TICKET: 'supportTicket', @@ -2472,7 +2473,6 @@ const CONST = { }, UNSUPPORTED_TYPE: { PAYCHECK: 'paycheck', - BILL: 'bill', }, CHAT_TYPE: chatTypes, WORKSPACE_CHAT_ROOMS: { diff --git a/src/components/MoneyReportHeaderPrimaryAction/useConfirmApproval.ts b/src/components/MoneyReportHeaderPrimaryAction/useConfirmApproval.ts index aa497df33633..c7e682f88f57 100644 --- a/src/components/MoneyReportHeaderPrimaryAction/useConfirmApproval.ts +++ b/src/components/MoneyReportHeaderPrimaryAction/useConfirmApproval.ts @@ -9,6 +9,7 @@ import {useGetPersonalDetailsByLogin} from '@hooks/usePersonalDetailByLogin'; import {usePersonalDetail} from '@hooks/usePersonalDetails'; import useTransactionsAndViolationsForReport from '@hooks/useTransactionsAndViolationsForReport'; +import {isBillReport} from '@libs/BillUtils'; import getNonEmptyStringOnyxID from '@libs/getNonEmptyStringOnyxID'; import {isSubmitPolicy} from '@libs/PolicyUtils'; import {hasHeldExpensesFromTransactions as hasHeldExpensesReportUtils, hasViolations as hasViolationsReportUtils} from '@libs/ReportUtils'; @@ -74,12 +75,16 @@ function useConfirmApproval( const hasViolations = hasViolationsReportUtils(moneyRequestReport?.reportID, transactionViolations, accountID, email ?? '', undefined, transactions); const isAnyTransactionOnHold = hasHeldExpensesReportUtils(transactions); + // The approved animation keeps Pay as the primary action until AnimatedSettlementButton ends it. Bills don't show + // Pay, so nothing would end the animation on a bill. + const shouldAnimateApproval = !isBillReport(moneyRequestReport); + const onApprove = (full: boolean) => { if (isDelegateAccessRestricted) { showDelegateNoAccessModal(); return; } - if (!isSubmitPolicy(policy)) { + if (shouldAnimateApproval && !isSubmitPolicy(policy)) { startApprovedAnimation(); } approveMoneyRequest({ @@ -97,7 +102,7 @@ function useConfirmApproval( ownerBillingGracePeriodEnd, ownerLogin, full, - onApproved: startApprovedAnimation, + onApproved: shouldAnimateApproval ? startApprovedAnimation : undefined, delegateEmail, delegateAccountID, isTrackIntentUser, diff --git a/src/components/ParentNavigationSubtitle.tsx b/src/components/ParentNavigationSubtitle.tsx index 6e451b426469..5ca1147d4c20 100644 --- a/src/components/ParentNavigationSubtitle.tsx +++ b/src/components/ParentNavigationSubtitle.tsx @@ -138,7 +138,7 @@ function ParentNavigationSubtitle({ currentFullScreenRoute?.name === NAVIGATORS.SEARCH_FULLSCREEN_NAVIGATOR); // Bills have no parent chat, so their subtitle shows only the policy name. - const shouldShowPolicyNameOnly = reportType === CONST.REPORT.UNSUPPORTED_TYPE.BILL && !reportName && !!workspaceName; + const shouldShowPolicyNameOnly = reportType === CONST.REPORT.TYPE.BILL && !reportName && !!workspaceName; // We should not display the parent navigation subtitle if the user does not have access to the parent chat (the reportName is empty in this case) if (!reportName && !shouldShowPolicyNameOnly) { diff --git a/src/hooks/useLifecycleActions.tsx b/src/hooks/useLifecycleActions.tsx index 798c89a96736..bd562757bb90 100644 --- a/src/hooks/useLifecycleActions.tsx +++ b/src/hooks/useLifecycleActions.tsx @@ -6,6 +6,7 @@ import {useOpenReportSubmitToPopover} from '@components/ReportSubmitToPopoverAnc import {useSearchQueryContext, useSearchResultsContext, useSearchSelectionActions, useSearchSelectionContext} from '@components/Search/SearchContext'; import Text from '@components/Text'; +import {isBillReport} from '@libs/BillUtils'; import getNonEmptyStringOnyxID from '@libs/getNonEmptyStringOnyxID'; import {getValidConnectedIntegration, isSubmitPolicy} from '@libs/PolicyUtils'; import {getFilteredReportActionsForReportView} from '@libs/ReportActionsUtils'; @@ -200,7 +201,10 @@ function useLifecycleActions({reportID, startApprovedAnimation, startAnimation, showDelegateNoAccessModal(); return; } - if (!skipAnimation && !isSubmitPolicy(policy)) { + + // Bills don't show Pay, so nothing would end the approved animation on a bill. + const shouldAnimateApproval = !skipAnimation && !isBillReport(moneyRequestReport); + if (shouldAnimateApproval && !isSubmitPolicy(policy)) { startApprovedAnimation(); } approveMoneyRequest({ @@ -218,7 +222,7 @@ function useLifecycleActions({reportID, startApprovedAnimation, startAnimation, ownerLogin: submitterLogin, amountOwed, onApproved: () => { - if (skipAnimation) { + if (!shouldAnimateApproval) { return; } startApprovedAnimation(); diff --git a/src/hooks/useSearchBulkActions.ts b/src/hooks/useSearchBulkActions.ts index 9b1ebd081c37..c574d74131bf 100644 --- a/src/hooks/useSearchBulkActions.ts +++ b/src/hooks/useSearchBulkActions.ts @@ -46,6 +46,7 @@ import { } from '@libs/actions/Search'; import initSplitExpense from '@libs/actions/SplitExpenses'; import {setNameValuePair} from '@libs/actions/User'; +import {isBillReport} from '@libs/BillUtils'; import {canResolveTransactionCard} from '@libs/CardUtils'; import {getConnectionCompanyID} from '@libs/CopyPolicySettingsUtils'; import deferModalPresentationAfterPopoverDismiss from '@libs/deferModalPresentationAfterPopoverDismiss'; @@ -570,7 +571,8 @@ function shouldShowBulkDuplicateOption({ const reportID = selectedTransactions[id]?.reportID; const submitterReport = reportID ? getReportOrDraftReport({reportID, searchReports, report: allReports?.[`${ONYXKEYS.COLLECTION.REPORT}${reportID}`]}) : undefined; - if (submitterReport && !isCurrentUserSubmitter(submitterReport)) { + // Copying an expense from a bill would turn the vendor's expense into the owner's own expense. + if (submitterReport && (isBillReport(submitterReport) || !isCurrentUserSubmitter(submitterReport))) { return false; } diff --git a/src/libs/BillPayReportActionUtils.ts b/src/libs/BillPayReportActionUtils.ts index ffc5e08e3869..a02c45d35240 100644 --- a/src/libs/BillPayReportActionUtils.ts +++ b/src/libs/BillPayReportActionUtils.ts @@ -4,8 +4,10 @@ import type {Report, ReportAction} from '@src/types/onyx'; import type {OnyxEntry} from 'react-native-onyx'; +import {isBillReport} from './BillUtils'; + function isBillPayReport(report: OnyxEntry, isInvoiceLinkedToBill: boolean): boolean { - return report?.type === CONST.REPORT.UNSUPPORTED_TYPE.BILL || (report?.type === CONST.REPORT.TYPE.INVOICE && isInvoiceLinkedToBill); + return isBillReport(report) || (report?.type === CONST.REPORT.TYPE.INVOICE && isInvoiceLinkedToBill); } function isBillPayHistoryAction(action: OnyxEntry, report: OnyxEntry, isInvoiceLinkedToBill: boolean): boolean { diff --git a/src/libs/BillUtils.ts b/src/libs/BillUtils.ts index 90aeac96b3c5..543f2e2c331b 100644 --- a/src/libs/BillUtils.ts +++ b/src/libs/BillUtils.ts @@ -3,12 +3,12 @@ import type {OnyxInputOrEntry, Report} from '@src/types/onyx'; /** Bills are the reports that receivers approve and pay for a vendor's invoice. */ function isBillReport(report: OnyxInputOrEntry): boolean { - return report?.type === CONST.REPORT.UNSUPPORTED_TYPE.BILL; + return report?.type === CONST.REPORT.TYPE.BILL; } /** Bills stay hidden from users without the newDotBillPay beta. */ function shouldHideBillReport(reportType: string | undefined, isBillPayBetaEnabled: boolean): boolean { - return reportType === CONST.REPORT.UNSUPPORTED_TYPE.BILL && !isBillPayBetaEnabled; + return reportType === CONST.REPORT.TYPE.BILL && !isBillPayBetaEnabled; } export {isBillReport, shouldHideBillReport}; diff --git a/src/libs/DebugUtils.ts b/src/libs/DebugUtils.ts index 2d4f991452fe..d0e013f9e386 100644 --- a/src/libs/DebugUtils.ts +++ b/src/libs/DebugUtils.ts @@ -489,6 +489,7 @@ function validateReportDraftProperty(key: keyof Report | keyof ReportNameValuePa case 'withdrawalIDs': return validateString(value); case 'hasOutstandingChildRequest': + case 'isHiddenForBillReceiver': case 'hasOutstandingChildTask': case 'isOwnPolicyExpenseChat': case 'isPinned': @@ -646,6 +647,7 @@ function validateReportDraftProperty(key: keyof Report | keyof ReportNameValuePa avatarUrl: CONST.RED_BRICK_ROAD_PENDING_ACTION, chatType: CONST.RED_BRICK_ROAD_PENDING_ACTION, hasOutstandingChildRequest: CONST.RED_BRICK_ROAD_PENDING_ACTION, + isHiddenForBillReceiver: CONST.RED_BRICK_ROAD_PENDING_ACTION, hasOutstandingChildTask: CONST.RED_BRICK_ROAD_PENDING_ACTION, isOwnPolicyExpenseChat: CONST.RED_BRICK_ROAD_PENDING_ACTION, isPinned: CONST.RED_BRICK_ROAD_PENDING_ACTION, diff --git a/src/libs/Formula.ts b/src/libs/Formula.ts index 0afa25bc56c3..2bda32f72618 100644 --- a/src/libs/Formula.ts +++ b/src/libs/Formula.ts @@ -675,7 +675,7 @@ function formatType(type: string | undefined): string { [CONST.REPORT.TYPE.EXPENSE]: 'Expense Report', [CONST.REPORT.TYPE.INVOICE]: 'Invoice', [CONST.REPORT.TYPE.CHAT]: 'Chat', - [CONST.REPORT.UNSUPPORTED_TYPE.BILL]: 'Bill', + [CONST.REPORT.TYPE.BILL]: 'Bill', [CONST.REPORT.UNSUPPORTED_TYPE.PAYCHECK]: 'Paycheck', [CONST.REPORT.TYPE.IOU]: 'IOU', [CONST.REPORT.TYPE.TASK]: 'Task', diff --git a/src/libs/NextStepUtils.ts b/src/libs/NextStepUtils.ts index bbcdfac0c6c0..82a3033b49b3 100644 --- a/src/libs/NextStepUtils.ts +++ b/src/libs/NextStepUtils.ts @@ -171,7 +171,7 @@ function buildNextStepMessage( const requiredDepositCurrency = nextStep.requiredDepositCurrency ? Str.htmlEncode(nextStep.requiredDepositCurrency) : undefined; // Auth sends the same approve and pay next steps for bills and expense reports, so the report type picks the wording. - const isBill = reportType === CONST.REPORT.UNSUPPORTED_TYPE.BILL; + const isBill = reportType === CONST.REPORT.TYPE.BILL; let message: string; if (nextStep.messageKey === CONST.NEXT_STEP.MESSAGE_KEY.WAITING_FOR_SUBMITTER_ACCOUNT) { message = translate('nextStep.message.waitingForSubmitterAccount', actor, actorType, eta, etaType, requiredDepositCurrency); diff --git a/src/libs/ReportActionsUtils.ts b/src/libs/ReportActionsUtils.ts index de4ac8148070..fa01c2d978bb 100644 --- a/src/libs/ReportActionsUtils.ts +++ b/src/libs/ReportActionsUtils.ts @@ -1717,6 +1717,15 @@ function getVisibleReportActionErrors(reportAction: OnyxEntry): Re return rest; } +/** + * Whether the action previews a vendor invoice that the current user pays through its linked bill. The bill receiver + * must not see that invoice in chats, but can still open it directly. + */ +function isReportPreviewHiddenForBillReceiver(reportAction: OnyxEntry): boolean { + const linkedReportID = getIOUReportIDFromReportActionPreview(reportAction); + return !!linkedReportID && !!getReportOrDraftReport({reportID: linkedReportID})?.isHiddenForBillReceiver; +} + /** * Checks if a reportAction is fit for display, meaning that it's not deprecated, is of a valid * and supported type, it's not deleted and also not closed. @@ -1825,6 +1834,10 @@ function shouldReportActionBeVisible( return false; } + if (isReportPreviewHiddenForBillReceiver(reportAction)) { + return false; + } + if (isDeletedReportPreviewWithError(reportAction)) { return true; } diff --git a/src/libs/ReportNameUtils.ts b/src/libs/ReportNameUtils.ts index 3c7411e62e9b..d481553fdcc3 100644 --- a/src/libs/ReportNameUtils.ts +++ b/src/libs/ReportNameUtils.ts @@ -30,6 +30,7 @@ import {format} from 'date-fns'; import {Str} from 'expensify-common'; import {getAddAgentRuleMessage, getDeleteAgentRuleMessage, getUpdateAgentRuleMessage} from './AgentRuleChangeLogUtils'; +import {isBillReport} from './BillUtils'; import getCollator from './CollatorUtils'; // eslint-disable-next-line import/no-cycle import {getForReportAction, getMovedReportID} from './ModifiedExpenseMessage'; @@ -1293,7 +1294,8 @@ function computeReportName({ return parentReportActionBasedName; } - if (report?.reportName && report.type === CONST.REPORT.TYPE.EXPENSE) { + // A bill keeps its stored name, which Auth sets from the vendor's invoice and the user can rename. + if (report?.reportName && (report.type === CONST.REPORT.TYPE.EXPENSE || isBillReport(report))) { return report?.reportName; } diff --git a/src/libs/ReportPreviewActionUtils.ts b/src/libs/ReportPreviewActionUtils.ts index 768ef73df93c..a08b16827c09 100644 --- a/src/libs/ReportPreviewActionUtils.ts +++ b/src/libs/ReportPreviewActionUtils.ts @@ -6,6 +6,7 @@ import type {ValueOf} from 'type-fest'; import {CONST as COMMON_CONST} from 'expensify-common'; +import {isBillReport} from './BillUtils'; import { arePaymentsEnabled, canAdminPayReport, @@ -142,6 +143,11 @@ function canPay( policy?: Policy, invoiceReceiverPolicy?: Policy, ) { + // Bills can't be paid in NewDot yet. + if (isBillReport(report)) { + return false; + } + const isExpense = isExpenseReport(report); if (isPayBlocked(report, policy, isReportArchived)) { diff --git a/src/libs/ReportPrimaryActionUtils.ts b/src/libs/ReportPrimaryActionUtils.ts index 579c0d7618f0..7355d798e2bc 100644 --- a/src/libs/ReportPrimaryActionUtils.ts +++ b/src/libs/ReportPrimaryActionUtils.ts @@ -7,6 +7,7 @@ import type {ValueOf} from 'type-fest'; import {CONST as COMMON_CONST} from 'expensify-common'; +import {isBillReport} from './BillUtils'; import { arePaymentsEnabled as arePaymentsEnabledUtils, canAdminPayReport, @@ -25,18 +26,10 @@ import { isPreferredExporter, isSubmitAndClose, isSubmitPolicy, - isSubmitterApproveBlockedOnSubmitWorkspace, } from './PolicyUtils'; +import {getAllReportActions, getOneTransactionThreadReportID, getOriginalMessage, getReportAction, hasPendingDEWSubmit, isMoneyRequestAction} from './ReportActionsUtils'; import { - getAllReportActions, - getOneTransactionThreadReportID, - getOriginalMessage, - getReportAction, - hasPendingDEWApprove, - hasPendingDEWSubmit, - isMoneyRequestAction, -} from './ReportActionsUtils'; -import { + canApproveExpenseReport, canHoldUnholdReportAction, getMoneyRequestSpendBreakdown, getParentReport, @@ -68,8 +61,6 @@ import { hasPendingRTERViolation as hasPendingRTERViolationTransactionUtils, isDuplicate, isOnHold as isOnHoldTransactionUtils, - isPending, - isScanning, isTransactionSubmittable, shouldShowBrokenConnectionViolationForMultipleTransactions, shouldShowBrokenConnectionViolation as shouldShowBrokenConnectionViolationTransactionUtils, @@ -180,38 +171,7 @@ function isSubmitAction( } function isApproveAction(report: Report, reportTransactions: Transaction[], currentUserAccountID: number, reportMetadata: OnyxEntry, policy?: Policy) { - // Cheap report-level checks first so the transaction scans below only run for reports the user can approve - const managerID = report?.managerID ?? CONST.DEFAULT_NUMBER_ID; - const isCurrentUserManager = managerID === currentUserAccountID; - if (!isCurrentUserManager || !isExpenseReportUtils(report) || !isProcessingReportUtils(report) || reportTransactions.length === 0) { - return false; - } - - if (isArchivedOrPendingDeletePolicy(policy)) { - return false; - } - - if (isSubmitterApproveBlockedOnSubmitWorkspace(policy, report.ownerAccountID, currentUserAccountID)) { - return false; - } - - const isSubmitWorkspace = isSubmitPolicy(policy); - const isApprovalEnabled = policy?.approvalMode && policy.approvalMode !== CONST.POLICY.APPROVAL_MODE.OPTIONAL; - if (!isApprovalEnabled && !isSubmitWorkspace) { - return false; - } - - const isDEWPolicy = hasDynamicExternalWorkflow(policy); - if (hasPendingDEWApprove(reportMetadata, isDEWPolicy)) { - return false; - } - - const isAnyReceiptBeingScanned = reportTransactions.some((transaction) => isScanning(transaction)); - if (isAnyReceiptBeingScanned) { - return false; - } - - return !reportTransactions.every((transaction) => isPending(transaction)); + return canApproveExpenseReport(report, reportTransactions, currentUserAccountID, reportMetadata, policy); } function isPrimaryPayAction({ @@ -228,6 +188,11 @@ function isPrimaryPayAction({ isSecondaryAction, canNonPayerAdminPay, }: IsPrimaryPayActionParams) { + // Bills can't be paid in NewDot yet. + if (isBillReport(report)) { + return false; + } + const isExpenseReport = isExpenseReportUtils(report); if (isPayBlocked(report, policy, isArchivedReport(reportNameValuePairs) || !!isChatReportArchived)) { @@ -383,6 +348,11 @@ function isReviewDuplicatesAction( policy: Policy | undefined, violations: OnyxCollection, ) { + // Resolving duplicates deletes expenses, and a bill must keep the expenses of the vendor's invoice. + if (isBillReport(report)) { + return false; + } + const hasDuplicates = reportTransactions.some((transaction) => isDuplicate(transaction, currentUserEmail, currentUserAccountID, report, ownerLogin, policy, violations?.[ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS + transaction.transactionID]), ); diff --git a/src/libs/ReportSecondaryActionUtils.ts b/src/libs/ReportSecondaryActionUtils.ts index 665bd76aac4d..19950fa15c2b 100644 --- a/src/libs/ReportSecondaryActionUtils.ts +++ b/src/libs/ReportSecondaryActionUtils.ts @@ -19,6 +19,7 @@ import type { import type {OnyxCollection, OnyxEntry} from 'react-native-onyx'; import type {ValueOf} from 'type-fest'; +import {isBillReport} from './BillUtils'; import {areTransactionsEligibleForMerge} from './MergeTransactionUtils'; import {getLoginByAccountID} from './PersonalDetailsUtils'; import { @@ -165,7 +166,8 @@ function isSplitAction( return true; } - if (!isExpenseReportUtils(report)) { + // A bill must keep the expenses of the vendor's invoice. + if (!isExpenseReportUtils(report) || isBillReport(report)) { return false; } @@ -367,7 +369,8 @@ function isApproveAction( isDuplicate(transaction, currentUserLogin, currentUserAccountID, report, ownerLogin, policy, violations?.[ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS + transaction.transactionID]), ); - if (isExpenseReport && isProcessingReport && reportHasDuplicatedTransactions) { + // Bills can't resolve duplicates, so the primary action is still Approve for a bill with duplicates. + if (isExpenseReport && isProcessingReport && reportHasDuplicatedTransactions && !isBillReport(report)) { return true; } @@ -468,7 +471,8 @@ function isCancelPaymentAction( const isExpenseReport = isExpenseReportUtils(report); const isIOUReport = isIOUReportUtils(report); - if (!isExpenseReport && !isIOUReport) { + // Bills can't be paid or have their payment canceled in NewDot yet, even when they were paid in Classic. + if ((!isExpenseReport && !isIOUReport) || isBillReport(report)) { return false; } @@ -520,7 +524,8 @@ function isCancelPaymentAction( } function isReceivedPaymentAction(report: Report, reportTransactions: Transaction[] = [], reportActions: ReportAction[] = [], policy?: Policy): boolean { - if (!isExpenseReportUtils(report) || !isCurrentUserSubmitter(report)) { + // The bill's owner pays the vendor, so the owner never receives a payment on it. + if (!isExpenseReportUtils(report) || isBillReport(report) || !isCurrentUserSubmitter(report)) { return false; } @@ -797,7 +802,8 @@ function isRetractAction(report: Report, policy?: Policy): boolean { // This should be removed after we change how instant submit works const isInstantSubmit = isInstantSubmitEnabled(policy); - if (!isExpenseReport || isInstantSubmit) { + // A bill arrives submitted from the vendor's invoice, so its owner can't take it back to draft. + if (!isExpenseReport || isInstantSubmit || isBillReport(report)) { return false; } @@ -820,7 +826,9 @@ function isReopenAction(report: Report, policy?: Policy): boolean { } const isExpenseReport = isExpenseReportUtils(report); - if (!isExpenseReport) { + + // A bill arrives submitted from the vendor's invoice, so it can't go back to draft. + if (!isExpenseReport || isBillReport(report)) { return false; } @@ -976,7 +984,8 @@ function isDuplicateReportAction(report: Report): boolean { return false; } - if (!isExpenseReportUtils(report)) { + // Copying a bill would turn the vendor's expenses into the owner's own expenses. + if (!isExpenseReportUtils(report) || isBillReport(report)) { return false; } @@ -989,6 +998,11 @@ function isDuplicateAction(report: Report, reportTransactions: Transaction[]): b return false; } + // Copying an expense from a bill would turn the vendor's expense into the owner's own expense. + if (isBillReport(report)) { + return false; + } + const reportTransaction = reportTransactions.at(0); // We can't duplicate per diem expenses that don't have start & end dates. diff --git a/src/libs/ReportUtils.ts b/src/libs/ReportUtils.ts index 4f2f48892500..b69c2b1e3df6 100644 --- a/src/libs/ReportUtils.ts +++ b/src/libs/ReportUtils.ts @@ -1521,11 +1521,11 @@ function isReportIDApproved(reportID: string | undefined) { } /** - * Checks if a report is an Expense report. + * Checks if a report is an Expense report. Bills count as expense reports, so the expense report view opens them. */ function isExpenseReport(reportOrID: OnyxInputOrEntry | string): boolean { const report = typeof reportOrID === 'string' ? (getReport(reportOrID, deprecatedAllReports) ?? null) : reportOrID; - return report?.type === CONST.REPORT.TYPE.EXPENSE; + return report?.type === CONST.REPORT.TYPE.EXPENSE || isBillReport(report); } /** @@ -3241,6 +3241,11 @@ function canAddOrDeleteTransactions(moneyRequestReport: OnyxEntry, rules return false; } + // A bill must keep exactly the expenses of the vendor's invoice. + if (isBillReport(moneyRequestReport)) { + return false; + } + // Adding or deleting transactions is not allowed on a closed report if (moneyRequestReport?.statusNum === CONST.REPORT.STATUS_NUM.CLOSED && !isOpenReport(moneyRequestReport)) { return false; @@ -3279,7 +3284,6 @@ function canAddTransaction( currentUserAccountID?: number, ): boolean { // A bill mirrors the vendor's invoice, so its expenses come only from that invoice. - // isMoneyRequestReport excludes bills today. This check keeps bills blocked once bills count as expense reports. if (isBillReport(moneyRequestReport) || !isMoneyRequestReport(moneyRequestReport)) { return false; } @@ -3372,7 +3376,8 @@ function isMoneyRequestReportEligibleForMerge( ): boolean { const report = typeof reportOrReportID === 'string' ? getReportOrDraftReport({reportID: reportOrReportID}) : reportOrReportID; - if (!isMoneyRequestReport(report) || isIOUReport(report)) { + // Auth can't merge expenses on a bill, because the bill must keep the expenses of the vendor's invoice. + if (!isMoneyRequestReport(report) || isIOUReport(report) || isBillReport(report)) { return false; } @@ -3486,6 +3491,62 @@ function canApproveIOU( return reportTransactions.length > 0 && isCurrentUserManager && !isReportOpen && !isApproved && !iouSettled && !isReportPayAtEnd && !isReportClosed; } +/** + * Whether the report header shows Approve to the current user. The bill green dot uses it too, so the dot never shows + * without the button. + */ +function canApproveExpenseReport( + report: OnyxEntry, + reportTransactions: Transaction[], + currentUserAccountID: number, + reportMetadata: OnyxEntry, + policy: OnyxEntry, +): boolean { + // Cheap report-level checks first so the transaction scans below only run for reports the user can approve + const managerID = report?.managerID ?? CONST.DEFAULT_NUMBER_ID; + const isCurrentUserManager = managerID === currentUserAccountID; + if (!report || !isCurrentUserManager || !isExpenseReport(report) || !isProcessingReport(report) || reportTransactions.length === 0) { + return false; + } + + if (isArchivedOrPendingDeletePolicy(policy)) { + return false; + } + + if (isSubmitterApproveBlockedOnSubmitWorkspace(policy, report.ownerAccountID, currentUserAccountID)) { + return false; + } + + const isSubmitWorkspace = isSubmitPolicy(policy); + const isApprovalEnabled = policy?.approvalMode && policy.approvalMode !== CONST.POLICY.APPROVAL_MODE.OPTIONAL; + if (!isApprovalEnabled && !isSubmitWorkspace) { + return false; + } + + const isDEWPolicy = hasDynamicExternalWorkflow(policy); + if (hasPendingDEWApprove(reportMetadata, isDEWPolicy)) { + return false; + } + + const isAnyReceiptBeingScanned = reportTransactions.some((transaction) => isScanning(transaction)); + if (isAnyReceiptBeingScanned) { + return false; + } + + return !reportTransactions.every((transaction) => isPending(transaction)); +} + +/** Whether the current user can approve the bill now. The header hides Approve when every expense is on hold. */ +function canApproveBill( + report: OnyxEntry, + policy: OnyxEntry, + reportMetadata: OnyxEntry, + currentUserAccountID: number, + reportTransactions: Transaction[], +): boolean { + return isBillReport(report) && canApproveExpenseReport(report, reportTransactions, currentUserAccountID, reportMetadata, policy) && !hasOnlyHeldExpenses(reportTransactions); +} + function canIOUBePaid( iouReport: OnyxInputOrEntry, chatReport: OnyxInputOrEntry, @@ -3500,7 +3561,8 @@ function canIOUBePaid( ) { const iouSettled = isSettled(iouReport); - if (isEmptyObject(iouReport) || iouReport.isWaitingForCancelledReimbursement) { + // Bills can't be paid in NewDot yet. + if (isEmptyObject(iouReport) || iouReport.isWaitingForCancelledReimbursement || isBillReport(iouReport)) { return false; } @@ -3938,6 +4000,11 @@ function canDeleteMoneyRequestReport( cardList: OnyxEntry, isReportLevelDelete = false, ): boolean { + // Auth can't delete a bill, and the bill must keep the expenses of the vendor's invoice. + if (isBillReport(report)) { + return false; + } + const isReportPolicyAdmin = isPolicyAdmin(policy); const transaction = reportTransactions.at(0); const transactionID = transaction?.transactionID; @@ -5386,28 +5453,44 @@ function getReasonAndReportActionThatRequiresAttention({ const invoiceReceiverPolicy = invoiceReceiverPolicyID ? resolvePolicy(invoiceReceiverPolicyID) : undefined; const actionTypeForAssigneeToComplete = getActionTypeForAssigneeToComplete(optionOrReport, parentReportAction); + // A bill holds no report previews, so it skips the scan for them below. + const isBill = isBillReport(optionOrReport); + // Compute IOU candidate upfront so we can compare timestamps with task candidate - const {reportAction: iouReportActionToApproveOrPay, actionBadge} = getIOUReportActionWithBadge({ - chatReport: optionOrReport, - policy, - reportMetadata, - invoiceReceiverPolicy, - currentUserLogin, - currentUserAccountID, - chatReportActions: reportActions, - allViolations: transactionViolations, - // Always false here because of the early return above, but we still pass it so getIOUReportActionWithBadge doesn't read the archived state from the Onyx cache - isChatReportArchived: isReportArchived, - allReports: reports, - allReportActionsParam: allReportActionsParam ?? allReportActions, - reportsTransactions, - }); + const {reportAction: iouReportActionToApproveOrPay, actionBadge} = isBill + ? {reportAction: undefined, actionBadge: undefined} + : getIOUReportActionWithBadge({ + chatReport: optionOrReport, + policy, + reportMetadata, + invoiceReceiverPolicy, + currentUserLogin, + currentUserAccountID, + chatReportActions: reportActions, + allViolations: transactionViolations, + // Always false here because of the early return above, but we still pass it so getIOUReportActionWithBadge doesn't read the archived state from the Onyx cache + isChatReportArchived: isReportArchived, + allReports: reports, + allReportActionsParam: allReportActionsParam ?? allReportActions, + reportsTransactions, + }); // Add only labels a green dot the chat would show anyway, so it must not change whether the dot shows. Run the checks // below as if no candidate was found, exactly like before Add existed. const dotCandidateAction = actionBadge === CONST.REPORT.ACTION_BADGE.ADD ? undefined : iouReportActionToApproveOrPay; + + // A bill has no parent chat, so its own expenses decide whether its approver must act. // Fall back to the chat's outstanding child so the pending-only check still runs when no badge action was found. - const iouReportID = getIOUReportIDFromReportActionPreview(dotCandidateAction) ?? optionOrReport.iouReportID; + const iouReportID = isBill ? optionOrReport.reportID : (getIOUReportIDFromReportActionPreview(dotCandidateAction) ?? optionOrReport.iouReportID); const transactions = getReportTransactions(iouReportID, reportsTransactions); + + // Bills have no parent chat to show a report preview badge, so the approver's green dot goes on the bill itself. + if (canApproveBill(optionOrReport, policy, reportMetadata, currentUserAccountID, transactions)) { + return { + reason: CONST.REQUIRES_ATTENTION_REASONS.IS_WAITING_FOR_ASSIGNEE_TO_COMPLETE_ACTION, + actionBadge: CONST.REPORT.ACTION_BADGE.APPROVE, + }; + } + const hasOnlyPendingTransactions = transactions.length > 0 && transactions.every((t) => isPending(t)); const iouReport = reports ? reports[`${ONYXKEYS.COLLECTION.REPORT}${iouReportID}`] : getReportOrDraftReport({reportID: iouReportID}); @@ -6144,6 +6227,11 @@ function getNextApproverAccountID(report: OnyxEntry, rules: OnyxCollecti } function canEditReportPolicy(report: OnyxEntry, reportPolicy: OnyxEntry): boolean { + // A bill stays on the policy that received the vendor's invoice. + if (isBillReport(report)) { + return false; + } + const isAdmin = isPolicyAdminPolicyUtils(reportPolicy); const isManager = isReportManager(report); const isSubmitter = isReportOwner(report); @@ -6418,6 +6506,11 @@ function canEditFieldOfMoneyRequest({ return canUnreportedBeMoved(transaction, allPolicies); } + // A bill must keep the expenses of the vendor's invoice. + if (isBillReport(moneyRequestReport)) { + return false; + } + const moneyRequestReportNameValuePair = reportNameValuePairs?.[`${ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS}${moneyRequestReport.reportID}`]; if (!isReportOutstanding(moneyRequestReport, moneyRequestReport.policyID, rules, moneyRequestReportNameValuePair)) { return false; @@ -6605,7 +6698,8 @@ function canHoldUnholdReportAction( const canModifyUnholdStatus = !isTrackExpenseMoneyReport && (isAdmin || (isActionOwner && isHoldActionCreator) || isApprover); const canHoldOrUnholdRequest = !isRequestSettled && !isApproved && !isClosed && !isDeletedParentAction(reportAction); - const canHoldRequest = canHoldOrUnholdRequest && !isOnHold && canModifyStatus && !isScanning(transaction) && !isReceiptBeingScanned(transaction); + // Approving part of a report moves its held expenses to a new expense report, which a bill can't do. + const canHoldRequest = canHoldOrUnholdRequest && !isOnHold && canModifyStatus && !isScanning(transaction) && !isReceiptBeingScanned(transaction) && !isBillReport(report); // Holding an actionless expense marks it on hold optimistically before the server returns the new action, and removing the hold needs that action's thread const canUnholdRequest = !isActionlessReportedExpense && !!(canHoldOrUnholdRequest && isOnHold && (isRequestIOU ? isHoldActionCreator : canModifyUnholdStatus)); @@ -10976,9 +11070,9 @@ function canAccessReport(report: OnyxEntry, isDefaultRoomsBetaEnabled: b return true; } -/** NewDot can't show unsupported report types. Bills are the exception for users with the newDotBillPay beta. */ +/** NewDot can't show unsupported report types. Bills count as unsupported for users without the newDotBillPay beta. */ function isUnsupportedReportType(reportType: string | undefined, isBillPayBetaEnabled: boolean): boolean { - if (reportType === CONST.REPORT.UNSUPPORTED_TYPE.BILL) { + if (reportType === CONST.REPORT.TYPE.BILL) { return shouldHideBillReport(reportType, isBillPayBetaEnabled); } return (Object.values(CONST.REPORT.UNSUPPORTED_TYPE) as string[]).includes(reportType ?? ''); @@ -11508,6 +11602,10 @@ function reasonForReportToBeInOptionList({ derivedIsEmptyReport, hasGuidesEmails, }: ShouldReportBeInOptionListParams): ValueOf | null { + if (report?.isHiddenForBillReceiver) { + return null; + } + const isInDefaultMode = !isInFocusMode; // Include the currently viewed report. If we excluded the currently viewed report, then there @@ -13278,7 +13376,8 @@ function canDuplicateExpenseIntoSourceReport({ isASAPSubmitBetaEnabled, rules, }: CanDuplicateExpenseIntoSourceReportParams): boolean { - if (!isExpenseReport(sourceReport) || isSourceReportArchived || !chatReport || isChatReportArchived || !isPolicyAccessible(policy, currentUserLogin)) { + // A bill's expenses come only from the vendor's invoice. + if (!isExpenseReport(sourceReport) || isBillReport(sourceReport) || isSourceReportArchived || !chatReport || isChatReportArchived || !isPolicyAccessible(policy, currentUserLogin)) { return false; } @@ -13468,7 +13567,6 @@ function isReportOutstanding( isEmptyObject(iouReport) || !isExpenseReport(iouReport) || // A bill's expenses come only from the vendor's invoice, so users can't add or move expenses to it. - // isExpenseReport excludes bills today. This check keeps bills blocked once bills count as expense reports. isBillReport(iouReport) || iouReport?.stateNum === undefined || iouReport?.statusNum === undefined || @@ -13480,6 +13578,7 @@ function isReportOutstanding( if (isArchivedReport(reportNameValuePair)) { return false; } + const currentRoute = navigationRef.getCurrentRoute(); const params = currentRoute?.params as MoneyRequestNavigatorParamList[typeof SCREENS.MONEY_REQUEST.STEP_CONFIRMATION] | ReportsSplitNavigatorParamList[typeof SCREENS.REPORT]; const activeReport = deprecatedAllReports?.[`${ONYXKEYS.COLLECTION.REPORT}${params?.reportID}`]; @@ -15018,6 +15117,11 @@ function canRejectReportAction(report: Report, currentUserAccountID: number | un return false; // Disable invoice } + // Auth's RejectExpenseReport doesn't support bills yet, so the approver sends a bill back with Unapprove instead. + if (isBillReport(report)) { + return false; + } + if (isReportBeingProcessed) { return true; // non-IOU reports can be rejected while processing } @@ -15836,6 +15940,8 @@ export { canDeleteTransaction, canBeAutoReimbursed, canApproveIOU, + canApproveBill, + canApproveExpenseReport, canIOUBePaid, canSubmitReport, canCreateRequest, diff --git a/src/libs/SearchUIUtils.ts b/src/libs/SearchUIUtils.ts index fdda01c8763a..0413ee694721 100644 --- a/src/libs/SearchUIUtils.ts +++ b/src/libs/SearchUIUtils.ts @@ -116,6 +116,7 @@ import {startMoneyRequest} from './actions/IOU/MoneyRequest'; import {createTransactionThreadReport} from './actions/Report'; import {getReportActionsFromSearchSnapshot, setOptimisticDataForTransactionThreadPreview} from './actions/Search'; import {convertAttendeesToArray} from './AttendeeUtils'; +import {isBillReport} from './BillUtils'; import {getCardFeedsForDisplay} from './CardFeedUtils'; import {getCardDescriptionForSearchTable, getFeedNameForDisplay, isPersonalCard} from './CardUtils'; import {getCategoryGLCode, getDecodedCategoryName} from './CategoryUtils'; @@ -3926,7 +3927,7 @@ function omitBillReportActionRows(rows: ReportActionListItemType[], data: OnyxTy } const report = data[`${ONYXKEYS.COLLECTION.REPORT}${reportID}`]; - return report?.reportID === reportID && report.type === CONST.REPORT.UNSUPPORTED_TYPE.BILL; + return report?.reportID === reportID && isBillReport(report); }; return rows.filter((row) => !isBill(row.reportID) && !isBill(getIOUReportIDFromReportActionPreview(row))); diff --git a/src/libs/actions/IOU/MoneyRequestBuilder.ts b/src/libs/actions/IOU/MoneyRequestBuilder.ts index 010c3340c614..9b00ccf36d2c 100644 --- a/src/libs/actions/IOU/MoneyRequestBuilder.ts +++ b/src/libs/actions/IOU/MoneyRequestBuilder.ts @@ -3,6 +3,7 @@ import type {LocaleContextProps} from '@components/LocaleContextProvider'; import type {CurrencyListActionsContextType} from '@hooks/useCurrencyList'; import type {WriteReadyBarrier} from '@libs/API'; +import {isBillReport} from '@libs/BillUtils'; import DateUtils from '@libs/DateUtils'; import {getMicroSecondOnyxErrorObject, getMicroSecondOnyxErrorWithTranslationKey} from '@libs/ErrorUtils'; import {isLocalFile} from '@libs/fileDownload/FileUtils'; @@ -1281,6 +1282,11 @@ function maybeUpdateReportNameForFormulaTitle( getCurrencyDecimals: CurrencyListActionsContextType['getCurrencyDecimals'], optimisticTransactions: Record = {}, ): OnyxTypes.Report { + // A bill keeps its stored name, which Auth sets from the vendor's invoice and the user can rename. + if (isBillReport(iouReport)) { + return iouReport; + } + const allReportNameValuePairs = getAllReportNameValuePairs(); const reportNameValuePairs = allReportNameValuePairs?.[`${ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS}${iouReport.reportID}`]; const titleField = reportNameValuePairs?.expensify_text_title; diff --git a/src/libs/actions/OnyxDerived/configs/visibleReportActions.ts b/src/libs/actions/OnyxDerived/configs/visibleReportActions.ts index 9d6173058431..215240c7ac42 100644 --- a/src/libs/actions/OnyxDerived/configs/visibleReportActions.ts +++ b/src/libs/actions/OnyxDerived/configs/visibleReportActions.ts @@ -1,19 +1,41 @@ -import {isActionableWhisperRequiringWritePermission, isActionOfType, isConciergeCategoryOptions, shouldReportActionBeVisible} from '@libs/ReportActionsUtils'; +import { + getIOUReportIDFromReportActionPreview, + isActionableWhisperRequiringWritePermission, + isActionOfType, + isConciergeCategoryOptions, + shouldReportActionBeVisible, +} from '@libs/ReportActionsUtils'; import {isSupportTicket} from '@libs/ReportUtils'; import createOnyxDerivedValueConfig from '@userActions/OnyxDerived/createOnyxDerivedValueConfig'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; -import type {ReportAction, ReportActions} from '@src/types/onyx'; +import type {Report, ReportAction, ReportActions} from '@src/types/onyx'; import type {VisibleReportActionsDerivedValue} from '@src/types/onyx/DerivedValues'; +import type {OnyxCollection} from 'react-native-onyx'; + /** * Returns true if the action's visibility depends on runtime context that can't be cached, - * such as write permissions, policy settings, or sibling actions. + * such as write permissions, policy settings, sibling actions, or the report it links to. + */ +function shouldSkipCachingAction(action: ReportAction, allReports: OnyxCollection): boolean { + return ( + isActionableWhisperRequiringWritePermission(action) || + isConciergeCategoryOptions(action) || + isActionOfType(action, CONST.REPORT.ACTIONS.TYPE.MARKED_REIMBURSED) || + isInvoicePreview(action, allReports) + ); +} + +/** + * An invoice preview is hidden from the bill receiver by the invoice's isHiddenForBillReceiver flag. The flag can change + * without the preview changing, so the preview's visibility is checked when it is shown instead. */ -function shouldSkipCachingAction(action: ReportAction): boolean { - return isActionableWhisperRequiringWritePermission(action) || isConciergeCategoryOptions(action) || isActionOfType(action, CONST.REPORT.ACTIONS.TYPE.MARKED_REIMBURSED); +function isInvoicePreview(action: ReportAction, allReports: OnyxCollection): boolean { + const linkedReportID = getIOUReportIDFromReportActionPreview(action); + return !!linkedReportID && allReports?.[`${ONYXKEYS.COLLECTION.REPORT}${linkedReportID}`]?.type === CONST.REPORT.TYPE.INVOICE; } /** @@ -26,6 +48,7 @@ function computeReportVisibility( currentUserAccountID: number | undefined, isSupportTicketReport: boolean, isReplacedSupportTicket: boolean, + allReports: OnyxCollection, ): Record { const reportVisibility: Record = {}; @@ -38,7 +61,7 @@ function computeReportVisibility( if (actionID !== action.reportActionID) { continue; } - if (shouldSkipCachingAction(action)) { + if (shouldSkipCachingAction(action, allReports)) { continue; } // A replacement ticket has its own active survey, so the original ticket's survey is stale. @@ -98,7 +121,7 @@ export default createOnyxDerivedValueConfig({ const report = allReports?.[`${ONYXKEYS.COLLECTION.REPORT}${reportID}`]; const isSupportTicketReport = isSupportTicket(report); const isReplacedSupportTicket = isSupportTicketReport && !!allReportNameValuePairs?.[`${ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS}${reportID}`]?.reopenedAsReportID; - result[reportID] = computeReportVisibility(reportActions, currentUserAccountID, isSupportTicketReport, isReplacedSupportTicket); + result[reportID] = computeReportVisibility(reportActions, currentUserAccountID, isSupportTicketReport, isReplacedSupportTicket, allReports); } return result; diff --git a/src/selectors/Report.ts b/src/selectors/Report.ts index 3e0575fea9af..83fcafc92300 100644 --- a/src/selectors/Report.ts +++ b/src/selectors/Report.ts @@ -364,6 +364,7 @@ function getStableReportSelector(report: OnyxEntry) { type: report.type, visibility: report.visibility, invoiceReceiver: report.invoiceReceiver, + isHiddenForBillReceiver: report.isHiddenForBillReceiver, transactionCount: report.transactionCount, parentReportID: report.parentReportID, parentReportActionID: report.parentReportActionID, diff --git a/src/types/onyx/Report.ts b/src/types/onyx/Report.ts index 87df9c892a44..422c6bf393bb 100644 --- a/src/types/onyx/Report.ts +++ b/src/types/onyx/Report.ts @@ -188,6 +188,9 @@ type Report = OnyxCommon.OnyxValueWithOfflineFeedback< /** Invoice room receiver data */ invoiceReceiver?: InvoiceReceiver; + /** Whether the receiver must not see this invoice, because they pay it through its linked bill */ + isHiddenForBillReceiver?: boolean; + /** Number of transactions in the report */ transactionCount?: number; diff --git a/src/types/utils/whitelistedReportKeys.ts b/src/types/utils/whitelistedReportKeys.ts index b03f41689721..d60b0ff327d1 100644 --- a/src/types/utils/whitelistedReportKeys.ts +++ b/src/types/utils/whitelistedReportKeys.ts @@ -46,6 +46,7 @@ type WhitelistedReport = OnyxCommon.OnyxValueWithOfflineFeedback< withdrawalIDs: unknown; visibility: unknown; invoiceReceiver: unknown; + isHiddenForBillReceiver: unknown; parentReportID: unknown; parentReportActionID: unknown; managerID: unknown; diff --git a/tests/ui/ParentNavigationSubtitleTest.tsx b/tests/ui/ParentNavigationSubtitleTest.tsx index b1472c74cd74..2cfdd9a3f313 100644 --- a/tests/ui/ParentNavigationSubtitleTest.tsx +++ b/tests/ui/ParentNavigationSubtitleTest.tsx @@ -444,7 +444,7 @@ describe('ParentNavigationSubtitle', () => { it('shows the status and policy name without a parent link or connecting words', async () => { // Given a bill has no parent chat to open. - await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${billReportID}`, createMock({reportID: billReportID, type: CONST.REPORT.UNSUPPORTED_TYPE.BILL})); + await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${billReportID}`, createMock({reportID: billReportID, type: CONST.REPORT.TYPE.BILL})); // When the subtitle renders with only the policy name. render( diff --git a/tests/ui/ReportActionItemTest.tsx b/tests/ui/ReportActionItemTest.tsx index 832ce3660948..d8a589070900 100644 --- a/tests/ui/ReportActionItemTest.tsx +++ b/tests/ui/ReportActionItemTest.tsx @@ -187,7 +187,7 @@ describe('ReportActionItem', () => { const senderAccountID = 321; const bill: Report = { reportID: '9876', - type: CONST.REPORT.UNSUPPORTED_TYPE.BILL, + type: CONST.REPORT.TYPE.BILL, ownerAccountID: ACTOR_ACCOUNT_ID, managerID: 789, billSenderAccountID: senderAccountID, @@ -272,8 +272,8 @@ describe('ReportActionItem', () => { }); it.each([ - [CONST.REPORT.UNSUPPORTED_TYPE.BILL, CONST.REPORT.ACTIONS.TYPE.CREATED, 'created this bill on behalf of sender1@sender.com'], - [CONST.REPORT.UNSUPPORTED_TYPE.BILL, CONST.REPORT.ACTIONS.TYPE.SUBMITTED, 'sent this bill to receiver@receiver.com'], + [CONST.REPORT.TYPE.BILL, CONST.REPORT.ACTIONS.TYPE.CREATED, 'created this bill on behalf of sender1@sender.com'], + [CONST.REPORT.TYPE.BILL, CONST.REPORT.ACTIONS.TYPE.SUBMITTED, 'sent this bill to receiver@receiver.com'], [CONST.REPORT.TYPE.INVOICE, CONST.REPORT.ACTIONS.TYPE.CREATED, 'created this invoice on behalf of sender1@sender.com'], [CONST.REPORT.TYPE.INVOICE, CONST.REPORT.ACTIONS.TYPE.SUBMITTED, 'sent this invoice to receiver@receiver.com'], ] as const)('uses the submission emails when personal details omit names for %s %s', async (type, actionName, message) => { diff --git a/tests/ui/SearchMoneyRequestReportPageTest.tsx b/tests/ui/SearchMoneyRequestReportPageTest.tsx index 9d650322d807..ae5301dcf9b4 100644 --- a/tests/ui/SearchMoneyRequestReportPageTest.tsx +++ b/tests/ui/SearchMoneyRequestReportPageTest.tsx @@ -428,7 +428,7 @@ describe('SearchMoneyRequestReportPage bill access', () => { // When the page renders the bill renderPage({ allReportTransactions: {[transaction.transactionID]: transaction}, - report: {...mockReport, type: CONST.REPORT.UNSUPPORTED_TYPE.BILL}, + report: {...mockReport, type: CONST.REPORT.TYPE.BILL}, }); await waitForBatchedUpdatesWithAct(); diff --git a/tests/ui/components/MoneyReportHeaderNextStepTest.tsx b/tests/ui/components/MoneyReportHeaderNextStepTest.tsx index ef621594fd46..b63977f68dfd 100644 --- a/tests/ui/components/MoneyReportHeaderNextStepTest.tsx +++ b/tests/ui/components/MoneyReportHeaderNextStepTest.tsx @@ -50,7 +50,7 @@ describe('MoneyReportHeaderNextStep', () => { it.each([ { messageKey: CONST.NEXT_STEP.MESSAGE_KEY.WAITING_TO_APPROVE, - reportType: CONST.REPORT.UNSUPPORTED_TYPE.BILL, + reportType: CONST.REPORT.TYPE.BILL, target: 'approve the bill', }, { @@ -60,7 +60,7 @@ describe('MoneyReportHeaderNextStep', () => { }, { messageKey: CONST.NEXT_STEP.MESSAGE_KEY.WAITING_TO_PAY, - reportType: CONST.REPORT.UNSUPPORTED_TYPE.BILL, + reportType: CONST.REPORT.TYPE.BILL, target: 'pay this bill', }, { diff --git a/tests/unit/BillPayAttentionTest.ts b/tests/unit/BillPayAttentionTest.ts new file mode 100644 index 000000000000..25f6007d667e --- /dev/null +++ b/tests/unit/BillPayAttentionTest.ts @@ -0,0 +1,127 @@ +import {getReportPrimaryAction} from '@libs/ReportPrimaryActionUtils'; +import {getReasonAndReportActionThatRequiresAttention} from '@libs/ReportUtils'; + +import CONST from '@src/CONST'; +import ONYXKEYS from '@src/ONYXKEYS'; +import type {Policy, Report, Transaction} from '@src/types/onyx'; + +import Onyx from 'react-native-onyx'; + +import createMock from '../utils/createMock'; +import waitForBatchedUpdates from '../utils/waitForBatchedUpdates'; + +const approverAccountID = 173; +const approverEmail = 'approver@receiver.com'; +const policy: Policy = createMock({ + id: 'billPolicy', + name: 'Bills', + type: CONST.POLICY.TYPE.CORPORATE, + role: CONST.POLICY.ROLE.USER, + owner: 'owner@receiver.com', + approvalMode: CONST.POLICY.APPROVAL_MODE.BASIC, + outputCurrency: CONST.CURRENCY.USD, +}); +const submittedBill = createMock({ + reportID: '9001', + type: CONST.REPORT.TYPE.BILL, + policyID: policy.id, + ownerAccountID: 172, + managerID: approverAccountID, + stateNum: CONST.REPORT.STATE_NUM.SUBMITTED, + statusNum: CONST.REPORT.STATUS_NUM.SUBMITTED, + total: -1250, + currency: CONST.CURRENCY.USD, +}); +const billTransaction = createMock({ + transactionID: '9002', + reportID: submittedBill.reportID, + amount: -1250, + currency: CONST.CURRENCY.USD, + merchant: 'Vendor', + created: '2026-11-01', +}); + +function getBadge(report: Report, accountID: number, email: string, reportPolicy: Policy = policy) { + return getReasonAndReportActionThatRequiresAttention({ + optionOrReport: report, + currentUserLogin: email, + currentUserAccountID: accountID, + transactionViolations: undefined, + reportMetadata: undefined, + policies: {[`${ONYXKEYS.COLLECTION.POLICY}${reportPolicy.id}`]: reportPolicy}, + allReportActions: {[`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${report.reportID}`]: {}}, + }); +} + +function getPrimaryAction(report: Report, reportPolicy: Policy, transaction: Transaction) { + return getReportPrimaryAction({ + report, + currentUserAccountID: approverAccountID, + currentUserLogin: approverEmail, + policy: reportPolicy, + ownerLogin: 'bob@receiver.com', + reportTransactions: [transaction], + violations: {}, + bankAccountList: {}, + chatReport: undefined, + isChatReportArchived: false, + rules: undefined, + }); +} + +describe('Bill Pay green dot', () => { + beforeAll(() => { + Onyx.init({keys: ONYXKEYS}); + return waitForBatchedUpdates(); + }); + + beforeEach(async () => { + await Onyx.clear(); + await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION}${billTransaction.transactionID}`, billTransaction); + await waitForBatchedUpdates(); + }); + + it('shows Approve on a submitted bill for its approver', () => { + // Given a submitted bill, which has no parent chat to carry a report preview badge + // When the Inbox checks whether the bill needs the approver's attention + // Then the approver sees the Approve green dot on the bill itself + expect(getBadge(submittedBill, approverAccountID, approverEmail)).toEqual({ + reason: CONST.REQUIRES_ATTENTION_REASONS.IS_WAITING_FOR_ASSIGNEE_TO_COMPLETE_ACTION, + actionBadge: CONST.REPORT.ACTION_BADGE.APPROVE, + }); + }); + + it('shows no Approve dot to other users or after approval', () => { + // Given the same submitted bill + // When another user checks it, or the approver checks it after approving it + // Then neither sees the Approve green dot, because only the approver of a submitted bill must act + expect(getBadge(submittedBill, 172, 'bob@receiver.com')?.actionBadge).toBeUndefined(); + expect(getBadge({...submittedBill, stateNum: CONST.REPORT.STATE_NUM.APPROVED, statusNum: CONST.REPORT.STATUS_NUM.APPROVED}, approverAccountID, approverEmail)?.actionBadge).not.toBe( + CONST.REPORT.ACTION_BADGE.APPROVE, + ); + }); + + it.each([ + ['approvals are on', policy, billTransaction, true], + ['approvals are off', {...policy, approvalMode: CONST.POLICY.APPROVAL_MODE.OPTIONAL}, billTransaction, false], + [ + 'a receipt is scanning', + policy, + {...billTransaction, amount: 0, merchant: CONST.TRANSACTION.PARTIAL_TRANSACTION_MERCHANT, receipt: {state: CONST.IOU.RECEIPT_STATE.SCANNING, source: 'receipt.jpg'}}, + false, + ], + ['every expense is on hold', policy, {...billTransaction, comment: {hold: '1'}}, false], + ] as const)('shows the Approve dot only when the header shows Approve, when %s', async (_, reportPolicy, transaction, shouldShowApprove) => { + // Given a submitted bill whose policy and expense decide whether the approver can approve it now + await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION}${transaction.transactionID}`, transaction); + await waitForBatchedUpdates(); + + // When the Inbox computes the bill's green dot and the report header computes its primary action + const badge = getBadge(submittedBill, approverAccountID, approverEmail, reportPolicy)?.actionBadge; + const primaryAction = getPrimaryAction(submittedBill, reportPolicy, transaction); + + // Then both agree, so the approver never gets a green dot for a bill they can't approve + expect(badge === CONST.REPORT.ACTION_BADGE.APPROVE).toBe(shouldShowApprove); + expect(primaryAction === CONST.REPORT.PRIMARY_ACTIONS.APPROVE).toBe(shouldShowApprove); + }); +}); diff --git a/tests/unit/BillPayTest.ts b/tests/unit/BillPayTest.ts new file mode 100644 index 000000000000..612f41a57d24 --- /dev/null +++ b/tests/unit/BillPayTest.ts @@ -0,0 +1,351 @@ +import {maybeUpdateReportNameForFormulaTitle} from '@libs/actions/IOU/MoneyRequestBuilder'; +import {isBillReport} from '@libs/BillUtils'; +import {navigationRef} from '@libs/Navigation/Navigation'; +import getReportPreviewAction from '@libs/ReportPreviewActionUtils'; +import {getReportPrimaryAction} from '@libs/ReportPrimaryActionUtils'; +import {getSecondaryReportActions, getSecondaryTransactionThreadActions} from '@libs/ReportSecondaryActionUtils'; +import { + canAddTransaction, + canApproveBill, + canDeleteMoneyRequestReport, + canDeleteTransaction, + canEditFieldOfMoneyRequest, + canHoldUnholdReportAction, + canIOUBePaid, + canRejectReportAction, + isExpenseReport, + isReportOutstanding, +} from '@libs/ReportUtils'; + +import CONST from '@src/CONST'; +import IntlStore from '@src/languages/IntlStore'; +import ONYXKEYS from '@src/ONYXKEYS'; +import type {Policy, PolicyReportField, Report, ReportAction, Transaction} from '@src/types/onyx'; + +import Onyx from 'react-native-onyx'; + +import createMock from '../utils/createMock'; +import waitForBatchedUpdates from '../utils/waitForBatchedUpdates'; + +const accountID = 123; +const email = 'payer@example.com'; +const policy: Policy = { + id: 'billPolicy', + name: 'Bills', + type: CONST.POLICY.TYPE.CORPORATE, + role: CONST.POLICY.ROLE.ADMIN, + owner: email, + ownerAccountID: accountID, + approver: email, + reimburser: email, + reimbursementChoice: CONST.POLICY.REIMBURSEMENT_CHOICES.REIMBURSEMENT_MANUAL, + approvalMode: CONST.POLICY.APPROVAL_MODE.BASIC, + outputCurrency: CONST.CURRENCY.USD, +}; +const bill: Report = { + reportID: '100', + type: CONST.REPORT.TYPE.BILL, + policyID: policy.id, + ownerAccountID: accountID, + managerID: accountID, + total: -125, + currency: CONST.CURRENCY.USD, + stateNum: CONST.REPORT.STATE_NUM.SUBMITTED, + statusNum: CONST.REPORT.STATUS_NUM.SUBMITTED, +}; +const expenseReport: Report = {...bill, reportID: '200', type: CONST.REPORT.TYPE.EXPENSE}; +const approvedBill: Report = {...bill, stateNum: CONST.REPORT.STATE_NUM.APPROVED, statusNum: CONST.REPORT.STATUS_NUM.APPROVED}; +const approvedExpenseReport: Report = {...approvedBill, reportID: expenseReport.reportID, type: CONST.REPORT.TYPE.EXPENSE}; + +function createTransaction(report: Report): Transaction { + return createMock({ + transactionID: `${report.reportID}1`, + reportID: report.reportID, + amount: -125, + currency: CONST.CURRENCY.USD, + merchant: 'Vendor', + created: '2026-11-01', + reimbursable: true, + }); +} + +function createIOUAction(report: Report): ReportAction { + return createMock>({ + reportActionID: `${report.reportID}2`, + reportID: report.reportID, + actionName: CONST.REPORT.ACTIONS.TYPE.IOU, + actorAccountID: accountID, + childReportID: `${report.reportID}3`, + created: '2026-11-01 00:00:00.000', + message: { + IOUTransactionID: `${report.reportID}1`, + IOUReportID: report.reportID, + type: CONST.IOU.REPORT_ACTION_TYPE.CREATE, + amount: 125, + currency: CONST.CURRENCY.USD, + }, + }); +} + +function getPrimaryAction(report: Report) { + return getReportPrimaryAction({ + report, + currentUserAccountID: accountID, + currentUserLogin: email, + policy, + ownerLogin: email, + reportTransactions: [createTransaction(report)], + violations: {}, + bankAccountList: {}, + chatReport: undefined, + isChatReportArchived: false, + rules: undefined, + }); +} + +function getSecondaryActions(report: Report) { + const transaction = createTransaction(report); + return getSecondaryReportActions({ + currentUserLogin: email, + currentUserAccountID: accountID, + submitterLogin: email, + report, + chatReport: undefined, + reportTransactions: [transaction], + originalTransaction: undefined, + violations: {}, + bankAccountList: {}, + policy, + reportActions: [createIOUAction(report)], + policies: {[`${ONYXKEYS.COLLECTION.POLICY}${policy.id}`]: policy}, + rules: undefined, + cardList: undefined, + }); +} + +function getTransactionThreadActions(report: Report) { + const iouAction = createIOUAction(report); + return getSecondaryTransactionThreadActions({ + currentUserLogin: email, + currentUserAccountID: accountID, + parentReport: report, + parentReportOwnerLogin: email, + parentReportActions: {[iouAction.reportActionID]: iouAction}, + reportTransaction: createTransaction(report), + reportAction: iouAction, + originalTransaction: undefined, + policy, + isChatReportArchived: false, + rules: undefined, + cardList: undefined, + }); +} + +describe('Bill Pay', () => { + beforeAll(async () => { + Onyx.init({keys: ONYXKEYS}); + await IntlStore.load(CONST.LOCALES.EN); + + // isReportOutstanding reads the current route, and these tests render no navigation container. + jest.spyOn(navigationRef, 'getCurrentRoute').mockReturnValue(undefined); + }); + + beforeEach(async () => { + await Onyx.clear(); + await Onyx.set(ONYXKEYS.SESSION, {accountID, email}); + await Onyx.set(ONYXKEYS.PERSONAL_DETAILS_LIST, {[accountID]: {accountID, login: email}}); + await Onyx.set(`${ONYXKEYS.COLLECTION.POLICY}${policy.id}`, policy); + await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${bill.reportID}`, bill); + await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${expenseReport.reportID}`, expenseReport); + await waitForBatchedUpdates(); + }); + + it('opens bills in the expense report view', () => { + // Given a bill + // When the app checks its type + // Then it treats the bill as an expense report, so the expense report view opens it + expect(isBillReport(bill)).toBe(true); + expect(isExpenseReport(bill)).toBe(true); + expect(isBillReport(expenseReport)).toBe(false); + }); + + it('lets only the approver approve a submitted bill', () => { + // Given a submitted bill waiting on its approver + // When the approver and another user check whether they can approve it, before and after approval + // Then only the approver can, and only while the bill is submitted + const transactions = [createTransaction(bill)]; + expect(canApproveBill(bill, policy, undefined, accountID, transactions)).toBe(true); + expect(canApproveBill(bill, policy, undefined, 456, transactions)).toBe(false); + expect(canApproveBill(approvedBill, policy, undefined, accountID, transactions)).toBe(false); + expect(canApproveBill(expenseReport, policy, undefined, accountID, transactions)).toBe(false); + }); + + it('shows Approve as the primary action of a submitted bill for its approver', () => { + // Given a submitted bill and the bill's approver + // When the report header resolves its primary action + // Then the approver sees Approve + expect(getPrimaryAction(bill)).toBe(CONST.REPORT.PRIMARY_ACTIONS.APPROVE); + }); + + it('hides Pay on an approved bill', () => { + // Given an approved bill and an approved expense report that the same admin can pay + const transactions = [createTransaction(approvedBill)]; + + // When the header, the report preview and the settlement button check for Pay + // Then only the expense report offers Pay, because bills can't be paid in NewDot yet + expect(getPrimaryAction(approvedExpenseReport)).toBe(CONST.REPORT.PRIMARY_ACTIONS.PAY); + expect(getPrimaryAction(approvedBill)).not.toBe(CONST.REPORT.PRIMARY_ACTIONS.PAY); + expect(canIOUBePaid(approvedExpenseReport, undefined, policy, {}, email, accountID, transactions, false, false)).toBe(true); + expect(canIOUBePaid(approvedBill, undefined, policy, {}, email, accountID, transactions, false, false)).toBe(false); + expect(canIOUBePaid(approvedBill, undefined, policy, {}, email, accountID, transactions, true, false)).toBe(false); + expect( + getReportPreviewAction({ + isReportArchived: false, + currentUserAccountID: accountID, + currentUserLogin: email, + report: approvedBill, + policy, + transactions, + bankAccountList: {}, + reportMetadata: undefined, + ownerLogin: email, + rules: undefined, + }), + ).not.toBe(CONST.REPORT.REPORT_PREVIEW_ACTIONS.PAY); + expect(getSecondaryActions(approvedBill)).not.toContain(CONST.REPORT.SECONDARY_ACTIONS.PAY); + expect(getSecondaryActions(approvedBill)).not.toContain(CONST.REPORT.SECONDARY_ACTIONS.RECEIVED_PAYMENT); + }); + + it('keeps Unapprove on an approved bill', () => { + // Given an approved bill + // When its approver opens the More menu + // Then they can still send it back with Unapprove + expect(getSecondaryActions(approvedBill)).toContain(CONST.REPORT.SECONDARY_ACTIONS.UNAPPROVE); + }); + + it('hides Cancel payment on a bill paid in Classic', () => { + // Given a bill and an expense report that were both marked as paid + const paidBill: Report = {...bill, stateNum: CONST.REPORT.STATE_NUM.APPROVED, statusNum: CONST.REPORT.STATUS_NUM.REIMBURSED}; + const paidExpenseReport: Report = {...paidBill, reportID: expenseReport.reportID, type: CONST.REPORT.TYPE.EXPENSE}; + + // When the payer opens the More menu + // Then only the expense report offers Cancel payment, because bills can't cancel payments in NewDot yet + expect(getSecondaryActions(paidExpenseReport)).toContain(CONST.REPORT.SECONDARY_ACTIONS.CANCEL_PAYMENT); + expect(getSecondaryActions(paidBill)).not.toContain(CONST.REPORT.SECONDARY_ACTIONS.CANCEL_PAYMENT); + }); + + it('hides Reject on a submitted bill', () => { + // Given a submitted bill and an expense report in the same state, both waiting on the current user's approval + // When the approver checks whether they can reject them + // Then only the expense report offers Reject, because Auth's RejectExpenseReport doesn't support bills yet + expect(canRejectReportAction(expenseReport, accountID, policy)).toBe(true); + expect(canRejectReportAction(bill, accountID, policy)).toBe(false); + expect(getSecondaryActions(bill)).not.toContain(CONST.REPORT.SECONDARY_ACTIONS.REJECT); + expect(getTransactionThreadActions(bill)).not.toContain(CONST.REPORT.TRANSACTION_SECONDARY_ACTIONS.REJECT); + }); + + it('blocks deleting a bill and its expenses', () => { + // Given a submitted bill and an expense report in the same state, both owned by the current user + const billTransaction = createTransaction(bill); + const expenseTransaction = createTransaction(expenseReport); + + // When the owner checks whether they can delete the report or its expenses + // Then only the expense report allows it, because a bill must keep the expenses of the vendor's invoice + expect(canDeleteTransaction(expenseReport, undefined)).toBe(true); + expect(canDeleteTransaction(bill, undefined)).toBe(false); + expect(canDeleteMoneyRequestReport(expenseReport, [expenseTransaction], [createIOUAction(expenseReport)], accountID, undefined, email, policy, undefined, true)).toBe(true); + expect(canDeleteMoneyRequestReport(bill, [billTransaction], [createIOUAction(bill)], accountID, undefined, email, policy, undefined, true)).toBe(false); + expect(canDeleteMoneyRequestReport(bill, [billTransaction], [createIOUAction(bill)], accountID, undefined, email, policy, undefined, false)).toBe(false); + expect(getSecondaryActions(bill)).not.toContain(CONST.REPORT.SECONDARY_ACTIONS.DELETE); + expect(getTransactionThreadActions(bill)).not.toContain(CONST.REPORT.TRANSACTION_SECONDARY_ACTIONS.DELETE); + }); + + it('blocks adding expenses to a bill and moving expenses into or out of it', () => { + // Given a submitted bill and an expense report in the same state + const billTransaction = createTransaction(bill); + + // When the owner tries to add an expense, move one out, or pick the report as a destination + // Then the bill allows none of them, because its expenses come only from the vendor's invoice + expect(canAddTransaction(expenseReport, undefined)).toBe(true); + expect(canAddTransaction(bill, undefined)).toBe(false); + expect(isReportOutstanding(expenseReport, policy.id, undefined, undefined)).toBe(true); + expect(isReportOutstanding(bill, policy.id, undefined, undefined)).toBe(false); + expect( + canEditFieldOfMoneyRequest({ + reportAction: createIOUAction(bill), + fieldToEdit: CONST.EDIT_REQUEST_FIELD.REPORT, + transaction: billTransaction, + report: bill, + policy, + reportNameValuePairs: undefined, + rules: undefined, + }), + ).toBe(false); + expect(getSecondaryActions(bill)).not.toContain(CONST.REPORT.SECONDARY_ACTIONS.ADD_EXPENSE); + expect(getSecondaryActions(bill)).not.toContain(CONST.REPORT.SECONDARY_ACTIONS.MOVE_EXPENSE); + expect(getTransactionThreadActions(bill)).not.toContain(CONST.REPORT.TRANSACTION_SECONDARY_ACTIONS.MOVE_EXPENSE); + }); + + it('blocks report actions that change a bill or copy its expenses', () => { + // Given a submitted bill and an expense report in the same state, both owned, approved and administered by the current user + const billTransaction = createTransaction(bill); + const reportActionsToBlock = [ + CONST.REPORT.SECONDARY_ACTIONS.RETRACT, + CONST.REPORT.SECONDARY_ACTIONS.SPLIT, + CONST.REPORT.SECONDARY_ACTIONS.MERGE, + CONST.REPORT.SECONDARY_ACTIONS.DUPLICATE_EXPENSE, + CONST.REPORT.SECONDARY_ACTIONS.DUPLICATE_REPORT, + ]; + const expenseActionsToBlock = [ + CONST.REPORT.TRANSACTION_SECONDARY_ACTIONS.HOLD, + CONST.REPORT.TRANSACTION_SECONDARY_ACTIONS.SPLIT, + CONST.REPORT.TRANSACTION_SECONDARY_ACTIONS.MERGE, + CONST.REPORT.TRANSACTION_SECONDARY_ACTIONS.DUPLICATE, + ]; + + // When they open the More menu on each report and on its expense + const expenseReportActions = getSecondaryActions(expenseReport); + const billActions = getSecondaryActions(bill); + const expenseReportExpenseActions = getTransactionThreadActions(expenseReport); + const billExpenseActions = getTransactionThreadActions(bill); + + // Then only the expense report offers them, because they would take the bill out of submitted or change the expenses of the vendor's invoice + expect(expenseReportActions).toEqual(expect.arrayContaining(reportActionsToBlock)); + expect(expenseReportExpenseActions).toEqual(expect.arrayContaining(expenseActionsToBlock)); + for (const action of [...reportActionsToBlock, CONST.REPORT.SECONDARY_ACTIONS.HOLD, CONST.REPORT.SECONDARY_ACTIONS.CHANGE_WORKSPACE]) { + expect(billActions).not.toContain(action); + } + for (const action of expenseActionsToBlock) { + expect(billExpenseActions).not.toContain(action); + } + expect(canHoldUnholdReportAction(bill, createIOUAction(bill), undefined, billTransaction, policy, accountID, undefined, email).canHoldRequest).toBe(false); + }); + + it('keeps the stored bill name when the policy title is a formula', async () => { + // Given a bill and an expense report whose title fields follow the policy title formula + const formulaPolicy: Policy = { + ...policy, + fieldList: { + // eslint-disable-next-line @typescript-eslint/naming-convention -- text_title is the backend field ID + text_title: createMock({fieldID: 'text_title', name: 'title', type: CONST.REPORT_FIELD_TYPES.FORMULA, defaultValue: '{report:type}', target: 'expense'}), + }, + }; + const formulaTitle = createMock({fieldID: 'text_title', name: 'title', type: CONST.REPORT_FIELD_TYPES.FORMULA, defaultValue: '{report:type}'}); + const namedBill: Report = {...bill, reportName: 'Bill #R00000001upZ'}; + const namedExpenseReport: Report = {...expenseReport, reportName: 'Old name'}; + // eslint-disable-next-line @typescript-eslint/naming-convention -- expensify_text_title is the backend's NVP name + await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS}${bill.reportID}`, {expensify_text_title: formulaTitle}); + // eslint-disable-next-line @typescript-eslint/naming-convention -- expensify_text_title is the backend's NVP name + await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS}${expenseReport.reportID}`, {expensify_text_title: formulaTitle}); + await waitForBatchedUpdates(); + + // When an expense change recomputes the report names optimistically + const getCurrencyDecimals = () => 2; + const updatedBill = maybeUpdateReportNameForFormulaTitle(namedBill, formulaPolicy, getCurrencyDecimals); + const updatedExpenseReport = maybeUpdateReportNameForFormulaTitle(namedExpenseReport, formulaPolicy, getCurrencyDecimals); + + // Then only the expense report follows the formula, and the bill keeps the name that Auth or the user gave it + expect(updatedExpenseReport.reportName).toBe('Expense Report'); + expect(updatedBill.reportName).toBe('Bill #R00000001upZ'); + }); +}); diff --git a/tests/unit/BillUtilsTest.ts b/tests/unit/BillUtilsTest.ts index 91d3abbc6e02..12b058eed874 100644 --- a/tests/unit/BillUtilsTest.ts +++ b/tests/unit/BillUtilsTest.ts @@ -6,7 +6,7 @@ import type {Report} from '@src/types/onyx'; describe('BillUtils', () => { describe('isBillReport', () => { it.each([ - {type: CONST.REPORT.UNSUPPORTED_TYPE.BILL, expected: true}, + {type: CONST.REPORT.TYPE.BILL, expected: true}, {type: CONST.REPORT.TYPE.INVOICE, expected: false}, {type: CONST.REPORT.TYPE.EXPENSE, expected: false}, ])('returns $expected for a $type report', ({type, expected}) => { @@ -28,8 +28,8 @@ describe('BillUtils', () => { describe('shouldHideBillReport', () => { it.each([ - {reportType: CONST.REPORT.UNSUPPORTED_TYPE.BILL, isBillPayBetaEnabled: false, expected: true}, - {reportType: CONST.REPORT.UNSUPPORTED_TYPE.BILL, isBillPayBetaEnabled: true, expected: false}, + {reportType: CONST.REPORT.TYPE.BILL, isBillPayBetaEnabled: false, expected: true}, + {reportType: CONST.REPORT.TYPE.BILL, isBillPayBetaEnabled: true, expected: false}, {reportType: CONST.REPORT.UNSUPPORTED_TYPE.PAYCHECK, isBillPayBetaEnabled: false, expected: false}, {reportType: CONST.REPORT.TYPE.INVOICE, isBillPayBetaEnabled: false, expected: false}, ])('returns $expected for $reportType when isBillPayBetaEnabled is $isBillPayBetaEnabled', ({reportType, isBillPayBetaEnabled, expected}) => { diff --git a/tests/unit/NextStepUtilsTest.ts b/tests/unit/NextStepUtilsTest.ts index 8ac27356320b..f38c8f730f41 100644 --- a/tests/unit/NextStepUtilsTest.ts +++ b/tests/unit/NextStepUtilsTest.ts @@ -1297,7 +1297,7 @@ describe('libs/NextStepUtils', () => { describe('buildNextStepMessage', () => { describe.each([ - {reportType: CONST.REPORT.UNSUPPORTED_TYPE.BILL, approveTarget: 'approve the bill', payTarget: 'pay this bill'}, + {reportType: CONST.REPORT.TYPE.BILL, approveTarget: 'approve the bill', payTarget: 'pay this bill'}, {reportType: CONST.REPORT.TYPE.EXPENSE, approveTarget: 'approve expenses', payTarget: 'pay expenses'}, {reportType: undefined, approveTarget: 'approve expenses', payTarget: 'pay expenses'}, ])('approve and pay wording for report type $reportType', ({reportType, approveTarget, payTarget}) => { diff --git a/tests/unit/OnyxDerived/visibleReportActionsTest.ts b/tests/unit/OnyxDerived/visibleReportActionsTest.ts index 0539db5c40c4..b1eb4bb6b8be 100644 --- a/tests/unit/OnyxDerived/visibleReportActionsTest.ts +++ b/tests/unit/OnyxDerived/visibleReportActionsTest.ts @@ -3,11 +3,13 @@ import visibleReportActionsConfig from '@libs/actions/OnyxDerived/configs/visibl import CONST from '@src/CONST'; import type {OnyxKey} from '@src/ONYXKEYS'; import ONYXKEYS from '@src/ONYXKEYS'; -import type {Report, ReportActions, ReportNameValuePairs} from '@src/types/onyx'; +import type {Report, ReportAction, ReportActions, ReportNameValuePairs} from '@src/types/onyx'; import type {VisibleReportActionsDerivedValue} from '@src/types/onyx/DerivedValues'; import type {OnyxCollection} from 'react-native-onyx'; +import createMock from '../../utils/createMock'; + describe('visibleReportActions', () => { describe('SESSION detected via triggeredKeys', () => { const reportActionsKeyA = `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}A`; @@ -80,4 +82,38 @@ describe('visibleReportActions', () => { expect(result[reportID]?.[surveyActionID]).toBe(false); expect(result[unrelatedReportID]).toBe(currentValue[unrelatedReportID]); }); + + it('leaves invoice previews out of the cache, so the invoice decides at display time whether the bill receiver sees them', () => { + // Given an invoice room with a preview of an invoice the receiver pays through its linked bill, and a chat with an expense report preview + const roomReportID = 'invoiceRoomReportID'; + const invoiceReportID = 'invoiceReportID'; + const chatReportID = 'chatReportID'; + const expenseReportID = 'expenseReportID'; + const makePreview = (reportActionID: string, linkedReportID: string): ReportAction => + createMock({ + reportActionID, + actionName: CONST.REPORT.ACTIONS.TYPE.REPORT_PREVIEW, + created: '2026-11-01 12:00:00.000', + message: {linkedReportID}, + }); + const allReportActions: OnyxCollection = { + [`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${roomReportID}`]: {invoicePreviewID: makePreview('invoicePreviewID', invoiceReportID)}, + [`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${chatReportID}`]: {expensePreviewID: makePreview('expensePreviewID', expenseReportID)}, + }; + const allReports: OnyxCollection = { + [`${ONYXKEYS.COLLECTION.REPORT}${invoiceReportID}`]: {reportID: invoiceReportID, type: CONST.REPORT.TYPE.INVOICE, isHiddenForBillReceiver: true}, + [`${ONYXKEYS.COLLECTION.REPORT}${expenseReportID}`]: {reportID: expenseReportID, type: CONST.REPORT.TYPE.EXPENSE}, + }; + + // When the derived value computes every report's visibility + const result = visibleReportActionsConfig.compute([allReportActions, undefined, allReports, {}], { + currentValue: undefined, + sourceValues: undefined, + triggeredKeys: new Set(), + }); + + // Then the invoice preview has no cached value, because the invoice's isHiddenForBillReceiver flag can change without the preview changing + expect(result[roomReportID]?.invoicePreviewID).toBeUndefined(); + expect(result[chatReportID]?.expensePreviewID).toBe(true); + }); }); diff --git a/tests/unit/ReportActionsUtilsTest.ts b/tests/unit/ReportActionsUtilsTest.ts index 58ede930b766..aa3d9e3ec394 100644 --- a/tests/unit/ReportActionsUtilsTest.ts +++ b/tests/unit/ReportActionsUtilsTest.ts @@ -2960,6 +2960,32 @@ describe('ReportActionsUtils', () => { }); describe('shouldReportActionBeVisible', () => { + it.each([ + [true, false], + [false, true], + ])('shows an invoice preview only when the invoice is not hidden for the bill receiver (isHiddenForBillReceiver: %s)', async (isHiddenForBillReceiver, expectedVisibility) => { + // Given an invoice room preview of an invoice that the current user may pay through its linked bill + const invoiceReportID = '9100'; + await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${invoiceReportID}`, {reportID: invoiceReportID, type: CONST.REPORT.TYPE.INVOICE, isHiddenForBillReceiver}); + await waitForBatchedUpdates(); + const reportPreviewAction = createMock>({ + reportActionID: '9101', + reportID: '9102', + actionName: CONST.REPORT.ACTIONS.TYPE.REPORT_PREVIEW, + created: '2026-11-01 00:00:00.000', + message: [{type: 'COMMENT', html: 'Invoice', text: 'Invoice'}], + originalMessage: {linkedReportID: invoiceReportID}, + }); + + // When the chat checks whether to show the preview, with and without the cached visibility + const visibility = ReportActionsUtils.shouldReportActionBeVisible(reportPreviewAction, reportPreviewAction.reportActionID, true); + const cachedVisibility = ReportActionsUtils.isReportActionVisible(reportPreviewAction, '9102', true, {}); + + // Then the bill receiver doesn't see the invoice preview, so the whole message row stays out of the chat + expect(visibility).toBe(expectedVisibility); + expect(cachedVisibility).toBe(expectedVisibility); + }); + it('keeps a closed support ticket action visible', () => { const reportAction: ReportAction = { actionName: CONST.REPORT.ACTIONS.TYPE.CLOSED, @@ -6683,8 +6709,8 @@ describe('ReportActionsUtils', () => { }); it.each([ - [CONST.REPORT.UNSUPPORTED_TYPE.BILL, false, CONST.REPORT.ACTIONS.TYPE.CREATED, 456, 456], - [CONST.REPORT.UNSUPPORTED_TYPE.BILL, false, CONST.REPORT.ACTIONS.TYPE.SUBMITTED, undefined, CONST.ACCOUNT_ID.CONCIERGE], + [CONST.REPORT.TYPE.BILL, false, CONST.REPORT.ACTIONS.TYPE.CREATED, 456, 456], + [CONST.REPORT.TYPE.BILL, false, CONST.REPORT.ACTIONS.TYPE.SUBMITTED, undefined, CONST.ACCOUNT_ID.CONCIERGE], [CONST.REPORT.TYPE.INVOICE, true, CONST.REPORT.ACTIONS.TYPE.SUBMITTED_AND_CLOSED, 456, 456], [CONST.REPORT.TYPE.INVOICE, true, CONST.REPORT.ACTIONS.TYPE.CREATED, undefined, CONST.ACCOUNT_ID.CONCIERGE], ] as const)('credits the bill creator for %s %s action %s with processor %s', (type, isInvoiceLinkedToBill, actionName, processorAccountID, expectedAccountID) => { diff --git a/tests/unit/ReportAlternateTextUtilsTest.ts b/tests/unit/ReportAlternateTextUtilsTest.ts index 5ef4001180ba..07b93378c909 100644 --- a/tests/unit/ReportAlternateTextUtilsTest.ts +++ b/tests/unit/ReportAlternateTextUtilsTest.ts @@ -516,6 +516,62 @@ describe('ReportAlternateTextUtils', () => { }); describe('getLastMessageTextForReport', () => { + it('describes the last visible message instead of an invoice hidden for the bill receiver', async () => { + // Given an invoice room whose newest action previews an invoice that the receiver pays through its linked bill + const room: Report = { + ...createRandomReport(0, CONST.REPORT.CHAT_TYPE.INVOICE), + reportID: '9200', + lastMessageText: 'Vendor sent an invoice', + }; + const invoice: Report = {...createRandomReport(1, undefined), reportID: '9201', type: CONST.REPORT.TYPE.INVOICE, isHiddenForBillReceiver: true}; + const commentAction = createMock({ + reportActionID: '9202', + actorAccountID: CURRENT_USER_ACCOUNT_ID, + reportID: room.reportID, + actionName: CONST.REPORT.ACTIONS.TYPE.ADD_COMMENT, + created: '2026-11-01 10:00:00.000', + message: [{type: 'COMMENT', html: 'Thanks for the order', text: 'Thanks for the order'}], + pendingAction: null, + isOptimisticAction: false, + }); + const invoicePreviewAction = createMock({ + reportActionID: '9203', + actorAccountID: CURRENT_USER_ACCOUNT_ID, + reportID: room.reportID, + actionName: CONST.REPORT.ACTIONS.TYPE.REPORT_PREVIEW, + created: '2026-11-01 11:00:00.000', + message: {linkedReportID: invoice.reportID}, + pendingAction: null, + isOptimisticAction: false, + }); + await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${room.reportID}`, room); + await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${invoice.reportID}`, invoice); + await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${room.reportID}`, { + [commentAction.reportActionID]: commentAction, + [invoicePreviewAction.reportActionID]: invoicePreviewAction, + }); + await waitForBatchedUpdatesWithAct(); + + // When the Inbox computes the room's last message + const lastMessage = getLastMessageTextForReport({ + dateFnsLocale: undefined, + conciergeReportID: undefined, + currentUserAccountID: CURRENT_USER_ACCOUNT_ID, + personalDetails: undefined, + translate: translateLocal, + convertToDisplayString, + report: room, + lastActorDetails: null, + isReportArchived: false, + currentUserLogin: CURRENT_USER_LOGIN, + formatPhoneNumber, + rules: undefined, + }); + + // Then it shows the comment, because the receiver must not see the invoice in the Inbox + expect(lastMessage).toBe('Thanks for the order'); + }); + it('formats an agent prompt update from its original message', () => { const report: Report = createRandomReport(0, undefined); const agentPromptUpdatedAction: ReportAction = { diff --git a/tests/unit/ReportNameUtilsTest.ts b/tests/unit/ReportNameUtilsTest.ts index 80abad3ddaec..575e8e725b86 100644 --- a/tests/unit/ReportNameUtilsTest.ts +++ b/tests/unit/ReportNameUtilsTest.ts @@ -307,6 +307,68 @@ describe('ReportNameUtils', () => { }); }); + describe('computeReportName - Bills', () => { + const billPolicy: Policy = { + ...createRandomPolicy(300, CONST.POLICY.TYPE.CORPORATE), + id: 'billPolicy', + name: 'Receiver Policy', + fieldList: { + // eslint-disable-next-line @typescript-eslint/naming-convention + text_title: { + defaultValue: '{report:type} {report:startdate}', + deletable: false, + externalIDs: [], + fieldID: 'text_title', + isTax: false, + name: 'title', + orderWeight: 0, + type: 'formula', + target: 'expense', + values: [], + disabledOptions: [], + keys: [], + }, + }, + }; + const bill: Report = { + reportID: '300', + type: CONST.REPORT.TYPE.BILL, + policyID: billPolicy.id, + ownerAccountID: currentUserAccountID, + managerID: currentUserAccountID, + stateNum: CONST.REPORT.STATE_NUM.SUBMITTED, + statusNum: CONST.REPORT.STATUS_NUM.SUBMITTED, + total: -12500, + currency: CONST.CURRENCY.USD, + reportName: 'Bill #R00000001upZ', + }; + + it.each([ + ['the default name from Auth', 'Bill #R00000001upZ'], + ['a name the user gave it', 'Office chairs for the new floor'], + ])('shows the stored name of a bill with %s', (_, reportName) => { + // Given a bill with a stored name, on a policy whose title field is a formula + const namedBill: Report = {...bill, reportName}; + + // When the Inbox, the header, and the derived report attributes compute its name + const computedName = computeReportName(namedBill, {}, {[`${ONYXKEYS.COLLECTION.POLICY}${billPolicy.id}`]: billPolicy}); + const moneyRequestReportName = getMoneyRequestReportName({ + report: namedBill, + policy: billPolicy, + personalDetailsList: participantsPersonalDetails, + linkedTransactions: [], + translate: translateLocal, + formatPhoneNumber, + convertToDisplayString, + }); + + // Then they show the stored name, so neither the policy title formula nor the amount replaces it + expect(computedName).toBe(reportName); + expect(moneyRequestReportName).toBe(reportName); + expect(getReportName(namedBill, computedName)).toBe(reportName); + }); + }); + describe('computeReportName - Policy expense chat', () => { test('Returns policy expense chat name when owner is set', async () => { const report: Report = { diff --git a/tests/unit/ReportNotFoundGuardTest.tsx b/tests/unit/ReportNotFoundGuardTest.tsx index c55f574a3bc8..0bd0e340f841 100644 --- a/tests/unit/ReportNotFoundGuardTest.tsx +++ b/tests/unit/ReportNotFoundGuardTest.tsx @@ -156,7 +156,7 @@ describe('ReportNotFoundGuard', () => { it('shows the not-found page for a bill when the user does not have the newDotBillPay beta', async () => { // Given a loaded bill and a user without the newDotBillPay beta - await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${REPORT_ID}`, {reportID: REPORT_ID, type: CONST.REPORT.UNSUPPORTED_TYPE.BILL}); + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${REPORT_ID}`, {reportID: REPORT_ID, type: CONST.REPORT.TYPE.BILL}); await Onyx.merge(`${ONYXKEYS.COLLECTION.RAM_ONLY_REPORT_LOADING_STATE}${REPORT_ID}`, {isLoadingInitialReportActions: false}); await waitForBatchedUpdates(); @@ -172,7 +172,7 @@ describe('ReportNotFoundGuard', () => { it('renders a bill when the user has the newDotBillPay beta', async () => { // Given a loaded bill and a user with the newDotBillPay beta await Onyx.set(ONYXKEYS.BETAS, [CONST.BETAS.NEW_DOT_BILL_PAY]); - await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${REPORT_ID}`, {reportID: REPORT_ID, type: CONST.REPORT.UNSUPPORTED_TYPE.BILL}); + await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${REPORT_ID}`, {reportID: REPORT_ID, type: CONST.REPORT.TYPE.BILL}); await Onyx.merge(`${ONYXKEYS.COLLECTION.RAM_ONLY_REPORT_LOADING_STATE}${REPORT_ID}`, {isLoadingInitialReportActions: false}); await waitForBatchedUpdates(); diff --git a/tests/unit/ReportUtilsTest.ts b/tests/unit/ReportUtilsTest.ts index 6eed7e290edf..349df14e6a82 100644 --- a/tests/unit/ReportUtilsTest.ts +++ b/tests/unit/ReportUtilsTest.ts @@ -4052,7 +4052,7 @@ describe('ReportUtils', () => { // Given a bill can receive its policy name without the policy record. const billReport: Report = { reportID: 'bill-subtitle', - type: CONST.REPORT.UNSUPPORTED_TYPE.BILL, + type: CONST.REPORT.TYPE.BILL, policyID: 'bill-policy', policyName: 'Bill Policy', ownerAccountID: currentUserAccountID, @@ -5175,7 +5175,7 @@ describe('ReportUtils', () => { const vendorAccountID = 20; const bill: Report = { ...LHNTestUtils.getFakeReport(), - type: CONST.REPORT.UNSUPPORTED_TYPE.BILL, + type: CONST.REPORT.TYPE.BILL, stateNum: CONST.REPORT.STATE_NUM.OPEN, statusNum: CONST.REPORT.STATUS_NUM.OPEN, policyID: paidPolicy.id, @@ -9693,7 +9693,7 @@ describe('ReportUtils', () => { {isBillPayBetaEnabled: true, expected: true}, ])('should include a bill only for users with the newDotBillPay beta (isBillPayBetaEnabled: $isBillPayBetaEnabled)', ({isBillPayBetaEnabled, expected}) => { // Given a bill with a draft, so the draft alone would include it in the list - const report: Report = {...LHNTestUtils.getFakeReport(), type: CONST.REPORT.UNSUPPORTED_TYPE.BILL}; + const report: Report = {...LHNTestUtils.getFakeReport(), type: CONST.REPORT.TYPE.BILL}; // When the list checks the bill for a user with or without the newDotBillPay beta const result = shouldReportBeInOptionList({ @@ -9718,7 +9718,7 @@ describe('ReportUtils', () => { it('should exclude a bill when the caller does not pass isBillPayBetaEnabled', () => { // Given a bill with a draft and a caller that only the LHN beta flag would cover - const report: Report = {...LHNTestUtils.getFakeReport(), type: CONST.REPORT.UNSUPPORTED_TYPE.BILL}; + const report: Report = {...LHNTestUtils.getFakeReport(), type: CONST.REPORT.TYPE.BILL}; // When another option list checks the bill without the flag const result = shouldReportBeInOptionList({ @@ -9740,6 +9740,31 @@ describe('ReportUtils', () => { expect(result).toBe(false); }); + it('should exclude an invoice that is hidden for the bill receiver', () => { + // Given an invoice that the receiver pays through its linked bill, even when it is the report the user is viewing + const report: Report = {...LHNTestUtils.getFakeReport(), type: CONST.REPORT.TYPE.INVOICE, isHiddenForBillReceiver: true}; + + // When the LHN checks the invoice for a user with the newDotBillPay beta + const result = shouldReportBeInOptionList({ + report, + chatReport: mockedChatReport, + currentReportId: report.reportID, + isInFocusMode: false, + isDefaultRoomsBetaEnabled: true, + isBillPayBetaEnabled: true, + doesReportHaveViolations: false, + excludeEmptyChats: false, + draftComment: 'Draft', + isReportArchived: undefined, + hasGuidesEmails: false, + conciergeReportID: undefined, + derivedIsEmptyReport: undefined, + }); + + // Then the invoice stays out, so the receiver sees only the bill + expect(result).toBe(false); + }); + it('should return true when the report is current active report', () => { const report = LHNTestUtils.getFakeReport(); const currentReportId = report.reportID; @@ -11761,8 +11786,8 @@ describe('ReportUtils', () => { describe('isUnsupportedReportType', () => { it.each([ - {reportType: CONST.REPORT.UNSUPPORTED_TYPE.BILL, isBillPayBetaEnabled: false, expected: true}, - {reportType: CONST.REPORT.UNSUPPORTED_TYPE.BILL, isBillPayBetaEnabled: true, expected: false}, + {reportType: CONST.REPORT.TYPE.BILL, isBillPayBetaEnabled: false, expected: true}, + {reportType: CONST.REPORT.TYPE.BILL, isBillPayBetaEnabled: true, expected: false}, {reportType: CONST.REPORT.UNSUPPORTED_TYPE.PAYCHECK, isBillPayBetaEnabled: true, expected: true}, {reportType: CONST.REPORT.TYPE.EXPENSE, isBillPayBetaEnabled: false, expected: false}, {reportType: undefined, isBillPayBetaEnabled: false, expected: false}, @@ -13379,7 +13404,7 @@ describe('ReportUtils', () => { stateNum: CONST.REPORT.STATE_NUM.OPEN, statusNum: CONST.REPORT.STATUS_NUM.OPEN, }; - const bill: Report = {...expenseReport, type: CONST.REPORT.UNSUPPORTED_TYPE.BILL}; + const bill: Report = {...expenseReport, type: CONST.REPORT.TYPE.BILL}; // When it's checked if each report is outstanding // Then only the expense report is offered as a report to add expenses to, because a bill's expenses come only from the vendor's invoice @@ -13525,7 +13550,7 @@ describe('ReportUtils', () => { statusNum: CONST.REPORT.STATUS_NUM.OPEN, ownerAccountID: currentUserAccountID, }; - const bill: Report = {...expenseReport, reportID: '10006', type: CONST.REPORT.UNSUPPORTED_TYPE.BILL}; + const bill: Report = {...expenseReport, reportID: '10006', type: CONST.REPORT.TYPE.BILL}; await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${expenseReport.reportID}`, expenseReport); await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${bill.reportID}`, bill); diff --git a/tests/unit/Search/SearchUIUtilsTest.ts b/tests/unit/Search/SearchUIUtilsTest.ts index 5371422c5f90..81b0ac1a6e81 100644 --- a/tests/unit/Search/SearchUIUtilsTest.ts +++ b/tests/unit/Search/SearchUIUtilsTest.ts @@ -3104,7 +3104,7 @@ describe('SearchUIUtils', () => { it('should leave out comments on a bill and previews that link to a bill', () => { // Given a chat search whose snapshot holds a comment on a bill and a preview of the bill in another chat // When the chat sections are built - const [sections] = getChatSections(CONST.REPORT.UNSUPPORTED_TYPE.BILL); + const [sections] = getChatSections(CONST.REPORT.TYPE.BILL); // Then neither action is listed, because bills stay out of Search until Search supports paying bills const reportActionIDs = sections.filter(SearchUIUtils.isReportActionListItemType).map((item) => item.reportActionID); @@ -3118,7 +3118,7 @@ describe('SearchUIUtils', () => { const [, expenseReportCount] = getChatSections(CONST.REPORT.TYPE.EXPENSE); // When the report is a bill instead - const [, billCount] = getChatSections(CONST.REPORT.UNSUPPORTED_TYPE.BILL); + const [, billCount] = getChatSections(CONST.REPORT.TYPE.BILL); // Then the count stays the same, because paging compares it with the server offset, which counts every action expect(billCount).toBe(expenseReportCount); diff --git a/tests/unit/SidebarFilterTest.ts b/tests/unit/SidebarFilterTest.ts index de053c2b1a36..58f529ea5ccb 100644 --- a/tests/unit/SidebarFilterTest.ts +++ b/tests/unit/SidebarFilterTest.ts @@ -279,14 +279,14 @@ xdescribe('Sidebar', () => { ); }); - it('filter paycheck and bill report', () => { + it('filters paycheck reports and reports that are not found', () => { const report1: Report = { ...LHNTestUtils.getFakeReport(), type: CONST.REPORT.UNSUPPORTED_TYPE.PAYCHECK, }; const report2: Report = { ...LHNTestUtils.getFakeReport(), - type: CONST.REPORT.UNSUPPORTED_TYPE.BILL, + type: CONST.REPORT.TYPE.BILL, errorFields: { notFound: { error: 'Report not found', diff --git a/tests/unit/SidebarUtilsTest.ts b/tests/unit/SidebarUtilsTest.ts index 8dd9d358c5e8..36419cc2c25a 100644 --- a/tests/unit/SidebarUtilsTest.ts +++ b/tests/unit/SidebarUtilsTest.ts @@ -1372,7 +1372,7 @@ describe('SidebarUtils', () => { const billReport = { ...createRandomReport(1, undefined), reportName: 'Bill', - type: CONST.REPORT.UNSUPPORTED_TYPE.BILL, + type: CONST.REPORT.TYPE.BILL, errorFields: undefined, } as Report; @@ -5656,7 +5656,7 @@ describe('SidebarUtils', () => { ...createRandomReport(1, undefined), reportID: '1', reportName: 'Bill', - type: CONST.REPORT.UNSUPPORTED_TYPE.BILL, + type: CONST.REPORT.TYPE.BILL, errorFields: undefined, }; const reports: OnyxCollection = { diff --git a/tests/unit/hooks/useConfirmApprovalTest.ts b/tests/unit/hooks/useConfirmApprovalTest.ts new file mode 100644 index 000000000000..c8f264ac9086 --- /dev/null +++ b/tests/unit/hooks/useConfirmApprovalTest.ts @@ -0,0 +1,96 @@ +import {act, renderHook} from '@testing-library/react-native'; + +import useConfirmApproval from '@components/MoneyReportHeaderPrimaryAction/useConfirmApproval'; + +import {approveMoneyRequest} from '@libs/actions/IOU/ReportWorkflow'; + +import CONST from '@src/CONST'; +import ONYXKEYS from '@src/ONYXKEYS'; + +import Onyx from 'react-native-onyx'; + +import waitForBatchedUpdates from '../../utils/waitForBatchedUpdates'; + +const ACCOUNT_ID = 12345; +const REPORT_ID = '1'; + +jest.mock('@libs/actions/IOU/ReportWorkflow', () => ({ + approveMoneyRequest: jest.fn(), +})); + +jest.mock('@hooks/useCurrentUserPersonalDetails', () => ({ + __esModule: true, + default: jest.fn(() => ({ + accountID: 12345, + email: 'approver@expensify.com', + login: 'approver@expensify.com', + })), +})); + +jest.mock('@hooks/useTransactionsAndViolationsForReport', () => ({ + __esModule: true, + default: jest.fn(() => ({transactions: {}, violations: {}})), +})); + +jest.mock('@components/DelegateNoAccessModalProvider', () => ({ + useDelegateNoAccessState: jest.fn(() => ({ + isDelegateAccessRestricted: false, + })), + useDelegateNoAccessActions: jest.fn(() => ({ + showDelegateNoAccessModal: jest.fn(), + })), +})); + +describe('useConfirmApproval', () => { + beforeAll(() => { + Onyx.init({keys: ONYXKEYS}); + }); + + beforeEach(async () => { + jest.clearAllMocks(); + await Onyx.clear(); + await waitForBatchedUpdates(); + }); + + async function approveReport(type: string) { + await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${REPORT_ID}`, { + reportID: REPORT_ID, + type, + managerID: ACCOUNT_ID, + stateNum: CONST.REPORT.STATE_NUM.SUBMITTED, + statusNum: CONST.REPORT.STATUS_NUM.SUBMITTED, + }); + await waitForBatchedUpdates(); + + const startApprovedAnimation = jest.fn(); + const {result} = renderHook(() => useConfirmApproval(REPORT_ID, startApprovedAnimation)); + await waitForBatchedUpdates(); + + act(() => { + result.current.onApprove(true); + }); + + const onApproved = jest.mocked(approveMoneyRequest).mock.calls.at(0)?.at(0)?.onApproved; + onApproved?.(); + return startApprovedAnimation; + } + + it('starts the approved animation for an expense report', async () => { + // Given an expense report waiting on the current user's approval + // When the user approves it + const startApprovedAnimation = await approveReport(CONST.REPORT.TYPE.EXPENSE); + + // Then the header plays the approved animation, which AnimatedSettlementButton ends + expect(startApprovedAnimation).toHaveBeenCalled(); + }); + + it('does not start the approved animation for a bill', async () => { + // Given a bill waiting on the current user's approval + // When the user approves it + const startApprovedAnimation = await approveReport(CONST.REPORT.TYPE.BILL); + + // Then no animation starts, because bills don't show Pay and nothing would end the animation + expect(jest.mocked(approveMoneyRequest)).toHaveBeenCalled(); + expect(startApprovedAnimation).not.toHaveBeenCalled(); + }); +}); diff --git a/tests/unit/hooks/useLifecycleActionsTest.ts b/tests/unit/hooks/useLifecycleActionsTest.ts new file mode 100644 index 000000000000..ca57f8a1bd72 --- /dev/null +++ b/tests/unit/hooks/useLifecycleActionsTest.ts @@ -0,0 +1,124 @@ +import {act, renderHook} from '@testing-library/react-native'; + +import useLifecycleActions from '@hooks/useLifecycleActions'; + +import {approveMoneyRequest} from '@libs/actions/IOU/ReportWorkflow'; + +import CONST from '@src/CONST'; +import ONYXKEYS from '@src/ONYXKEYS'; + +import Onyx from 'react-native-onyx'; + +import waitForBatchedUpdates from '../../utils/waitForBatchedUpdates'; + +const ACCOUNT_ID = 12345; +const REPORT_ID = '1'; + +jest.mock('@libs/actions/IOU/ReportWorkflow', () => ({ + approveMoneyRequest: jest.fn(), + reopenReport: jest.fn(), + retractReport: jest.fn(), + submitReport: jest.fn(), + unapproveExpenseReport: jest.fn(), +})); + +jest.mock('@hooks/useCurrentUserPersonalDetails', () => ({ + __esModule: true, + default: jest.fn(() => ({ + accountID: 12345, + email: 'approver@expensify.com', + login: 'approver@expensify.com', + })), +})); + +jest.mock('@hooks/useTransactionsAndViolationsForReport', () => ({ + __esModule: true, + default: jest.fn(() => ({transactions: {}, violations: {}})), +})); + +jest.mock('@components/DelegateNoAccessModalProvider', () => ({ + useDelegateNoAccessState: jest.fn(() => ({ + isDelegateAccessRestricted: false, + })), + useDelegateNoAccessActions: jest.fn(() => ({ + showDelegateNoAccessModal: jest.fn(), + })), +})); + +jest.mock('@components/ReportSubmitToPopoverAnchor', () => ({ + useOpenReportSubmitToPopover: jest.fn(() => jest.fn()), +})); + +jest.mock('@components/Search/SearchContext', () => ({ + useSearchQueryContext: jest.fn(() => ({currentSearchQueryJSON: undefined, currentSearchKey: undefined})), + useSearchResultsContext: jest.fn(() => ({currentSearchResults: undefined})), + useSearchSelectionContext: jest.fn(() => ({selectedTransactionIDs: []})), + useSearchSelectionActions: jest.fn(() => ({clearSelectedTransactions: jest.fn()})), +})); + +jest.mock('@hooks/useConfirmModal', () => ({ + __esModule: true, + default: jest.fn(() => ({showConfirmModal: jest.fn()})), +})); + +describe('useLifecycleActions', () => { + beforeAll(() => { + Onyx.init({keys: ONYXKEYS}); + }); + + beforeEach(async () => { + jest.clearAllMocks(); + await Onyx.clear(); + await waitForBatchedUpdates(); + }); + + async function approveReport(type: string) { + await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${REPORT_ID}`, { + reportID: REPORT_ID, + type, + managerID: ACCOUNT_ID, + stateNum: CONST.REPORT.STATE_NUM.SUBMITTED, + statusNum: CONST.REPORT.STATUS_NUM.SUBMITTED, + }); + await waitForBatchedUpdates(); + + const startApprovedAnimation = jest.fn(); + const {result} = renderHook(() => + useLifecycleActions({ + reportID: REPORT_ID, + startApprovedAnimation, + startAnimation: jest.fn(), + startSubmittingAnimation: jest.fn(), + onHoldMenuOpen: jest.fn(), + }), + ); + await waitForBatchedUpdates(); + + act(() => { + result.current.confirmApproval(); + }); + + const onApproved = jest.mocked(approveMoneyRequest).mock.calls.at(0)?.at(0)?.onApproved; + onApproved?.(); + return startApprovedAnimation; + } + + it('starts the approved animation for an expense report', async () => { + // Given an expense report waiting on the current user's approval + // When the user approves it from the More menu + const startApprovedAnimation = await approveReport(CONST.REPORT.TYPE.EXPENSE); + + // Then the header plays the approved animation, which AnimatedSettlementButton ends + expect(startApprovedAnimation).toHaveBeenCalled(); + }); + + it('does not start the approved animation for a bill', async () => { + // Given a bill waiting on the current user's approval + // When the user approves it from the More menu + const startApprovedAnimation = await approveReport(CONST.REPORT.TYPE.BILL); + + // Then no animation starts, because bills don't show Pay and nothing would end the animation + expect(jest.mocked(approveMoneyRequest)).toHaveBeenCalled(); + expect(startApprovedAnimation).not.toHaveBeenCalled(); + }); +}); diff --git a/tests/unit/useReportActionAvatarsTest.tsx b/tests/unit/useReportActionAvatarsTest.tsx index c6d3f3b74eb1..669eaf564800 100644 --- a/tests/unit/useReportActionAvatarsTest.tsx +++ b/tests/unit/useReportActionAvatarsTest.tsx @@ -48,7 +48,7 @@ describe('useReportActionAvatars', () => { [CONST.REPORT.ACTIONS.TYPE.SUBMITTED, 0], ] as const)('credits bill action %s to processor %s or Concierge instead of the receiver', async (actionName, processor) => { // Given bill intake creates and submits the bill with the receiver's token. - const report: Report = {reportID: '9400', type: CONST.REPORT.UNSUPPORTED_TYPE.BILL, ownerAccountID: 123, managerID: 123}; + const report: Report = {reportID: '9400', type: CONST.REPORT.TYPE.BILL, ownerAccountID: 123, managerID: 123}; const action = createMock({actionName, actorAccountID: 123}); const createdAction = createMock>({ actionName: CONST.REPORT.ACTIONS.TYPE.CREATED, From 4313ae30de79c23a76babf0e072b490644124a92 Mon Sep 17 00:00:00 2001 From: Carlos Alvarez Date: Mon, 23 Nov 2026 16:01:41 -0500 Subject: [PATCH 02/17] Keep the pay next step on approved bills and let the title field edit a bill --- src/libs/NextStepUtils.ts | 6 ++++-- src/libs/ReportUtils.ts | 6 ++++++ tests/unit/NextStepUtilsTest.ts | 25 +++++++++++++++++++++++ tests/unit/ReportUtilsTest.ts | 35 +++++++++++++++++++++++++++++++++ 4 files changed, 70 insertions(+), 2 deletions(-) diff --git a/src/libs/NextStepUtils.ts b/src/libs/NextStepUtils.ts index 140ffaf06f0e..a09e0955a147 100644 --- a/src/libs/NextStepUtils.ts +++ b/src/libs/NextStepUtils.ts @@ -16,6 +16,7 @@ import type {ValueOf} from 'type-fest'; import {addMonths, format, isPast, parseISO, setDate} from 'date-fns'; import {Str} from 'expensify-common'; +import {isBillReport} from './BillUtils'; import DateUtils from './DateUtils'; import Log from './Log'; import { @@ -389,8 +390,9 @@ function buildOptimisticNextStep(params: BuildOptimisticNextStepParams): ReportN const reimbursementChoice = getReimbursementChoice(policy); const isReimbursementDisabled = reimbursementChoice === CONST.POLICY.REIMBURSEMENT_CHOICES.REIMBURSEMENT_NO; - // The server returns no further action for approved reports on workspaces that reimburse outside Expensify (Indirect) - const isReimbursementManual = reimbursementChoice === CONST.POLICY.REIMBURSEMENT_CHOICES.REIMBURSEMENT_MANUAL; + // The server returns no further action for approved expense reports on policies that reimburse outside Expensify (Indirect). + // Bills still wait for the payer, because manual reimbursement only skips expense reports. + const isReimbursementManual = reimbursementChoice === CONST.POLICY.REIMBURSEMENT_CHOICES.REIMBURSEMENT_MANUAL && !isBillReport(report); if (isInvoiceReport(report) || reimbursableSpend === 0 || isReimbursementDisabled || isReimbursementManual) { nextStep = nextStepNoActionRequired; break; diff --git a/src/libs/ReportUtils.ts b/src/libs/ReportUtils.ts index 3ac156a5b330..5517e03bad72 100644 --- a/src/libs/ReportUtils.ts +++ b/src/libs/ReportUtils.ts @@ -5871,6 +5871,12 @@ function isReportFieldOfTypeTitle(reportField: OnyxEntry): bo } function isReportFieldTargetMatchingReport(report: OnyxEntry, reportField: PolicyReportField): boolean { + // The policy title field targets expense reports, but a bill can be renamed like one. Other policy report fields + // stay off bills. + if (isBillReport(report) && isReportFieldOfTypeTitle(reportField)) { + return true; + } + return reportField.target === report?.type || (report?.type === CONST.REPORT.TYPE.EXPENSE && !reportField.target); } diff --git a/tests/unit/NextStepUtilsTest.ts b/tests/unit/NextStepUtilsTest.ts index bf03dce9d455..500e345bdf32 100644 --- a/tests/unit/NextStepUtilsTest.ts +++ b/tests/unit/NextStepUtilsTest.ts @@ -759,6 +759,31 @@ describe('libs/NextStepUtils', () => { expect(result).toMatchObject(expectedResult); }); + test('a bill on a policy with manual reimbursements still waits for the payer', () => { + // Given a bill on a policy that reimburses expense reports outside Expensify (Indirect) + const manualPolicy = {...policy, reimbursementChoice: CONST.POLICY.REIMBURSEMENT_CHOICES.REIMBURSEMENT_MANUAL}; + const bill = {...report, type: CONST.REPORT.TYPE.BILL}; + + // When the bill is approved + const result = buildOptimisticNextStep({ + rules: undefined, + report: bill, + policy: manualPolicy, + currentUserAccountIDParam: currentUserAccountID, + currentUserEmailParam: currentUserEmail, + hasViolations: false, + isASAPSubmitBetaEnabled: false, + predictedNextStatus: CONST.REPORT.STATUS_NUM.APPROVED, + shouldFixViolations: false, + isUnapprove: false, + isReopen: false, + isTrackIntentUser: false, + }); + + // Then the bill waits for the payer, as the server says, because manual reimbursement only skips expense reports + expect(result).toMatchObject({messageKey: CONST.NEXT_STEP.MESSAGE_KEY.WAITING_TO_PAY, icon: CONST.NEXT_STEP.ICONS.HOURGLASS}); + }); + test('non-payer still waits for an admin to pay', () => { return Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}${policyID}`, { reimbursementChoice: CONST.POLICY.REIMBURSEMENT_CHOICES.REIMBURSEMENT_MANUAL, diff --git a/tests/unit/ReportUtilsTest.ts b/tests/unit/ReportUtilsTest.ts index cd61fb5be203..d011a3bd9c9b 100644 --- a/tests/unit/ReportUtilsTest.ts +++ b/tests/unit/ReportUtilsTest.ts @@ -220,6 +220,7 @@ import { isReportExportedOrPending, isReportFieldDisabled, isReportFieldDisabledForUser, + isReportFieldTargetMatchingReport, isReportManager, isReportOutstanding, isReportParticipant, @@ -25959,6 +25960,40 @@ describe('ReportUtils', () => { }); }); + describe('isReportFieldTargetMatchingReport', () => { + const getField = (fieldID: string): PolicyReportField => ({ + fieldID, + name: 'Field', + type: CONST.REPORT_FIELD_TYPES.TEXT, + defaultValue: '', + deletable: true, + target: CONST.POLICY.DEFAULT_FIELD_LIST_TARGET, + values: [], + keys: [], + externalIDs: [], + disabledOptions: [], + orderWeight: 1, + isTax: false, + }); + const bill: Report = {reportID: '1', type: CONST.REPORT.TYPE.BILL}; + + it('matches the title field on a bill, so the approver can rename the bill', () => { + // Given the policy title field, which targets expense reports + + // When we check it against a bill + // Then it matches, because a bill is renamed like an expense report + expect(isReportFieldTargetMatchingReport(bill, getField(CONST.REPORT_FIELD_TITLE_FIELD_ID))).toBe(true); + }); + + it('does not match other expense report fields on a bill', () => { + // Given a custom policy report field for expense reports + + // When we check it against a bill + // Then it doesn't match, because bills don't show policy report fields + expect(isReportFieldTargetMatchingReport(bill, getField('text_customField'))).toBe(false); + }); + }); + describe('getTitleFieldWithFallback', () => { it('returns the policy title field when it exists', () => { const titleField: PolicyReportField = { From 8cef3b8e92419681c149a807f6bbd739915cdb56 Mon Sep 17 00:00:00 2001 From: Carlos Alvarez Date: Mon, 23 Nov 2026 17:27:23 -0500 Subject: [PATCH 03/17] Remove the bill check from the formula title update --- src/libs/actions/IOU/MoneyRequestBuilder.ts | 6 ---- tests/unit/BillPayTest.ts | 31 +-------------------- 2 files changed, 1 insertion(+), 36 deletions(-) diff --git a/src/libs/actions/IOU/MoneyRequestBuilder.ts b/src/libs/actions/IOU/MoneyRequestBuilder.ts index 6b0b81d51771..2d2593202a7d 100644 --- a/src/libs/actions/IOU/MoneyRequestBuilder.ts +++ b/src/libs/actions/IOU/MoneyRequestBuilder.ts @@ -4,7 +4,6 @@ import type {PersonalDetailsByLogin} from '@components/PersonalDetailsByLoginPro import type {CurrencyListActionsContextType} from '@hooks/useCurrencyList'; import type {WriteReadyBarrier} from '@libs/API'; -import {isBillReport} from '@libs/BillUtils'; import DateUtils from '@libs/DateUtils'; import {getMicroSecondOnyxErrorObject, getMicroSecondOnyxErrorWithTranslationKey} from '@libs/ErrorUtils'; import {isLocalFile} from '@libs/fileDownload/FileUtils'; @@ -1294,11 +1293,6 @@ function maybeUpdateReportNameForFormulaTitle( getCurrencyDecimals: CurrencyListActionsContextType['getCurrencyDecimals'], optimisticTransactions: Record = {}, ): OnyxTypes.Report { - // A bill keeps its stored name, which Auth sets from the vendor's invoice and the user can rename. - if (isBillReport(iouReport)) { - return iouReport; - } - const allReportNameValuePairs = getAllReportNameValuePairs(); const reportNameValuePairs = allReportNameValuePairs?.[`${ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS}${iouReport.reportID}`]; const titleField = reportNameValuePairs?.expensify_text_title; diff --git a/tests/unit/BillPayTest.ts b/tests/unit/BillPayTest.ts index 612f41a57d24..faad44b68789 100644 --- a/tests/unit/BillPayTest.ts +++ b/tests/unit/BillPayTest.ts @@ -1,4 +1,3 @@ -import {maybeUpdateReportNameForFormulaTitle} from '@libs/actions/IOU/MoneyRequestBuilder'; import {isBillReport} from '@libs/BillUtils'; import {navigationRef} from '@libs/Navigation/Navigation'; import getReportPreviewAction from '@libs/ReportPreviewActionUtils'; @@ -20,7 +19,7 @@ import { import CONST from '@src/CONST'; import IntlStore from '@src/languages/IntlStore'; import ONYXKEYS from '@src/ONYXKEYS'; -import type {Policy, PolicyReportField, Report, ReportAction, Transaction} from '@src/types/onyx'; +import type {Policy, Report, ReportAction, Transaction} from '@src/types/onyx'; import Onyx from 'react-native-onyx'; @@ -320,32 +319,4 @@ describe('Bill Pay', () => { } expect(canHoldUnholdReportAction(bill, createIOUAction(bill), undefined, billTransaction, policy, accountID, undefined, email).canHoldRequest).toBe(false); }); - - it('keeps the stored bill name when the policy title is a formula', async () => { - // Given a bill and an expense report whose title fields follow the policy title formula - const formulaPolicy: Policy = { - ...policy, - fieldList: { - // eslint-disable-next-line @typescript-eslint/naming-convention -- text_title is the backend field ID - text_title: createMock({fieldID: 'text_title', name: 'title', type: CONST.REPORT_FIELD_TYPES.FORMULA, defaultValue: '{report:type}', target: 'expense'}), - }, - }; - const formulaTitle = createMock({fieldID: 'text_title', name: 'title', type: CONST.REPORT_FIELD_TYPES.FORMULA, defaultValue: '{report:type}'}); - const namedBill: Report = {...bill, reportName: 'Bill #R00000001upZ'}; - const namedExpenseReport: Report = {...expenseReport, reportName: 'Old name'}; - // eslint-disable-next-line @typescript-eslint/naming-convention -- expensify_text_title is the backend's NVP name - await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS}${bill.reportID}`, {expensify_text_title: formulaTitle}); - // eslint-disable-next-line @typescript-eslint/naming-convention -- expensify_text_title is the backend's NVP name - await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS}${expenseReport.reportID}`, {expensify_text_title: formulaTitle}); - await waitForBatchedUpdates(); - - // When an expense change recomputes the report names optimistically - const getCurrencyDecimals = () => 2; - const updatedBill = maybeUpdateReportNameForFormulaTitle(namedBill, formulaPolicy, getCurrencyDecimals); - const updatedExpenseReport = maybeUpdateReportNameForFormulaTitle(namedExpenseReport, formulaPolicy, getCurrencyDecimals); - - // Then only the expense report follows the formula, and the bill keeps the name that Auth or the user gave it - expect(updatedExpenseReport.reportName).toBe('Expense Report'); - expect(updatedBill.reportName).toBe('Bill #R00000001upZ'); - }); }); From 7dac65abafb3e6bc9e82cf532c1b4fafda88897a Mon Sep 17 00:00:00 2001 From: Carlos Alvarez Date: Tue, 24 Nov 2026 10:18:30 -0500 Subject: [PATCH 04/17] Keep isReimbursementManual about the policy and skip payment for expense reports only --- src/libs/NextStepUtils.ts | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/libs/NextStepUtils.ts b/src/libs/NextStepUtils.ts index a09e0955a147..6b273c5a0986 100644 --- a/src/libs/NextStepUtils.ts +++ b/src/libs/NextStepUtils.ts @@ -390,10 +390,12 @@ function buildOptimisticNextStep(params: BuildOptimisticNextStepParams): ReportN const reimbursementChoice = getReimbursementChoice(policy); const isReimbursementDisabled = reimbursementChoice === CONST.POLICY.REIMBURSEMENT_CHOICES.REIMBURSEMENT_NO; - // The server returns no further action for approved expense reports on policies that reimburse outside Expensify (Indirect). + // The server returns no further action for approved reports on workspaces that reimburse outside Expensify (Indirect) + const isReimbursementManual = reimbursementChoice === CONST.POLICY.REIMBURSEMENT_CHOICES.REIMBURSEMENT_MANUAL; + // Bills still wait for the payer, because manual reimbursement only skips expense reports. - const isReimbursementManual = reimbursementChoice === CONST.POLICY.REIMBURSEMENT_CHOICES.REIMBURSEMENT_MANUAL && !isBillReport(report); - if (isInvoiceReport(report) || reimbursableSpend === 0 || isReimbursementDisabled || isReimbursementManual) { + const shouldSkipPayment = isReimbursementManual && !isBillReport(report); + if (isInvoiceReport(report) || reimbursableSpend === 0 || isReimbursementDisabled || shouldSkipPayment) { nextStep = nextStepNoActionRequired; break; } From 74f74a15bdd55d219577a27c201c79f7a6cad3e2 Mon Sep 17 00:00:00 2001 From: Carlos Alvarez Date: Tue, 24 Nov 2026 10:18:31 -0500 Subject: [PATCH 05/17] Let canApproveBill ignore held expenses, because bills can't be held --- src/libs/ReportUtils.ts | 4 ++-- tests/unit/BillPayAttentionTest.ts | 1 - 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/src/libs/ReportUtils.ts b/src/libs/ReportUtils.ts index 5517e03bad72..81c2518c97ea 100644 --- a/src/libs/ReportUtils.ts +++ b/src/libs/ReportUtils.ts @@ -3552,7 +3552,7 @@ function canApproveExpenseReport( return !hasOnlyUnsettledExpenses(reportTransactions, report); } -/** Whether the current user can approve the bill now. The header hides Approve when every expense is on hold. */ +/** Whether the current user can approve the bill now. */ function canApproveBill( report: OnyxEntry, policy: OnyxEntry, @@ -3560,7 +3560,7 @@ function canApproveBill( currentUserAccountID: number, reportTransactions: Transaction[], ): boolean { - return isBillReport(report) && canApproveExpenseReport(report, reportTransactions, currentUserAccountID, reportMetadata, policy) && !hasOnlyHeldExpenses(reportTransactions); + return isBillReport(report) && canApproveExpenseReport(report, reportTransactions, currentUserAccountID, reportMetadata, policy); } function canIOUBePaid( diff --git a/tests/unit/BillPayAttentionTest.ts b/tests/unit/BillPayAttentionTest.ts index 25f6007d667e..bfee136f1ce9 100644 --- a/tests/unit/BillPayAttentionTest.ts +++ b/tests/unit/BillPayAttentionTest.ts @@ -110,7 +110,6 @@ describe('Bill Pay green dot', () => { {...billTransaction, amount: 0, merchant: CONST.TRANSACTION.PARTIAL_TRANSACTION_MERCHANT, receipt: {state: CONST.IOU.RECEIPT_STATE.SCANNING, source: 'receipt.jpg'}}, false, ], - ['every expense is on hold', policy, {...billTransaction, comment: {hold: '1'}}, false], ] as const)('shows the Approve dot only when the header shows Approve, when %s', async (_, reportPolicy, transaction, shouldShowApprove) => { // Given a submitted bill whose policy and expense decide whether the approver can approve it now await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION}${transaction.transactionID}`, transaction); From 82f0efdcf8c386c6b409ac6023394deaa779ea11 Mon Sep 17 00:00:00 2001 From: Carlos Alvarez Date: Tue, 24 Nov 2026 10:18:33 -0500 Subject: [PATCH 06/17] Check the bill's green dot without skipping the report preview scan --- src/libs/ReportUtils.ts | 41 ++++++++++++++++++----------------------- 1 file changed, 18 insertions(+), 23 deletions(-) diff --git a/src/libs/ReportUtils.ts b/src/libs/ReportUtils.ts index 81c2518c97ea..1a8e6cad44d2 100644 --- a/src/libs/ReportUtils.ts +++ b/src/libs/ReportUtils.ts @@ -5515,41 +5515,36 @@ function getReasonAndReportActionThatRequiresAttention({ const invoiceReceiverPolicy = invoiceReceiverPolicyID ? resolvePolicy(invoiceReceiverPolicyID) : undefined; const actionTypeForAssigneeToComplete = getActionTypeForAssigneeToComplete(optionOrReport, parentReportAction); - // A bill holds no report previews, so it skips the scan for them below. - const isBill = isBillReport(optionOrReport); - // Compute IOU candidate upfront so we can compare timestamps with task candidate const { reportAction: iouReportActionToApproveOrPay, actionBadge, isBlockedOnlyByHeldReports, - } = isBill - ? {reportAction: undefined, actionBadge: undefined, isBlockedOnlyByHeldReports: false} - : getIOUReportActionWithBadge({ - chatReport: optionOrReport, - policy, - reportMetadata, - invoiceReceiverPolicy, - currentUserLogin, - currentUserAccountID, - chatReportActions: reportActions, - allViolations: transactionViolations, - // Always false here because of the early return above, but we still pass it so getIOUReportActionWithBadge doesn't read the archived state from the Onyx cache - isChatReportArchived: isReportArchived, - allReports: reports, - allReportActionsParam: allReportActionsParam ?? allReportActions, - reportsTransactions, - }); + } = getIOUReportActionWithBadge({ + chatReport: optionOrReport, + policy, + reportMetadata, + invoiceReceiverPolicy, + currentUserLogin, + currentUserAccountID, + chatReportActions: reportActions, + allViolations: transactionViolations, + // Always false here because of the early return above, but we still pass it so getIOUReportActionWithBadge doesn't read the archived state from the Onyx cache + isChatReportArchived: isReportArchived, + allReports: reports, + allReportActionsParam: allReportActionsParam ?? allReportActions, + reportsTransactions, + }); // Add only labels a green dot the chat would show anyway, so it must not change whether the dot shows. Run the checks // below as if no candidate was found, exactly like before Add existed. const dotCandidateAction = actionBadge === CONST.REPORT.ACTION_BADGE.ADD ? undefined : iouReportActionToApproveOrPay; - // A bill has no parent chat, so its own expenses decide whether its approver must act. + // A bill's own expenses decide whether its approver must act on it. // Fall back to the chat's outstanding child so the pending-only check still runs when no badge action was found. - const iouReportID = isBill ? optionOrReport.reportID : (getIOUReportIDFromReportActionPreview(dotCandidateAction) ?? optionOrReport.iouReportID); + const iouReportID = isBillReport(optionOrReport) ? optionOrReport.reportID : (getIOUReportIDFromReportActionPreview(dotCandidateAction) ?? optionOrReport.iouReportID); const transactions = getReportTransactions(iouReportID, reportsTransactions); - // Bills have no parent chat to show a report preview badge, so the approver's green dot goes on the bill itself. + // The bill's approver gets the green dot on the bill itself. if (canApproveBill(optionOrReport, policy, reportMetadata, currentUserAccountID, transactions)) { return { reason: CONST.REQUIRES_ATTENTION_REASONS.IS_WAITING_FOR_ASSIGNEE_TO_COMPLETE_ACTION, From c9a3e9a3aa5db61b9f8253eb5256f2c21ff04da1 Mon Sep 17 00:00:00 2001 From: Carlos Alvarez Date: Tue, 24 Nov 2026 10:18:34 -0500 Subject: [PATCH 07/17] Keep isExpenseReport for expense reports only and opt bills in where they need it --- .../MoneyRequestReportTransactionList.tsx | 3 ++- .../ReportActionItem/MoneyRequestView.tsx | 3 ++- .../TransactionItemRowWide.tsx | 5 +++-- src/components/TransactionItemRow/index.tsx | 3 ++- src/libs/NextStepUtils.ts | 2 +- src/libs/ReportNameUtils.ts | 3 ++- src/libs/ReportSecondaryActionUtils.ts | 2 +- src/libs/ReportUtils.ts | 19 ++++++++++--------- src/libs/TransactionPreviewUtils.ts | 3 ++- src/libs/actions/IOU/MoneyRequestBuilder.ts | 5 +++-- src/libs/actions/IOU/UpdateMoneyRequest.ts | 3 ++- .../report/ReportActionItemContentCreated.tsx | 3 ++- .../useReportActionsListData.ts | 3 ++- .../useReportActionsListRenderItem.tsx | 3 ++- tests/unit/BillPayTest.ts | 6 ++++-- 15 files changed, 40 insertions(+), 26 deletions(-) diff --git a/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx b/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx index 9b9c7986af15..758db7a89bda 100644 --- a/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx +++ b/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx @@ -18,6 +18,7 @@ import useThemeStyles from '@hooks/useThemeStyles'; import {turnOnMobileSelectionMode} from '@libs/actions/MobileSelectionMode'; import {CAROUSEL_SOURCE} from '@libs/actions/TransactionThreadNavigation'; +import {isBillReport} from '@libs/BillUtils'; import {getReportRowPolicy, getReportRowReport} from '@libs/MoneyRequestReportUtils'; import {getMoneyRequestSpendBreakdown, getReportOfflinePendingActionAndErrors, isExpenseReport, isIOUReport} from '@libs/ReportUtils'; import {getTransactionPendingAction} from '@libs/TransactionUtils'; @@ -238,7 +239,7 @@ function MoneyRequestReportTransactionList({ policyTagLists, }); - const shouldShowGroupedTransactions = isExpenseReport(report) && !isIOUReport(report); + const shouldShowGroupedTransactions = (isExpenseReport(report) || isBillReport(report)) && !isIOUReport(report); const {currentSelection, currentGroupBy, shouldGroupTransactions, selectLayout} = useMoneyRequestReportLayout(shouldShowGroupedTransactions); const {groupedTransactions, listItems, visualOrderTransactions, visualOrderTransactionIDs, lastTransactionID} = useMoneyRequestReportGroupedTransactions({ diff --git a/src/components/ReportActionItem/MoneyRequestView.tsx b/src/components/ReportActionItem/MoneyRequestView.tsx index 588ea0c87c03..35c49269758a 100644 --- a/src/components/ReportActionItem/MoneyRequestView.tsx +++ b/src/components/ReportActionItem/MoneyRequestView.tsx @@ -54,6 +54,7 @@ import {updateMoneyRequestBillable, updateMoneyRequestCategory, updateMoneyReque import {openExternalLink} from '@libs/actions/Link'; import initSplitExpense from '@libs/actions/SplitExpenses'; import {enrichAndSortAttendees, getIsMissingAttendeesViolation} from '@libs/AttendeeUtils'; +import {isBillReport} from '@libs/BillUtils'; import {getBrokenConnectionUrlToFixPersonalCard, getCommercialFeedCardDescription, getCompanyCardDescription} from '@libs/CardUtils'; import {getDecodedLeafCategoryName, isCategoryMissing} from '@libs/CategoryUtils'; import DistanceRequestUtils from '@libs/DistanceRequestUtils'; @@ -377,7 +378,7 @@ function MoneyRequestView({ ? translate('common.reservationNightsWithNightlyRate', {count: reservationNights, nightlyRate: convertToDisplayString(actualAmount / reservationNights, actualCurrency)}) : ''; - const transactionOriginalAmount = transaction && getOriginalAmountForDisplay(transaction, isExpenseReport(moneyRequestReport)); + const transactionOriginalAmount = transaction && getOriginalAmountForDisplay(transaction, isExpenseReport(moneyRequestReport) || isBillReport(moneyRequestReport)); const formattedOriginalAmount = transactionOriginalAmount && transactionOriginalCurrency && convertToDisplayString(transactionOriginalAmount, transactionOriginalCurrency); const isFromCardImport = isCardTransactionTransactionUtils(transaction); const cardProgramName = diff --git a/src/components/TransactionItemRow/TransactionItemRowWide.tsx b/src/components/TransactionItemRow/TransactionItemRowWide.tsx index 9518f9370803..7a41a5d8970e 100644 --- a/src/components/TransactionItemRow/TransactionItemRowWide.tsx +++ b/src/components/TransactionItemRow/TransactionItemRowWide.tsx @@ -25,6 +25,7 @@ import useStyleUtils from '@hooks/useStyleUtils'; import useTheme from '@hooks/useTheme'; import useThemeStyles from '@hooks/useThemeStyles'; +import {isBillReport} from '@libs/BillUtils'; import getBase62ReportID from '@libs/getBase62ReportID'; import {getVendorDisplayName} from '@libs/PolicyUtils'; import {getReportName} from '@libs/ReportNameUtils'; @@ -580,7 +581,7 @@ function TransactionItemRowWide({ style={[getSearchColumnStyles(CONST.SEARCH.TABLE_COLUMNS.ORIGINAL_AMOUNT, {isAmountColumnWide, shouldRemoveTotalColumnFlex})]} > @@ -694,7 +695,7 @@ function TransactionItemRowWide({ ); case CONST.SEARCH.TABLE_COLUMNS.TOTAL: { - const isFromExpenseReport = isExpenseReport(transactionItem.report ?? report); + const isFromExpenseReport = isExpenseReport(transactionItem.report ?? report) || isBillReport(transactionItem.report ?? report); const {amount: totalAmount, currency: totalCurrency} = getTotalForDisplay(transactionItem, report?.currency ?? policy?.outputCurrency, isFromExpenseReport); return ( 0; const attendeesCount = transactionAttendees.length ?? 0; - const totalAmount = getAmount(transactionItem, isExpenseReport(report)); + const totalAmount = getAmount(transactionItem, isExpenseReport(report) || isBillReport(report)); return ( | string): boolean { const report = typeof reportOrID === 'string' ? (getReport(reportOrID, deprecatedAllReports) ?? null) : reportOrID; - return report?.type === CONST.REPORT.TYPE.EXPENSE || isBillReport(report); + return report?.type === CONST.REPORT.TYPE.EXPENSE; } /** @@ -2971,11 +2971,11 @@ function isMoneyRequest(reportOrID: OnyxEntry | string): boolean { } /** - * Checks if a report is an IOU or expense report. + * Checks if a report is an IOU, expense, or bill report. */ function isMoneyRequestReport(reportOrID: OnyxInputOrEntry | string, reports?: Report[] | OnyxCollection): boolean { const report = typeof reportOrID === 'string' ? (getReport(reportOrID, reports ?? deprecatedAllReports) ?? null) : reportOrID; - return isIOUReport(report) || isExpenseReport(report); + return isIOUReport(report) || isExpenseReport(report) || isBillReport(report); } /** @@ -3521,7 +3521,7 @@ function canApproveExpenseReport( // Cheap report-level checks first so the transaction scans below only run for reports the user can approve const managerID = report?.managerID ?? CONST.DEFAULT_NUMBER_ID; const isCurrentUserManager = managerID === currentUserAccountID; - if (!report || !isCurrentUserManager || !isExpenseReport(report) || !isProcessingReport(report) || reportTransactions.length === 0) { + if (!report || !isCurrentUserManager || (!isExpenseReport(report) && !isBillReport(report)) || !isProcessingReport(report) || reportTransactions.length === 0) { return false; } @@ -5725,8 +5725,9 @@ function getMoneyRequestSpendBreakdown(report: OnyxInputOrEntry, searchR // There is a possibility that if the Expense report has a negative total. // This is because there are instances where you can get a credit back on your card, // or you enter a negative expense to "offset" future expenses - nonReimbursableSpend = isExpenseReport(moneyRequestReport) ? nonReimbursableSpend * -1 : Math.abs(nonReimbursableSpend); - totalSpend = isExpenseReport(moneyRequestReport) ? totalSpend * -1 : Math.abs(totalSpend); + const isStoredNegative = isExpenseReport(moneyRequestReport) || isBillReport(moneyRequestReport); + nonReimbursableSpend = isStoredNegative ? nonReimbursableSpend * -1 : Math.abs(nonReimbursableSpend); + totalSpend = isStoredNegative ? totalSpend * -1 : Math.abs(totalSpend); const totalDisplaySpend = totalSpend; const reimbursableSpend = totalDisplaySpend - nonReimbursableSpend; @@ -6089,7 +6090,7 @@ function getAvailableReportFields(report: OnyxEntry, policyReportFields: } function isTransactionFromExpenseReport(report: OnyxInputOrEntry, policy: OnyxInputOrEntry): boolean { - return isEmptyObject(report) ? isGroupPolicyPolicyUtils(policy) : isExpenseReport(report); + return isEmptyObject(report) ? isGroupPolicyPolicyUtils(policy) : isExpenseReport(report) || isBillReport(report); } /** @@ -6943,7 +6944,7 @@ function getTransactionReportName({ return translate('violations.noRoute'); } - const isFromExpenseReport = !isEmptyObject(report) && isExpenseReport(report); + const isFromExpenseReport = !isEmptyObject(report) && (isExpenseReport(report) || isBillReport(report)); if (isSentMoneyReportAction(reportAction)) { return getIOUReportActionDisplayMessage(translate, reportAction as ReportAction, convertToDisplayString, undefined, linkedTransaction); diff --git a/src/libs/TransactionPreviewUtils.ts b/src/libs/TransactionPreviewUtils.ts index 7e816f87e443..e89e8697c73f 100644 --- a/src/libs/TransactionPreviewUtils.ts +++ b/src/libs/TransactionPreviewUtils.ts @@ -15,6 +15,7 @@ import truncate from 'lodash/truncate'; import type {ActionErrorsByTransaction, TransactionDetails} from './ReportUtils'; import {setReviewDuplicatesKey} from './actions/Transaction'; +import {isBillReport} from './BillUtils'; import {isCategoryMissing} from './CategoryUtils'; import DateUtils from './DateUtils'; import createDynamicRoute from './Navigation/helpers/dynamicRoutesUtils/createDynamicRoute'; @@ -251,7 +252,7 @@ function getTransactionPreviewTextAndTranslationPaths({ } if (hasFieldErrors && RBRMessage === undefined) { - const isFromExpenseReport = isExpenseReport(iouReport); + const isFromExpenseReport = isExpenseReport(iouReport) || isBillReport(iouReport); const amountMissing = isAmountMissing(transaction, isFromExpenseReport); const merchantMissing = isFromExpenseReport && isMerchantMissing(transaction); if (amountMissing && merchantMissing) { diff --git a/src/libs/actions/IOU/MoneyRequestBuilder.ts b/src/libs/actions/IOU/MoneyRequestBuilder.ts index 2d2593202a7d..d71c8f072308 100644 --- a/src/libs/actions/IOU/MoneyRequestBuilder.ts +++ b/src/libs/actions/IOU/MoneyRequestBuilder.ts @@ -4,6 +4,7 @@ import type {PersonalDetailsByLogin} from '@components/PersonalDetailsByLoginPro import type {CurrencyListActionsContextType} from '@hooks/useCurrencyList'; import type {WriteReadyBarrier} from '@libs/API'; +import {isBillReport} from '@libs/BillUtils'; import DateUtils from '@libs/DateUtils'; import {getMicroSecondOnyxErrorObject, getMicroSecondOnyxErrorWithTranslationKey} from '@libs/ErrorUtils'; import {isLocalFile} from '@libs/fileDownload/FileUtils'; @@ -1874,7 +1875,7 @@ function calculateDiffAmount( if (!iouReport) { return 0; } - const isExpenseReportLocal = isExpenseReport(iouReport) || isInvoiceReportReportUtils(iouReport); + const isExpenseReportLocal = isExpenseReport(iouReport) || isBillReport(iouReport) || isInvoiceReportReportUtils(iouReport); const updatedCurrency = getCurrency(updatedTransaction); const currentCurrency = getCurrency(transaction); @@ -1913,7 +1914,7 @@ function getUpdatedMoneyRequestReportData( let updatedMoneyRequestReport: OnyxTypes.OnyxInputOrEntry; if (!iouReport) { updatedMoneyRequestReport = null; - } else if ((isExpenseReport(iouReport) || isInvoiceReportReportUtils(iouReport)) && !Number.isNaN(iouReport.total) && iouReport.total !== undefined) { + } else if ((isExpenseReport(iouReport) || isBillReport(iouReport) || isInvoiceReportReportUtils(iouReport)) && !Number.isNaN(iouReport.total) && iouReport.total !== undefined) { // Capture previous fresh reimbursable totals before mutating, so the diff applies whether or // not the iouReport already had reimbursableTotal/unheldReimbursableTotal populated locally. const previousReimbursableTotal = getReimbursableTotal(iouReport); diff --git a/src/libs/actions/IOU/UpdateMoneyRequest.ts b/src/libs/actions/IOU/UpdateMoneyRequest.ts index c22ca51fc8e6..6dabfeb115e7 100644 --- a/src/libs/actions/IOU/UpdateMoneyRequest.ts +++ b/src/libs/actions/IOU/UpdateMoneyRequest.ts @@ -3,6 +3,7 @@ import type {CurrencyListActionsContextType} from '@hooks/useCurrencyList'; import * as API from '@libs/API'; import type {UpdateMoneyRequestParams} from '@libs/API/parameters'; import {WRITE_COMMANDS} from '@libs/API/types'; +import {isBillReport} from '@libs/BillUtils'; import DistanceRequestUtils from '@libs/DistanceRequestUtils'; import {getMicroSecondOnyxErrorWithTranslationKey} from '@libs/ErrorUtils'; import {getChangedTagLevels} from '@libs/MerchantRuleSuggestionUtils'; @@ -1943,7 +1944,7 @@ function getUpdateMoneyRequestParams(params: GetUpdateMoneyRequestParamsType): U const errorFields = Object.fromEntries(Object.keys(pendingFields).map((key) => [key, getMicroSecondOnyxErrorWithTranslationKey('iou.error.genericEditFailureMessage')])); const isTransactionOnHold = isOnHold(transaction); - const isFromExpenseReport = isExpenseReport(iouReport) || isInvoiceReportReportUtils(iouReport); + const isFromExpenseReport = isExpenseReport(iouReport) || isBillReport(iouReport) || isInvoiceReportReportUtils(iouReport); // Drop the waypoints from the changes fed to getUpdatedTransaction when they didn't actually change, // so we skip the waypoints branch that flips isLoading and clobbers amount/merchant before being // re-overridden by the distance branch. diff --git a/src/pages/inbox/report/ReportActionItemContentCreated.tsx b/src/pages/inbox/report/ReportActionItemContentCreated.tsx index bf735ecf6478..34879dbd2b85 100644 --- a/src/pages/inbox/report/ReportActionItemContentCreated.tsx +++ b/src/pages/inbox/report/ReportActionItemContentCreated.tsx @@ -12,6 +12,7 @@ import useOnyx from '@hooks/useOnyx'; import usePolicy from '@hooks/usePolicy'; import useThemeStyles from '@hooks/useThemeStyles'; +import {isBillReport} from '@libs/BillUtils'; import getNonEmptyStringOnyxID from '@libs/getNonEmptyStringOnyxID'; import {isMessageDeleted, isReversedTransaction as isReversedTransactionReportActionsUtils, isTransactionThread} from '@libs/ReportActionsUtils'; import {isCanceledTaskReport, isExpenseReport, isInvoiceReport, isIOUReport, isSupportTicket, isTaskReport} from '@libs/ReportUtils'; @@ -159,7 +160,7 @@ function ReportActionItemContentCreated({parentReportAction, transactionID, draf ); } - if (isExpenseReport(report) || isIOUReport(report) || isInvoiceReport(report)) { + if (isExpenseReport(report) || isBillReport(report) || isIOUReport(report) || isInvoiceReport(report)) { return ( ) => { diff --git a/tests/unit/BillPayTest.ts b/tests/unit/BillPayTest.ts index faad44b68789..504c2a63037d 100644 --- a/tests/unit/BillPayTest.ts +++ b/tests/unit/BillPayTest.ts @@ -13,6 +13,7 @@ import { canIOUBePaid, canRejectReportAction, isExpenseReport, + isMoneyRequestReport, isReportOutstanding, } from '@libs/ReportUtils'; @@ -162,9 +163,10 @@ describe('Bill Pay', () => { it('opens bills in the expense report view', () => { // Given a bill // When the app checks its type - // Then it treats the bill as an expense report, so the expense report view opens it + // Then it treats the bill as a money request report, so the expense report view opens it expect(isBillReport(bill)).toBe(true); - expect(isExpenseReport(bill)).toBe(true); + expect(isMoneyRequestReport(bill)).toBe(true); + expect(isExpenseReport(bill)).toBe(false); expect(isBillReport(expenseReport)).toBe(false); }); From 5b2d98ecfd3b11e4b9edaefb941ab8bbb8706c7a Mon Sep 17 00:00:00 2001 From: Carlos Alvarez Date: Tue, 24 Nov 2026 10:18:43 -0500 Subject: [PATCH 08/17] Remove the bill checks that strict isExpenseReport already covers in secondary actions --- src/libs/ReportSecondaryActionUtils.ts | 22 +++++++--------------- 1 file changed, 7 insertions(+), 15 deletions(-) diff --git a/src/libs/ReportSecondaryActionUtils.ts b/src/libs/ReportSecondaryActionUtils.ts index 16808ac9c14c..63a0f6310b84 100644 --- a/src/libs/ReportSecondaryActionUtils.ts +++ b/src/libs/ReportSecondaryActionUtils.ts @@ -170,8 +170,7 @@ function isSplitAction( return true; } - // A bill must keep the expenses of the vendor's invoice. - if (!isExpenseReportUtils(report) || isBillReport(report)) { + if (!isExpenseReportUtils(report)) { return false; } @@ -371,8 +370,7 @@ function isApproveAction( isDuplicate(transaction, currentUserLogin, currentUserAccountID, report, ownerLogin, policy, violations?.[ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS + transaction.transactionID]), ); - // Bills can't resolve duplicates, so the primary action is still Approve for a bill with duplicates. - if (isExpenseReport && isProcessingReport && reportHasDuplicatedTransactions && !isBillReport(report)) { + if (isExpenseReport && isProcessingReport && reportHasDuplicatedTransactions) { return true; } @@ -469,8 +467,7 @@ function isCancelPaymentAction( const isExpenseReport = isExpenseReportUtils(report); const isIOUReport = isIOUReportUtils(report); - // Bills can't be paid or have their payment canceled in NewDot yet, even when they were paid in Classic. - if ((!isExpenseReport && !isIOUReport) || isBillReport(report)) { + if (!isExpenseReport && !isIOUReport) { return false; } @@ -522,8 +519,7 @@ function isCancelPaymentAction( } function isReceivedPaymentAction(report: Report, reportTransactions: Transaction[] = [], reportActions: ReportAction[] = [], policy?: Policy): boolean { - // The bill's owner pays the vendor, so the owner never receives a payment on it. - if (!isExpenseReportUtils(report) || isBillReport(report) || !isCurrentUserSubmitter(report)) { + if (!isExpenseReportUtils(report) || !isCurrentUserSubmitter(report)) { return false; } @@ -800,8 +796,7 @@ function isRetractAction(report: Report, policy?: Policy): boolean { // This should be removed after we change how instant submit works const isInstantSubmit = isInstantSubmitEnabled(policy); - // A bill arrives submitted from the vendor's invoice, so its owner can't take it back to draft. - if (!isExpenseReport || isInstantSubmit || isBillReport(report)) { + if (!isExpenseReport || isInstantSubmit) { return false; } @@ -824,9 +819,7 @@ function isReopenAction(report: Report, policy?: Policy): boolean { } const isExpenseReport = isExpenseReportUtils(report); - - // A bill arrives submitted from the vendor's invoice, so it can't go back to draft. - if (!isExpenseReport || isBillReport(report)) { + if (!isExpenseReport) { return false; } @@ -982,8 +975,7 @@ function isDuplicateReportAction(report: Report): boolean { return false; } - // Copying a bill would turn the vendor's expenses into the owner's own expenses. - if (!isExpenseReportUtils(report) || isBillReport(report)) { + if (!isExpenseReportUtils(report)) { return false; } From 2a9035aa9e86026e1eb195f3b42333bb8fd9b38c Mon Sep 17 00:00:00 2001 From: Carlos Alvarez Date: Tue, 24 Nov 2026 10:18:44 -0500 Subject: [PATCH 09/17] Allow merging only on expense reports, which leaves out bills --- src/libs/ReportUtils.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/libs/ReportUtils.ts b/src/libs/ReportUtils.ts index e385b42c4aec..2c4ef312d14a 100644 --- a/src/libs/ReportUtils.ts +++ b/src/libs/ReportUtils.ts @@ -3390,8 +3390,7 @@ function isMoneyRequestReportEligibleForMerge( ): boolean { const report = typeof reportOrReportID === 'string' ? getReportOrDraftReport({reportID: reportOrReportID}) : reportOrReportID; - // Auth can't merge expenses on a bill, because the bill must keep the expenses of the vendor's invoice. - if (!isMoneyRequestReport(report) || isIOUReport(report) || isBillReport(report)) { + if (!isExpenseReport(report)) { return false; } From e5d28d425fb95861c45f7fc722785849224284c3 Mon Sep 17 00:00:00 2001 From: Carlos Alvarez Date: Tue, 24 Nov 2026 10:18:45 -0500 Subject: [PATCH 10/17] Remove the bill check from canDuplicateExpenseIntoSourceReport --- src/libs/ReportUtils.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/libs/ReportUtils.ts b/src/libs/ReportUtils.ts index 2c4ef312d14a..1a8904a8f0be 100644 --- a/src/libs/ReportUtils.ts +++ b/src/libs/ReportUtils.ts @@ -13530,8 +13530,7 @@ function canDuplicateExpenseIntoSourceReport({ isASAPSubmitBetaEnabled, rules, }: CanDuplicateExpenseIntoSourceReportParams): boolean { - // A bill's expenses come only from the vendor's invoice. - if (!isExpenseReport(sourceReport) || isBillReport(sourceReport) || isSourceReportArchived || !chatReport || isChatReportArchived || !isPolicyAccessible(policy, currentUserLogin)) { + if (!isExpenseReport(sourceReport) || isSourceReportArchived || !chatReport || isChatReportArchived || !isPolicyAccessible(policy, currentUserLogin)) { return false; } From c51a2314422336a01bd73e14ebf62896b85fd244 Mon Sep 17 00:00:00 2001 From: Carlos Alvarez Date: Tue, 24 Nov 2026 10:26:09 -0500 Subject: [PATCH 11/17] Add isExpenseOrBillReport for the places that treat bills like expense reports --- .../MoneyRequestReportTransactionList.tsx | 5 ++--- .../ReportActionItem/MoneyRequestView.tsx | 4 ++-- .../TransactionItemRowWide.tsx | 7 +++--- src/components/TransactionItemRow/index.tsx | 5 ++--- src/libs/NextStepUtils.ts | 4 ++-- src/libs/ReportNameUtils.ts | 4 ++-- src/libs/ReportSecondaryActionUtils.ts | 4 ++-- src/libs/ReportUtils.ts | 22 +++++++++++++------ src/libs/TransactionPreviewUtils.ts | 5 ++--- src/libs/actions/IOU/MoneyRequestBuilder.ts | 6 ++--- src/libs/actions/IOU/UpdateMoneyRequest.ts | 4 ++-- .../report/ReportActionItemContentCreated.tsx | 5 ++--- .../useReportActionsListData.ts | 5 ++--- .../useReportActionsListRenderItem.tsx | 5 ++--- tests/unit/BillPayTest.ts | 2 ++ 15 files changed, 45 insertions(+), 42 deletions(-) diff --git a/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx b/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx index 758db7a89bda..023991799dc2 100644 --- a/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx +++ b/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx @@ -18,9 +18,8 @@ import useThemeStyles from '@hooks/useThemeStyles'; import {turnOnMobileSelectionMode} from '@libs/actions/MobileSelectionMode'; import {CAROUSEL_SOURCE} from '@libs/actions/TransactionThreadNavigation'; -import {isBillReport} from '@libs/BillUtils'; import {getReportRowPolicy, getReportRowReport} from '@libs/MoneyRequestReportUtils'; -import {getMoneyRequestSpendBreakdown, getReportOfflinePendingActionAndErrors, isExpenseReport, isIOUReport} from '@libs/ReportUtils'; +import {getMoneyRequestSpendBreakdown, getReportOfflinePendingActionAndErrors, isExpenseOrBillReport, isIOUReport} from '@libs/ReportUtils'; import {getTransactionPendingAction} from '@libs/TransactionUtils'; import type ActionListRefType from '@pages/inbox/ActionListTypes'; @@ -239,7 +238,7 @@ function MoneyRequestReportTransactionList({ policyTagLists, }); - const shouldShowGroupedTransactions = (isExpenseReport(report) || isBillReport(report)) && !isIOUReport(report); + const shouldShowGroupedTransactions = isExpenseOrBillReport(report) && !isIOUReport(report); const {currentSelection, currentGroupBy, shouldGroupTransactions, selectLayout} = useMoneyRequestReportLayout(shouldShowGroupedTransactions); const {groupedTransactions, listItems, visualOrderTransactions, visualOrderTransactionIDs, lastTransactionID} = useMoneyRequestReportGroupedTransactions({ diff --git a/src/components/ReportActionItem/MoneyRequestView.tsx b/src/components/ReportActionItem/MoneyRequestView.tsx index 35c49269758a..bb95860a1037 100644 --- a/src/components/ReportActionItem/MoneyRequestView.tsx +++ b/src/components/ReportActionItem/MoneyRequestView.tsx @@ -54,7 +54,6 @@ import {updateMoneyRequestBillable, updateMoneyRequestCategory, updateMoneyReque import {openExternalLink} from '@libs/actions/Link'; import initSplitExpense from '@libs/actions/SplitExpenses'; import {enrichAndSortAttendees, getIsMissingAttendeesViolation} from '@libs/AttendeeUtils'; -import {isBillReport} from '@libs/BillUtils'; import {getBrokenConnectionUrlToFixPersonalCard, getCommercialFeedCardDescription, getCompanyCardDescription} from '@libs/CardUtils'; import {getDecodedLeafCategoryName, isCategoryMissing} from '@libs/CategoryUtils'; import DistanceRequestUtils from '@libs/DistanceRequestUtils'; @@ -93,6 +92,7 @@ import { canUserPerformWriteAction as canUserPerformWriteActionReportUtils, getTransactionDetails, isActionCreator, + isExpenseOrBillReport, isExpenseReport, isInvoiceReport, isOpenReport, @@ -378,7 +378,7 @@ function MoneyRequestView({ ? translate('common.reservationNightsWithNightlyRate', {count: reservationNights, nightlyRate: convertToDisplayString(actualAmount / reservationNights, actualCurrency)}) : ''; - const transactionOriginalAmount = transaction && getOriginalAmountForDisplay(transaction, isExpenseReport(moneyRequestReport) || isBillReport(moneyRequestReport)); + const transactionOriginalAmount = transaction && getOriginalAmountForDisplay(transaction, isExpenseOrBillReport(moneyRequestReport)); const formattedOriginalAmount = transactionOriginalAmount && transactionOriginalCurrency && convertToDisplayString(transactionOriginalAmount, transactionOriginalCurrency); const isFromCardImport = isCardTransactionTransactionUtils(transaction); const cardProgramName = diff --git a/src/components/TransactionItemRow/TransactionItemRowWide.tsx b/src/components/TransactionItemRow/TransactionItemRowWide.tsx index 7a41a5d8970e..b35d16762729 100644 --- a/src/components/TransactionItemRow/TransactionItemRowWide.tsx +++ b/src/components/TransactionItemRow/TransactionItemRowWide.tsx @@ -25,11 +25,10 @@ import useStyleUtils from '@hooks/useStyleUtils'; import useTheme from '@hooks/useTheme'; import useThemeStyles from '@hooks/useThemeStyles'; -import {isBillReport} from '@libs/BillUtils'; import getBase62ReportID from '@libs/getBase62ReportID'; import {getVendorDisplayName} from '@libs/PolicyUtils'; import {getReportName} from '@libs/ReportNameUtils'; -import {getReimbursableTotal, isCurrentUserSubmitter, isExpenseReport} from '@libs/ReportUtils'; +import {getReimbursableTotal, isCurrentUserSubmitter, isExpenseOrBillReport} from '@libs/ReportUtils'; import {getViolationsForTransaction} from '@libs/SearchUIUtils'; import {COPYABLE_TEXT_DATA_SET} from '@libs/SelectionScraper'; import {getShiftKeyFromEvent} from '@libs/shiftRangeSelection'; @@ -581,7 +580,7 @@ function TransactionItemRowWide({ style={[getSearchColumnStyles(CONST.SEARCH.TABLE_COLUMNS.ORIGINAL_AMOUNT, {isAmountColumnWide, shouldRemoveTotalColumnFlex})]} > @@ -695,7 +694,7 @@ function TransactionItemRowWide({ ); case CONST.SEARCH.TABLE_COLUMNS.TOTAL: { - const isFromExpenseReport = isExpenseReport(transactionItem.report ?? report) || isBillReport(transactionItem.report ?? report); + const isFromExpenseReport = isExpenseOrBillReport(transactionItem.report ?? report); const {amount: totalAmount, currency: totalCurrency} = getTotalForDisplay(transactionItem, report?.currency ?? policy?.outputCurrency, isFromExpenseReport); return ( 0; const attendeesCount = transactionAttendees.length ?? 0; - const totalAmount = getAmount(transactionItem, isExpenseReport(report) || isBillReport(report)); + const totalAmount = getAmount(transactionItem, isExpenseOrBillReport(report)); return ( | string): boolean return report?.type === CONST.REPORT.TYPE.EXPENSE; } +/** + * Checks if a report is an expense report or a bill. A bill stores its expenses like an expense report, and its + * approver approves it like one. + */ +function isExpenseOrBillReport(report: OnyxInputOrEntry): boolean { + return isExpenseReport(report) || isBillReport(report); +} + /** * Checks if a report is an IOU report using report or reportID */ @@ -2975,7 +2983,7 @@ function isMoneyRequest(reportOrID: OnyxEntry | string): boolean { */ function isMoneyRequestReport(reportOrID: OnyxInputOrEntry | string, reports?: Report[] | OnyxCollection): boolean { const report = typeof reportOrID === 'string' ? (getReport(reportOrID, reports ?? deprecatedAllReports) ?? null) : reportOrID; - return isIOUReport(report) || isExpenseReport(report) || isBillReport(report); + return isIOUReport(report) || isExpenseOrBillReport(report); } /** @@ -3520,7 +3528,7 @@ function canApproveExpenseReport( // Cheap report-level checks first so the transaction scans below only run for reports the user can approve const managerID = report?.managerID ?? CONST.DEFAULT_NUMBER_ID; const isCurrentUserManager = managerID === currentUserAccountID; - if (!report || !isCurrentUserManager || (!isExpenseReport(report) && !isBillReport(report)) || !isProcessingReport(report) || reportTransactions.length === 0) { + if (!report || !isCurrentUserManager || !isExpenseOrBillReport(report) || !isProcessingReport(report) || reportTransactions.length === 0) { return false; } @@ -5724,9 +5732,8 @@ function getMoneyRequestSpendBreakdown(report: OnyxInputOrEntry, searchR // There is a possibility that if the Expense report has a negative total. // This is because there are instances where you can get a credit back on your card, // or you enter a negative expense to "offset" future expenses - const isStoredNegative = isExpenseReport(moneyRequestReport) || isBillReport(moneyRequestReport); - nonReimbursableSpend = isStoredNegative ? nonReimbursableSpend * -1 : Math.abs(nonReimbursableSpend); - totalSpend = isStoredNegative ? totalSpend * -1 : Math.abs(totalSpend); + nonReimbursableSpend = isExpenseOrBillReport(moneyRequestReport) ? nonReimbursableSpend * -1 : Math.abs(nonReimbursableSpend); + totalSpend = isExpenseOrBillReport(moneyRequestReport) ? totalSpend * -1 : Math.abs(totalSpend); const totalDisplaySpend = totalSpend; const reimbursableSpend = totalDisplaySpend - nonReimbursableSpend; @@ -6089,7 +6096,7 @@ function getAvailableReportFields(report: OnyxEntry, policyReportFields: } function isTransactionFromExpenseReport(report: OnyxInputOrEntry, policy: OnyxInputOrEntry): boolean { - return isEmptyObject(report) ? isGroupPolicyPolicyUtils(policy) : isExpenseReport(report) || isBillReport(report); + return isEmptyObject(report) ? isGroupPolicyPolicyUtils(policy) : isExpenseOrBillReport(report); } /** @@ -6943,7 +6950,7 @@ function getTransactionReportName({ return translate('violations.noRoute'); } - const isFromExpenseReport = !isEmptyObject(report) && (isExpenseReport(report) || isBillReport(report)); + const isFromExpenseReport = !isEmptyObject(report) && isExpenseOrBillReport(report); if (isSentMoneyReportAction(reportAction)) { return getIOUReportActionDisplayMessage(translate, reportAction as ReportAction, convertToDisplayString, undefined, linkedTransaction); @@ -16423,6 +16430,7 @@ export { generateIsEmptyReport, isEmptyReport, isRootGroupChat, + isExpenseOrBillReport, isExpenseReport, isExpenseRequest, isFinancialReportsForBusinesses, diff --git a/src/libs/TransactionPreviewUtils.ts b/src/libs/TransactionPreviewUtils.ts index e89e8697c73f..2cb0a1f45c1b 100644 --- a/src/libs/TransactionPreviewUtils.ts +++ b/src/libs/TransactionPreviewUtils.ts @@ -15,7 +15,6 @@ import truncate from 'lodash/truncate'; import type {ActionErrorsByTransaction, TransactionDetails} from './ReportUtils'; import {setReviewDuplicatesKey} from './actions/Transaction'; -import {isBillReport} from './BillUtils'; import {isCategoryMissing} from './CategoryUtils'; import DateUtils from './DateUtils'; import createDynamicRoute from './Navigation/helpers/dynamicRoutesUtils/createDynamicRoute'; @@ -28,7 +27,7 @@ import { isMessageDeleted, isMoneyRequestAction, } from './ReportActionsUtils'; -import {hasActionWithErrorsForTransaction, hasReceiptError, isExpenseReport, isReportApproved, isSettled} from './ReportUtils'; +import {hasActionWithErrorsForTransaction, hasReceiptError, isExpenseOrBillReport, isReportApproved, isSettled} from './ReportUtils'; import StringUtils from './StringUtils'; import { getAmount, @@ -252,7 +251,7 @@ function getTransactionPreviewTextAndTranslationPaths({ } if (hasFieldErrors && RBRMessage === undefined) { - const isFromExpenseReport = isExpenseReport(iouReport) || isBillReport(iouReport); + const isFromExpenseReport = isExpenseOrBillReport(iouReport); const amountMissing = isAmountMissing(transaction, isFromExpenseReport); const merchantMissing = isFromExpenseReport && isMerchantMissing(transaction); if (amountMissing && merchantMissing) { diff --git a/src/libs/actions/IOU/MoneyRequestBuilder.ts b/src/libs/actions/IOU/MoneyRequestBuilder.ts index d71c8f072308..ba1b0bf5db02 100644 --- a/src/libs/actions/IOU/MoneyRequestBuilder.ts +++ b/src/libs/actions/IOU/MoneyRequestBuilder.ts @@ -4,7 +4,6 @@ import type {PersonalDetailsByLogin} from '@components/PersonalDetailsByLoginPro import type {CurrencyListActionsContextType} from '@hooks/useCurrencyList'; import type {WriteReadyBarrier} from '@libs/API'; -import {isBillReport} from '@libs/BillUtils'; import DateUtils from '@libs/DateUtils'; import {getMicroSecondOnyxErrorObject, getMicroSecondOnyxErrorWithTranslationKey} from '@libs/ErrorUtils'; import {isLocalFile} from '@libs/fileDownload/FileUtils'; @@ -37,6 +36,7 @@ import { getUnheldReimbursableTotal, hasViolations as hasViolationsReportUtils, isDeprecatedGroupDM, + isExpenseOrBillReport, isExpenseReport, isGroupChat, isInvoiceReport as isInvoiceReportReportUtils, @@ -1875,7 +1875,7 @@ function calculateDiffAmount( if (!iouReport) { return 0; } - const isExpenseReportLocal = isExpenseReport(iouReport) || isBillReport(iouReport) || isInvoiceReportReportUtils(iouReport); + const isExpenseReportLocal = isExpenseOrBillReport(iouReport) || isInvoiceReportReportUtils(iouReport); const updatedCurrency = getCurrency(updatedTransaction); const currentCurrency = getCurrency(transaction); @@ -1914,7 +1914,7 @@ function getUpdatedMoneyRequestReportData( let updatedMoneyRequestReport: OnyxTypes.OnyxInputOrEntry; if (!iouReport) { updatedMoneyRequestReport = null; - } else if ((isExpenseReport(iouReport) || isBillReport(iouReport) || isInvoiceReportReportUtils(iouReport)) && !Number.isNaN(iouReport.total) && iouReport.total !== undefined) { + } else if ((isExpenseOrBillReport(iouReport) || isInvoiceReportReportUtils(iouReport)) && !Number.isNaN(iouReport.total) && iouReport.total !== undefined) { // Capture previous fresh reimbursable totals before mutating, so the diff applies whether or // not the iouReport already had reimbursableTotal/unheldReimbursableTotal populated locally. const previousReimbursableTotal = getReimbursableTotal(iouReport); diff --git a/src/libs/actions/IOU/UpdateMoneyRequest.ts b/src/libs/actions/IOU/UpdateMoneyRequest.ts index 6dabfeb115e7..4d42e6aafdc5 100644 --- a/src/libs/actions/IOU/UpdateMoneyRequest.ts +++ b/src/libs/actions/IOU/UpdateMoneyRequest.ts @@ -3,7 +3,6 @@ import type {CurrencyListActionsContextType} from '@hooks/useCurrencyList'; import * as API from '@libs/API'; import type {UpdateMoneyRequestParams} from '@libs/API/parameters'; import {WRITE_COMMANDS} from '@libs/API/types'; -import {isBillReport} from '@libs/BillUtils'; import DistanceRequestUtils from '@libs/DistanceRequestUtils'; import {getMicroSecondOnyxErrorWithTranslationKey} from '@libs/ErrorUtils'; import {getChangedTagLevels} from '@libs/MerchantRuleSuggestionUtils'; @@ -18,6 +17,7 @@ import { getReportTransactions, getTransactionDetails, hasViolations as hasViolationsReportUtils, + isExpenseOrBillReport, isExpenseReport, isInvoiceReport as isInvoiceReportReportUtils, isOneTransactionThread, @@ -1944,7 +1944,7 @@ function getUpdateMoneyRequestParams(params: GetUpdateMoneyRequestParamsType): U const errorFields = Object.fromEntries(Object.keys(pendingFields).map((key) => [key, getMicroSecondOnyxErrorWithTranslationKey('iou.error.genericEditFailureMessage')])); const isTransactionOnHold = isOnHold(transaction); - const isFromExpenseReport = isExpenseReport(iouReport) || isBillReport(iouReport) || isInvoiceReportReportUtils(iouReport); + const isFromExpenseReport = isExpenseOrBillReport(iouReport) || isInvoiceReportReportUtils(iouReport); // Drop the waypoints from the changes fed to getUpdatedTransaction when they didn't actually change, // so we skip the waypoints branch that flips isLoading and clobbers amount/merchant before being // re-overridden by the distance branch. diff --git a/src/pages/inbox/report/ReportActionItemContentCreated.tsx b/src/pages/inbox/report/ReportActionItemContentCreated.tsx index 34879dbd2b85..d6b8c4c82c2b 100644 --- a/src/pages/inbox/report/ReportActionItemContentCreated.tsx +++ b/src/pages/inbox/report/ReportActionItemContentCreated.tsx @@ -12,10 +12,9 @@ import useOnyx from '@hooks/useOnyx'; import usePolicy from '@hooks/usePolicy'; import useThemeStyles from '@hooks/useThemeStyles'; -import {isBillReport} from '@libs/BillUtils'; import getNonEmptyStringOnyxID from '@libs/getNonEmptyStringOnyxID'; import {isMessageDeleted, isReversedTransaction as isReversedTransactionReportActionsUtils, isTransactionThread} from '@libs/ReportActionsUtils'; -import {isCanceledTaskReport, isExpenseReport, isInvoiceReport, isIOUReport, isSupportTicket, isTaskReport} from '@libs/ReportUtils'; +import {isCanceledTaskReport, isExpenseOrBillReport, isInvoiceReport, isIOUReport, isSupportTicket, isTaskReport} from '@libs/ReportUtils'; import CONST from '@src/CONST'; import type {TranslationPaths} from '@src/languages/types'; @@ -160,7 +159,7 @@ function ReportActionItemContentCreated({parentReportAction, transactionID, draf ); } - if (isExpenseReport(report) || isBillReport(report) || isIOUReport(report) || isInvoiceReport(report)) { + if (isExpenseOrBillReport(report) || isIOUReport(report) || isInvoiceReport(report)) { return ( ) => { diff --git a/tests/unit/BillPayTest.ts b/tests/unit/BillPayTest.ts index 504c2a63037d..38ea66a4af85 100644 --- a/tests/unit/BillPayTest.ts +++ b/tests/unit/BillPayTest.ts @@ -12,6 +12,7 @@ import { canHoldUnholdReportAction, canIOUBePaid, canRejectReportAction, + isExpenseOrBillReport, isExpenseReport, isMoneyRequestReport, isReportOutstanding, @@ -167,6 +168,7 @@ describe('Bill Pay', () => { expect(isBillReport(bill)).toBe(true); expect(isMoneyRequestReport(bill)).toBe(true); expect(isExpenseReport(bill)).toBe(false); + expect(isExpenseOrBillReport(bill)).toBe(true); expect(isBillReport(expenseReport)).toBe(false); }); From 9206881cafaa1abfa50207eb90d43cd801357ef3 Mon Sep 17 00:00:00 2001 From: Carlos Alvarez Date: Tue, 24 Nov 2026 10:31:56 -0500 Subject: [PATCH 12/17] Use isExpenseOrBillReport where bills need expense report display, edit, and title behavior --- .../ReportActionItem/MoneyRequestView.tsx | 3 +- src/libs/MoneyRequestUtils.ts | 4 +- src/libs/ReportAlternateTextUtils.ts | 10 ++--- src/libs/ReportNameUtils.ts | 2 +- src/libs/ReportUtils.ts | 40 ++++++++++--------- src/libs/SidebarUtils.ts | 4 +- src/libs/computeReportName.ts | 4 +- .../report/ContextMenu/ContextMenuActions.tsx | 4 +- .../actionContents/ActionContentRouter.tsx | 4 +- tests/unit/BillPayTest.ts | 18 +++++++++ 10 files changed, 56 insertions(+), 37 deletions(-) diff --git a/src/components/ReportActionItem/MoneyRequestView.tsx b/src/components/ReportActionItem/MoneyRequestView.tsx index bb95860a1037..eba0afb56bfd 100644 --- a/src/components/ReportActionItem/MoneyRequestView.tsx +++ b/src/components/ReportActionItem/MoneyRequestView.tsx @@ -93,7 +93,6 @@ import { getTransactionDetails, isActionCreator, isExpenseOrBillReport, - isExpenseReport, isInvoiceReport, isOpenReport, isReportApproved, @@ -1898,7 +1897,7 @@ function MoneyRequestView({ /> )} - {!!parentReport && isExpenseReport(parentReport) && !isFromReviewDuplicates && !isFromMergeTransaction && ( + {!!parentReport && isExpenseOrBillReport(parentReport) && !isFromReviewDuplicates && !isFromMergeTransaction && ( , transaction: OnyxEntry !!participant.isPolicyExpenseChat); + return isExpenseOrBillReport(report) || isPolicyExpenseChat(report) || isExpenseRequest(report) || !!transaction?.participants?.some((participant) => !!participant.isPolicyExpenseChat); } type AmountHasUnsavedChangesParams = { diff --git a/src/libs/ReportAlternateTextUtils.ts b/src/libs/ReportAlternateTextUtils.ts index e6045c5903b2..2eff30c72443 100644 --- a/src/libs/ReportAlternateTextUtils.ts +++ b/src/libs/ReportAlternateTextUtils.ts @@ -244,7 +244,7 @@ import { isDM, isDeprecatedGroupDM, isDomainRoom, - isExpenseReport, + isExpenseOrBillReport, isGroupChat as isGroupChatUtil, isInvoiceRoom, isMoneyRequestReport as reportUtilsIsMoneyRequestReport, @@ -800,7 +800,7 @@ function getLastMessageTextForReport({ } else if (isInviteOrRemovedAction(lastReportAction)) { lastMessageTextFromReport = getRoomChangeLogMessage(translate, lastReportAction); } else if (isRenamedAction(lastReportAction)) { - lastMessageTextFromReport = getRenamedAction(translate, lastReportAction, isExpenseReport(report)); + lastMessageTextFromReport = getRenamedAction(translate, lastReportAction, isExpenseOrBillReport(report)); } else if (isActionOfType(lastReportAction, CONST.REPORT.ACTIONS.TYPE.DELETED_TRANSACTION)) { lastMessageTextFromReport = getDeletedTransactionMessage(translate, lastReportAction, convertToDisplayString); } else if (isActionOfType(lastReportAction, CONST.REPORT.ACTIONS.TYPE.UNDELETED_TRANSACTION)) { @@ -991,9 +991,9 @@ function getLastMessageTextForReport({ lastMessageTextFromReport = translate('iou.receiptScanning', {count: scanningTransactions.length}); } else if (report?.transactionCount && report?.transactionCount > 0 && report?.currency) { const latestVisibleMoneyRequestAction = getLatestVisibleMoneyRequestAction(reportID, canUserPerformWrite, sortedActions?.[reportID], visibleReportActionsDataParam); - if (isExpenseReport(report) && latestVisibleMoneyRequestAction) { + if (isExpenseOrBillReport(report) && latestVisibleMoneyRequestAction) { lastMessageTextFromReport = getExpenseReportPreviewText(report, latestVisibleMoneyRequestAction, translate, transactions, convertToDisplayString); - } else if (!isExpenseReport(report)) { + } else if (!isExpenseOrBillReport(report)) { lastMessageTextFromReport = lastVisibleMessage?.lastMessageText; } else if (!isCreatedAction(lastReportAction)) { lastMessageTextFromReport = @@ -1282,7 +1282,7 @@ function getReportAlternateText({ const isThreadReport = isChatThread(report); const isTaskReportFlag = isTaskReport(report); const isAllowedToComment = canUserPerformWriteAction(report, isReportArchived); - const isExpense = isExpenseReport(report); + const isExpense = isExpenseOrBillReport(report); const reportMetadata = reportMetadataParam ?? getReportMetadata(report.reportID); // eslint-disable-next-line @typescript-eslint/no-deprecated const resolvedOneTransactionThreadReportID = oneTransactionThreadReportID ?? deprecatedCachedOneTransactionThreadReportIDs[report.reportID]; diff --git a/src/libs/ReportNameUtils.ts b/src/libs/ReportNameUtils.ts index c4e59f1d662d..ec2cedaef4ad 100644 --- a/src/libs/ReportNameUtils.ts +++ b/src/libs/ReportNameUtils.ts @@ -303,7 +303,7 @@ function getMoneyRequestReportName({ const formattedAmount = convertToDisplayString(moneyRequestTotal, report?.currency); let payerOrApproverName; - if (isExpenseReport(report)) { + if (isExpenseOrBillReport(report)) { const parentReport = getParentReport(report); payerOrApproverName = getPolicyName({report: parentReport ?? report, policy, unavailableTranslation: translate('workspace.common.unavailable')}); } else if (isInvoiceReport(report)) { diff --git a/src/libs/ReportUtils.ts b/src/libs/ReportUtils.ts index 2a9416893bb2..b786a47c5207 100644 --- a/src/libs/ReportUtils.ts +++ b/src/libs/ReportUtils.ts @@ -1500,7 +1500,7 @@ function isInvoiceReport(report: OnyxInputOrEntry): boolean { } function isFinancialReportsForBusinesses(report: OnyxEntry): boolean { - return report?.type === CONST.REPORT.TYPE.EXPENSE || report?.type === CONST.REPORT.TYPE.INVOICE; + return report?.type === CONST.REPORT.TYPE.EXPENSE || report?.type === CONST.REPORT.TYPE.BILL || report?.type === CONST.REPORT.TYPE.INVOICE; } function isNewDotInvoice(invoiceRoomID: string | undefined): boolean { @@ -2928,7 +2928,7 @@ function isExpenseRequest(report: OnyxInputOrEntry): report is Thread { if (isThread(report)) { const parentReportAction = allReportActions?.[`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${report.parentReportID}`]?.[report.parentReportActionID]; const parentReport = getReport(report?.parentReportID, deprecatedAllReports); - return isExpenseReport(parentReport) && !isEmptyObject(parentReportAction) && isTransactionThread(parentReportAction); + return isExpenseOrBillReport(parentReport) && !isEmptyObject(parentReportAction) && isTransactionThread(parentReportAction); } return false; } @@ -5005,7 +5005,7 @@ function getIcons({ if (isExpenseRequest(report)) { return getIconsForExpenseRequest(report, personalDetails, policy, translate, resolvedParentReportAction); } - if (isExpenseReport(report)) { + if (isExpenseOrBillReport(report)) { return getIconsForExpenseReport(report, personalDetails, policy, formatPhoneNumber, translate); } if (isIOUReport(report)) { @@ -5359,7 +5359,7 @@ function getActionTypeForAssigneeToComplete( return CONST.REPORT.ACTION_TYPES_FOR_ASSIGNEE_TO_COMPLETE.TASK; } - if (isProcessingReport(report) && isExpenseReport(report)) { + if (isProcessingReport(report) && isExpenseOrBillReport(report)) { return CONST.REPORT.ACTION_TYPES_FOR_ASSIGNEE_TO_COMPLETE.EXPENSE; } } @@ -5819,7 +5819,7 @@ function getNegatedReportTotals( } function getBillableAndTaxTotal(report: OnyxEntry, transactions: Array>) { - if (!isExpenseReport(report)) { + if (!isExpenseOrBillReport(report)) { return { billableTotal: 0, taxTotal: 0, @@ -5993,7 +5993,7 @@ function canEditReportTitle( getAvailableReportFields(report, Object.values(policy?.fieldList ?? {})).find((reportField) => isReportFieldOfTypeTitle(reportField)) ?? getTitleFieldWithFallback(policy); const isFieldDisabled = isReportFieldDisabled(report, titleField, policy, rules, reportOwnerLogin); - return !isFieldDisabled && isAdminOwnerApproverOrReportOwner(report, policy, currentUserAccountID) && isExpenseReport(report) && isGroupPolicyPolicyUtils(policy); + return !isFieldDisabled && isAdminOwnerApproverOrReportOwner(report, policy, currentUserAccountID) && isExpenseOrBillReport(report) && isGroupPolicyPolicyUtils(policy); } /** @@ -6232,7 +6232,9 @@ function canEditMoneyRequest( const moneyRequestReport = report ?? getReportOrDraftReport({reportID: String(moneyRequestReportID)}); // Without an IOU action, the submitter of an expense report stands in for the requester, because only they can add expenses to it. // This function has no current-user parameter, so it passes the same module-level account ID that isActionRequestor uses. - const isRequestor = isActionlessReportedExpense ? isExpenseReport(moneyRequestReport) && isCurrentUserSubmitter(moneyRequestReport, deprecatedCurrentUserAccountID) : isActionRequestor; + const isRequestor = isActionlessReportedExpense + ? isExpenseOrBillReport(moneyRequestReport) && isCurrentUserSubmitter(moneyRequestReport, deprecatedCurrentUserAccountID) + : isActionRequestor; const isSubmitted = isProcessingReport(moneyRequestReport); if (isIOUReport(moneyRequestReport)) { @@ -6454,8 +6456,8 @@ function canCurrentUserEditExpense( reportPolicy: OnyxEntry, rules: OnyxCollection, ): boolean { - const isAdmin = isExpenseReport(moneyRequestReport) && reportPolicy?.role === CONST.POLICY.ROLE.ADMIN; - const isManager = isExpenseReport(moneyRequestReport) && deprecatedCurrentUserAccountID === moneyRequestReport?.managerID; + const isAdmin = isExpenseOrBillReport(moneyRequestReport) && reportPolicy?.role === CONST.POLICY.ROLE.ADMIN; + const isManager = isExpenseOrBillReport(moneyRequestReport) && deprecatedCurrentUserAccountID === moneyRequestReport?.managerID; const isRequestor = deprecatedCurrentUserAccountID === reportAction?.actorAccountID; const ownerLogin = getLoginByAccountID(moneyRequestReport?.ownerAccountID, getAllPersonalDetails()); const isApprover = @@ -6540,8 +6542,8 @@ function canEditFieldOfMoneyRequest({ // This will be fixed as part of https://github.com/Expensify/Expensify/issues/507850 const reportPolicy = policy ?? getPolicy(moneyRequestReport?.policyID); // Moving an expense to another report weighs these two on their own rather than as part of the combined check. - const isAdmin = isExpenseReport(moneyRequestReport) && reportPolicy?.role === CONST.POLICY.ROLE.ADMIN; - const isManager = isExpenseReport(moneyRequestReport) && deprecatedCurrentUserAccountID === moneyRequestReport?.managerID; + const isAdmin = isExpenseOrBillReport(moneyRequestReport) && reportPolicy?.role === CONST.POLICY.ROLE.ADMIN; + const isManager = isExpenseOrBillReport(moneyRequestReport) && deprecatedCurrentUserAccountID === moneyRequestReport?.managerID; // Admins can add or replace a receipt on an approved expense so a missing receipt can still be provided after approval. const isAdminChangingReceiptOnApprovedReport = isAdmin && fieldToEdit === CONST.EDIT_REQUEST_FIELD.RECEIPT && !isDeleteAction && !isSettled(moneyRequestReport); @@ -6593,7 +6595,7 @@ function canEditFieldOfMoneyRequest({ if (fieldToEdit === CONST.EDIT_REQUEST_FIELD.DISTANCE_RATE) { // The distance rate can be modified only on the distance expense reports - return (isExpenseReport(moneyRequestReport) || isUnreportedExpense) && isDistanceRequest(transaction); + return (isExpenseOrBillReport(moneyRequestReport) || isUnreportedExpense) && isDistanceRequest(transaction); } if (fieldToEdit === CONST.EDIT_REQUEST_FIELD.REPORT) { @@ -7112,7 +7114,7 @@ function getReportPreviewMessage( const parentReport = getParentReport(report); const policyName = getPolicyName({report: parentReport ?? report, policy, unavailableTranslation: translate('workspace.common.unavailable')}); - const payerName = isExpenseReport(report) + const payerName = isExpenseOrBillReport(report) ? policyName : getDisplayNameForParticipant({ accountID: report.managerID, @@ -7324,7 +7326,7 @@ function getReportPreviewReportActionMessage( // report action and read back by every viewer, so it must not follow the locale of whoever happened to build it. These mirror // `workspace.common.unavailable` and `common.hidden` in `src/languages/en.ts`, and ReportUtilsTest asserts they do not drift from them. const policyName = getPolicyName({report: parentReport ?? report, policy, unavailableTranslation: 'Unavailable workspace'}); - const payerName = isExpenseReport(report) + const payerName = isExpenseOrBillReport(report) ? policyName : getDisplayNameForParticipant({ accountID: report.managerID, @@ -12466,7 +12468,7 @@ function shouldReportShowSubscript(report: OnyxEntry, isReportArchived = return true; } - if (isExpenseReport(report)) { + if (isExpenseOrBillReport(report)) { return true; } @@ -12958,7 +12960,7 @@ function getIOUReportActionDisplayMessage( } } - const amount = getTransactionAmount(transaction, !isEmptyObject(iouReport) && isExpenseReport(iouReport), transaction?.reportID === CONST.REPORT.UNREPORTED_REPORT_ID) ?? 0; + const amount = getTransactionAmount(transaction, !isEmptyObject(iouReport) && isExpenseOrBillReport(iouReport), transaction?.reportID === CONST.REPORT.UNREPORTED_REPORT_ID) ?? 0; const formattedAmount = convertToDisplayString(amount, getCurrency(transaction)) ?? ''; const isRequestSettled = isSettled(IOUReportID); const isApproved = isReportApproved({report: iouReport}); @@ -15980,7 +15982,7 @@ function getTransactionSortValue( case CONST.SEARCH.SORT_BY_COLUMNS.TAG_GL_CODE: return getTagGLCode(policyTagLists, getTag(transaction)); case CONST.SEARCH.TABLE_COLUMNS.TOTAL_AMOUNT: - return getTransactionAmount(transaction, isExpenseReport(report), transaction.reportID === CONST.REPORT.UNREPORTED_REPORT_ID); + return getTransactionAmount(transaction, isExpenseOrBillReport(report), transaction.reportID === CONST.REPORT.UNREPORTED_REPORT_ID); case CONST.SEARCH.TABLE_COLUMNS.TOTAL: return Math.abs(transaction.convertedAmount ?? 0); case CONST.SEARCH.TABLE_COLUMNS.DESCRIPTION: @@ -15994,13 +15996,13 @@ function getTransactionSortValue( case CONST.SEARCH.TABLE_COLUMNS.EXCHANGE_RATE: return getExchangeRate(transaction, report?.currency); case CONST.SEARCH.TABLE_COLUMNS.ORIGINAL_AMOUNT: - return getOriginalAmountForDisplay(transaction, isExpenseReport(report)); + return getOriginalAmountForDisplay(transaction, isExpenseOrBillReport(report)); case CONST.SEARCH.TABLE_COLUMNS.MCC: return getMCCForDisplay(transaction.mcc); case CONST.SEARCH.TABLE_COLUMNS.TAX_CODE: return transaction.taxCode ?? ''; case CONST.SEARCH.TABLE_COLUMNS.TAX_AMOUNT: - return getTaxAmount(transaction, isExpenseReport(report)); + return getTaxAmount(transaction, isExpenseOrBillReport(report)); case CONST.SEARCH.TABLE_COLUMNS.TAX_RATE: return getTaxName(translate, policy, transaction) ?? ''; case CONST.SEARCH.TABLE_COLUMNS.CARD: diff --git a/src/libs/SidebarUtils.ts b/src/libs/SidebarUtils.ts index c197eecd8ee0..b2bfe6879909 100644 --- a/src/libs/SidebarUtils.ts +++ b/src/libs/SidebarUtils.ts @@ -67,7 +67,7 @@ import { isChatRoom, isChatThread, isConciergeChatReport, - isExpenseReport, + isExpenseOrBillReport, isExpenseRequest, isHiddenForCurrentUser, isInvoiceReport, @@ -972,7 +972,7 @@ function getOptionData({ result.isConciergeThread = isChatThread(report) && !!conciergeReportID && report.parentReportID === conciergeReportID; result.participants = report.participants; - const isExpense = isExpenseReport(report); + const isExpense = isExpenseOrBillReport(report); const hasMultipleParticipants = participantPersonalDetailList.length > 1 || result.isChatRoom || result.isPolicyExpenseChat || isExpense; const subtitle = getChatRoomSubtitle(report, policy, conciergeReportID, translate, rules, false, isReportArchived); diff --git a/src/libs/computeReportName.ts b/src/libs/computeReportName.ts index 82eed2ecc823..e36740c59d46 100644 --- a/src/libs/computeReportName.ts +++ b/src/libs/computeReportName.ts @@ -165,7 +165,7 @@ import { isChatThread, isClosedExpenseReportWithNoExpenses, isConciergeChatReport, - isExpenseReport, + isExpenseOrBillReport, isGroupChat, isInvoiceReport, isInvoiceRoom, @@ -715,7 +715,7 @@ function computeReportNameBasedOnReportAction({ } if (isRenamedAction(parentReportAction)) { - return getRenamedAction(translate, parentReportAction, isExpenseReport(parentReport)); + return getRenamedAction(translate, parentReportAction, isExpenseOrBillReport(parentReport)); } if (isActionOfType(parentReportAction, CONST.REPORT.ACTIONS.TYPE.RESOLVED_DUPLICATES)) { diff --git a/src/pages/inbox/report/ContextMenu/ContextMenuActions.tsx b/src/pages/inbox/report/ContextMenu/ContextMenuActions.tsx index e5390805dc9c..a37003b6292b 100644 --- a/src/pages/inbox/report/ContextMenu/ContextMenuActions.tsx +++ b/src/pages/inbox/report/ContextMenu/ContextMenuActions.tsx @@ -213,7 +213,7 @@ import { getUnreportedTransactionMessage, getWorkspaceNameUpdatedMessage, isChatThread, - isExpenseReport, + isExpenseOrBillReport, isResolvedSupportTicket, isSelfDM, isSupportTicket, @@ -1386,7 +1386,7 @@ const ContextMenuActions: ContextMenuAction[] = [ } else if (isActionableTrackExpense(reportAction)) { setClipboardMessage(CONST.ACTIONABLE_TRACK_EXPENSE_WHISPER_MESSAGE); } else if (isRenamedAction(reportAction)) { - setClipboardMessage(getRenamedAction(translate, reportAction, isExpenseReport(report))); + setClipboardMessage(getRenamedAction(translate, reportAction, isExpenseOrBillReport(report))); } else if ( isActionOfType(reportAction, CONST.REPORT.ACTIONS.TYPE.SUBMITTED) || isActionOfType(reportAction, CONST.REPORT.ACTIONS.TYPE.SUBMITTED_AND_CLOSED) || diff --git a/src/pages/inbox/report/actionContents/ActionContentRouter.tsx b/src/pages/inbox/report/actionContents/ActionContentRouter.tsx index 6be7e297b8d9..6bbcfa28e50e 100644 --- a/src/pages/inbox/report/actionContents/ActionContentRouter.tsx +++ b/src/pages/inbox/report/actionContents/ActionContentRouter.tsx @@ -58,7 +58,7 @@ import { isTaskAction, isTripPreview, } from '@libs/ReportActionsUtils'; -import {getMovedActionMessage, isExpenseReport, isInvoiceReport} from '@libs/ReportUtils'; +import {getMovedActionMessage, isExpenseOrBillReport, isInvoiceReport} from '@libs/ReportUtils'; import ReportActionItemBasicMessage from '@pages/inbox/report/ReportActionItemBasicMessage'; @@ -535,7 +535,7 @@ function ActionContentRouter({ ); } if (isRenamedAction(action)) { - return ; + return ; } if (isActionOfType(action, CONST.REPORT.ACTIONS.TYPE.INTEGRATION_SYNC_FAILED)) { return ( diff --git a/tests/unit/BillPayTest.ts b/tests/unit/BillPayTest.ts index 38ea66a4af85..05a92bcfe3af 100644 --- a/tests/unit/BillPayTest.ts +++ b/tests/unit/BillPayTest.ts @@ -12,6 +12,8 @@ import { canHoldUnholdReportAction, canIOUBePaid, canRejectReportAction, + canEditReportTitle, + getMoneyRequestSpendBreakdown, isExpenseOrBillReport, isExpenseReport, isMoneyRequestReport, @@ -172,6 +174,22 @@ describe('Bill Pay', () => { expect(isBillReport(expenseReport)).toBe(false); }); + it('shows the total of a bill like the total of an expense report', () => { + // Given a bill and an expense report that both store their total as a negative amount + // When the app computes the totals it displays + // Then both show the same positive total + expect(getMoneyRequestSpendBreakdown(bill).totalDisplaySpend).toBe(125); + expect(getMoneyRequestSpendBreakdown(bill).totalDisplaySpend).toBe(getMoneyRequestSpendBreakdown(expenseReport).totalDisplaySpend); + }); + + it('lets the approver rename a bill', () => { + // Given a submitted bill on a group policy and its approver + // When the app checks whether the approver can edit the title + // Then the approver can rename the bill like an expense report + expect(canEditReportTitle(bill, policy, accountID, undefined, email)).toBe(canEditReportTitle(expenseReport, policy, accountID, undefined, email)); + expect(canEditReportTitle(bill, policy, accountID, undefined, email)).toBe(true); + }); + it('lets only the approver approve a submitted bill', () => { // Given a submitted bill waiting on its approver // When the approver and another user check whether they can approve it, before and after approval From fe71571e94f5319b7f7609b22a4e48f5769d05a7 Mon Sep 17 00:00:00 2001 From: Carlos Alvarez Date: Tue, 24 Nov 2026 13:06:15 -0500 Subject: [PATCH 13/17] Don't open the report history from a bill's next step --- src/components/MoneyReportHeaderNextStep.tsx | 16 +++++++++++++ src/components/MoneyReportHeaderStatusBar.tsx | 16 ++++++++----- .../MoneyReportHeaderNextStepTest.tsx | 23 ++++++++++++++++++- 3 files changed, 48 insertions(+), 7 deletions(-) diff --git a/src/components/MoneyReportHeaderNextStep.tsx b/src/components/MoneyReportHeaderNextStep.tsx index 48c658eaa99c..5f5cd2668f8a 100644 --- a/src/components/MoneyReportHeaderNextStep.tsx +++ b/src/components/MoneyReportHeaderNextStep.tsx @@ -4,6 +4,7 @@ import useLocalize from '@hooks/useLocalize'; import useNetwork from '@hooks/useNetwork'; import useNextStep from '@hooks/useNextStep'; import useOnyx from '@hooks/useOnyx'; +import useThemeStyles from '@hooks/useThemeStyles'; import getNonEmptyStringOnyxID from '@libs/getNonEmptyStringOnyxID'; import {buildNextStepMessage} from '@libs/NextStepUtils'; @@ -14,6 +15,7 @@ import ONYXKEYS from '@src/ONYXKEYS'; import {getReportType} from '@selectors/Report'; import React from 'react'; +import {View} from 'react-native'; import MoneyReportHeaderHistoryButton from './MoneyReportHeaderHistoryButton'; import MoneyReportHeaderStatusBar from './MoneyReportHeaderStatusBar'; @@ -27,6 +29,7 @@ type MoneyReportHeaderNextStepProps = { * Renders the next step status bar or a skeleton loader. */ function MoneyReportHeaderNextStep({reportID}: MoneyReportHeaderNextStepProps) { + const styles = useThemeStyles(); const {isOffline} = useNetwork(); const isLoadingInitialReportActions = useIsReportLoadPending(reportID); const nextStep = useNextStep(reportID); @@ -37,6 +40,19 @@ function MoneyReportHeaderNextStep({reportID}: MoneyReportHeaderNextStepProps) { const showNextStepBar = !!nextStep; const showNextStepSkeleton = !nextStep && !!isLoadingInitialReportActions && !isOffline; + // The report history page doesn't support bills, so a bill's next step doesn't open it. + if (showNextStepBar && reportType === CONST.REPORT.TYPE.BILL) { + return ( + + + + ); + } + if (showNextStepBar) { return ( ; type IconMap = Record; -function MoneyReportHeaderStatusBar({nextStep, reportType}: MoneyReportHeaderStatusBarProps) { +function MoneyReportHeaderStatusBar({nextStep, reportType, shouldShowCaret = true}: MoneyReportHeaderStatusBarProps) { const styles = useThemeStyles(); const theme = useTheme(); const {translate, formatPhoneNumber, dateFnsLocale} = useLocalize(); @@ -46,6 +49,11 @@ function MoneyReportHeaderStatusBar({nextStep, reportType}: MoneyReportHeaderSta const currentUserAccountID = currentUserPersonalDetails.accountID; const messageContent = !nextStep ? '' : buildNextStepMessage(nextStep, translate, dateFnsLocale, currentUserAccountID, formatPhoneNumber, reportType); + const message = ( + + + + ); return ( @@ -57,11 +65,7 @@ function MoneyReportHeaderStatusBar({nextStep, reportType}: MoneyReportHeaderSta fill={nextStep?.iconFill ?? theme.icon} /> - - - - - + {shouldShowCaret ? {message} : message} ); } diff --git a/tests/ui/components/MoneyReportHeaderNextStepTest.tsx b/tests/ui/components/MoneyReportHeaderNextStepTest.tsx index 3d92b6cc984f..08c4c002f319 100644 --- a/tests/ui/components/MoneyReportHeaderNextStepTest.tsx +++ b/tests/ui/components/MoneyReportHeaderNextStepTest.tsx @@ -1,4 +1,4 @@ -import {render, waitFor} from '@testing-library/react-native'; +import {render, screen, waitFor} from '@testing-library/react-native'; import MoneyReportHeaderNextStep from '@components/MoneyReportHeaderNextStep'; import RenderHTML from '@components/RenderHTML'; @@ -94,4 +94,25 @@ describe('MoneyReportHeaderNextStep', () => { ), ); }); + + it.each([ + {reportType: CONST.REPORT.TYPE.BILL, shouldOpenReportHistory: false}, + {reportType: CONST.REPORT.TYPE.EXPENSE, shouldOpenReportHistory: true}, + ])('opens the report history from the next step: $shouldOpenReportHistory for a $reportType report', async ({reportType, shouldOpenReportHistory}) => { + // Given a report that waits on its approver + jest.mocked(useNextStep).mockReturnValue({ + messageKey: CONST.NEXT_STEP.MESSAGE_KEY.WAITING_TO_APPROVE, + icon: CONST.NEXT_STEP.ICONS.HOURGLASS, + actorAccountID: 780072, + }); + await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`, {reportID, type: reportType}); + await waitForBatchedUpdates(); + + // When the header renders the next step + render(); + await waitForBatchedUpdates(); + + // Then only an expense report's next step is a button that opens the report history, which doesn't support bills + expect(screen.queryAllByRole(CONST.ROLE.BUTTON)).toHaveLength(shouldOpenReportHistory ? 1 : 0); + }); }); From 0cd11f5f21523d25ecc980371c4d1010b0d96dfe Mon Sep 17 00:00:00 2001 From: Carlos Alvarez Date: Mon, 30 Nov 2026 12:20:14 -0700 Subject: [PATCH 14/17] Open the report history page for bills on group policies --- src/components/MoneyReportHeaderNextStep.tsx | 16 ------------- src/components/MoneyReportHeaderStatusBar.tsx | 16 +++++-------- .../MoneyReportHeaderStatusBarSection.tsx | 4 ++-- src/libs/ReportUtils.ts | 8 +++++++ src/pages/ReportHistoryPage/index.tsx | 4 ++-- .../MoneyReportHeaderNextStepTest.tsx | 23 +------------------ tests/unit/BillPayTest.ts | 10 ++++++++ 7 files changed, 29 insertions(+), 52 deletions(-) diff --git a/src/components/MoneyReportHeaderNextStep.tsx b/src/components/MoneyReportHeaderNextStep.tsx index 5f5cd2668f8a..48c658eaa99c 100644 --- a/src/components/MoneyReportHeaderNextStep.tsx +++ b/src/components/MoneyReportHeaderNextStep.tsx @@ -4,7 +4,6 @@ import useLocalize from '@hooks/useLocalize'; import useNetwork from '@hooks/useNetwork'; import useNextStep from '@hooks/useNextStep'; import useOnyx from '@hooks/useOnyx'; -import useThemeStyles from '@hooks/useThemeStyles'; import getNonEmptyStringOnyxID from '@libs/getNonEmptyStringOnyxID'; import {buildNextStepMessage} from '@libs/NextStepUtils'; @@ -15,7 +14,6 @@ import ONYXKEYS from '@src/ONYXKEYS'; import {getReportType} from '@selectors/Report'; import React from 'react'; -import {View} from 'react-native'; import MoneyReportHeaderHistoryButton from './MoneyReportHeaderHistoryButton'; import MoneyReportHeaderStatusBar from './MoneyReportHeaderStatusBar'; @@ -29,7 +27,6 @@ type MoneyReportHeaderNextStepProps = { * Renders the next step status bar or a skeleton loader. */ function MoneyReportHeaderNextStep({reportID}: MoneyReportHeaderNextStepProps) { - const styles = useThemeStyles(); const {isOffline} = useNetwork(); const isLoadingInitialReportActions = useIsReportLoadPending(reportID); const nextStep = useNextStep(reportID); @@ -40,19 +37,6 @@ function MoneyReportHeaderNextStep({reportID}: MoneyReportHeaderNextStepProps) { const showNextStepBar = !!nextStep; const showNextStepSkeleton = !nextStep && !!isLoadingInitialReportActions && !isOffline; - // The report history page doesn't support bills, so a bill's next step doesn't open it. - if (showNextStepBar && reportType === CONST.REPORT.TYPE.BILL) { - return ( - - - - ); - } - if (showNextStepBar) { return ( ; type IconMap = Record; -function MoneyReportHeaderStatusBar({nextStep, reportType, shouldShowCaret = true}: MoneyReportHeaderStatusBarProps) { +function MoneyReportHeaderStatusBar({nextStep, reportType}: MoneyReportHeaderStatusBarProps) { const styles = useThemeStyles(); const theme = useTheme(); const {translate, formatPhoneNumber, dateFnsLocale} = useLocalize(); @@ -49,11 +46,6 @@ function MoneyReportHeaderStatusBar({nextStep, reportType, shouldShowCaret = tru const currentUserAccountID = currentUserPersonalDetails.accountID; const messageContent = !nextStep ? '' : buildNextStepMessage(nextStep, translate, dateFnsLocale, currentUserAccountID, formatPhoneNumber, reportType); - const message = ( - - - - ); return ( @@ -65,7 +57,11 @@ function MoneyReportHeaderStatusBar({nextStep, reportType, shouldShowCaret = tru fill={nextStep?.iconFill ?? theme.icon} /> - {shouldShowCaret ? {message} : message} + + + + + ); } diff --git a/src/components/MoneyReportHeaderStatusBarSection.tsx b/src/components/MoneyReportHeaderStatusBarSection.tsx index 8565ca351c06..8add563196e0 100644 --- a/src/components/MoneyReportHeaderStatusBarSection.tsx +++ b/src/components/MoneyReportHeaderStatusBarSection.tsx @@ -5,7 +5,7 @@ import useTheme from '@hooks/useTheme'; import useTransactionsAndViolationsForReport from '@hooks/useTransactionsAndViolationsForReport'; import getNonEmptyStringOnyxID from '@libs/getNonEmptyStringOnyxID'; -import {isGroupPolicyExpenseReport, isProcessingReport} from '@libs/ReportUtils'; +import {isGroupPolicyExpenseOrBillReport, isProcessingReport} from '@libs/ReportUtils'; import {getUnsuppressibleBrokenConnectionTransactionID} from '@libs/TransactionUtils'; import variables from '@styles/variables'; @@ -55,7 +55,7 @@ function MoneyReportHeaderStatusBarSection({reportID, statusBarType, iouTransact /> ); - const canOpenReportHistory = isGroupPolicyExpenseReport(moneyRequestReport, policy?.type); + const canOpenReportHistory = isGroupPolicyExpenseOrBillReport(moneyRequestReport, policy?.type); const getStatusBar = (icon: React.ReactNode, description: string) => { const statusBar = ( , policyType: strin return isExpenseReport(report) && isGroupPolicyByType(policyType); } +/** + * Checks if a report is an expense report or a bill on a group policy. Their report history pages show the same steps. + */ +function isGroupPolicyExpenseOrBillReport(report: OnyxEntry, policyType: string | undefined): boolean { + return isExpenseOrBillReport(report) && isGroupPolicyByType(policyType); +} + /** * Checks if the supplied report is an invoice report in Open state and status. */ @@ -16468,6 +16475,7 @@ export { isSupportTicket, isOptimisticPersonalDetail, isGroupPolicyExpenseReport, + isGroupPolicyExpenseOrBillReport, isPayer, isPolicyAdmin, isPolicyExpenseChat, diff --git a/src/pages/ReportHistoryPage/index.tsx b/src/pages/ReportHistoryPage/index.tsx index e4fcafebeccf..cddae3fb41ec 100644 --- a/src/pages/ReportHistoryPage/index.tsx +++ b/src/pages/ReportHistoryPage/index.tsx @@ -19,7 +19,7 @@ import Navigation from '@libs/Navigation/Navigation'; import type {PlatformStackScreenProps} from '@libs/Navigation/PlatformStackNavigation/types'; import type {ReportHistoryNavigatorParamList} from '@libs/Navigation/types'; import {hasDynamicExternalWorkflow} from '@libs/PolicyUtils'; -import {isGroupPolicyExpenseReport, isOpenExpenseReport, shouldShowMarkAsDone} from '@libs/ReportUtils'; +import {isGroupPolicyExpenseOrBillReport, isOpenExpenseReport, shouldShowMarkAsDone} from '@libs/ReportUtils'; import type {WithReportOrNotFoundProps} from '@pages/inbox/report/withReportOrNotFound'; import withReportOrNotFound from '@pages/inbox/report/withReportOrNotFound'; @@ -83,7 +83,7 @@ function ReportHistoryPage({report}: ReportHistoryPageProps) { testID="ReportHistoryPage" shouldShowOfflineIndicator={false} > - + Navigation.goBack(backPath)} diff --git a/tests/ui/components/MoneyReportHeaderNextStepTest.tsx b/tests/ui/components/MoneyReportHeaderNextStepTest.tsx index 08c4c002f319..3d92b6cc984f 100644 --- a/tests/ui/components/MoneyReportHeaderNextStepTest.tsx +++ b/tests/ui/components/MoneyReportHeaderNextStepTest.tsx @@ -1,4 +1,4 @@ -import {render, screen, waitFor} from '@testing-library/react-native'; +import {render, waitFor} from '@testing-library/react-native'; import MoneyReportHeaderNextStep from '@components/MoneyReportHeaderNextStep'; import RenderHTML from '@components/RenderHTML'; @@ -94,25 +94,4 @@ describe('MoneyReportHeaderNextStep', () => { ), ); }); - - it.each([ - {reportType: CONST.REPORT.TYPE.BILL, shouldOpenReportHistory: false}, - {reportType: CONST.REPORT.TYPE.EXPENSE, shouldOpenReportHistory: true}, - ])('opens the report history from the next step: $shouldOpenReportHistory for a $reportType report', async ({reportType, shouldOpenReportHistory}) => { - // Given a report that waits on its approver - jest.mocked(useNextStep).mockReturnValue({ - messageKey: CONST.NEXT_STEP.MESSAGE_KEY.WAITING_TO_APPROVE, - icon: CONST.NEXT_STEP.ICONS.HOURGLASS, - actorAccountID: 780072, - }); - await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`, {reportID, type: reportType}); - await waitForBatchedUpdates(); - - // When the header renders the next step - render(); - await waitForBatchedUpdates(); - - // Then only an expense report's next step is a button that opens the report history, which doesn't support bills - expect(screen.queryAllByRole(CONST.ROLE.BUTTON)).toHaveLength(shouldOpenReportHistory ? 1 : 0); - }); }); diff --git a/tests/unit/BillPayTest.ts b/tests/unit/BillPayTest.ts index 05a92bcfe3af..e4460350a38d 100644 --- a/tests/unit/BillPayTest.ts +++ b/tests/unit/BillPayTest.ts @@ -15,6 +15,7 @@ import { canEditReportTitle, getMoneyRequestSpendBreakdown, isExpenseOrBillReport, + isGroupPolicyExpenseOrBillReport, isExpenseReport, isMoneyRequestReport, isReportOutstanding, @@ -190,6 +191,15 @@ describe('Bill Pay', () => { expect(canEditReportTitle(bill, policy, accountID, undefined, email)).toBe(true); }); + it('opens the report history of a bill on a group policy', () => { + // Given a bill and an expense report on a group policy, and a bill on a personal policy + // When the app checks whether the report history page can show them + // Then it shows the bill like the expense report, and only on a group policy + expect(isGroupPolicyExpenseOrBillReport(bill, CONST.POLICY.TYPE.CORPORATE)).toBe(true); + expect(isGroupPolicyExpenseOrBillReport(expenseReport, CONST.POLICY.TYPE.CORPORATE)).toBe(true); + expect(isGroupPolicyExpenseOrBillReport(bill, CONST.POLICY.TYPE.PERSONAL)).toBe(false); + }); + it('lets only the approver approve a submitted bill', () => { // Given a submitted bill waiting on its approver // When the approver and another user check whether they can approve it, before and after approval From 4ad26596e982f6e99b93198df7a2df4517539c96 Mon Sep 17 00:00:00 2001 From: Carlos Alvarez Date: Tue, 1 Dec 2026 08:46:46 -0700 Subject: [PATCH 15/17] Fix bill test calls after main changed their signatures --- tests/unit/BillPayTest.ts | 4 ++-- tests/unit/NextStepUtilsTest.ts | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/tests/unit/BillPayTest.ts b/tests/unit/BillPayTest.ts index 88ae06aa82c7..32817a76cdf3 100644 --- a/tests/unit/BillPayTest.ts +++ b/tests/unit/BillPayTest.ts @@ -187,8 +187,8 @@ describe('Bill Pay', () => { // Given a submitted bill on a group policy and its approver // When the app checks whether the approver can edit the title // Then the approver can rename the bill like an expense report - expect(canEditReportTitle(bill, policy, accountID, undefined, email, email)).toBe(canEditReportTitle(expenseReport, policy, accountID, undefined, email, email)); - expect(canEditReportTitle(bill, policy, accountID, undefined, email, email)).toBe(true); + expect(canEditReportTitle(bill, policy, accountID, undefined, email, email, [])).toBe(canEditReportTitle(expenseReport, policy, accountID, undefined, email, email, [])); + expect(canEditReportTitle(bill, policy, accountID, undefined, email, email, [])).toBe(true); }); it('opens the report history of a bill on a group policy', () => { diff --git a/tests/unit/NextStepUtilsTest.ts b/tests/unit/NextStepUtilsTest.ts index 2f0524df6cc9..f4133231036f 100644 --- a/tests/unit/NextStepUtilsTest.ts +++ b/tests/unit/NextStepUtilsTest.ts @@ -787,6 +787,7 @@ describe('libs/NextStepUtils', () => { // When the bill is approved const result = buildOptimisticNextStep({ rules: undefined, + personalDetailsByLogins, report: bill, policy: manualPolicy, currentUserAccountIDParam: currentUserAccountID, From e52986115a242d12261a4815ccc3c0e963671bfc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lucien=20Akchot=C3=A9?= Date: Wed, 2 Dec 2026 07:38:37 +0100 Subject: [PATCH 16/17] pass `policyApprovalRules` in BillPayTest --- tests/unit/BillPayTest.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/unit/BillPayTest.ts b/tests/unit/BillPayTest.ts index 32817a76cdf3..03a0621df3df 100644 --- a/tests/unit/BillPayTest.ts +++ b/tests/unit/BillPayTest.ts @@ -123,6 +123,7 @@ function getSecondaryActions(report: Report) { reportActions: [createIOUAction(report)], policies: {[`${ONYXKEYS.COLLECTION.POLICY}${policy.id}`]: policy}, rules: undefined, + policyApprovalRules: undefined, cardList: undefined, }); } From 64bb941d6d0683205d58353e9926bfcb78cc4fdc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lucien=20Akchot=C3=A9?= Date: Wed, 2 Dec 2026 07:38:39 +0100 Subject: [PATCH 17/17] pass archived flag in useConfirmApproval test --- tests/unit/hooks/useConfirmApprovalTest.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/unit/hooks/useConfirmApprovalTest.ts b/tests/unit/hooks/useConfirmApprovalTest.ts index c8f264ac9086..7824ab6fa18b 100644 --- a/tests/unit/hooks/useConfirmApprovalTest.ts +++ b/tests/unit/hooks/useConfirmApprovalTest.ts @@ -63,7 +63,7 @@ describe('useConfirmApproval', () => { await waitForBatchedUpdates(); const startApprovedAnimation = jest.fn(); - const {result} = renderHook(() => useConfirmApproval(REPORT_ID, startApprovedAnimation)); + const {result} = renderHook(() => useConfirmApproval(REPORT_ID, startApprovedAnimation, false)); await waitForBatchedUpdates(); act(() => {