Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 6 additions & 8 deletions src/components/KYCWall/BaseKYCWall.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import useOnyx from '@hooks/useOnyx';
import useParentReportAction from '@hooks/useParentReportAction';
import {usePersonalDetail} from '@hooks/usePersonalDetails';
import useReportTransactions from '@hooks/useReportTransactions';
import useSubmitterWorkspaceChatActions from '@hooks/useSubmitterWorkspaceChatActions';

import {openPersonalBankAccountSetupView, setPersonalBankAccountContinueKYCOnSuccess} from '@libs/actions/BankAccounts';
import {completePaymentOnboarding, savePreferredPaymentMethod} from '@libs/actions/IOU/PayMoneyRequest';
Expand All @@ -20,7 +21,7 @@ import setNavigationActionToMicrotaskQueue from '@libs/Navigation/helpers/setNav
import Navigation from '@libs/Navigation/Navigation';
import {hasExpensifyPaymentMethod} from '@libs/PaymentUtils';
import {getAccessiblePolicyBankAccount} from '@libs/PolicyPaymentUtils';
import {getAllPolicyExpenseChatReportActions, getBankAccountRoute, getInvoiceReceiverPolicyID, isExpenseReport as isExpenseReportReportUtils, isIOUReport} from '@libs/ReportUtils';
import {getBankAccountRoute, getInvoiceReceiverPolicyID, isExpenseReport as isExpenseReportReportUtils, isIOUReport} from '@libs/ReportUtils';
import {getEligibleExistingBusinessBankAccounts, getOpenConnectedToPolicyBusinessBankAccounts} from '@libs/WorkflowUtils';

