From 85037a02b53a7c84721f0763871d828fa70c4709 Mon Sep 17 00:00:00 2001 From: Monil Bhavsar Date: Mon, 5 Oct 2026 21:22:55 +0530 Subject: [PATCH] Revert "Merge pull request #101226 from lorretheboy/fix-v2/95750" This reverts commit 06d44f6ff70e43b27cc7a6943f2452eb2a8f35bc, reversing changes made to 901155d74da8954c96aada81b94f0c1e4415ceac. --- .../OptionRowLHN/OptionRowLHNData.tsx | 2 - .../ListItem/ExpenseReportListItem.tsx | 3 - .../ListItem/ReportListItemHeader.tsx | 2 - .../ListItem/TransactionListItem/index.tsx | 2 - src/components/SettlementButton/index.tsx | 5 +- src/hooks/usePaymentContext.tsx | 5 +- src/hooks/useSearchBulkActions.ts | 8 +- src/libs/PolicyPaymentUtils.ts | 61 --------- src/libs/PolicyUtils.ts | 12 -- src/libs/ReportAlternateTextUtils.ts | 13 -- src/libs/ReportNameUtils.ts | 8 +- src/libs/ReportPreviewActionUtils.ts | 10 +- src/libs/ReportPrimaryActionUtils.ts | 13 +- src/libs/ReportSecondaryActionUtils.ts | 37 ++--- src/libs/ReportUtils.ts | 70 ++-------- src/libs/SidebarUtils.ts | 6 - src/libs/actions/IOU/PayMoneyRequest.ts | 9 -- src/libs/actions/IOU/ReportWorkflow.ts | 11 +- src/libs/actions/Search.ts | 18 +-- src/libs/getBankAccountLastFourDigits.ts | 50 +------ .../report/ContextMenu/ContextMenuActions.tsx | 2 +- .../actionContents/IouReportActionMessage.tsx | 6 +- .../report/actionContents/PaymentContent.tsx | 12 +- src/selectors/Policy.ts | 7 +- tests/actions/IOUTest/ReportWorkflowTest.ts | 76 ----------- tests/actions/ReportPreviewActionUtilsTest.ts | 90 +------------ tests/unit/PaymentUtilsTest.ts | 66 +-------- tests/unit/PolicyUtilsTest.ts | 103 +------------- tests/unit/ReportPrimaryActionUtilsTest.ts | 48 ------- tests/unit/ReportSecondaryActionUtilsTest.ts | 105 +-------------- tests/unit/ReportUtilsTest.ts | 127 +++--------------- .../Search/handleActionButtonPressTest.ts | 4 - .../unit/getBankAccountLastFourDigitsTest.ts | 107 ++------------- 33 files changed, 104 insertions(+), 994 deletions(-) delete mode 100644 src/libs/PolicyPaymentUtils.ts diff --git a/src/components/LHNOptionsList/OptionRowLHN/OptionRowLHNData.tsx b/src/components/LHNOptionsList/OptionRowLHN/OptionRowLHNData.tsx index 2bfb0e791321..e90e1e05fb5a 100644 --- a/src/components/LHNOptionsList/OptionRowLHN/OptionRowLHNData.tsx +++ b/src/components/LHNOptionsList/OptionRowLHN/OptionRowLHNData.tsx @@ -132,7 +132,6 @@ function OptionRowLHNData({ const [policyTags] = useOnyx(`${ONYXKEYS.COLLECTION.POLICY_TAGS}${fullReport?.policyID}`); const [isTrackIntentUser] = useOnyx(ONYXKEYS.NVP_INTRO_SELECTED, {selector: isTrackIntentUserSelector}); const [rules] = useOnyx(ONYXKEYS.COLLECTION.RULE); - const [bankAccountList] = useOnyx(ONYXKEYS.BANK_ACCOUNT_LIST); const card = useGetExpensifyCardFromReportAction({reportAction: lastAction, policyID: fullReport?.policyID}); @@ -178,7 +177,6 @@ function OptionRowLHNData({ isTrackIntentUser, formatPhoneNumber, rules, - bankAccountList, }); // For single-sender IOUs, trim to the sender's avatar to match the header. diff --git a/src/components/Search/SearchList/ListItem/ExpenseReportListItem.tsx b/src/components/Search/SearchList/ListItem/ExpenseReportListItem.tsx index 15dd5c010b1e..9cc00e330b80 100644 --- a/src/components/Search/SearchList/ListItem/ExpenseReportListItem.tsx +++ b/src/components/Search/SearchList/ListItem/ExpenseReportListItem.tsx @@ -251,7 +251,6 @@ function ExpenseReportListItemInner({ delegateEmail, delegateAccountID, conciergeChat, - bankAccountList, } = useReportPaymentContext({ chatReportPolicyID: chatReport?.policyID, }); @@ -323,7 +322,6 @@ function ExpenseReportListItemInner({ allViolations: liveViolationsForSnapshotTransactions, rules, conciergeChat, - bankAccountList, }); }, [ currentSearchHash, @@ -368,7 +366,6 @@ function ExpenseReportListItemInner({ liveViolationsForSnapshotTransactions, rules, conciergeChat, - bankAccountList, shouldShowMarkAsDoneCopy, ]); diff --git a/src/components/Search/SearchList/ListItem/ReportListItemHeader.tsx b/src/components/Search/SearchList/ListItem/ReportListItemHeader.tsx index 7eec94f816e1..924bbce28f73 100644 --- a/src/components/Search/SearchList/ListItem/ReportListItemHeader.tsx +++ b/src/components/Search/SearchList/ListItem/ReportListItemHeader.tsx @@ -301,7 +301,6 @@ function ReportListItemHeaderInner({ delegateEmail, delegateAccountID, conciergeChat, - bankAccountList, } = useReportPaymentContext({ chatReportPolicyID: chatReport?.policyID, }); @@ -356,7 +355,6 @@ function ReportListItemHeaderInner({ allViolations, rules, conciergeChat, - bankAccountList, }); }; return !isLargeScreenWidth ? ( diff --git a/src/components/Search/SearchList/ListItem/TransactionListItem/index.tsx b/src/components/Search/SearchList/ListItem/TransactionListItem/index.tsx index b46e64653255..44cfa441b498 100644 --- a/src/components/Search/SearchList/ListItem/TransactionListItem/index.tsx +++ b/src/components/Search/SearchList/ListItem/TransactionListItem/index.tsx @@ -161,7 +161,6 @@ function TransactionListItemInner({ delegateEmail, delegateAccountID, conciergeChat, - bankAccountList, } = useReportPaymentContext({ chatReportPolicyID: chatReport?.policyID, }); @@ -267,7 +266,6 @@ function TransactionListItemInner({ allViolations, rules, conciergeChat, - bankAccountList, }); }; diff --git a/src/components/SettlementButton/index.tsx b/src/components/SettlementButton/index.tsx index 768b63c42ae5..9ba745cf70c2 100644 --- a/src/components/SettlementButton/index.tsx +++ b/src/components/SettlementButton/index.tsx @@ -29,7 +29,6 @@ import {getLastPolicyBankAccountID, getLastPolicyPaymentMethod} from '@libs/acti import {isBankAccountPartiallySetup, showUnlockAlreadyRequestedModal} from '@libs/BankAccountUtils'; import Navigation from '@libs/Navigation/Navigation'; import {formatPaymentMethods, getActivePaymentType, getBusinessBankAccountOptions, matchesCurrency} from '@libs/PaymentUtils'; -import {canAccessPolicyBankAccount} from '@libs/PolicyPaymentUtils'; import {isPaidGroupPolicy, isPolicyAdmin, sortPoliciesByName} from '@libs/PolicyUtils'; import {hasRequestFromCurrentAccount} from '@libs/ReportActionsUtils'; import { @@ -152,8 +151,8 @@ function SettlementButton({ const formattedPaymentMethods = formatPaymentMethods(bankAccountList ?? {}, fundList ?? {}, styles, translate); const hasIntentToPay = ((formattedPaymentMethods.length === 1 && isIOUReport(iouReport)) || - (canAccessPolicyBankAccount(policy, bankAccountList) && - (policy?.achAccount?.state === CONST.BANK_ACCOUNT.STATE.OPEN || policy?.achAccount?.state === CONST.BANK_ACCOUNT.STATE.LOCKED))) && + policy?.achAccount?.state === CONST.BANK_ACCOUNT.STATE.OPEN || + policy?.achAccount?.state === CONST.BANK_ACCOUNT.STATE.LOCKED) && !lastPaymentMethod; const {isBetaEnabled} = usePermissions(); const [introSelected] = useOnyx(ONYXKEYS.NVP_INTRO_SELECTED); diff --git a/src/hooks/usePaymentContext.tsx b/src/hooks/usePaymentContext.tsx index b6e66e28ba5d..7875d3496bec 100644 --- a/src/hooks/usePaymentContext.tsx +++ b/src/hooks/usePaymentContext.tsx @@ -4,7 +4,7 @@ import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import {delegateEmailSelector} from '@src/selectors/Account'; import {hasSeenTourSelector} from '@src/selectors/Onboarding'; -import type {BankAccountList, BillingGraceEndPeriod, IntroSelected, Policy, Report} from '@src/types/onyx'; +import type {BillingGraceEndPeriod, IntroSelected, Policy, Report} from '@src/types/onyx'; import type {OnyxCollection, OnyxEntry} from 'react-native-onyx'; @@ -36,7 +36,6 @@ type PaymentContextValue = { defaultWorkspaceName: string; delegateEmail: string | undefined; delegateAccountID: number | undefined; - bankAccountList: OnyxEntry; }; type ReportPaymentContextValue = PaymentContextValue & { @@ -69,7 +68,6 @@ function usePaymentContextValues(): PaymentContextValue { const [delegateEmail] = useOnyx(ONYXKEYS.ACCOUNT, {selector: delegateEmailSelector}); const delegateAccountID = useDelegateAccountID(); const activePolicy = usePolicy(activePolicyID); - const [bankAccountList] = useOnyx(ONYXKEYS.BANK_ACCOUNT_LIST); const defaultWorkspaceName = generateDefaultWorkspaceName(email ?? '', displayName, lastWorkspaceNumber, translate); @@ -91,7 +89,6 @@ function usePaymentContextValues(): PaymentContextValue { defaultWorkspaceName, delegateEmail, delegateAccountID, - bankAccountList, }; } diff --git a/src/hooks/useSearchBulkActions.ts b/src/hooks/useSearchBulkActions.ts index 9d1677cbf871..20a48fe3b36d 100644 --- a/src/hooks/useSearchBulkActions.ts +++ b/src/hooks/useSearchBulkActions.ts @@ -53,7 +53,6 @@ import Navigation from '@libs/Navigation/Navigation'; import TransitionTracker from '@libs/Navigation/TransitionTracker'; import Parser from '@libs/Parser'; import {getLoginByAccountID} from '@libs/PersonalDetailsUtils'; -import {canAccessPolicyBankAccount} from '@libs/PolicyPaymentUtils'; import {getConnectedIntegration, isAdminOfCardEnabledPolicy, isSubmitPolicy} from '@libs/PolicyUtils'; import {getReportAccountingExportActions, isMergeActionForSelectedTransactions} from '@libs/ReportSecondaryActionUtils'; import { @@ -1035,10 +1034,7 @@ function useSearchBulkActions({queryJSON}: UseSearchBulkActionsParams) { const policyIDsWithVBBA = useMemo(() => { const result = []; for (const policy of Object.values(policies ?? {})) { - // Bulk pay funds from the workspace bank account when no account was picked in the menu, so a workspace only - // counts here if the workspace account is actually shared with the current user. Anyone else has to open the - // report and pick an account of their own. That includes a payer the account was never shared with. - if (!policy || !canAccessPolicyBankAccount(policy, bankAccountList)) { + if (!policy?.achAccount?.bankAccountID) { continue; } @@ -1046,7 +1042,7 @@ function useSearchBulkActions({queryJSON}: UseSearchBulkActionsParams) { } return result; - }, [policies, bankAccountList]); + }, [policies]); const exportSearchData = searchResults?.data; const exportSearchType = searchResults?.search.type ?? queryJSON?.type; diff --git a/src/libs/PolicyPaymentUtils.ts b/src/libs/PolicyPaymentUtils.ts deleted file mode 100644 index e0eff6e1be73..000000000000 --- a/src/libs/PolicyPaymentUtils.ts +++ /dev/null @@ -1,61 +0,0 @@ -import type {BankAccount, BankAccountList, Policy} from '@src/types/onyx'; - -import type {OnyxEntry} from 'react-native-onyx'; - -import {getKnownAccountIDByLogin} from './PersonalDetailsUtils'; - -/** - * The policy fields that identify the workspace bank account and who pays from it. Components that only attribute a - * payment subscribe to this shape (see `policyPaymentAttributionSelector`) instead of the whole policy. - */ -type PolicyPaymentAttribution = Pick; - -/** - * The workspace's connected bank account as it appears in the current user's own `bankAccountList`, or undefined when - * the account is not shared with them. - */ -function getAccessiblePolicyBankAccount(policy: OnyxEntry, bankAccountList: OnyxEntry): BankAccount | undefined { - const policyBankAccountID = policy?.achAccount?.bankAccountID; - - if (!policyBankAccountID) { - return undefined; - } - - return bankAccountList?.[policyBankAccountID]; -} - -/** - * Whether the user can actually pay from the workspace's connected bank account. This gates every place that would - * otherwise default a payment to `policy.achAccount`. Paying with, or displaying, an account the user has no access to - * is always wrong. See `getAccessiblePolicyBankAccount` for why `bankAccountList` is the authority. - */ -function canAccessPolicyBankAccount(policy: OnyxEntry, bankAccountList: OnyxEntry): boolean { - return !!getAccessiblePolicyBankAccount(policy, bankAccountList); -} - -/** - * Whether a payment made by `payerAccountID` can be assumed to have been funded by the workspace's connected bank - * account. - */ -function wasPaidWithPolicyBankAccount(policy: OnyxEntry, payerAccountID: number | undefined): boolean { - const reimburserEmail = policy?.reimburser ?? policy?.achAccount?.reimburser; - - // Without a designated payer, any admin pays from the workspace account, so it is the right guess. - if (!reimburserEmail) { - return true; - } - - const reimburserAccountID = getKnownAccountIDByLogin(reimburserEmail); - - // The viewer may not have the payer's personal details loaded. We can't rule the payer out, so keep the workspace - // account instead of hiding it for everyone who hasn't interacted with the payer. - if (reimburserAccountID === undefined) { - return true; - } - - return !!payerAccountID && reimburserAccountID === payerAccountID; -} - -export {canAccessPolicyBankAccount, getAccessiblePolicyBankAccount, wasPaidWithPolicyBankAccount}; - -export type {PolicyPaymentAttribution}; diff --git a/src/libs/PolicyUtils.ts b/src/libs/PolicyUtils.ts index 2a38ecaed167..3767fbdcd717 100644 --- a/src/libs/PolicyUtils.ts +++ b/src/libs/PolicyUtils.ts @@ -818,17 +818,6 @@ function isPolicyPayer(policy: OnyxEntry, currentUserLogin: string | und return canPayOnPolicy && currentUserLogin === reimburserEmail; } -/** - * Whether an admin/payments admin who isn't the designated workspace payer can still pay reports on the policy. - * Unlike `isPolicyPayer`/`isPayer`, this must not drive active prompting (badges, GBRs, next steps, pay to-dos), which stay payer-only. - */ -function canAdminPayReport(policy: OnyxInputOrEntry, currentUserLogin: string): boolean { - const isReimbursementConfigured = - policy?.reimbursementChoice === CONST.POLICY.REIMBURSEMENT_CHOICES.REIMBURSEMENT_YES || policy?.reimbursementChoice === CONST.POLICY.REIMBURSEMENT_CHOICES.REIMBURSEMENT_MANUAL; - - return isGroupPolicy(policy) && isReimbursementConfigured && canMemberWrite(policy, currentUserLogin, CONST.POLICY.POLICY_FEATURE.WORKFLOWS_PAYMENTS); -} - /** Check if the passed employee is an approver in the policy's employeeList */ function isPolicyApprover(policy: OnyxInputOrEntry, employeeLogin: string) { if (policy?.approver === employeeLogin) { @@ -3723,7 +3712,6 @@ export { isPolicyMember, isMemberInHomeAndOfficeWorkspace, isPolicyPayer, - canAdminPayReport, getReimburserEmail, getOwnerChangePayerSuccessData, PAYER_ROLES, diff --git a/src/libs/ReportAlternateTextUtils.ts b/src/libs/ReportAlternateTextUtils.ts index 98484cc99221..cb664d049ddc 100644 --- a/src/libs/ReportAlternateTextUtils.ts +++ b/src/libs/ReportAlternateTextUtils.ts @@ -5,7 +5,6 @@ import type {CurrencyListActionsContextType} from '@hooks/useCurrencyList'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import type { - BankAccountList, Card, CardList, PersonalDetails, @@ -503,7 +502,6 @@ function getLastMessageTextForReport({ oneTransactionThreadReportID, lastOriginalAction, rules, - bankAccountList, }: { translate: LocalizedTranslate; convertToDisplayString: CurrencyListActionsContextType['convertToDisplayString']; @@ -531,9 +529,6 @@ function getLastMessageTextForReport({ oneTransactionThreadReportID?: string; lastOriginalAction?: OnyxEntry; rules: OnyxCollection; - - /** The current user's bank accounts, used to name the account a report was paid with in the preview. */ - bankAccountList?: OnyxEntry; }): string { const reportID = report?.reportID; const canUserPerformWrite = canUserPerformWriteAction(report, isReportArchived); @@ -603,7 +598,6 @@ function getLastMessageTextForReport({ shouldConsiderScanningReceiptOrPendingRoute: true, policy, isForListPreview: true, - bankAccountList, }); lastMessageTextFromReport = formatReportLastMessageText(Parser.htmlToText(properSchemaForMoneyRequestMessage)); } else if (isReportPreviewAction(lastReportAction)) { @@ -632,7 +626,6 @@ function getLastMessageTextForReport({ policy, isForListPreview: true, originalReportAction: lastReportAction, - bankAccountList, }); lastMessageTextFromReport = formatReportLastMessageText(Parser.htmlToText(reportPreviewMessage)); } @@ -978,7 +971,6 @@ function getLastMessageTextForReport({ shouldConsiderScanningReceiptOrPendingRoute: true, policy, isForListPreview: true, - bankAccountList, }), ), ) || lastVisibleMessage?.lastMessageText; @@ -1196,9 +1188,6 @@ type GetReportAlternateTextParams = { convertToDisplayString: CurrencyListActionsContextType['convertToDisplayString']; convertToDisplayStringWithoutCurrency: CurrencyListActionsContextType['convertToDisplayStringWithoutCurrency']; rules: OnyxCollection; - - /** The current user's bank accounts, used to name the account a report was paid with in the preview. */ - bankAccountList?: OnyxEntry; }; /** @@ -1237,7 +1226,6 @@ function getReportAlternateText({ convertToDisplayString, convertToDisplayStringWithoutCurrency, rules, - bankAccountList, }: GetReportAlternateTextParams): string | undefined { let alternateText: string | undefined; const isChatRoomReport = isChatRoom(report); @@ -1302,7 +1290,6 @@ function getReportAlternateText({ oneTransactionThreadReportID: resolvedOneTransactionThreadReportID, lastOriginalAction, rules, - bankAccountList, }); const getLastActorDisplayNamePrefix = () => diff --git a/src/libs/ReportNameUtils.ts b/src/libs/ReportNameUtils.ts index 8ab94854f153..923629556429 100644 --- a/src/libs/ReportNameUtils.ts +++ b/src/libs/ReportNameUtils.ts @@ -37,7 +37,6 @@ import createDynamicRoute from './Navigation/helpers/dynamicRoutesUtils/createDy import {getCurrentUserEmail} from './Network/NetworkStore'; import Parser from './Parser'; import {getPersonalDetailsByID, temporaryGetDisplayNameOrDefault} from './PersonalDetailsUtils'; -import {wasPaidWithPolicyBankAccount} from './PolicyPaymentUtils'; import {getCleanedTagName, isPolicyAdmin, isPolicyFieldListEmpty} from './PolicyUtils'; import { getActionableCard3DSTransactionApprovalMessage, @@ -853,12 +852,7 @@ function computeReportNameBasedOnReportAction({ if (isMoneyRequestAction(parentReportAction)) { const originalMessage = getOriginalMessage(parentReportAction); - - // Prefer the account stored on the action: the payer is not always the workspace payer, so the policy's - // ACH account can belong to a different bank account than the one the report was actually paid with, and - // attributing it to a non-payer admin's payment shows a different account to every other viewer. - const policyAccountNumber = wasPaidWithPolicyBankAccount(reportPolicy, parentReportAction?.actorAccountID) ? reportPolicy?.achAccount?.accountNumber : undefined; - const last4Digits = (originalMessage?.accountNumber ?? policyAccountNumber)?.slice(-4) ?? ''; + const last4Digits = originalMessage?.accountNumber?.slice(-4) ?? reportPolicy?.achAccount?.accountNumber?.slice(-4) ?? ''; if (originalMessage?.type === CONST.IOU.REPORT_ACTION_TYPE.PAY) { if (originalMessage.paymentType === CONST.IOU.PAYMENT_TYPE.ELSEWHERE) { diff --git a/src/libs/ReportPreviewActionUtils.ts b/src/libs/ReportPreviewActionUtils.ts index c21af6716a21..dbb7bc7de2cd 100644 --- a/src/libs/ReportPreviewActionUtils.ts +++ b/src/libs/ReportPreviewActionUtils.ts @@ -6,12 +6,14 @@ import type {ValueOf} from 'type-fest'; import { arePaymentsEnabled, - canAdminPayReport, + canMemberWrite, + getReimbursementChoice, getSubmitToAccountID, getValidConnectedIntegration, hasDynamicExternalWorkflow, hasIntegrationAutoSync, isArchivedOrPendingDeletePolicy, + isGroupPolicy, isPreferredExporter, isSubmitterApproveBlockedOnSubmitWorkspace, } from './PolicyUtils'; @@ -137,7 +139,11 @@ function canPay( const isReportPayer = isPayer(currentUserAccountID, currentUserLogin, report, bankAccountList, policy, false); // The admin pay path is for workspace expense reports. Personal policies should only offer Pay to the actual payer. - const canPayReport = isReportPayer || canAdminPayReport(policy, currentUserLogin); + const canPayReport = + isReportPayer || + (isGroupPolicy(policy) && + getReimbursementChoice(policy) === CONST.POLICY.REIMBURSEMENT_CHOICES.REIMBURSEMENT_MANUAL && + canMemberWrite(policy, currentUserLogin, CONST.POLICY.POLICY_FEATURE.WORKFLOWS_PAYMENTS)); const isPaymentsEnabled = arePaymentsEnabled(policy); const isProcessing = isProcessingReport(report); const isApprovalEnabled = policy ? policy.approvalMode && policy.approvalMode !== CONST.POLICY.APPROVAL_MODE.OPTIONAL : false; diff --git a/src/libs/ReportPrimaryActionUtils.ts b/src/libs/ReportPrimaryActionUtils.ts index 12167f984cc0..0c43b8a05b9d 100644 --- a/src/libs/ReportPrimaryActionUtils.ts +++ b/src/libs/ReportPrimaryActionUtils.ts @@ -7,8 +7,9 @@ import type {ValueOf} from 'type-fest'; import { arePaymentsEnabled as arePaymentsEnabledUtils, - canAdminPayReport, + canMemberWrite, getManagerAccountID, + getReimbursementChoice, getSubmitToAccountID, getValidConnectedIntegration, hasDynamicExternalWorkflow, @@ -236,7 +237,14 @@ function isPrimaryPayAction({ return false; } const isReportPayer = isPayer(currentUserAccountID, currentUserLogin, report, bankAccountList, policy, false); - const canPayReport = isReportPayer || (!!canNonPayerAdminPay && canAdminPayReport(policy, currentUserLogin)); + + // The admin pay path is for workspace expense reports. Personal policies should only offer Pay to the actual payer. + const canPayReport = + isReportPayer || + (canNonPayerAdminPay && + isGroupPolicy(policy) && + getReimbursementChoice(policy) === CONST.POLICY.REIMBURSEMENT_CHOICES.REIMBURSEMENT_MANUAL && + canMemberWrite(policy, currentUserLogin, CONST.POLICY.POLICY_FEATURE.WORKFLOWS_PAYMENTS)); const arePaymentsEnabled = arePaymentsEnabledUtils(policy); const isReportApproved = isReportApprovedUtils({report}); const isReportClosed = isClosedReportUtils(report); @@ -523,7 +531,6 @@ function getReportPrimaryAction(params: GetReportPrimaryActionParams): ValueOf): number | undefined { - const originalMessage = action ? getOriginalMessage(action) : undefined; - const actionBankAccountID = originalMessage && 'bankAccountID' in originalMessage ? originalMessage.bankAccountID : undefined; - - if (actionBankAccountID) { - return actionBankAccountID; - } - - // Only assume the workspace account for a payment the designated payer made, same rule as the paid-with messages. - return wasPaidWithPolicyBankAccount(policy, action?.actorAccountID) ? policy?.achAccount?.bankAccountID : undefined; -} - function isCancelPaymentAction( currentAccountID: number, currentUserEmail: string, @@ -494,6 +478,16 @@ function isCancelPaymentAction( return everyPayActionHasPaymentType(payActions, (paymentType) => paymentType === CONST.IOU.PAYMENT_TYPE.EXPENSIFY); } + // Mirror the pay gate (canIOUBePaid.canPay): whoever could mark the report paid can cancel it, no admin requirement. + const canCancelPayment = + isPayer || + (getReimbursementChoice(policy) === CONST.POLICY.REIMBURSEMENT_CHOICES.REIMBURSEMENT_MANUAL && + canMemberWrite(policy, currentUserEmail, CONST.POLICY.POLICY_FEATURE.WORKFLOWS_PAYMENTS)); + + if (!canCancelPayment) { + return false; + } + const payActions = getReportPayActions(report.reportID); const latestPayAction = getLatestPayAction(payActions); const latestPaymentType = getPayActionPaymentType(latestPayAction); @@ -501,17 +495,6 @@ function isCancelPaymentAction( // An undetermined payment type (no pay action) is treated as paid elsewhere below so we still surface Cancel. const isPaidViaBankAccount = !!latestPaymentType && latestPaymentType !== CONST.IOU.PAYMENT_TYPE.ELSEWHERE; - // Mirror the pay gate (canIOUBePaid.canPay): whoever could mark the report paid can cancel it, no admin requirement. - // A non-payer admin can always cancel a manual (paid elsewhere) payment, but a bank payment only when the account - // it was funded from is shared with them. This matches Classic, since cancelling reverses a debit on that account. - const paymentBankAccountID = isPaidViaBankAccount ? getPayActionBankAccountID(latestPayAction, policy) : undefined; - const canAccessPaymentBankAccount = !!paymentBankAccountID && !!bankAccountList?.[paymentBankAccountID]; - const canCancelPayment = isPayer || (canAdminPayReport(policy, currentUserEmail) && (!isPaidViaBankAccount || canAccessPaymentBankAccount)); - - if (!canCancelPayment) { - return false; - } - // For reports marked as paid elsewhere or when we can't determine payment type, show cancel button if (report.stateNum === CONST.REPORT.STATE_NUM.APPROVED && report.statusNum === CONST.REPORT.STATUS_NUM.REIMBURSED && !isPaidViaBankAccount) { return true; diff --git a/src/libs/ReportUtils.ts b/src/libs/ReportUtils.ts index 93ac1701fa20..5ee1c7ddc53f 100644 --- a/src/libs/ReportUtils.ts +++ b/src/libs/ReportUtils.ts @@ -100,7 +100,6 @@ import type {AddCommentOrAttachmentParams} from './API/parameters'; import type {FormulaContext, compute as computeFormula, computeWithMetadata as computeFormulaWithMetadata} from './Formula'; import type {MoneyRequestNavigatorParamList, ReportsSplitNavigatorParamList} from './Navigation/types'; import type {PersonalDetailsOnyxUpdate} from './PersonalDetailsUtils'; -import type {PolicyPaymentAttribution} from './PolicyPaymentUtils'; import type {LastVisibleMessage} from './ReportActionsUtils'; import type {AvatarSource} from './UserAvatarUtils'; @@ -437,12 +436,6 @@ type BuildOptimisticIOUReportActionParams = { linkedExpenseReportAction?: OnyxEntry; payAsBusiness?: boolean; bankAccountID?: number | undefined; - /** - * Masked number of the bank account the report was actually paid with. Stored on the action so every viewer sees - * the same account, since the payer's account is not present in every viewer's `bankAccountList` and the policy's - * ACH account can belong to a different bank account than the one used to pay. - */ - accountNumber?: string; isPersonalTrackingExpense?: boolean; reportActionID?: string; // TODO: delegateAccountIDParam will be made required when all callers pass the value (https://github.com/Expensify/App/issues/66425) @@ -6027,8 +6020,6 @@ type GetReportPreviewMessageBaseParams = { isForListPreview?: boolean; /** This can be either a report preview action or the IOU action. This will be the original report preview action in cases where `iouReportAction` was unwrapped from a report preview action. Otherwise, it will be the same as `iouReportAction`. */ originalReportAction?: OnyxInputOrEntry; - /** The current user's bank accounts, used to name the account a report was paid with. */ - bankAccountList?: OnyxEntry; }; /** @@ -6063,15 +6054,7 @@ function getReportPreviewMessage( convertToDisplayString: CurrencyListActionsContextType['convertToDisplayString'], params: GetReportPreviewMessageBaseParams, ): string { - const { - reportOrID, - iouReportAction = null, - shouldConsiderScanningReceiptOrPendingRoute = false, - isPreviewMessageForParentChatReport = false, - policy, - isForListPreview = false, - bankAccountList, - } = params; + const {reportOrID, iouReportAction = null, shouldConsiderScanningReceiptOrPendingRoute = false, isPreviewMessageForParentChatReport = false, policy, isForListPreview = false} = params; const originalReportAction = params.originalReportAction ?? iouReportAction; const report = typeof reportOrID === 'string' ? getReport(reportOrID, deprecatedAllReports) : reportOrID; const reportActionMessage = getReportActionHtml(iouReportAction); @@ -6193,10 +6176,7 @@ function getReportPreviewMessage( report.isWaitingOnBankAccount ) { translatePhraseKey = 'iou.paidWithExpensify'; - - // A paying admin can record `bankAccountID` on a workspace payment too, so the report type is what says - // whether this was an invoice, matching `getIOUReportActionDisplayMessage`. - const isFromInvoice = isInvoiceReport(report) && !!originalMessage?.bankAccountID; + const isFromInvoice = !!originalMessage?.bankAccountID; if (originalMessage?.automaticAction) { translatePhraseKey = 'iou.automaticallyPaidWithExpensify'; } @@ -6226,13 +6206,7 @@ function getReportPreviewMessage( actualPayerName = actualPayerName && isForListPreview && !isPreviewMessageForParentChatReport ? `${actualPayerName}:` : actualPayerName; const payerDisplayName = isPreviewMessageForParentChatReport ? payerName : actualPayerName; if (translatePhraseKey === 'iou.businessBankAccount') { - const last4Digits = getBankAccountLastFourDigits({ - bankAccountID: originalMessage?.bankAccountID, - bankAccountList, - policy: policy ?? undefined, - accountNumber: originalMessage?.accountNumber, - payerAccountID, - }); + const last4Digits = originalMessage?.accountNumber?.slice(-4) ?? policy?.achAccount?.accountNumber?.slice(-4) ?? ''; const crossBorderMessage = originalMessage ? getCrossBorderReimbursedMessage(translate, originalMessage, convertToDisplayString, last4Digits) : undefined; if (crossBorderMessage) { return crossBorderMessage; @@ -6323,15 +6297,7 @@ function getReportPreviewReportActionMessage( params: Omit & {policy?: OnyxInputOrEntry}, getCurrencyDecimals: CurrencyListActionsContextType['getCurrencyDecimals'], ): string { - const { - reportOrID, - iouReportAction = null, - shouldConsiderScanningReceiptOrPendingRoute = false, - isPreviewMessageForParentChatReport = false, - policy, - isForListPreview = false, - bankAccountList, - } = params; + const {reportOrID, iouReportAction = null, shouldConsiderScanningReceiptOrPendingRoute = false, isPreviewMessageForParentChatReport = false, policy, isForListPreview = false} = params; const originalReportAction = params.originalReportAction ?? iouReportAction; const report = typeof reportOrID === 'string' ? getReport(reportOrID, deprecatedAllReports) : reportOrID; const reportActionMessage = getReportActionHtml(iouReportAction); @@ -6447,9 +6413,7 @@ function getReportPreviewReportActionMessage( report.isWaitingOnBankAccount ) { translatePhraseKey = 'iou.paidWithExpensify'; - // A paying admin can record `bankAccountID` on a workspace payment too, so the report type is what says - // whether this was an invoice, matching `getIOUReportActionDisplayMessage`. - const isFromInvoice = isInvoiceReport(report) && !!originalMessage?.bankAccountID; + const isFromInvoice = !!originalMessage?.bankAccountID; if (originalMessage?.automaticAction) { translatePhraseKey = 'iou.automaticallyPaidWithExpensify'; } @@ -6474,13 +6438,7 @@ function getReportPreviewReportActionMessage( actualPayerName = actualPayerName && isForListPreview && !isPreviewMessageForParentChatReport ? `${actualPayerName}:` : actualPayerName; const payerDisplayName = isPreviewMessageForParentChatReport ? payerName : actualPayerName; if (translatePhraseKey === 'iou.businessBankAccount') { - const last4Digits = getBankAccountLastFourDigits({ - bankAccountID: originalMessage?.bankAccountID, - bankAccountList, - policy: reportPolicy, - accountNumber: originalMessage?.accountNumber, - payerAccountID, - }); + const last4Digits = originalMessage?.accountNumber?.slice(-4) ?? reportPolicy?.achAccount?.accountNumber?.slice(-4) ?? ''; // This variant returns raw English to match the surrounding non-localized preview strings. if (originalMessage?.creditedAmount && originalMessage.creditedCurrency) { @@ -8039,7 +7997,6 @@ function buildOptimisticIOUReportAction(params: BuildOptimisticIOUReportActionPa isPersonalTrackingExpense = false, payAsBusiness, bankAccountID, - accountNumber, reportActionID, delegateAccountIDParam, isSubmitterMarkedPaymentReceived, @@ -8081,11 +8038,6 @@ function buildOptimisticIOUReportAction(params: BuildOptimisticIOUReportActionPa if (isSubmitterMarkedPaymentReceived) { originalMessage.isSubmitterMarkedPaymentReceived = true; } - - // Persist the masked account used to pay so every viewer resolves the same account (see `accountNumber` above). - if (accountNumber) { - originalMessage.accountNumber = accountNumber; - } } if (type !== CONST.IOU.REPORT_ACTION_TYPE.PAY) { @@ -11708,7 +11660,7 @@ function getIOUReportActionDisplayMessage( translate: LocalizedTranslate, reportAction: OnyxEntry, convertToDisplayString: CurrencyListActionsContextType['convertToDisplayString'], - policy: OnyxEntry, + policyACHAccountNumber: string | undefined, transaction?: OnyxEntry, bankAccountList?: OnyxEntry, ): string { @@ -11723,13 +11675,7 @@ function getIOUReportActionDisplayMessage( let translationKey: TranslationPaths; if (originalMessage?.type === CONST.IOU.REPORT_ACTION_TYPE.PAY) { - const last4Digits = getBankAccountLastFourDigits({ - bankAccountID: originalMessage?.bankAccountID, - bankAccountList, - policy, - accountNumber: originalMessage?.accountNumber, - payerAccountID: reportAction?.actorAccountID, - }); + const last4Digits = originalMessage?.accountNumber?.slice(-4) ?? getBankAccountLastFourDigits(originalMessage?.bankAccountID, bankAccountList, policyACHAccountNumber); const crossBorderMessage = getCrossBorderReimbursedMessage(translate, originalMessage, convertToDisplayString, last4Digits); switch (originalMessage.paymentType) { diff --git a/src/libs/SidebarUtils.ts b/src/libs/SidebarUtils.ts index 27909783ab10..956a15f5adcf 100644 --- a/src/libs/SidebarUtils.ts +++ b/src/libs/SidebarUtils.ts @@ -6,7 +6,6 @@ import type {ReportsToDisplayInLHN} from '@hooks/useSidebarOrderedReports'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import type { - BankAccountList, Card, GuideAccountIDsDerivedValue, PersonalDetails, @@ -726,7 +725,6 @@ function getOptionData({ isTrackIntentUser, formatPhoneNumber, rules, - bankAccountList, }: { report: OnyxEntry; oneTransactionThreadReport: OnyxEntry; @@ -757,9 +755,6 @@ function getOptionData({ isTrackIntentUser?: boolean; formatPhoneNumber: LocaleContextProps['formatPhoneNumber']; rules: OnyxCollection; - - /** The current user's bank accounts, used to name the account a report was paid with in the preview. */ - bankAccountList?: OnyxEntry; }): OptionData | undefined { // When a user signs out, Onyx is cleared. Due to the lazy rendering with a virtual list, it's possible for // this method to be called after the Onyx data has been cleared out. In that case, it's fine to do @@ -918,7 +913,6 @@ function getOptionData({ convertToDisplayString, convertToDisplayStringWithoutCurrency, rules, - bankAccountList, }); result.isIOUReportOwner = isIOUOwnedByCurrentUser(result as Report); diff --git a/src/libs/actions/IOU/PayMoneyRequest.ts b/src/libs/actions/IOU/PayMoneyRequest.ts index f6158d88904c..99c9210f4a54 100644 --- a/src/libs/actions/IOU/PayMoneyRequest.ts +++ b/src/libs/actions/IOU/PayMoneyRequest.ts @@ -31,7 +31,6 @@ import playSound, {SOUNDS} from '@libs/Sound'; import {shouldRestrictUserBillableActions} from '@libs/SubscriptionUtils'; import {shouldSplitScanFailedTransactions} from '@libs/TransactionUtils'; -import {getBankAccountFromID} from '@userActions/BankAccounts'; import {buildPolicyData, generatePolicyID} from '@userActions/Policy/Policy'; import type {BuildPolicyDataKeys} from '@userActions/Policy/Policy'; import {completeOnboarding} from '@userActions/Report'; @@ -264,13 +263,6 @@ function getPayMoneyRequestParams({ const shouldMoveScanFailedTransactions = !!full && isExpenseReport(iouReport) && shouldSplitScanFailedTransactions(reportTransactions, iouReport); - // Store the masked account actually paid with on the action itself, so every viewer resolves the same account. - // The paying admin may not be the workspace payer, so the account can be their own (looked up in `bankAccountList`) - // rather than the policy's ACH account; we fall back to the policy account when it is the one being used. - const paidWithBankAccount = getBankAccountFromID(bankAccountID); - const paidAccountNumber = - paidWithBankAccount?.accountData?.accountNumber ?? (bankAccountID === reportPolicy?.achAccount?.bankAccountID ? reportPolicy?.achAccount?.accountNumber : undefined); - const optimisticIOUReportAction = buildOptimisticIOUReportAction({ type: CONST.IOU.REPORT_ACTION_TYPE.PAY, amount: isExpenseReport(iouReport) ? -total : total, @@ -283,7 +275,6 @@ function getPayMoneyRequestParams({ isSettlingUp: true, payAsBusiness, bankAccountID, - accountNumber: paidAccountNumber, delegateAccountIDParam: delegateAccountID, getCurrencyDecimals, }); diff --git a/src/libs/actions/IOU/ReportWorkflow.ts b/src/libs/actions/IOU/ReportWorkflow.ts index 04ef40919d6b..6e0c5e480d50 100644 --- a/src/libs/actions/IOU/ReportWorkflow.ts +++ b/src/libs/actions/IOU/ReportWorkflow.ts @@ -19,12 +19,13 @@ import {getIsOffline} from '@libs/NetworkState'; import {buildOptimisticNextStep} from '@libs/NextStepUtils'; import { arePaymentsEnabled, - canAdminPayReport, + canMemberWrite, getAccountIDForSubmitManagerEmail, getReimbursementChoice, getSubmitReportManagerAccountID, hasDynamicExternalWorkflow, isArchivedOrPendingDeletePolicy, + isGroupPolicy, isPaidGroupPolicy, isSubmitAndClose, isSubmitPolicy, @@ -243,7 +244,13 @@ function canIOUBePaid( } const isReportPayer = isPayerReportUtils(currentUserAccountID, currentUserLogin, iouReport, bankAccountList, policy, onlyShowPayElsewhere); - const canPay = isReportPayer || canAdminPayReport(policy, currentUserLogin); + + // The admin pay path is for workspace expense reports. Personal policies should only offer Pay to the actual payer. + const canPay = + isReportPayer || + (isGroupPolicy(policy) && + getReimbursementChoice(policy) === CONST.POLICY.REIMBURSEMENT_CHOICES.REIMBURSEMENT_MANUAL && + canMemberWrite(policy, currentUserLogin, CONST.POLICY.POLICY_FEATURE.WORKFLOWS_PAYMENTS)); const {reimbursableSpend, nonReimbursableSpend} = getMoneyRequestSpendBreakdown(iouReport); const isAutoReimbursable = getReimbursementChoice(policy) === CONST.POLICY.REIMBURSEMENT_CHOICES.REIMBURSEMENT_YES ? false : canBeAutoReimbursed(iouReport, policy); diff --git a/src/libs/actions/Search.ts b/src/libs/actions/Search.ts index 1231a3f57f96..55331b75f16f 100644 --- a/src/libs/actions/Search.ts +++ b/src/libs/actions/Search.ts @@ -39,7 +39,6 @@ import enhanceParameters from '@libs/Network/enhanceParameters'; import {getIsOffline} from '@libs/NetworkState'; import {rand64} from '@libs/NumberUtils'; import {getActivePaymentType} from '@libs/PaymentUtils'; -import {canAccessPolicyBankAccount} from '@libs/PolicyPaymentUtils'; import { getAccountIDForSubmitManagerEmail, getSubmitReportManagerAccountID, @@ -285,7 +284,6 @@ type HandleActionButtonPressParams = { rules: OnyxCollection; conciergeChat: OnyxEntry; getCurrencyDecimals: CurrencyListActionsContextType['getCurrencyDecimals']; - bankAccountList: OnyxEntry; }; function handleActionButtonPress({ @@ -328,7 +326,6 @@ function handleActionButtonPress({ rules, conciergeChat, getCurrencyDecimals, - bankAccountList, }: HandleActionButtonPressParams) { // The transactionIDList is needed to handle actions taken on `status:""` where transactions on single expense reports can be approved/paid. // We need the transactionID to display the loading indicator for that list item's action. @@ -383,7 +380,6 @@ function handleActionButtonPress({ conciergeChat, getCurrencyDecimals, rules, - bankAccountList, }); return; case CONST.SEARCH.ACTION_TYPES.APPROVE: @@ -626,7 +622,6 @@ type GetPayActionCallbackParams = { conciergeChat: OnyxEntry; getCurrencyDecimals: CurrencyListActionsContextType['getCurrencyDecimals']; rules: OnyxCollection; - bankAccountList: OnyxEntry; }; function getPayActionCallback({ @@ -657,7 +652,6 @@ function getPayActionCallback({ conciergeChat, getCurrencyDecimals, rules, - bankAccountList, }: GetPayActionCallbackParams) { if (!item.reportID) { Log.info('[SearchPay] Dropping row pay: item has no reportID'); @@ -670,13 +664,9 @@ function getPayActionCallback({ return; } - const paymentPolicy = snapshotPolicy ?? policy; - if (lastPolicyPaymentMethod !== CONST.IOU.PAYMENT_TYPE.ELSEWHERE) { - // One-tap pay here always funds the payment from the workspace bank account, so it's only valid for someone the - // account is actually shared with. Anyone else has to pay from an account of their own, so open the report and let - // them pick it instead of silently paying with (and reporting) the workspace one. - if (!canAccessPolicyBankAccount(paymentPolicy, bankAccountList)) { + const hasVBBA = !!snapshotPolicy?.achAccount?.bankAccountID; + if (!hasVBBA) { goToItem(); return; } @@ -698,14 +688,14 @@ function getPayActionCallback({ currentUserAccountID: currentUserAccountID ?? CONST.DEFAULT_NUMBER_ID, currentUserLogin: currentUserLogin ?? '', activePolicy, - policy: paymentPolicy, + policy: snapshotPolicy ?? policy, chatReportPolicy: chatReportPolicyForPayment, isASAPSubmitBetaEnabled, isSelfTourViewed, userBillingGracePeriodEnds, amountOwed, ownerBillingGracePeriodEnd, - methodID: lastPolicyPaymentMethod === CONST.IOU.PAYMENT_TYPE.VBBA ? paymentPolicy?.achAccount?.bankAccountID : undefined, + methodID: lastPolicyPaymentMethod === CONST.IOU.PAYMENT_TYPE.VBBA ? snapshotPolicy?.achAccount?.bankAccountID : undefined, additionalOnyxData: getSearchPayOnyxData(hash, item.reportID, currentSearchKey), chatReportActions, delegateAccountID, diff --git a/src/libs/getBankAccountLastFourDigits.ts b/src/libs/getBankAccountLastFourDigits.ts index 743cdfb9cfa9..ebf8eef28f61 100644 --- a/src/libs/getBankAccountLastFourDigits.ts +++ b/src/libs/getBankAccountLastFourDigits.ts @@ -2,42 +2,13 @@ import type {BankAccount} from '@src/types/onyx'; import type {OnyxEntry} from 'react-native-onyx'; -import type {PolicyPaymentAttribution} from './PolicyPaymentUtils'; - -import {getAccessiblePolicyBankAccount, wasPaidWithPolicyBankAccount} from './PolicyPaymentUtils'; - -type GetBankAccountLastFourDigitsParams = { - /** The account the payment action names, when the paying admin picked one. */ - bankAccountID: number | undefined; - - /** The current user's own bank accounts, used to resolve `bankAccountID` and the workspace account. */ - bankAccountList: OnyxEntry>; - - /** The policy the report belongs to. Only its bank account and designated payer are read. */ - policy: OnyxEntry; - - /** - * Masked account number stored on the payment action itself. It is the only viewer-independent source, so it wins - * over any local lookup. The payer's account is not in every viewer's `bankAccountList`, and falling back to the - * policy account would show a different account to different people for the same payment. - */ - accountNumber?: string; - - /** - * Who made the payment. The workspace account is only a valid guess when the payment came from the designated - * payer. For anyone else it belongs to a different bank account than the one actually used. - */ - payerAccountID?: number; -}; - /** * Get the last 4 digits of a bank account used for payment. + * + * `policyACHAccountNumber` is the account number of the policy's default reimbursement account + * (`policy.achAccount.accountNumber`), used as a fallback when the payment doesn't name an account. */ -function getBankAccountLastFourDigits({bankAccountID, bankAccountList, policy, accountNumber, payerAccountID}: GetBankAccountLastFourDigitsParams): string { - if (accountNumber) { - return accountNumber.slice(-4); - } - +function getBankAccountLastFourDigits(bankAccountID: number | undefined, bankAccountList: OnyxEntry>, policyACHAccountNumber: string | undefined): string { const bankAccount = bankAccountID ? bankAccountList?.[bankAccountID] : null; if (bankAccount?.accountData?.accountNumber) { @@ -48,18 +19,7 @@ function getBankAccountLastFourDigits({bankAccountID, bankAccountList, policy, a if (bankAccountID != null) { return ''; } - - // The action doesn't say which account was used, so only fall back to the workspace account when the designated - // payer made the payment. - if (!wasPaidWithPolicyBankAccount(policy, payerAccountID)) { - return ''; - } - - // Resolve the workspace account through `bankAccountList` when we can. `achAccount.accountNumber` goes stale while - // `achAccount.bankAccountID` moves on, so the two can name different accounts. The ID is the one that was debited. - const policyBankAccount = getAccessiblePolicyBankAccount(policy, bankAccountList); - - return (policyBankAccount?.accountData?.accountNumber ?? policy?.achAccount?.accountNumber)?.slice(-4) ?? ''; + return policyACHAccountNumber?.slice(-4) ?? ''; } export default getBankAccountLastFourDigits; diff --git a/src/pages/inbox/report/ContextMenu/ContextMenuActions.tsx b/src/pages/inbox/report/ContextMenu/ContextMenuActions.tsx index 1b8e2b36f77f..4495a006444a 100644 --- a/src/pages/inbox/report/ContextMenu/ContextMenuActions.tsx +++ b/src/pages/inbox/report/ContextMenu/ContextMenuActions.tsx @@ -1090,7 +1090,7 @@ const ContextMenuActions: ContextMenuAction[] = [ const displayMessage = getReimbursementDeQueuedOrCanceledActionMessage(translate, reportAction, report?.ownerAccountID, convertToDisplayString); Clipboard.setString(displayMessage); } else if (isMoneyRequestAction(reportAction)) { - const displayMessage = getIOUReportActionDisplayMessage(translate, reportAction, convertToDisplayString, policy, transaction, bankAccountList); + const displayMessage = getIOUReportActionDisplayMessage(translate, reportAction, convertToDisplayString, policy?.achAccount?.accountNumber, transaction, bankAccountList); if (displayMessage === Parser.htmlToText(displayMessage)) { Clipboard.setString(displayMessage); } else { diff --git a/src/pages/inbox/report/actionContents/IouReportActionMessage.tsx b/src/pages/inbox/report/actionContents/IouReportActionMessage.tsx index 1f8cea3ada91..7cb0c9f2597e 100644 --- a/src/pages/inbox/report/actionContents/IouReportActionMessage.tsx +++ b/src/pages/inbox/report/actionContents/IouReportActionMessage.tsx @@ -12,7 +12,7 @@ import type {ReportAction} from '@src/types/onyx'; import type {StyleProp, TextStyle, ViewStyle} from 'react-native'; -import {policyPaymentAttributionSelector} from '@selectors/Policy'; +import {policyACHAccountNumberSelector} from '@selectors/Policy'; import React from 'react'; import ReportActionMessageContent from './ReportActionMessageContent'; @@ -38,13 +38,13 @@ function IouReportActionMessage({action, displayAsGroup, reportID, style, isHidd const [report] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${getNonEmptyStringOnyxID(reportID)}`); const [transaction] = useOnyx(`${ONYXKEYS.COLLECTION.TRANSACTION}${getNonEmptyStringOnyxID(getLinkedTransactionID(action))}`); const [bankAccountList] = useOnyx(ONYXKEYS.BANK_ACCOUNT_LIST); - const [policyPaymentAttribution] = useOnyx(`${ONYXKEYS.COLLECTION.POLICY}${getNonEmptyStringOnyxID(report?.policyID)}`, {selector: policyPaymentAttributionSelector}); + const [policyACHAccountNumber] = useOnyx(`${ONYXKEYS.COLLECTION.POLICY}${getNonEmptyStringOnyxID(report?.policyID)}`, {selector: policyACHAccountNumberSelector}); let iouMessage: string | undefined; const isIOUAction = isActionOfType(action, CONST.REPORT.ACTIONS.TYPE.IOU); const originalMessageType = isIOUAction ? getOriginalMessage(action)?.type : undefined; if (isIOUAction && originalMessageType !== CONST.IOU.REPORT_ACTION_TYPE.TRACK) { - iouMessage = getIOUReportActionDisplayMessage(translate, action, convertToDisplayString, policyPaymentAttribution, transaction, bankAccountList); + iouMessage = getIOUReportActionDisplayMessage(translate, action, convertToDisplayString, policyACHAccountNumber, transaction, bankAccountList); } return ( diff --git a/src/pages/inbox/report/actionContents/PaymentContent.tsx b/src/pages/inbox/report/actionContents/PaymentContent.tsx index 0a6948038e15..39c92a018d7e 100644 --- a/src/pages/inbox/report/actionContents/PaymentContent.tsx +++ b/src/pages/inbox/report/actionContents/PaymentContent.tsx @@ -13,7 +13,7 @@ import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import type * as OnyxTypes from '@src/types/onyx'; -import {policyPaymentAttributionSelector} from '@selectors/Policy'; +import {policyACHAccountNumberSelector} from '@selectors/Policy'; import React from 'react'; type PaymentContentProps = { @@ -24,7 +24,7 @@ type PaymentContentProps = { function PaymentContent({action, expectedDate, policyID}: PaymentContentProps) { const [bankAccountList] = useOnyx(ONYXKEYS.BANK_ACCOUNT_LIST); - const [policyPaymentAttribution] = useOnyx(`${ONYXKEYS.COLLECTION.POLICY}${policyID}`, {selector: policyPaymentAttributionSelector}); + const [policyACHAccountNumber] = useOnyx(`${ONYXKEYS.COLLECTION.POLICY}${policyID}`, {selector: policyACHAccountNumberSelector}); const {translate, dateFnsLocale} = useLocalize(); const {convertToDisplayString} = useCurrencyListActions(); const originalMessage = getOriginalMessage(action); @@ -41,13 +41,7 @@ function PaymentContent({action, expectedDate, policyID}: PaymentContentProps) { } if (paymentType === CONST.IOU.PAYMENT_TYPE.VBBA) { - const last4Digits = getBankAccountLastFourDigits({ - bankAccountID: originalMessage.bankAccountID, - bankAccountList, - policy: policyPaymentAttribution, - accountNumber: originalMessage.accountNumber, - payerAccountID: action.actorAccountID, - }); + const last4Digits = originalMessage.accountNumber?.slice(-4) ?? getBankAccountLastFourDigits(originalMessage.bankAccountID, bankAccountList, policyACHAccountNumber); const crossBorderMessage = getCrossBorderReimbursedMessage(translate, originalMessage, convertToDisplayString, last4Digits); const paymentMessage = crossBorderMessage ?? translate(wasAutoPaid ? 'iou.automaticallyPaidWithBusinessBankAccount' : 'iou.businessBankAccount', '', last4Digits); const translation = getPaymentMessageWithExpectedDate(translate, dateFnsLocale, paymentMessage, expectedDate); diff --git a/src/selectors/Policy.ts b/src/selectors/Policy.ts index 05dd3089a295..1a2212d2ed13 100644 --- a/src/selectors/Policy.ts +++ b/src/selectors/Policy.ts @@ -4,7 +4,6 @@ import {hasSynchronizationErrorMessage, isConnectionInProgress, isConnectionUnve import {getDisplayNameForWorkspace} from '@libs/actions/Policy/Policy'; import isTeachersUnitePolicyID from '@libs/isTeachersUnitePolicyID'; import {getConnectedHRProvider} from '@libs/merge/HRUtils'; -import type {PolicyPaymentAttribution} from '@libs/PolicyPaymentUtils'; import { canSendInvoice, getActiveAdminWorkspaces, @@ -515,9 +514,7 @@ const policyRoleSelector = (policy: OnyxEntry) => policy?.role; const areInvoicesEnabledSelector = (policy: OnyxEntry) => policy?.areInvoicesEnabled; -/** The policy fields that attribute a payment to a bank account (see `getBankAccountLastFourDigits`). */ -const policyPaymentAttributionSelector = (policy: OnyxEntry): PolicyPaymentAttribution | undefined => - policy ? {achAccount: policy.achAccount, reimburser: policy.reimburser} : undefined; +const policyACHAccountNumberSelector = (policy: OnyxEntry) => policy?.achAccount?.accountNumber; function isAdminForPolicyByIDSelector(policyID?: string) { return (policies: OnyxCollection | null): boolean => { @@ -580,7 +577,7 @@ export { policyRoleSelector, policyTypeSelector, areInvoicesEnabledSelector, - policyPaymentAttributionSelector, + policyACHAccountNumberSelector, createAdminPoliciesSelector, isAdminForPolicyByIDSelector, }; diff --git a/tests/actions/IOUTest/ReportWorkflowTest.ts b/tests/actions/IOUTest/ReportWorkflowTest.ts index fa82e38ff54a..7b8390a52b57 100644 --- a/tests/actions/IOUTest/ReportWorkflowTest.ts +++ b/tests/actions/IOUTest/ReportWorkflowTest.ts @@ -3710,82 +3710,6 @@ describe('actions/IOU/ReportWorkflow', () => { expect(canIOUBePaid(fakeReport, policyChat, fakePolicy, {}, RORY_EMAIL, RORY_ACCOUNT_ID, [], true, false)).toBeTruthy(); }); - it('allows a non-payer admin to pay when a bank account is connected (reimburseYes)', async () => { - const DESIGNATED_PAYER_EMAIL = 'designated-payer@mail.com'; - const policyChat = createRandomReport(1, CONST.REPORT.CHAT_TYPE.POLICY_EXPENSE_CHAT); - const fakePolicy: Policy = { - ...createRandomPolicy(1), - id: 'AA', - type: CONST.POLICY.TYPE.TEAM, - approvalMode: CONST.POLICY.APPROVAL_MODE.OPTIONAL, - reimbursementChoice: CONST.POLICY.REIMBURSEMENT_CHOICES.REIMBURSEMENT_YES, - role: CONST.POLICY.ROLE.ADMIN, - achAccount: { - reimburser: DESIGNATED_PAYER_EMAIL, - bankAccountID: 1, - accountNumber: '1234567890', - routingNumber: '987654321', - addressName: 'Test Address', - bankName: 'Test Bank', - }, - }; - - const fakeReport: Report = { - ...createRandomReport(1, undefined), - type: CONST.REPORT.TYPE.EXPENSE, - policyID: 'AA', - stateNum: CONST.REPORT.STATE_NUM.APPROVED, - statusNum: CONST.REPORT.STATUS_NUM.APPROVED, - ownerAccountID: CARLOS_ACCOUNT_ID, - managerID: CARLOS_ACCOUNT_ID, - isWaitingOnBankAccount: false, - total: -100, - }; - - await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}${fakePolicy.id}`, fakePolicy); - - // Rory is an admin but not the designated reimburser, so the Pay option comes from canAdminPayReport rather than isPayer. - expect(isPayer(RORY_ACCOUNT_ID, RORY_EMAIL, fakeReport, {}, fakePolicy, false)).toBeFalsy(); - expect(canIOUBePaid(fakeReport, policyChat, fakePolicy, {}, RORY_EMAIL, RORY_ACCOUNT_ID, [], false, false)).toBeTruthy(); - }); - - it('does not allow a non-payer admin to pay when reimbursementChoice is not configured', async () => { - const DESIGNATED_PAYER_EMAIL = 'designated-payer@mail.com'; - const policyChat = createRandomReport(1, CONST.REPORT.CHAT_TYPE.POLICY_EXPENSE_CHAT); - const fakePolicy: Policy = { - ...createRandomPolicy(1), - id: 'AA', - type: CONST.POLICY.TYPE.TEAM, - approvalMode: CONST.POLICY.APPROVAL_MODE.OPTIONAL, - reimbursementChoice: undefined, - role: CONST.POLICY.ROLE.ADMIN, - achAccount: { - reimburser: DESIGNATED_PAYER_EMAIL, - bankAccountID: 1, - accountNumber: '1234567890', - routingNumber: '987654321', - addressName: 'Test Address', - bankName: 'Test Bank', - }, - }; - - const fakeReport: Report = { - ...createRandomReport(1, undefined), - type: CONST.REPORT.TYPE.EXPENSE, - policyID: 'AA', - stateNum: CONST.REPORT.STATE_NUM.APPROVED, - statusNum: CONST.REPORT.STATUS_NUM.APPROVED, - ownerAccountID: CARLOS_ACCOUNT_ID, - managerID: CARLOS_ACCOUNT_ID, - isWaitingOnBankAccount: false, - total: -100, - }; - - await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}${fakePolicy.id}`, fakePolicy); - - expect(canIOUBePaid(fakeReport, policyChat, fakePolicy, {}, RORY_EMAIL, RORY_ACCOUNT_ID, [], false, false)).toBeFalsy(); - }); - it('allows admins to mark report with only non-reimbursable expenses as paid (onlyShowPayElsewhere=true)', async () => { const policyChat = createRandomReport(1, CONST.REPORT.CHAT_TYPE.POLICY_EXPENSE_CHAT); const reportID = '999'; diff --git a/tests/actions/ReportPreviewActionUtilsTest.ts b/tests/actions/ReportPreviewActionUtilsTest.ts index 603b9c3d268d..9fd7d35f62bb 100644 --- a/tests/actions/ReportPreviewActionUtilsTest.ts +++ b/tests/actions/ReportPreviewActionUtilsTest.ts @@ -6,7 +6,7 @@ import type * as PolicyUtils from '@libs/PolicyUtils'; import {getValidConnectedIntegration, isGroupPolicy} from '@libs/PolicyUtils'; import getReportPreviewAction from '@libs/ReportPreviewActionUtils'; import type * as ReportUtils from '@libs/ReportUtils'; -import {hasOnlyNonReimbursableTransactions, isPayer} from '@libs/ReportUtils'; +import {hasOnlyNonReimbursableTransactions} from '@libs/ReportUtils'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; @@ -886,94 +886,6 @@ describe('getReportPreviewAction', () => { ).toBe(CONST.REPORT.REPORT_PREVIEW_ACTIONS.PAY); }); - /** - * Builds a non-payer admin scenario: the current user is a workspace admin on a paid group policy, but someone else is the - * designated reimburser. The policy is written to Onyx (and referenced by `policyID`) because `isPayer` resolves the policy - * type through `ReportUtils.isPaidGroupPolicy`, which reads Onyx. Without it, `isPayer` falls back to a bare admin check and - * would report the user as the payer, hiding whatever `canAdminPayReport` decides. - */ - async function setUpNonPayerAdminScenario(reimbursementChoice: Policy['reimbursementChoice']) { - const DESIGNATED_PAYER_EMAIL = 'designated-payer@mail.com'; - const policy = createRandomPolicy(0); - policy.role = CONST.POLICY.ROLE.ADMIN; - policy.type = CONST.POLICY.TYPE.CORPORATE; - policy.reimbursementChoice = reimbursementChoice; - policy.achAccount = { - reimburser: DESIGNATED_PAYER_EMAIL, - bankAccountID: 1, - accountNumber: '1234567890', - routingNumber: '987654321', - addressName: 'Test Address', - bankName: 'Test Bank', - }; - - const report = { - ...createRandomReport(REPORT_ID, undefined), - type: CONST.REPORT.TYPE.EXPENSE, - policyID: policy.id, - ownerAccountID: CURRENT_USER_ACCOUNT_ID + 1, - statusNum: CONST.REPORT.STATUS_NUM.APPROVED, - stateNum: CONST.REPORT.STATE_NUM.APPROVED, - total: -100, - isWaitingOnBankAccount: false, - }; - - await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}${policy.id}`, policy); - await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${REPORT_ID}`, report); - - const transaction = { - ...createRandomTransaction(REPORT_ID), - reportID: `${REPORT_ID}`, - }; - - return {policy, report, transaction}; - } - - it('canPay should return PAY for non-payer admin when a bank account is connected (reimburseYes)', async () => { - const {policy, report, transaction} = await setUpNonPayerAdminScenario(CONST.POLICY.REIMBURSEMENT_CHOICES.REIMBURSEMENT_YES); - - const {result: isReportArchived} = renderHook(() => useReportIsArchived(report?.parentReportID)); - await waitForBatchedUpdatesWithAct(); - - // The Pay option must come from canAdminPayReport, not from isPayer. - expect(isPayer(CURRENT_USER_ACCOUNT_ID, CURRENT_USER_EMAIL, report, {}, policy, false)).toBe(false); - expect( - getReportPreviewAction({ - isReportArchived: isReportArchived.current, - currentUserAccountID: CURRENT_USER_ACCOUNT_ID, - currentUserLogin: CURRENT_USER_EMAIL, - report, - policy, - transactions: [transaction], - bankAccountList: {}, - reportMetadata: undefined, - ownerLogin: CURRENT_USER_EMAIL, - rules: undefined, - }), - ).toBe(CONST.REPORT.REPORT_PREVIEW_ACTIONS.PAY); - }); - - it('canPay should not return PAY for non-payer admin when reimbursementChoice is not configured', async () => { - const {policy, report, transaction} = await setUpNonPayerAdminScenario(undefined); - - const {result: isReportArchived} = renderHook(() => useReportIsArchived(report?.parentReportID)); - await waitForBatchedUpdatesWithAct(); - expect( - getReportPreviewAction({ - isReportArchived: isReportArchived.current, - currentUserAccountID: CURRENT_USER_ACCOUNT_ID, - currentUserLogin: CURRENT_USER_EMAIL, - report, - policy, - transactions: [transaction], - bankAccountList: {}, - reportMetadata: undefined, - ownerLogin: CURRENT_USER_EMAIL, - rules: undefined, - }), - ).not.toBe(CONST.REPORT.REPORT_PREVIEW_ACTIONS.PAY); - }); - it('canPay should not return PAY for the expense owner in a 1:1 IOU on a personal policy with manual reimbursement', async () => { const managerAccountID = CURRENT_USER_ACCOUNT_ID + 1; const report = { diff --git a/tests/unit/PaymentUtilsTest.ts b/tests/unit/PaymentUtilsTest.ts index 16ce58615886..729c31eeebb2 100644 --- a/tests/unit/PaymentUtilsTest.ts +++ b/tests/unit/PaymentUtilsTest.ts @@ -4,24 +4,19 @@ import {approveMoneyRequest} from '@libs/actions/IOU/ReportWorkflow'; import Navigation from '@libs/Navigation/Navigation'; import {getActivePaymentType, getBusinessBankAccountOptions, selectPaymentType} from '@libs/PaymentUtils'; import type {SelectPaymentTypeParams} from '@libs/PaymentUtils'; -import {wasPaidWithPolicyBankAccount} from '@libs/PolicyPaymentUtils'; import {shouldRestrictUserBillableActions} from '@libs/SubscriptionUtils'; import CONST from '@src/CONST'; import {calculateWalletTransferBalanceFee} from '@src/libs/PaymentUtils'; -import ONYXKEYS from '@src/ONYXKEYS'; import ROUTES from '@src/ROUTES'; -import type {Policy, Report} from '@src/types/onyx'; +import type {Report} from '@src/types/onyx'; import type {PaymentMethodType} from '@src/types/onyx/OriginalMessage'; import type PaymentMethod from '@src/types/onyx/PaymentMethod'; -import Onyx from 'react-native-onyx'; - import createMockPaymentMethod from '../utils/collections/paymentMethods'; import createRandomPolicy from '../utils/collections/policies'; import createMock from '../utils/createMock'; import {getCurrencyDecimalsLocal} from '../utils/TestHelper'; -import waitForBatchedUpdates from '../utils/waitForBatchedUpdates'; jest.mock('@libs/Navigation/Navigation', () => ({ navigate: jest.fn(), @@ -535,62 +530,3 @@ describe('PaymentUtils', () => { }); }); }); - -describe('wasPaidWithPolicyBankAccount', () => { - const PAYER_EMAIL = 'payer@test.com'; - const PAYER_ACCOUNT_ID = 101; - const NON_PAYER_ADMIN_ACCOUNT_ID = 102; - - const policyWithDesignatedPayer: Policy = { - ...createRandomPolicy(2, CONST.POLICY.TYPE.CORPORATE), - reimbursementChoice: CONST.POLICY.REIMBURSEMENT_CHOICES.REIMBURSEMENT_YES, - reimburser: PAYER_EMAIL, - }; - - beforeAll(() => { - Onyx.init({keys: ONYXKEYS}); - }); - - beforeEach(async () => { - await Onyx.set(ONYXKEYS.PERSONAL_DETAILS_LIST, { - [PAYER_ACCOUNT_ID]: {accountID: PAYER_ACCOUNT_ID, login: PAYER_EMAIL}, - [NON_PAYER_ADMIN_ACCOUNT_ID]: {accountID: NON_PAYER_ADMIN_ACCOUNT_ID, login: 'wsadmin@test.com'}, - }); - await waitForBatchedUpdates(); - }); - - afterEach(async () => { - await Onyx.clear(); - await waitForBatchedUpdates(); - }); - - it('returns true when the designated payer made the payment', () => { - expect(wasPaidWithPolicyBankAccount(policyWithDesignatedPayer, PAYER_ACCOUNT_ID)).toBe(true); - }); - - it('returns false when an admin who is not the designated payer made the payment', () => { - expect(wasPaidWithPolicyBankAccount(policyWithDesignatedPayer, NON_PAYER_ADMIN_ACCOUNT_ID)).toBe(false); - }); - - it('falls back to the reimburser stored on the bank account when the workspace has no reimburser', () => { - const policy: Policy = { - ...policyWithDesignatedPayer, - reimburser: undefined, - achAccount: { - bankAccountID: 1111, - accountNumber: 'XXXXXX1111', - routingNumber: '123456789', - addressName: 'Test bank account', - bankName: 'Test bank', - reimburser: PAYER_EMAIL, - }, - }; - - expect(wasPaidWithPolicyBankAccount(policy, PAYER_ACCOUNT_ID)).toBe(true); - expect(wasPaidWithPolicyBankAccount(policy, NON_PAYER_ADMIN_ACCOUNT_ID)).toBe(false); - }); - - it('returns true for any payer when the workspace has no designated payer', () => { - expect(wasPaidWithPolicyBankAccount({...policyWithDesignatedPayer, reimburser: undefined}, NON_PAYER_ADMIN_ACCOUNT_ID)).toBe(true); - }); -}); diff --git a/tests/unit/PolicyUtilsTest.ts b/tests/unit/PolicyUtilsTest.ts index 0c4d89079348..35631fd7a8d5 100644 --- a/tests/unit/PolicyUtilsTest.ts +++ b/tests/unit/PolicyUtilsTest.ts @@ -5,7 +5,6 @@ import useDefaultFundID from '@hooks/useDefaultFundID'; import DateUtils from '@libs/DateUtils'; import Navigation from '@libs/Navigation/Navigation'; -import {canAccessPolicyBankAccount, getAccessiblePolicyBankAccount} from '@libs/PolicyPaymentUtils'; import { arePolicyRulesEnabled, canEditWorkspaceSettings, @@ -17,6 +16,8 @@ import { evaluateApprovalWorkflowRule, findVendorByID, getVendorFeaturePolicyIDs, + getVendorDisplayName, + hasVendorFeatureOnAnyPolicy, getActivePolicies, getActivePoliciesWithExpenseChat, getActivePoliciesWithExpenseChatAndPerDiemEnabled, @@ -40,7 +41,6 @@ import { getActiveVendorMatchingIntegration, getMatchingVendorByID, getMatchingVendors, - getVendorDisplayName, getVendorEmptyState, getVendorRuleDisplayValue, getPolicyApproverLogins, @@ -82,7 +82,6 @@ import { hasPolicyRulesError, hasPolicyWithXeroConnection, hasVendorFeature, - hasVendorFeatureOnAnyPolicy, isBusinessCentralVendorMatchingActive, isArchivedPolicy, isDualEntryVendorMatchingActive, @@ -6365,104 +6364,6 @@ describe('getDefaultWorkspacePlanType', () => { }); }); -describe('canAccessPolicyBankAccount', () => { - const PAYER_EMAIL = 'payer@test.com'; - const NON_PAYER_ADMIN_EMAIL = 'admin@test.com'; - const POLICY_BANK_ACCOUNT_ID = 1111; - - const policyWithBankAccount: Policy = { - ...createRandomPolicy(1, CONST.POLICY.TYPE.CORPORATE), - role: CONST.POLICY.ROLE.ADMIN, - reimbursementChoice: CONST.POLICY.REIMBURSEMENT_CHOICES.REIMBURSEMENT_YES, - reimburser: PAYER_EMAIL, - achAccount: { - bankAccountID: POLICY_BANK_ACCOUNT_ID, - accountNumber: 'XXXXXX1111', - routingNumber: '123456789', - addressName: 'Test bank account', - bankName: 'Test bank', - reimburser: PAYER_EMAIL, - state: CONST.BANK_ACCOUNT.STATE.OPEN, - }, - employeeList: { - [PAYER_EMAIL]: {email: PAYER_EMAIL, role: CONST.POLICY.ROLE.ADMIN}, - [NON_PAYER_ADMIN_EMAIL]: {email: NON_PAYER_ADMIN_EMAIL, role: CONST.POLICY.ROLE.ADMIN}, - }, - }; - - const bankAccountListWithPolicyAccount = { - [POLICY_BANK_ACCOUNT_ID]: {methodID: POLICY_BANK_ACCOUNT_ID, bankCurrency: CONST.CURRENCY.USD, bankCountry: CONST.COUNTRY.US}, - }; - - // The designated payer is the case that produced the original bug: the workspace account was advertised on their Pay - // button but never shared with them, so the backend debited a different account. - it('returns false for the designated payer when the workspace account is missing from their bank account list', () => { - expect(canAccessPolicyBankAccount(policyWithBankAccount, {})).toBe(false); - }); - - it('returns true for the designated payer when the workspace account is in their bank account list', () => { - expect(canAccessPolicyBankAccount(policyWithBankAccount, bankAccountListWithPolicyAccount)).toBe(true); - }); - - it('returns false when the bank account list only holds other accounts', () => { - const otherAccountID = POLICY_BANK_ACCOUNT_ID + 1; - expect( - canAccessPolicyBankAccount(policyWithBankAccount, { - [otherAccountID]: {methodID: otherAccountID, bankCurrency: CONST.CURRENCY.USD, bankCountry: CONST.COUNTRY.US}, - }), - ).toBe(false); - }); - - it('returns false when the workspace has no connected bank account', () => { - expect(canAccessPolicyBankAccount({...policyWithBankAccount, achAccount: undefined}, bankAccountListWithPolicyAccount)).toBe(false); - }); - - it('returns false when there is no policy', () => { - expect(canAccessPolicyBankAccount(undefined, bankAccountListWithPolicyAccount)).toBe(false); - }); -}); - -describe('getAccessiblePolicyBankAccount', () => { - const POLICY_BANK_ACCOUNT_ID = 1111; - - // `achAccount.accountNumber` is deliberately a different account's number than the one `bankAccountID` resolves to. - // The two really do fall out of sync, and reading the number off `achAccount` is what makes a Pay button name an - // account other than the one the payment debits. - const policyWithStaleAccountNumber: Policy = { - ...createRandomPolicy(1, CONST.POLICY.TYPE.CORPORATE), - achAccount: { - bankAccountID: POLICY_BANK_ACCOUNT_ID, - accountNumber: 'XXXXXX9999', - routingNumber: '123456789', - addressName: 'Test bank account', - bankName: 'Test bank', - reimburser: 'payer@test.com', - state: CONST.BANK_ACCOUNT.STATE.OPEN, - }, - }; - - const bankAccountList = { - [POLICY_BANK_ACCOUNT_ID]: { - methodID: POLICY_BANK_ACCOUNT_ID, - bankCurrency: CONST.CURRENCY.USD, - bankCountry: CONST.COUNTRY.US, - accountData: {accountNumber: 'XXXXXX1234'}, - }, - }; - - it('resolves the account number through the bank account list rather than the stale one on achAccount', () => { - expect(getAccessiblePolicyBankAccount(policyWithStaleAccountNumber, bankAccountList)?.accountData?.accountNumber).toBe('XXXXXX1234'); - }); - - it('returns undefined when the workspace account is not shared with the user', () => { - expect(getAccessiblePolicyBankAccount(policyWithStaleAccountNumber, {})).toBeUndefined(); - }); - - it('returns undefined when the workspace has no connected bank account', () => { - expect(getAccessiblePolicyBankAccount({...policyWithStaleAccountNumber, achAccount: undefined}, bankAccountList)).toBeUndefined(); - }); -}); - describe('getPolicyApproverLogins', () => { it('returns an empty set when policy is undefined', () => { expect(getPolicyApproverLogins(undefined).size).toBe(0); diff --git a/tests/unit/ReportPrimaryActionUtilsTest.ts b/tests/unit/ReportPrimaryActionUtilsTest.ts index b913d72dc68b..c8a6780f5b49 100644 --- a/tests/unit/ReportPrimaryActionUtilsTest.ts +++ b/tests/unit/ReportPrimaryActionUtilsTest.ts @@ -1089,54 +1089,6 @@ describe('getPrimaryAction', () => { ).not.toBe(CONST.REPORT.PRIMARY_ACTIONS.PAY); }); - it('should return PAY for non-payer admin when a bank account is connected (reimburseYes)', async () => { - const payerEmail = 'payer@vba-test.com'; - const submitterEmail = 'member@vba-test.com'; - const report = createMock({ - reportID: REPORT_ID, - type: CONST.REPORT.TYPE.EXPENSE, - policyID: POLICY_ID, - ownerAccountID: CURRENT_USER_ACCOUNT_ID + 10, - stateNum: CONST.REPORT.STATE_NUM.APPROVED, - statusNum: CONST.REPORT.STATUS_NUM.APPROVED, - total: -300, - isWaitingOnBankAccount: false, - }); - await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${REPORT_ID}`, report); - const policy = createMock({ - id: POLICY_ID, - type: CONST.POLICY.TYPE.TEAM, - role: CONST.POLICY.ROLE.ADMIN, - owner: payerEmail, - reimbursementChoice: CONST.POLICY.REIMBURSEMENT_CHOICES.REIMBURSEMENT_YES, - achAccount: {reimburser: payerEmail}, - employeeList: { - [CURRENT_USER_EMAIL]: {role: CONST.POLICY.ROLE.ADMIN}, - [payerEmail]: {role: CONST.POLICY.ROLE.ADMIN}, - [submitterEmail]: {role: CONST.POLICY.ROLE.USER}, - }, - }); - const transaction = createMock({ - reportID: `${REPORT_ID}`, - }); - - expect( - getReportPrimaryAction({ - currentUserLogin: CURRENT_USER_EMAIL, - currentUserAccountID: CURRENT_USER_ACCOUNT_ID, - report, - ownerLogin: submitterEmail, - chatReport, - reportTransactions: [transaction], - violations: {}, - bankAccountList: {}, - policy, - isChatReportArchived: false, - rules: undefined, - }), - ).toBe(CONST.REPORT.PRIMARY_ACTIONS.PAY); - }); - it('should return PAY for non-reimburser payments admin in manual reimbursement mode when owner is payer', async () => { const ownerEmail = 'owner@manual-test.com'; const report = createMock({ diff --git a/tests/unit/ReportSecondaryActionUtilsTest.ts b/tests/unit/ReportSecondaryActionUtilsTest.ts index be4c293946df..e15da76f3606 100644 --- a/tests/unit/ReportSecondaryActionUtilsTest.ts +++ b/tests/unit/ReportSecondaryActionUtilsTest.ts @@ -13,7 +13,7 @@ import * as ReportActionsUtils from '@src/libs/ReportActionsUtils'; import * as ReportUtils from '@src/libs/ReportUtils'; import * as TransactionUtils from '@src/libs/TransactionUtils'; import ONYXKEYS from '@src/ONYXKEYS'; -import type {BankAccountList, Policy, Report, ReportAction, ReportNameValuePairs, Transaction, TransactionViolation} from '@src/types/onyx'; +import type {Policy, Report, ReportAction, ReportNameValuePairs, Transaction, TransactionViolation} from '@src/types/onyx'; import type {Connections} from '@src/types/onyx/Policy'; import type {ValueOf} from 'type-fest'; @@ -508,109 +508,6 @@ describe('getSecondaryAction', () => { expect(result.includes(CONST.REPORT.SECONDARY_ACTIONS.CANCEL_PAYMENT)).toBe(false); }); - describe('CANCEL_PAYMENT for a non-payer admin on a workspace with a connected bank account', () => { - const DESIGNATED_PAYER_EMAIL = 'payer@vba-test.com'; - const WORKSPACE_BANK_ACCOUNT_ID = 1111; - const ADMIN_OWN_BANK_ACCOUNT_ID = 2222; - const PAY_ACTION_ID = 'pay_action_id'; - - // Reimbursement is configured (reimburseYes) and someone else is the reimburser, so `isPayer` is false for - // ADMIN_EMAIL and Cancel can only come from the non-payer admin path. - const policy = createMock({ - id: POLICY_ID, - type: CONST.POLICY.TYPE.CORPORATE, - role: CONST.POLICY.ROLE.ADMIN, - owner: DESIGNATED_PAYER_EMAIL, - approvalMode: CONST.POLICY.APPROVAL_MODE.OPTIONAL, - reimbursementChoice: CONST.POLICY.REIMBURSEMENT_CHOICES.REIMBURSEMENT_YES, - reimburser: DESIGNATED_PAYER_EMAIL, - outputCurrency: CONST.CURRENCY.USD, - achAccount: {reimburser: DESIGNATED_PAYER_EMAIL, bankAccountID: WORKSPACE_BANK_ACCOUNT_ID}, - employeeList: { - [ADMIN_EMAIL]: {role: CONST.POLICY.ROLE.ADMIN}, - [DESIGNATED_PAYER_EMAIL]: {role: CONST.POLICY.ROLE.ADMIN}, - }, - }); - const report = createMock({ - reportID: REPORT_ID, - type: CONST.REPORT.TYPE.EXPENSE, - policyID: POLICY_ID, - ownerAccountID: EMPLOYEE_ACCOUNT_ID, - stateNum: CONST.REPORT.STATE_NUM.APPROVED, - statusNum: CONST.REPORT.STATUS_NUM.REIMBURSED, - total: -10000, - isWaitingOnBankAccount: false, - // Auth reports the bank reimbursement as still cancellable so the outcome depends on the access gate alone. - canCancelReimbursement: true, - }); - const transaction = createMock({reportID: REPORT_ID, amount: 10000}); - - function buildPayAction(paymentType: ValueOf, bankAccountID?: number): ReportAction { - return createMock({ - reportActionID: PAY_ACTION_ID, - actionName: CONST.REPORT.ACTIONS.TYPE.IOU, - actorAccountID: ADMIN_ACCOUNT_ID, - message: {type: CONST.IOU.REPORT_ACTION_TYPE.PAY, paymentType, bankAccountID}, - created: '2020-01-01 00:00:00.000', - }); - } - - async function getActionsForAdmin(payAction: ReportAction, bankAccountList: BankAccountList) { - // beforeEach's Onyx.clear isn't awaited; explicit clear guarantees a clean policy collection for this seed. - await Onyx.clear(); - await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}${POLICY_ID}`, policy); - await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${REPORT_ID}`, report); - await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${REPORT_ID}`, {[PAY_ACTION_ID]: payAction}); - await waitForBatchedUpdates(); - - return getSecondaryReportActions({ - currentUserLogin: ADMIN_EMAIL, - currentUserAccountID: ADMIN_ACCOUNT_ID, - submitterLogin: EMPLOYEE_EMAIL, - report, - chatReport, - reportTransactions: [transaction], - originalTransaction: createMock({}), - violations: {}, - bankAccountList, - policy, - reportActions: [payAction], - rules: undefined, - }); - } - - it('includes CANCEL_PAYMENT when the report was marked as paid', async () => { - const result = await getActionsForAdmin(buildPayAction(CONST.IOU.PAYMENT_TYPE.ELSEWHERE), {}); - expect(result.includes(CONST.REPORT.SECONDARY_ACTIONS.CANCEL_PAYMENT)).toBe(true); - }); - - it('includes CANCEL_PAYMENT when the bank account used to pay is shared with the admin', async () => { - const result = await getActionsForAdmin(buildPayAction(CONST.IOU.PAYMENT_TYPE.VBBA, ADMIN_OWN_BANK_ACCOUNT_ID), { - [ADMIN_OWN_BANK_ACCOUNT_ID]: {methodID: ADMIN_OWN_BANK_ACCOUNT_ID, bankCurrency: CONST.CURRENCY.USD, bankCountry: CONST.COUNTRY.US}, - }); - expect(result.includes(CONST.REPORT.SECONDARY_ACTIONS.CANCEL_PAYMENT)).toBe(true); - }); - - it('does not include CANCEL_PAYMENT when the bank account used to pay is not shared with the admin', async () => { - const result = await getActionsForAdmin(buildPayAction(CONST.IOU.PAYMENT_TYPE.VBBA, ADMIN_OWN_BANK_ACCOUNT_ID), { - [WORKSPACE_BANK_ACCOUNT_ID]: {methodID: WORKSPACE_BANK_ACCOUNT_ID, bankCurrency: CONST.CURRENCY.USD, bankCountry: CONST.COUNTRY.US}, - }); - expect(result.includes(CONST.REPORT.SECONDARY_ACTIONS.CANCEL_PAYMENT)).toBe(false); - }); - - it('falls back to the workspace bank account when the pay action does not name one', async () => { - const payAction = buildPayAction(CONST.IOU.PAYMENT_TYPE.VBBA); - - const withWorkspaceAccount = await getActionsForAdmin(payAction, { - [WORKSPACE_BANK_ACCOUNT_ID]: {methodID: WORKSPACE_BANK_ACCOUNT_ID, bankCurrency: CONST.CURRENCY.USD, bankCountry: CONST.COUNTRY.US}, - }); - expect(withWorkspaceAccount.includes(CONST.REPORT.SECONDARY_ACTIONS.CANCEL_PAYMENT)).toBe(true); - - const withoutWorkspaceAccount = await getActionsForAdmin(payAction, {}); - expect(withoutWorkspaceAccount.includes(CONST.REPORT.SECONDARY_ACTIONS.CANCEL_PAYMENT)).toBe(false); - }); - }); - it('does not include CANCEL_PAYMENT past the NACHA cutoff after a paid-elsewhere payment was cancelled and re-paid via bank', async () => { // Cancelling doesn't remove the original pay action, so the report keeps a stale ELSEWHERE action next to the // newer bank one. Cancel eligibility must follow the latest (bank) payment and respect its cutoff, not fall back diff --git a/tests/unit/ReportUtilsTest.ts b/tests/unit/ReportUtilsTest.ts index 16252e5c3736..c7ad7090a2a6 100644 --- a/tests/unit/ReportUtilsTest.ts +++ b/tests/unit/ReportUtilsTest.ts @@ -593,16 +593,11 @@ describe('ReportUtils', () => { describe('getIOUReportActionDisplayMessage', () => { const iouReportID = '1234567890'; const policyID = 332; - const reimburserEmail = 'reimburser@example.com'; - const reimburserAccountID = 332001; - // The workspace account is only a valid fallback for a payment made by the designated payer, so the pay action - // has to come from the reimburser for these messages to name it. const reportAction = { ...createRandomReportAction(44), actionName: CONST.REPORT.ACTIONS.TYPE.IOU, reportID: iouReportID, - actorAccountID: reimburserAccountID, originalMessage: {type: CONST.IOU.REPORT_ACTION_TYPE.PAY, paymentType: CONST.IOU.PAYMENT_TYPE.VBBA}, }; @@ -616,18 +611,10 @@ describe('ReportUtils', () => { routingNumber: '011401533', addressName: 'Bank Workspace', bankName: 'Test Bank', - reimburser: reimburserEmail, + reimburser: 'reimburser@example.com', }, }; - beforeAll(async () => { - await Onyx.merge(ONYXKEYS.PERSONAL_DETAILS_LIST, {[reimburserAccountID]: {accountID: reimburserAccountID, login: reimburserEmail}}); - }); - - afterAll(async () => { - await Onyx.merge(ONYXKEYS.PERSONAL_DETAILS_LIST, {[reimburserAccountID]: null}); - }); - it('should return the right message when payment type is ACH', async () => { await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}${policyID}`, policyWithBank); await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${iouReportID}`, iouReport); @@ -636,16 +623,16 @@ describe('ReportUtils', () => { const last4Digits = policyWithBank.achAccount?.accountNumber.slice(-4); const paidSystemMessage = translate(CONST.LOCALES.EN, 'iou.businessBankAccount', '', last4Digits); - expect(getIOUReportActionDisplayMessage(translateLocal, reportAction, convertToDisplayString, policyWithBank, undefined)).toBe(paidSystemMessage); + expect(getIOUReportActionDisplayMessage(translateLocal, reportAction, convertToDisplayString, policyWithBank.achAccount?.accountNumber, undefined)).toBe(paidSystemMessage); }); - it('should use the passed policy (not module-level allPolicies) for the bank account last 4 digits', () => { - // Given a policy passed explicitly, with no matching policy read from Onyx + it('should use the passed ACH account number (not module-level allPolicies) for the bank account last 4 digits', () => { + // Given an ACH account number passed explicitly, with no matching policy read from Onyx const last4Digits = policyWithBank.achAccount?.accountNumber.slice(-4); const paidSystemMessage = translate(CONST.LOCALES.EN, 'iou.businessBankAccount', '', last4Digits); - // Then the ACH last 4 digits are resolved from the passed policy alone - expect(getIOUReportActionDisplayMessage(translateLocal, reportAction, convertToDisplayString, policyWithBank, undefined)).toBe(paidSystemMessage); + // Then the ACH last 4 digits are resolved from the passed account number alone + expect(getIOUReportActionDisplayMessage(translateLocal, reportAction, convertToDisplayString, policyWithBank.achAccount?.accountNumber, undefined)).toBe(paidSystemMessage); }); it('should show the bank account from the action accountNumber instead of the policy default', async () => { @@ -661,7 +648,9 @@ describe('ReportUtils', () => { const paidSystemMessage = translate(CONST.LOCALES.EN, 'iou.businessBankAccount', '', '4321'); // Then the message shows the last 4 digits of that account, not the policy default - expect(getIOUReportActionDisplayMessage(translateLocal, actionWithAccountNumber, convertToDisplayString, policyWithBank, undefined)).toBe(paidSystemMessage); + expect(getIOUReportActionDisplayMessage(translateLocal, actionWithAccountNumber, convertToDisplayString, policyWithBank.achAccount?.accountNumber, undefined)).toBe( + paidSystemMessage, + ); }); it('should show the cross-border FX message with the credited amount and both account last-4s', async () => { @@ -685,7 +674,7 @@ describe('ReportUtils', () => { debitBankAccount: '6789', creditBankAccount: '3335', }); - expect(getIOUReportActionDisplayMessage(translateLocal, crossBorderAction, convertToDisplayString, policyWithBank, undefined)).toBe(expectedMessage); + expect(getIOUReportActionDisplayMessage(translateLocal, crossBorderAction, convertToDisplayString, policyWithBank.achAccount?.accountNumber, undefined)).toBe(expectedMessage); }); it('should return received payment when submitter marked payment received', () => { @@ -700,7 +689,7 @@ describe('ReportUtils', () => { }, }; - expect(getIOUReportActionDisplayMessage(translateLocal, paymentReceivedReportAction, convertToDisplayString, policyWithBank, undefined)).toBe( + expect(getIOUReportActionDisplayMessage(translateLocal, paymentReceivedReportAction, convertToDisplayString, policyWithBank.achAccount?.accountNumber, undefined)).toBe( translateLocal('iou.receivedPaymentReportAction'), ); }); @@ -716,7 +705,9 @@ describe('ReportUtils', () => { }, }; - expect(getIOUReportActionDisplayMessage(translateLocal, paidElsewhereReportAction, convertToDisplayString, policyWithBank, undefined)).toBe(translateLocal('iou.paidElsewhere')); + expect(getIOUReportActionDisplayMessage(translateLocal, paidElsewhereReportAction, convertToDisplayString, policyWithBank.achAccount?.accountNumber, undefined)).toBe( + translateLocal('iou.paidElsewhere'), + ); }); it('should return an empty string for a non-money-request action', () => { @@ -725,10 +716,10 @@ describe('ReportUtils', () => { actionName: CONST.REPORT.ACTIONS.TYPE.CREATED, }; - expect(getIOUReportActionDisplayMessage(translateLocal, createdAction, convertToDisplayString, policyWithBank, undefined)).toBe(''); + expect(getIOUReportActionDisplayMessage(translateLocal, createdAction, convertToDisplayString, policyWithBank.achAccount?.accountNumber, undefined)).toBe(''); }); - it('should use the passed policy for the last 4 digits of an automatic VBBA payment', () => { + it('should use the passed ACH account number for the last 4 digits of an automatic VBBA payment', () => { // Given an automatically-paid VBBA action with no accountNumber on the action itself const automaticVBBAAction = { ...reportAction, @@ -737,8 +728,8 @@ describe('ReportUtils', () => { const last4Digits = policyWithBank.achAccount?.accountNumber.slice(-4); const expected = translate(CONST.LOCALES.EN, 'iou.automaticallyPaidWithBusinessBankAccount', '', last4Digits); - // Then the workspace-rules message resolves the last 4 digits from the passed policy - expect(getIOUReportActionDisplayMessage(translateLocal, automaticVBBAAction, convertToDisplayString, policyWithBank, undefined)).toBe(expected); + // Then the workspace-rules message resolves the last 4 digits from the passed account number + expect(getIOUReportActionDisplayMessage(translateLocal, automaticVBBAAction, convertToDisplayString, policyWithBank.achAccount?.accountNumber, undefined)).toBe(expected); }); it('should return the workspace-rules message for an automatic Expensify payment', () => { @@ -747,32 +738,11 @@ describe('ReportUtils', () => { originalMessage: {type: CONST.IOU.REPORT_ACTION_TYPE.PAY, paymentType: CONST.IOU.PAYMENT_TYPE.EXPENSIFY, automaticAction: true}, }; - expect(getIOUReportActionDisplayMessage(translateLocal, automaticExpensifyAction, convertToDisplayString, policyWithBank, undefined)).toBe( + expect(getIOUReportActionDisplayMessage(translateLocal, automaticExpensifyAction, convertToDisplayString, policyWithBank.achAccount?.accountNumber, undefined)).toBe( translate(CONST.LOCALES.EN, 'iou.automaticallyPaidWithExpensify', ''), ); }); - it('should not attribute a non-payer admin VBBA payment to the workspace bank account', () => { - // Given a VBBA pay action with no account on it, made by an admin who is not the designated payer - const nonPayerAdminAction = {...reportAction, actorAccountID: reimburserAccountID + 1}; - - // Then the message does not guess the workspace account, since the admin paid from an account of their own - expect(getIOUReportActionDisplayMessage(translateLocal, nonPayerAdminAction, convertToDisplayString, policyWithBank, undefined)).toBe( - translate(CONST.LOCALES.EN, 'iou.businessBankAccount', '', ''), - ); - }); - - it('should keep the workspace bank account when the reimburser is not in personal details', () => { - // Given a policy whose reimburser this viewer has never interacted with (no personal details loaded) - const policyWithUnknownReimburser: Policy = {...policyWithBank, reimburser: 'unknown-reimburser@example.com'}; - const last4Digits = policyWithBank.achAccount?.accountNumber.slice(-4); - - // Then the payer can't be ruled out, so the message keeps the workspace account instead of blanking the digits - expect(getIOUReportActionDisplayMessage(translateLocal, reportAction, convertToDisplayString, policyWithUnknownReimburser, undefined)).toBe( - translate(CONST.LOCALES.EN, 'iou.businessBankAccount', '', last4Digits), - ); - }); - it('should return the approved amount when the IOU report is approved', async () => { // Given an approved (not yet settled) expense report and a matching CREATE action const approvedReportID = '9988776655'; @@ -19927,8 +19897,6 @@ describe('ReportUtils', () => { describe('settled report paid with a business bank account', () => { const settledPolicyID = '445'; - const reimburserEmail = 'reimburser@example.com'; - const reimburserAccountID = 445001; const settledPolicy: Policy = { ...createRandomPolicy(Number(settledPolicyID), CONST.POLICY.TYPE.TEAM), id: settledPolicyID, @@ -19938,7 +19906,7 @@ describe('ReportUtils', () => { routingNumber: '011401533', addressName: 'Settled Workspace', bankName: 'Test Bank', - reimburser: reimburserEmail, + reimburser: 'reimburser@example.com', }, }; const settledReport: Report = { @@ -19955,25 +19923,17 @@ describe('ReportUtils', () => { amount: 10000, currency: CONST.CURRENCY.USD, }; - // The workspace account is only a valid fallback for a payment made by the designated payer, so the - // action has to come from the reimburser for these previews to name it. const payReportAction: ReportAction = { - ...LHNTestUtils.getFakeReportAction(reimburserEmail), - actorAccountID: reimburserAccountID, + ...LHNTestUtils.getFakeReportAction(), actionName: CONST.REPORT.ACTIONS.TYPE.IOU, originalMessage: payOriginalMessage, }; beforeEach(async () => { - await Onyx.merge(ONYXKEYS.PERSONAL_DETAILS_LIST, {[reimburserAccountID]: {accountID: reimburserAccountID, login: reimburserEmail}}); await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}${settledPolicyID}`, settledPolicy); await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${settledReport.reportID}`, settledReport); }); - afterEach(async () => { - await Onyx.merge(ONYXKEYS.PERSONAL_DETAILS_LIST, {[reimburserAccountID]: null}); - }); - it('shows the bank account from the action accountNumber instead of the policy default', () => { // Given a pay action that carries the masked accountNumber of the bank account actually used const actionWithAccountNumber: ReportAction = { @@ -19999,51 +19959,6 @@ describe('ReportUtils', () => { expect(result).toBe(translate(CONST.LOCALES.EN, 'iou.businessBankAccount', '', '0000')); }); - describe('when the payment names the bank account it came from', () => { - // A paying admin picks the account to pay from, so a workspace payment now carries a bankAccountID the - // same way an invoice payment does. That must not turn the preview into the invoice wording - // ("paid $100.00 with personal account 6281"). It is a workspace payment and reads "paid with bank - // account 6281", which is also what PaymentContent renders on the action itself. - const actionNamingAccount: ReportAction = { - ...payReportAction, - originalMessage: {...payOriginalMessage, bankAccountID: 6281001, accountNumber: 'XXXXXX6281'}, - }; - - it('keeps the bank account wording in the localized preview', () => { - const englishTranslate: LocalizedTranslate = (path, ...parameters) => translate(CONST.LOCALES.EN, path, ...parameters); - - const result = getReportPreviewMessage(englishTranslate, convertToDisplayString, { - reportOrID: settledReport, - iouReportAction: actionNamingAccount, - originalReportAction: actionNamingAccount, - policy: settledPolicy, - }); - - expect(result).toBe(translate(CONST.LOCALES.EN, 'iou.businessBankAccount', '', '6281')); - }); - - it('keeps the bank account wording in the stored report action message', () => { - const result = getReportPreviewReportActionMessage( - {reportOrID: settledReport, iouReportAction: actionNamingAccount, originalReportAction: actionNamingAccount, policy: settledPolicy}, - getCurrencyDecimalsLocal, - ); - - expect(result).toBe(translate(CONST.LOCALES.EN, 'iou.businessBankAccount', '', '6281')); - }); - - it('resolves the account through bankAccountList when the action only carries its ID', () => { - // Given the payer paid from an account other than the workspace one, and the action recorded only its ID - const actionNamingAccountID: ReportAction = {...payReportAction, originalMessage: {...payOriginalMessage, bankAccountID: 5678001}}; - const bankAccountList = createMock({5678001: {accountData: {accountNumber: 'XXXXXX5678'}}}); - const englishTranslate: LocalizedTranslate = (path, ...parameters) => translate(CONST.LOCALES.EN, path, ...parameters); - const params = {reportOrID: settledReport, iouReportAction: actionNamingAccountID, originalReportAction: actionNamingAccountID, policy: settledPolicy, bankAccountList}; - - // Then both previews name that account, matching PaymentContent, rather than the workspace default - expect(getReportPreviewMessage(englishTranslate, convertToDisplayString, params)).toBe(translate(CONST.LOCALES.EN, 'iou.businessBankAccount', '', '5678')); - expect(getReportPreviewReportActionMessage(params, getCurrencyDecimalsLocal)).toBe(translate(CONST.LOCALES.EN, 'iou.businessBankAccount', '', '5678')); - }); - }); - it('matches the localized getReportPreviewMessage output when translated to English', () => { const englishTranslate: LocalizedTranslate = (path, ...parameters) => translate(CONST.LOCALES.EN, path, ...parameters); const params = {reportOrID: settledReport, iouReportAction: payReportAction, originalReportAction: payReportAction, policy: settledPolicy}; diff --git a/tests/unit/Search/handleActionButtonPressTest.ts b/tests/unit/Search/handleActionButtonPressTest.ts index 2f6f345b2cf7..19f7893ebff5 100644 --- a/tests/unit/Search/handleActionButtonPressTest.ts +++ b/tests/unit/Search/handleActionButtonPressTest.ts @@ -362,7 +362,6 @@ describe('handleActionButtonPress', () => { isTrackIntentUser: false, allViolations: undefined, rules: undefined, - bankAccountList: undefined, }); expect(goToItem).not.toHaveBeenCalled(); }); @@ -392,7 +391,6 @@ describe('handleActionButtonPress', () => { isTrackIntentUser: false, allViolations: undefined, rules: undefined, - bankAccountList: undefined, }); expect(onHoldMenuOpen).toHaveBeenCalledWith(mockReportItemWithHold, CONST.IOU.REPORT_ACTION_TYPE.APPROVE); @@ -422,7 +420,6 @@ describe('handleActionButtonPress', () => { isTrackIntentUser: false, allViolations: undefined, rules: undefined, - bankAccountList: undefined, }); expect(goToItem).toHaveBeenCalledTimes(0); }); @@ -460,7 +457,6 @@ describe('handleActionButtonPress', () => { rules: undefined, conciergeChat: undefined, getCurrencyDecimals: getCurrencyDecimalsLocal, - bankAccountList: undefined, }); // Then: hasViolations is evaluated against the passed collection, proving the deprecated global getter is no longer used, diff --git a/tests/unit/getBankAccountLastFourDigitsTest.ts b/tests/unit/getBankAccountLastFourDigitsTest.ts index f96997786659..d3aad4f045e9 100644 --- a/tests/unit/getBankAccountLastFourDigitsTest.ts +++ b/tests/unit/getBankAccountLastFourDigitsTest.ts @@ -1,13 +1,6 @@ import getBankAccountLastFourDigits from '@libs/getBankAccountLastFourDigits'; -import CONST from '@src/CONST'; -import ONYXKEYS from '@src/ONYXKEYS'; -import type {BankAccount, Policy} from '@src/types/onyx'; - -import Onyx from 'react-native-onyx'; - -import createRandomPolicy from '../utils/collections/policies'; -import waitForBatchedUpdates from '../utils/waitForBatchedUpdates'; +import type {BankAccount} from '@src/types/onyx'; function createBankAccountList(bankAccountID: number, accountNumber?: string): Record { return { @@ -20,117 +13,35 @@ function createBankAccountList(bankAccountID: number, accountNumber?: string): R } describe('libs/getBankAccountLastFourDigits', () => { - const POLICY_BANK_ACCOUNT_ID = 1111; - const PAYER_EMAIL = 'payer@test.com'; - const PAYER_ACCOUNT_ID = 101; - const NON_PAYER_ADMIN_ACCOUNT_ID = 102; - - const policy: Policy = { - ...createRandomPolicy(3, CONST.POLICY.TYPE.CORPORATE), - reimbursementChoice: CONST.POLICY.REIMBURSEMENT_CHOICES.REIMBURSEMENT_YES, - reimburser: PAYER_EMAIL, - achAccount: { - bankAccountID: POLICY_BANK_ACCOUNT_ID, - accountNumber: 'XXXXXX1111', - routingNumber: '123456789', - addressName: 'Test bank account', - bankName: 'Test bank', - reimburser: PAYER_EMAIL, - }, - }; - - beforeAll(() => { - Onyx.init({keys: ONYXKEYS}); - }); - - beforeEach(async () => { - await Onyx.set(ONYXKEYS.PERSONAL_DETAILS_LIST, { - [PAYER_ACCOUNT_ID]: {accountID: PAYER_ACCOUNT_ID, login: PAYER_EMAIL}, - [NON_PAYER_ADMIN_ACCOUNT_ID]: {accountID: NON_PAYER_ADMIN_ACCOUNT_ID, login: 'wsadmin@test.com'}, - }); - await waitForBatchedUpdates(); - }); - - afterEach(async () => { - await Onyx.clear(); - await waitForBatchedUpdates(); - }); - - it('uses the account stored on the payment action over anything resolved locally', () => { - // Given a payment action that carries its own masked account number - // When the digits are resolved for a non-payer admin's payment - // Then the action's number wins, since it is the only viewer-independent source - expect(getBankAccountLastFourDigits({bankAccountID: undefined, bankAccountList: {}, policy, accountNumber: 'XXXXXX0000', payerAccountID: NON_PAYER_ADMIN_ACCOUNT_ID})).toBe('0000'); - }); - it('returns the last four digits of the account the payment names', () => { - // Given the named account is in the viewer's bank account list const bankAccountList = createBankAccountList(123, '1234567890'); - // Then its account number is used - expect(getBankAccountLastFourDigits({bankAccountID: 123, bankAccountList, policy, payerAccountID: PAYER_ACCOUNT_ID})).toBe('7890'); + expect(getBankAccountLastFourDigits(123, bankAccountList, '9999999999')).toBe('7890'); }); it('returns an empty string when the named account is missing from the list, so a multi-VBBA payment never shows the policy account digits', () => { - // Given the payment names an account the viewer doesn't have const bankAccountList = createBankAccountList(456, '1234567890'); - // Then nothing is shown rather than the workspace account - expect(getBankAccountLastFourDigits({bankAccountID: 123, bankAccountList, policy, payerAccountID: PAYER_ACCOUNT_ID})).toBe(''); + expect(getBankAccountLastFourDigits(123, bankAccountList, '9999999999')).toBe(''); }); it('returns an empty string when the named account carries no account number', () => { - // Given the named account has no account data const bankAccountList = createBankAccountList(123); - // Then nothing is shown - expect(getBankAccountLastFourDigits({bankAccountID: 123, bankAccountList, policy, payerAccountID: PAYER_ACCOUNT_ID})).toBe(''); + expect(getBankAccountLastFourDigits(123, bankAccountList, '9999999999')).toBe(''); }); it('returns an empty string when the payment names an account but the list has not loaded', () => { - // Given no bank account list at all - // Then nothing is shown, since the named account can't be resolved - expect(getBankAccountLastFourDigits({bankAccountID: 123, bankAccountList: undefined, policy, payerAccountID: PAYER_ACCOUNT_ID})).toBe(''); - }); - - it('falls back to the workspace account for a payment made by the designated payer', () => { - // Given a payment by the designated payer that names no account - // Then the workspace account is assumed - expect(getBankAccountLastFourDigits({bankAccountID: undefined, bankAccountList: {}, policy, payerAccountID: PAYER_ACCOUNT_ID})).toBe('1111'); - }); - - it('prefers the workspace account number from the bank account list over the stale one on the policy', () => { - // Given the viewer has the workspace account, whose number differs from the one cached on the policy - const bankAccountList = createBankAccountList(POLICY_BANK_ACCOUNT_ID, '9999999999'); - - // Then the number of the account that is actually debited is shown - expect(getBankAccountLastFourDigits({bankAccountID: undefined, bankAccountList, policy, payerAccountID: PAYER_ACCOUNT_ID})).toBe('9999'); - }); - - it('does not attribute the workspace account to a payment made by a non-payer admin', () => { - // Given a payment by an admin who isn't the designated payer and names no account - // Then no digits are shown, since that admin paid from an account of their own - expect(getBankAccountLastFourDigits({bankAccountID: undefined, bankAccountList: {}, policy, payerAccountID: NON_PAYER_ADMIN_ACCOUNT_ID})).toBe(''); + expect(getBankAccountLastFourDigits(123, undefined, '9999999999')).toBe(''); }); - it('does not attribute the workspace account to a payment that names another bank account', () => { - // Given a payment by the designated payer that names an account other than the workspace one - // Then the workspace account is not assumed - expect(getBankAccountLastFourDigits({bankAccountID: 2222, bankAccountList: {}, policy, payerAccountID: PAYER_ACCOUNT_ID})).toBe(''); - }); - - it('keeps the workspace account when the reimburser cannot be resolved from personal details', async () => { - // Given a viewer who has never interacted with the designated payer, so their personal details aren't loaded - await Onyx.set(ONYXKEYS.PERSONAL_DETAILS_LIST, {[NON_PAYER_ADMIN_ACCOUNT_ID]: {accountID: NON_PAYER_ADMIN_ACCOUNT_ID, login: 'wsadmin@test.com'}}); - await waitForBatchedUpdates(); + it("falls back to the workspace's reimbursement account when the payment names no account", () => { + const bankAccountList = createBankAccountList(123, '1234567890'); - // Then the payer can't be ruled out, so the pre-existing workspace account fallback is kept - expect(getBankAccountLastFourDigits({bankAccountID: undefined, bankAccountList: {}, policy, payerAccountID: PAYER_ACCOUNT_ID})).toBe('1111'); + expect(getBankAccountLastFourDigits(undefined, bankAccountList, '9999999999')).toBe('9999'); }); it('returns an empty string when the payment names no account and the workspace has none either', () => { - // Given no bank account anywhere - // Then nothing is shown - expect(getBankAccountLastFourDigits({bankAccountID: undefined, bankAccountList: undefined, policy: undefined})).toBe(''); + expect(getBankAccountLastFourDigits(undefined, undefined, undefined)).toBe(''); }); });