import {createWorkspaceFromIOUPayment} from '@userActions/Policy/Policy';
Expand Down Expand Up @@ -95,8 +96,7 @@ function KYCWall({
const localCurrency = currentUserDetails.localCurrencyCode ?? CONST.CURRENCY.USD;
const reportPreviewAction = useParentReportAction(iouReport);
const reportTransactions = useReportTransactions(iouReport?.reportID);
const [allReports] = useOnyx(ONYXKEYS.COLLECTION.REPORT);
const [allReportActions] = useOnyx(ONYXKEYS.COLLECTION.REPORT_ACTIONS);
const submitterWorkspaceChatActions = useSubmitterWorkspaceChatActions(isIOUReport(iouReport) ? ownerAccountID : undefined);
const anchorRef = useRef<ComponentRef<typeof View>>(null);
const transferBalanceButtonRef = useRef<unknown>(null);

Expand Down Expand Up @@ -167,14 +167,13 @@ function KYCWall({
} else if (paymentMethod === CONST.PAYMENT_METHODS.DEBIT_CARD) {
Navigation.navigate(addDebitCardRoute ?? ROUTES.INBOX);
} else if (paymentMethod === CONST.PAYMENT_METHODS.BUSINESS_BANK_ACCOUNT || policy) {
const filteredReportActions = getAllPolicyExpenseChatReportActions(allReports, allReportActions);
if (iouReport && isIOUReport(iouReport)) {
const adminPolicy = policies?.[`${ONYXKEYS.COLLECTION.POLICY}${policy?.id}`];
if (adminPolicy) {
const inviteResult = moveIOUReportToPolicyAndInviteSubmitter(
iouReport,
adminPolicy,
filteredReportActions,
submitterWorkspaceChatActions,
reportPreviewAction,
currentUserAccountID,
employeeLogin,
Expand Down Expand Up @@ -220,7 +219,7 @@ function KYCWall({
currentUserLocalCurrency: localCurrency,
lastWorkspaceNumber,
localeTranslate: translate,
reportActionsList: filteredReportActions,
reportActionsList: submitterWorkspaceChatActions,
doesEmployeePersonalDetailExist: doesSubmitterPersonalDetailExist ?? false,
getCurrencyDecimals,
reportTransactions,
Expand Down Expand Up @@ -323,8 +322,7 @@ function KYCWall({
introSelected,
translate,
reportTransactions,
allReports,
allReportActions,
submitterWorkspaceChatActions,
lastPaymentMethod,
isSelfTourViewed,
conciergeChat,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,27 +5,28 @@ import type {PaymentActionParams} from '@components/SettlementButton/types';

import {useCurrencyListActions} from '@hooks/useCurrencyList';
import useNetwork from '@hooks/useNetwork';
import useOnyx from '@hooks/useOnyx';
import useOnyx, {getSnapshotKeyData} from '@hooks/useOnyx';
import {getParticipantsInvoiceReport} from '@hooks/useParticipantsInvoiceReport';
import {useReportPaymentContext} from '@hooks/usePaymentContext';
import usePayViaABA from '@hooks/usePayViaABA';
import usePayWithWiseQuote from '@hooks/usePayWithWiseQuote';
import usePolicy from '@hooks/usePolicy';
import useReportIsArchived from '@hooks/useReportIsArchived';
import useReportWithTransactionsAndViolations from '@hooks/useReportWithTransactionsAndViolations';
import useThemeStyles from '@hooks/useThemeStyles';

import {payInvoice} from '@libs/actions/IOU/PayMoneyRequest';
import {getChatReportWithFallback, getSearchPayOnyxData} from '@libs/actions/Search';
import getNonEmptyStringOnyxID from '@libs/getNonEmptyStringOnyxID';
import Log from '@libs/Log';
import {canIOUBePaid, getReimbursableTotal, isArchivedReport, isIndividualInvoiceRoom, isInvoiceReport} from '@libs/ReportUtils';
import {canIOUBePaid, getReimbursableTotal, isIndividualInvoiceRoom, isInvoiceReport} from '@libs/ReportUtils';

import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import ROUTES from '@src/ROUTES';
import type {Report} from '@src/types/onyx';
import type {Report, ReportNameValuePairs} from '@src/types/onyx';

import type {OnyxEntry} from 'react-native-onyx';
import type {OnyxCollection, OnyxEntry} from 'react-native-onyx';

import {hasSeenTourSelector, isTrackIntentUserSelector} from '@selectors/Onboarding';
import React from 'react';
Expand All @@ -52,9 +53,6 @@ function PayActionCell({isLoading, policyID, reportID, hash, amount, shouldDisab
const policy = usePolicy(policyID);
const {payReportsViaABA, isDownloadingABAFile} = usePayViaABA();
const [bankAccountList] = useOnyx(ONYXKEYS.BANK_ACCOUNT_LIST);
const [allReports] = useOnyx(ONYXKEYS.COLLECTION.REPORT);
const [allReportActions] = useOnyx(ONYXKEYS.COLLECTION.REPORT_ACTIONS);
const [reportNameValuePairs] = useOnyx(ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS);

const invoiceReceiverPolicyID = chatReport?.invoiceReceiver && 'policyID' in chatReport.invoiceReceiver ? chatReport.invoiceReceiver.policyID : undefined;
const invoiceReceiverPolicy = usePolicy(invoiceReceiverPolicyID);
Expand All @@ -74,7 +72,7 @@ function PayActionCell({isLoading, policyID, reportID, hash, amount, shouldDisab
chatReportPolicyID: chatReport?.policyID,
});

const isChatReportArchived = isArchivedReport(reportNameValuePairs?.[`${ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS}${chatReport?.reportID}`]);
const isChatReportArchived = useReportIsArchived(chatReport?.reportID);
const canBePaid = canIOUBePaid(
iouReport,
chatReport,
Expand Down Expand Up @@ -140,20 +138,28 @@ function PayActionCell({isLoading, policyID, reportID, hash, amount, shouldDisab
Log.info('[SearchPay] Dropping invoice row pay: chat report is not loaded', false, {reportID});
return;
}
const existingB2BInvoiceReport = getParticipantsInvoiceReport(
allReports,
reportNameValuePairs,
activePolicyID,
CONST.REPORT.INVOICE_RECEIVER_TYPE.BUSINESS,
invoiceReceiverPolicyID ?? chatReport?.policyID,
);
// eslint-disable-next-line rulesdir/no-onyx-get-snapshot-key -- deliberately live, not the Search snapshot the old useOnyx read outside to-do lists: payInvoice builds optimistic data against live keys, so the invoice room lookup tries live reports and name-value pairs first and the snapshot only when live has no match
const [allReports, reportNameValuePairs] = await Onyx.multiGet([ONYXKEYS.COLLECTION.REPORT, ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS]);
const receiverPolicyID = invoiceReceiverPolicyID ?? chatReport?.policyID;
let existingB2BInvoiceReport = getParticipantsInvoiceReport(allReports, reportNameValuePairs, activePolicyID, CONST.REPORT.INVOICE_RECEIVER_TYPE.BUSINESS, receiverPolicyID);
const snapshot = !existingB2BInvoiceReport && hash !== undefined ? await Onyx.get(`${ONYXKEYS.COLLECTION.SNAPSHOT}${hash}`) : undefined;
if (snapshot) {
existingB2BInvoiceReport = getParticipantsInvoiceReport(
getSnapshotKeyData<typeof ONYXKEYS.COLLECTION.REPORT, OnyxCollection<Report>>(snapshot, ONYXKEYS.COLLECTION.REPORT),
getSnapshotKeyData<typeof ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS, OnyxCollection<ReportNameValuePairs>>(snapshot, ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS),
activePolicyID,
CONST.REPORT.INVOICE_RECEIVER_TYPE.BUSINESS,
receiverPolicyID,
);
}

// getPayMoneyRequestParams resolves the chat report from `chatReport` but swaps to `existingB2BInvoiceReport`
// when paying an individual invoice room as a business. `payAsBusiness` is only known at click time, so pick
// the right report's actions here in the function scope.
const shouldUseB2BInvoiceReport = !!payAsBusiness && !!existingB2BInvoiceReport && isIndividualInvoiceRoom(chatReport);
const chatReportActions =
allReportActions?.[`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${getNonEmptyStringOnyxID(shouldUseB2BInvoiceReport ? existingB2BInvoiceReport?.reportID : chatReport?.reportID)}`];
const chatReportActionsID = getNonEmptyStringOnyxID(shouldUseB2BInvoiceReport ? existingB2BInvoiceReport?.reportID : chatReport?.reportID);
// eslint-disable-next-line rulesdir/no-onyx-get-snapshot-key -- deliberately live, not the Search snapshot the old useOnyx read outside to-do lists: the payment updates the report preview in live report actions, so it must find it there
const chatReportActions = await Onyx.get(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${chatReportActionsID}`);

const {conciergeChat, rules, introSelected, isTrackIntentUser, isSelfTourViewed} = await readPaymentInputs();
payInvoice({
Expand Down Expand Up @@ -201,6 +207,8 @@ function PayActionCell({isLoading, policyID, reportID, hash, amount, shouldDisab
}

const {conciergeChat, rules, introSelected, userBillingGracePeriodEnds, amountOwed, ownerBillingGracePeriodEnd, isTrackIntentUser, isSelfTourViewed} = await readPaymentInputs();
// eslint-disable-next-line rulesdir/no-onyx-get-snapshot-key -- deliberately live, not the Search snapshot the old useOnyx read outside to-do lists: the payment updates the report preview in live report actions, so it must find it there
const chatReportActions = await Onyx.get(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${getNonEmptyStringOnyxID(chatReport?.reportID)}`);
Comment thread
sosek108 marked this conversation as resolved.
Resolved
payWithWiseQuote({
bankAccountList,
isASAPSubmitBetaEnabled,
Expand All @@ -223,7 +231,7 @@ function PayActionCell({isLoading, policyID, reportID, hash, amount, shouldDisab
methodID: type === CONST.IOU.PAYMENT_TYPE.VBBA ? methodID : undefined,
isWiseReimbursementsBetaEnabled,
additionalOnyxData,
chatReportActions: allReportActions?.[`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${getNonEmptyStringOnyxID(chatReport?.reportID)}`],
chatReportActions,
delegateAccountID,
isTrackIntentUser,
conciergeChat,
Expand Down
1 change: 1 addition & 0 deletions src/hooks/useOnyx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,3 +93,4 @@ const useOnyx: UseOnyxWithoutSnapshots = <TKey extends OnyxKey, TReturnValue = O
};

export default useOnyx;
export {getKeyData as getSnapshotKeyData};
43 changes: 43 additions & 0 deletions src/hooks/useSubmitterWorkspaceChatActions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import {isPolicyExpenseChat, isThread} from '@libs/ReportUtils';

import ONYXKEYS from '@src/ONYXKEYS';
import type {ReportActions} from '@src/types/onyx';

import type {OnyxCollection} from 'react-native-onyx';

import useOnyx from './useOnyx';

/** Report actions of the submitter's workspace chats, keyed like the REPORT_ACTIONS collection. Empty when `submitterAccountID` is undefined. */
function useSubmitterWorkspaceChatActions(submitterAccountID: number | undefined): OnyxCollection<ReportActions> {
const [submitterWorkspaceChatIDs] = useOnyx(ONYXKEYS.COLLECTION.REPORT, {
selector: (reports) => {
if (submitterAccountID === undefined) {
return undefined;
}
const reportIDs: string[] = [];
for (const report of Object.values(reports ?? {})) {
if (report?.reportID && report.ownerAccountID === submitterAccountID && isPolicyExpenseChat(report) && !isThread(report)) {
reportIDs.push(report.reportID);
}
}
return reportIDs;
},
});
const [submitterWorkspaceChatActions] = useOnyx(ONYXKEYS.COLLECTION.REPORT_ACTIONS, {
selector: (allReportActions) => {
const reportActions: OnyxCollection<ReportActions> = {};
for (const reportID of submitterWorkspaceChatIDs ?? []) {
const key = `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportID}` as const;
const actions = allReportActions?.[key];
if (actions) {
reportActions[key] = actions;
}
}
return reportActions;
},
});

return submitterWorkspaceChatActions;
}

export default useSubmitterWorkspaceChatActions;
156 changes: 156 additions & 0 deletions tests/ui/components/KYCWallTest.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
import {act, render} from '@testing-library/react-native';

import ComposeProviders from '@components/ComposeProviders';
import {CurrentUserPersonalDetailsProvider} from '@components/CurrentUserPersonalDetailsProvider';
import KYCWall from '@components/KYCWall';
import type {ContinueActionParams, KYCWallRef} from '@components/KYCWall/types';
import {LocaleContextProvider} from '@components/LocaleContextProvider';
import OnyxListItemProvider from '@components/OnyxListItemProvider';

import type * as ReportActionsModule from '@libs/actions/Report';
import {moveIOUReportToPolicyAndInviteSubmitter} from '@libs/actions/Report';

import CONST from '@src/CONST';
import IntlStore from '@src/languages/IntlStore';
import ONYXKEYS from '@src/ONYXKEYS';
import ROUTES from '@src/ROUTES';
import type {Policy, Report, ReportActions} from '@src/types/onyx';

import React from 'react';
import Onyx from 'react-native-onyx';

import createRandomPolicy from '../../utils/collections/policies';
import createRandomReportAction from '../../utils/collections/reportActions';
import waitForBatchedUpdatesWithAct from '../../utils/waitForBatchedUpdatesWithAct';

jest.mock('@libs/Navigation/Navigation', () => ({
__esModule: true,
default: {
navigate: jest.fn(),
goBack: jest.fn(),
getActiveRoute: jest.fn(() => ''),
},
}));

jest.mock('@libs/actions/Report', () => {
const actual = jest.requireActual<typeof ReportActionsModule>('@libs/actions/Report');
return {
...actual,
__esModule: true,
moveIOUReportToPolicy: jest.fn(() => undefined),
moveIOUReportToPolicyAndInviteSubmitter: jest.fn(() => undefined),
};
});

const mockedMoveIOUReportToPolicyAndInviteSubmitter = jest.mocked(moveIOUReportToPolicyAndInviteSubmitter);

const POLICY_ID = 'kyc-wall-policy';
const WORKSPACE_CHAT_ID = '300';

const iouReport = {
reportID: '100',
chatReportID: '200',
type: CONST.REPORT.TYPE.IOU,
ownerAccountID: 2,
managerID: 1,
currency: CONST.CURRENCY.USD,
} as Report;

const adminPolicy: Policy = {
...createRandomPolicy(1, CONST.POLICY.TYPE.TEAM, 'Admin workspace'),
id: POLICY_ID,
role: CONST.POLICY.ROLE.ADMIN,
outputCurrency: CONST.CURRENCY.USD,
};

const workspaceChat = {
reportID: WORKSPACE_CHAT_ID,
type: CONST.REPORT.TYPE.CHAT,
chatType: CONST.REPORT.CHAT_TYPE.POLICY_EXPENSE_CHAT,
policyID: POLICY_ID,
ownerAccountID: iouReport.ownerAccountID,
} as Report;

const workspaceChatAction = createRandomReportAction(1);
const workspaceChatActions: ReportActions = {[workspaceChatAction.reportActionID]: workspaceChatAction};

describe('KYCWall', () => {
beforeAll(() => {
Onyx.init({keys: ONYXKEYS});
IntlStore.load(CONST.LOCALES.EN);
});

afterEach(async () => {
jest.clearAllMocks();
await Onyx.clear();
});

it('should pass the submitter workspace chat actions when moving an IOU report to a workspace', async () => {
// Given an IOU report payer without a payment method who administers a workspace
await Onyx.set(`${ONYXKEYS.COLLECTION.POLICY}${POLICY_ID}`, adminPolicy);
let continueAction: ((params?: ContinueActionParams) => void) | undefined;
render(
<ComposeProviders components={[OnyxListItemProvider, LocaleContextProvider, CurrentUserPersonalDetailsProvider]}>
<KYCWall
ref={React.createRef<KYCWallRef>()}
iouReport={iouReport}
chatReportID={iouReport.chatReportID}
enablePaymentsRoute={ROUTES.ENABLE_PAYMENTS}
onSuccessfulKYC={jest.fn()}
>
{(triggerKYCFlow) => {
continueAction = triggerKYCFlow;
}}
</KYCWall>
</ComposeProviders>,
);
await waitForBatchedUpdatesWithAct();

// And the workspace chat and its actions land in Onyx after the wall rendered
await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${WORKSPACE_CHAT_ID}`, workspaceChat);
await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${WORKSPACE_CHAT_ID}`, workspaceChatActions);
await waitForBatchedUpdatesWithAct();

// When the payer picks the workspace to pay through
act(() => {
continueAction?.({policy: adminPolicy});
});
await waitForBatchedUpdatesWithAct();

// Then the move should get those actions, because the wall subscribes to the submitter's workspace chats so the report joins the existing chat
expect(mockedMoveIOUReportToPolicyAndInviteSubmitter.mock.calls.at(0)?.at(2)).toEqual({[`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${WORKSPACE_CHAT_ID}`]: workspaceChatActions});
});

it('should not pass workspace chats of other members when moving an IOU report to a workspace', async () => {
// Given an IOU report payer who administers a workspace where only another member has a workspace chat
await Onyx.set(`${ONYXKEYS.COLLECTION.POLICY}${POLICY_ID}`, adminPolicy);
await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${WORKSPACE_CHAT_ID}`, {...workspaceChat, ownerAccountID: 3});
await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${WORKSPACE_CHAT_ID}`, workspaceChatActions);
let continueAction: ((params?: ContinueActionParams) => void) | undefined;
render(
<ComposeProviders components={[OnyxListItemProvider, LocaleContextProvider, CurrentUserPersonalDetailsProvider]}>
<KYCWall
ref={React.createRef<KYCWallRef>()}
iouReport={iouReport}
chatReportID={iouReport.chatReportID}
enablePaymentsRoute={ROUTES.ENABLE_PAYMENTS}
onSuccessfulKYC={jest.fn()}
>
{(triggerKYCFlow) => {
continueAction = triggerKYCFlow;
}}
</KYCWall>
</ComposeProviders>,
);
await waitForBatchedUpdatesWithAct();

// When the payer picks the workspace to pay through
act(() => {
continueAction?.({policy: adminPolicy});
});
await waitForBatchedUpdatesWithAct();

// Then the move should get no workspace chat actions, because only the submitter's own workspace chat can receive the report
expect(mockedMoveIOUReportToPolicyAndInviteSubmitter.mock.calls.at(0)?.at(2)).toEqual({});
});
});
Loading
Loading