Skip to content

[No QA] Implement MoveIOUReportToPolicyAndInviteSubmitter#58337

Merged
luacmartins merged 15 commits intoExpensify:mainfrom
ikevin127:ikevin127-moveIOUReportToPolicyAndInviteSubmitter
Mar 31, 2025
Merged

[No QA] Implement MoveIOUReportToPolicyAndInviteSubmitter#58337
luacmartins merged 15 commits intoExpensify:mainfrom
ikevin127:ikevin127-moveIOUReportToPolicyAndInviteSubmitter

Conversation

@ikevin127
Copy link
Contributor

@ikevin127 ikevin127 commented Mar 13, 2025

Explanation of Change

Implements this section of the #migrate: Simplified actions framework for all reports design doc.

Fixed Issues

$ #57472
PROPOSAL:

Tests

Pre-requisite: a user (not member of any workspace), a workspace with an admin.

  1. [user] Request money (IOU) from admin.
  2. [admin] Open the IOU report and select change workspace (append /change-workspace to the URL in order to open the workspace selector).
  3. [admin] Move the IOU report to the admin's workspace.
  4. Verify that the IOU report was converted to an Expense report and the user was invited to the workspace.
  5. Verify that the user has a workspace chat created for them.
  6. Verify that the report preview was removed from the DM and added to the user's workspace chat.

If any other clarifications are needed, feel free to tag @luacmartins and ask 👍

  • Verify that no errors appear in the JS console

Offline tests

QA Steps

  • Verify that no errors appear in the JS console

PR Author Checklist

  • I linked the correct issue in the ### Fixed Issues section above
  • I wrote clear testing steps that cover the changes made in this PR
    • I added steps for local testing in the Tests section
    • I added steps for the expected offline behavior in the Offline steps section
    • I added steps for Staging and/or Production testing in the QA steps section
    • I added steps to cover failure scenarios (i.e. verify an input displays the correct error message if the entered data is not correct)
    • I turned off my network connection and tested it while offline to ensure it matches the expected behavior (i.e. verify the default avatar icon is displayed if app is offline)
    • I tested this PR with a High Traffic account against the staging or production API to ensure there are no regressions (e.g. long loading states that impact usability).
  • I included screenshots or videos for tests on all platforms
  • I ran the tests on all platforms & verified they passed on:
    • Android: Native
    • Android: mWeb Chrome
    • iOS: Native
    • iOS: mWeb Safari
    • MacOS: Chrome / Safari
    • MacOS: Desktop
  • I verified there are no console errors (if there's a console error not related to the PR, report it or open an issue for it to be fixed)
  • I followed proper code patterns (see Reviewing the code)
    • I verified that any callback methods that were added or modified are named for what the method does and never what callback they handle (i.e. toggleReport and not onIconClick)
    • I verified that comments were added to code that is not self explanatory
    • I verified that any new or modified comments were clear, correct English, and explained "why" the code was doing something instead of only explaining "what" the code was doing.
    • I verified any copy / text shown in the product is localized by adding it to src/languages/* files and using the translation method
      • If any non-english text was added/modified, I used JaimeGPT to get English > Spanish translation. I then posted it in #expensify-open-source and it was approved by an internal Expensify engineer. Link to Slack message:
    • I verified all numbers, amounts, dates and phone numbers shown in the product are using the localization methods
    • I verified any copy / text that was added to the app is grammatically correct in English. It adheres to proper capitalization guidelines (note: only the first word of header/labels should be capitalized), and is either coming verbatim from figma or has been approved by marketing (in order to get marketing approval, ask the Bug Zero team member to add the Waiting for copy label to the issue)
    • I verified proper file naming conventions were followed for any new files or renamed files. All non-platform specific files are named after what they export and are not named "index.js". All platform-specific files are named for the platform the code supports as outlined in the README.
    • I verified the JSDocs style guidelines (in STYLE.md) were followed
  • If a new code pattern is added I verified it was agreed to be used by multiple Expensify engineers
  • I followed the guidelines as stated in the Review Guidelines
  • I tested other components that can be impacted by my changes (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar are working as expected)
  • I verified all code is DRY (the PR doesn't include any logic written more than once, with the exception of tests)
  • I verified any variables that can be defined as constants (ie. in CONST.ts or at the top of the file that uses the constant) are defined as such
  • I verified that if a function's arguments changed that all usages have also been updated correctly
  • If any new file was added I verified that:
    • The file has a description of what it does and/or why is needed at the top of the file if the code is not self explanatory
  • If a new CSS style is added I verified that:
    • A similar style doesn't already exist
    • The style can't be created with an existing StyleUtils function (i.e. StyleUtils.getBackgroundAndBorderStyle(theme.componentBG))
  • If the PR modifies code that runs when editing or sending messages, I tested and verified there is no unexpected behavior for all supported markdown - URLs, single line code, code blocks, quotes, headings, bold, strikethrough, and italic.
  • If the PR modifies a generic component, I tested and verified that those changes do not break usages of that component in the rest of the App (i.e. if a shared library or component like Avatar is modified, I verified that Avatar is working as expected in all cases)
  • If the PR modifies a component related to any of the existing Storybook stories, I tested and verified all stories for that component are still working as expected.
  • If the PR modifies a component or page that can be accessed by a direct deeplink, I verified that the code functions as expected when the deeplink is used - from a logged in and logged out account.
  • If the PR modifies the UI (e.g. new buttons, new UI components, changing the padding/spacing/sizing, moving components, etc) or modifies the form input styles:
    • I verified that all the inputs inside a form are aligned with each other.
    • I added Design label and/or tagged @Expensify/design so the design team can review the changes.
  • If a new page is added, I verified it's using the ScrollView component to make it scrollable when more elements are added to the page.
  • I added unit tests for any new feature or bug fix in this PR to help automatically prevent regressions in this user flow.
  • If the main branch was merged into this PR after a review, I tested again and verified the outcome was still expected according to the Test steps.

Screenshots/Videos

web.mov
Android: Native
Android: mWeb Chrome
iOS: Native
iOS: mWeb Safari
MacOS: Chrome / Safari
MacOS: Desktop

@luacmartins luacmartins self-requested a review March 13, 2025 15:26
@ikevin127 ikevin127 marked this pull request as ready for review March 13, 2025 20:29
@ikevin127 ikevin127 requested a review from a team as a code owner March 13, 2025 20:29
@melvin-bot melvin-bot bot requested review from dukenv0307 and removed request for a team March 13, 2025 20:29
@melvin-bot
Copy link

melvin-bot bot commented Mar 13, 2025

@dukenv0307 Please copy/paste the Reviewer Checklist from here into a new comment on this PR and complete it. If you have the K2 extension, you can simply click: [this button]

@dukenv0307
Copy link
Contributor

It's still on hold

@luacmartins
Copy link
Contributor

@dukenv0307 I think we can do a preliminary review of the code here, while we wait for the backend

@dukenv0307
Copy link
Contributor

@ikevin127 Do we need to fill the test sections and screenshots?

@ikevin127
Copy link
Contributor Author

@dukenv0307 I asked a similar question regarding testing on a similar PR (#58078) where I'm reviewing:

How do we go about testing this type of PRs of new functions that are not actually used in the app yet, how do we verify that they comply with the doc specs other than reading the code and assuming ?

The answer from CME was:

Ideally, we wait for the backend PR to be available so we can test it end to end.

So I guess for now you'd only be doing:

a preliminary review of the code here, while we wait for the backend

cleanUpSetQueries[`${ONYXKEYS.COLLECTION.REPORT_DRAFT_COMMENT}${reportID}`] = null;
cleanUpSetQueries[`${ONYXKEYS.COLLECTION.REPORT_ACTIONS_DRAFTS}${reportID}`] = null;
});
Onyx.mergeCollection(ONYXKEYS.COLLECTION.REPORT, cleanUpMergeQueries);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we need cleanUpMergeQueries here since it's empty?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Makes sense, I will delete the Onyx.mergeCollection and remove the unused cleanUpMergeQueries.

@luacmartins
Copy link
Contributor

@ikevin127 what's the latest on this one?

@ikevin127
Copy link
Contributor Author

@luacmartins Looks like there's 1 conflict and I also have to apply this change requested by reviewer.

But then what's next when it comes to advancing this PR ? I remember I asked you in the other issue where I'm reviewing, how do we test these PRs in order to verify that the implementation is correct and you said:

Ideally, we wait for the backend PR to be available so we can test it end to end.

Is the BE PR available for MoveIOUReportToPolicyAndInviteSubmitter ? And if yes, how can the reviewer test that the FE implementation is complete according to the design doc when the BE API is called, essentially, how is the end to end test being done exactly for these PRs ?

♻️ I will use the answer for this to review #58078 as well since you just tagged me there to prioritize the review.

@ikevin127 ikevin127 mentioned this pull request Mar 20, 2025
58 tasks
@luacmartins
Copy link
Contributor

@ikevin127 yes, the API command is available.

I think the test steps are something like this:

Pre-requisite: a user (not member of any workspace), a workspace with an admin

  1. [user] Request money (IOU) from admin
  2. [admin] Open the IOU report and select change workspace
  3. [admin] Move the IOU report to the workspace the admin is an admin of
  4. Verify that the IOU report was converted to an Expense report and the user was invited to the workspace
  5. Verify that the user has a workspace chat created for them
  6. Verify that the report preview was removed from the DM and added to the user's workspace chat

@ikevin127
Copy link
Contributor Author

ikevin127 commented Mar 20, 2025

@dukenv0307 I resolved the conflict and removed the unused cleanUpMergeQueries mentioned in review comment. This is ready for testing, you have some steps in this comment and I asked for additional clarifications in Slack DM, here's the Q&A:

Q:

Hey, quick question on PRs 58078 and 58337, you mentioned in the testing steps steps select change workspace:

Should we actually add a button (UI) in the app as part of the PR or only do this locally to be able to test and once tested only push the function as ready to use but don't push UI buttons with these PRs ?

Asking because the design doc doesn't mention any UI implementation for any of the 2 PRs functions, only functional tests.

A:

We're adding the UI implementation in a separate PR
so for testing, you can manually navigate to /change-workspace page

If you need any other clarifications feel free to tag @luacmartins and ask 👍
Note: Updated PR Tests with the provided steps / clarifications.

@luacmartins
Copy link
Contributor

I'll pause review on this PR until #58078 is merged, since this PR depends on that

@ikevin127
Copy link
Contributor Author

ikevin127 commented Mar 20, 2025

I'm actively reviewing that one and will have a report posted there today.
Will also drop more testing steps for local dev here to help the reviewer on this PR with testing.

✅ Done with the review on the other PR, @dukenv0307 feel free to use the same review method I used in the other PR to review this one 👍

* @param reportID - The ID of the IOU report to move
* @param policyID - The ID of the policy to move the report to
*/
function moveIOUReportToPolicyAndInviteSubmitter(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please update/add the param names in the description

@dukenv0307
Copy link
Contributor

In ReportChangeWorkspacePage modify the existing selectPolicy function to use the newly added moveIOUReportToPolicy function.

I'm stuck on this step, moveIOUReportToPolicyAndInviteSubmitter requires more params than changeReportPolicy. Can you please elaborate?

@ikevin127
Copy link
Contributor Author

I think I'll pass the other params from within the function since we should already have them there. The initial (current) implementation is pretty much inspired from the other PR so I'll have to align it after the most recent updates 👍

@ikevin127
Copy link
Contributor Author

@luacmartins 🟢 Merged the PR with latest changes after the other PR was merged and I also updated this PRs moveIOUReportToPolicyAndInviteSubmitter function to further align with the requirements.

♻️ Using your testing steps from #58337 (comment), when attempting the move by clicking on a workspace in the change workspace selector, UI wise it looks like it does what it should but the MoveIOUReportToPolicyAndInviteSubmitter API call actually fails with:

{
    "jsonCode": 400,
    "message": "400 Unique Constraints Violation",
    "source": "auth-via-api",
    "onyxData": [],
    "requestID": "926252ad0fc6fb3c-SJC"
}

and upon refreshing the UI (on WS Owner / Admin side) the changes are reverted - while on the User side nothing changes since the API call failed.

⚠️ Not sure what this fail is about, most likely I'm either not passing the correct parameters / did not configure the moveIOUReportToPolicyAndInviteSubmitter correctly or possibly a BE issue? 🤔 Let me know what you think once you take a look at the code.

Possible reasons coming from the FE part of this PR are:

    // -> here I'm not sure we're supposed to pass the IOU's ownerAccountID when creating the Expense
    const ownerAccountID = iouReport.ownerAccountID;
    const expenseChatReportID = getPolicyExpenseChat(ownerAccountID, policyID)?.reportID;
    const parameters: MoveIOUReportToPolicyAndInviteSubmitterParams = {
        iouReportID,
        policyID,
        policyExpenseChatReportID: expenseChatReportID,
        // -> here not sure I'm passing the right policyExpenseCreatedReportActionID
        policyExpenseCreatedReportActionID: expenseReport.parentReportActionID ?? String(CONST.DEFAULT_NUMBER_ID), 
        changePolicyReportActionID: changePolicyReportAction.reportActionID,
    };

const ownerAccountID = iouReport.ownerAccountID;

// Create an optimistic policy expense chat for the submitter who's not a policy member
let optimisticExpenseChatReportID: string | undefined;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
let optimisticExpenseChatReportID: string | undefined;
let optimisticPolicyExpenseChatReportID: string | undefined;

const changePolicyReportAction = buildOptimisticChangePolicyReportAction(iouReport.policyID, policyID, true);
optimisticData.push({
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${optimisticExpenseChatReportID}`,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The action should be added to the IOU/Expense report, not the workspace chat
Screenshot 2025-03-27 at 11 38 40 AM

@luacmartins
Copy link
Contributor

On the Admin side, the User (submitter) does not seem to appear in WS -> Members

This is a BE bug. I have a PR in review to fix it.

On the Admin side, the CHANGEPOLICY action message says (previously 7E0E3B370F6A0994) while on the User

Yea, this is known and we're discussing the solution for it. I don't think we need to block this PR on it though

@ikevin127
Copy link
Contributor Author

@luacmartins Thanks for the clarifications and suggestions, applied them and here's the latest look:

web.mov

🟢 I think this is ready for review, please let me know!

Copy link
Contributor

@luacmartins luacmartins left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We shouldn't commit the changes to Mobile-Expensify

@luacmartins
Copy link
Contributor

@ikevin127 try this diff, I've tested and things work well. I moved some things around since it made more sense to start by inviting the user to the policy, creating the workspace chat and then moving the report over.

diff --git a/src/libs/actions/Report.ts b/src/libs/actions/Report.ts
index d350826d125..238e7244e7c 100644
--- a/src/libs/actions/Report.ts
+++ b/src/libs/actions/Report.ts
@@ -86,7 +86,7 @@ import {rand64} from '@libs/NumberUtils';
 import Parser from '@libs/Parser';
 import * as PersonalDetailsUtils from '@libs/PersonalDetailsUtils';
 import * as PhoneNumber from '@libs/PhoneNumber';
-import {extractPolicyIDFromPath, getDefaultApprover, getPolicy, isPolicyAdmin as isPolicyAdminPolicyUtils} from '@libs/PolicyUtils';
+import {extractPolicyIDFromPath, getDefaultApprover, getPolicy, isPolicyAdmin as isPolicyAdminPolicyUtils, isPolicyMember} from '@libs/PolicyUtils';
 import processReportIDDeeplink from '@libs/processReportIDDeeplink';
 import Pusher from '@libs/Pusher';
 import type {UserIsLeavingRoomEvent, UserIsTypingEvent} from '@libs/Pusher/types';
@@ -5094,38 +5094,99 @@ function moveIOUReportToPolicy(reportID: string, policyID: string) {
 function moveIOUReportToPolicyAndInviteSubmitter(reportID: string, policyID: string) {
     const iouReport = allReports?.[`${ONYXKEYS.COLLECTION.REPORT}${reportID}`];
     const policy = getPolicy(policyID);
-    const isPolicyAdmin = isPolicyAdminPolicyUtils(policy);
 
-    // This flow only works for IOU reports
-    if (!policy || !iouReport || !isPolicyAdmin || !isIOUReportUsingReport(iouReport)) {
+    if (!policy || !iouReport) {
         return;
     }
 
-    // We do not want to create negative amount expenses
-    if (ReportActionsUtils.hasRequestFromCurrentAccount(reportID, iouReport.managerID ?? CONST.DEFAULT_NUMBER_ID)) {
+    const isPolicyAdmin = isPolicyAdminPolicyUtils(policy);
+    const submitterAccountID = iouReport.ownerAccountID;
+    const submitterEmail = PersonalDetailsUtils.getLoginByAccountID(submitterAccountID ?? CONST.DEFAULT_NUMBER_ID);
+    const submitterLogin = PhoneNumber.addSMSDomainIfPhoneNumber(submitterEmail);
+
+    // This flow only works for admins moving an IOU report to a policy where the submitter is NOT yet a member of the policy
+    if (!isPolicyAdmin || !isIOUReportUsingReport(iouReport) || !submitterAccountID || !submitterEmail || isPolicyMember(submitterLogin, policyID)) {
         return;
     }
 
-    // Generate new variables for the policy
-    const policyName = policy.name ?? '';
-    const iouReportID = iouReport.reportID;
-    const ownerAccountID = iouReport.ownerAccountID;
-
-    // Create an optimistic policy expense chat for the submitter who's not a policy member
-    let optimisticPolicyExpenseChatReportID: string | undefined;
-    let optimisticPolicyExpenseChatCreatedReportActionID: string | undefined;
-
-    if (ownerAccountID) {
-        const employeeEmail = allPersonalDetails?.[ownerAccountID]?.login ?? '';
-        const employeeWorkspaceChat = createPolicyExpenseChats(policyID, {[employeeEmail]: ownerAccountID}, true);
-        optimisticPolicyExpenseChatReportID = employeeWorkspaceChat.reportCreationData[employeeEmail]?.reportID;
-        optimisticPolicyExpenseChatCreatedReportActionID = employeeWorkspaceChat.reportCreationData[employeeEmail]?.reportActionID;
+    // We only allow moving IOU report to a policy if it doesn't have requests from multiple users, as we do not want to create negative amount expenses
+    if (ReportActionsUtils.hasRequestFromCurrentAccount(reportID, iouReport.managerID ?? CONST.DEFAULT_NUMBER_ID)) {
+        return;
     }
 
     const optimisticData: OnyxUpdate[] = [];
     const successData: OnyxUpdate[] = [];
     const failureData: OnyxUpdate[] = [];
 
+    // Optimistically add the submitter to the workspace and create a workspace chat for them
+    const policyKey = `${ONYXKEYS.COLLECTION.POLICY}${policyID}` as const;
+    const invitedEmailsToAccountIDs: InvitedEmailsToAccountIDs = {
+        [submitterEmail]: submitterAccountID,
+    };
+
+    // Set up new member optimistic data
+    const role = CONST.POLICY.ROLE.USER;
+
+    // Get personal details onyx data (similar to addMembersToWorkspace)
+    const {newAccountIDs, newLogins} = PersonalDetailsUtils.getNewAccountIDsAndLogins([submitterLogin], [submitterAccountID]);
+    const newPersonalDetailsOnyxData = PersonalDetailsUtils.getPersonalDetailsOnyxDataForOptimisticUsers(newLogins, newAccountIDs);
+
+    // Build announce room members data for the new member
+    const announceRoomMembers = buildRoomMembersOnyxData(CONST.REPORT.CHAT_TYPE.POLICY_ANNOUNCE, policyID, [submitterAccountID]);
+
+    // Create policy expense chat for the submitter
+    const policyExpenseChats = createPolicyExpenseChats(policyID, invitedEmailsToAccountIDs);
+    const optimisticPolicyExpenseChatReportID = policyExpenseChats.reportCreationData[submitterEmail].reportID;
+    const optimisticPolicyExpenseChatCreatedReportActionID = policyExpenseChats.reportCreationData[submitterEmail].reportActionID;
+
+    // Set up optimistic member state
+    const optimisticMembersState: OnyxCollectionInputValue<PolicyEmployee> = {
+        [submitterLogin]: {
+            role,
+            email: submitterLogin,
+            pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD,
+            submitsTo: getDefaultApprover(allPolicies?.[policyKey]),
+        },
+    };
+
+    const successMembersState: OnyxCollectionInputValue<PolicyEmployee> = {
+        [submitterLogin]: {pendingAction: null},
+    };
+
+    const failureMembersState: OnyxCollectionInputValue<PolicyEmployee> = {
+        [submitterLogin]: {
+            errors: ErrorUtils.getMicroSecondOnyxErrorWithTranslationKey('workspace.people.error.genericAdd'),
+        },
+    };
+
+    optimisticData.push({
+        onyxMethod: Onyx.METHOD.MERGE,
+        key: policyKey,
+        value: {
+            employeeList: optimisticMembersState,
+        },
+    });
+
+    successData.push({
+        onyxMethod: Onyx.METHOD.MERGE,
+        key: policyKey,
+        value: {
+            employeeList: successMembersState,
+        },
+    });
+
+    failureData.push({
+        onyxMethod: Onyx.METHOD.MERGE,
+        key: policyKey,
+        value: {
+            employeeList: failureMembersState,
+        },
+    });
+
+    optimisticData.push(...newPersonalDetailsOnyxData.optimisticData, ...policyExpenseChats.onyxOptimisticData, ...announceRoomMembers.optimisticData);
+    successData.push(...newPersonalDetailsOnyxData.finallyData, ...policyExpenseChats.onyxSuccessData, ...announceRoomMembers.successData);
+    failureData.push(...policyExpenseChats.onyxFailureData, ...announceRoomMembers.failureData);
+
     // Next we need to convert the IOU report to Expense report.
     // We need to change:
     // - report type
@@ -5134,26 +5195,26 @@ function moveIOUReportToPolicyAndInviteSubmitter(reportID: string, policyID: str
     // - update the chatReportID to point to the workspace chat if the policy has policy expense chat enabled
     const expenseReport = {
         ...iouReport,
-        chatReportID: policy.isPolicyExpenseChatEnabled ? optimisticPolicyExpenseChatReportID : undefined,
+        chatReportID: optimisticPolicyExpenseChatReportID,
         policyID,
-        policyName,
-        parentReportID: iouReport.parentReportID,
+        policyName: policy.name,
+        parentReportID: optimisticPolicyExpenseChatReportID,
         type: CONST.REPORT.TYPE.EXPENSE,
         total: -(iouReport?.total ?? 0),
     };
     optimisticData.push({
         onyxMethod: Onyx.METHOD.MERGE,
-        key: `${ONYXKEYS.COLLECTION.REPORT}${iouReportID}`,
+        key: `${ONYXKEYS.COLLECTION.REPORT}${reportID}`,
         value: expenseReport,
     });
     failureData.push({
         onyxMethod: Onyx.METHOD.MERGE,
-        key: `${ONYXKEYS.COLLECTION.REPORT}${iouReportID}`,
+        key: `${ONYXKEYS.COLLECTION.REPORT}${reportID}`,
         value: iouReport,
     });
 
     // The expense report transactions need to have the amount reversed to negative values
-    const reportTransactions = getReportTransactions(iouReportID);
+    const reportTransactions = getReportTransactions(reportID);
 
     // For performance reasons, we are going to compose a merge collection data for transactions
     const transactionsOptimisticData: Record<string, Transaction> = {};
@@ -5180,10 +5241,9 @@ function moveIOUReportToPolicyAndInviteSubmitter(reportID: string, policyID: str
     });
 
     // We need to move the report preview action from the DM to the workspace chat.
-    const parentReportActions = allReportActions?.[`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${iouReport.parentReportID}`];
-    const parentReportActionID = iouReport.parentReportActionID;
-    const reportPreview = iouReport?.parentReportID && parentReportActionID ? parentReportActions?.[parentReportActionID] : undefined;
     const oldChatReportID = iouReport.chatReportID;
+    const reportPreviewActionID = iouReport.parentReportActionID;
+    const reportPreview = !!oldChatReportID && !!reportPreviewActionID ? allReportActions?.[oldChatReportID]?.[reportPreviewActionID] : undefined;
 
     if (reportPreview?.reportActionID) {
         optimisticData.push({
@@ -5214,12 +5274,12 @@ function moveIOUReportToPolicyAndInviteSubmitter(reportID: string, policyID: str
     const changePolicyReportAction = buildOptimisticChangePolicyReportAction(iouReport.policyID, policyID, true);
     optimisticData.push({
         onyxMethod: Onyx.METHOD.MERGE,
-        key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${optimisticPolicyExpenseChatCreatedReportActionID}`,
+        key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportID}`,
         value: {[changePolicyReportAction.reportActionID]: changePolicyReportAction},
     });
     successData.push({
         onyxMethod: Onyx.METHOD.MERGE,
-        key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${optimisticPolicyExpenseChatCreatedReportActionID}`,
+        key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportID}`,
         value: {
             [changePolicyReportAction.reportActionID]: {
                 ...changePolicyReportAction,
@@ -5229,7 +5289,7 @@ function moveIOUReportToPolicyAndInviteSubmitter(reportID: string, policyID: str
     });
     failureData.push({
         onyxMethod: Onyx.METHOD.MERGE,
-        key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${optimisticPolicyExpenseChatCreatedReportActionID}`,
+        key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportID}`,
         value: {[changePolicyReportAction.reportActionID]: null},
     });
 
@@ -5247,90 +5307,12 @@ function moveIOUReportToPolicyAndInviteSubmitter(reportID: string, policyID: str
         key: `${ONYXKEYS.COLLECTION.REPORT}${oldChatReportID}`,
         value: {
             hasOutstandingChildRequest: true,
-            iouReportID,
+            iouReportID: reportID,
         },
     });
 
-    // Optimistically add the submitter to the workspace and create a workspace chat for them
-    const submitterAccountID = iouReport.ownerAccountID;
-    const submitterEmail = PersonalDetailsUtils.getLoginByAccountID(submitterAccountID ?? CONST.DEFAULT_NUMBER_ID);
-
-    if (!!submitterAccountID && !!submitterEmail) {
-        const policyKey = `${ONYXKEYS.COLLECTION.POLICY}${policyID}` as const;
-        const invitedEmailsToAccountIDs: InvitedEmailsToAccountIDs = {
-            [submitterEmail]: submitterAccountID,
-        };
-
-        // Set up new member optimistic data
-        const role = CONST.POLICY.ROLE.USER;
-        const submitterLogin = PhoneNumber.addSMSDomainIfPhoneNumber(submitterEmail);
-
-        // Get personal details onyx data (similar to addMembersToWorkspace)
-        const {newAccountIDs, newLogins} = PersonalDetailsUtils.getNewAccountIDsAndLogins([submitterLogin], [submitterAccountID]);
-        const newPersonalDetailsOnyxData = PersonalDetailsUtils.getPersonalDetailsOnyxDataForOptimisticUsers(newLogins, newAccountIDs);
-
-        // Build announce room members data for the new member
-        const announceRoomMembers = buildRoomMembersOnyxData(CONST.REPORT.CHAT_TYPE.POLICY_ANNOUNCE, policyID, [submitterAccountID]);
-
-        // Create policy expense chat for the submitter
-        const membersChats = createPolicyExpenseChats(policyID, invitedEmailsToAccountIDs);
-
-        // Set up optimistic member state
-        const optimisticMembersState: OnyxCollectionInputValue<PolicyEmployee> = {
-            [submitterLogin]: {
-                role,
-                email: submitterLogin,
-                pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD,
-                submitsTo: getDefaultApprover(allPolicies?.[policyKey]),
-            },
-        };
-
-        const successMembersState: OnyxCollectionInputValue<PolicyEmployee> = {
-            [submitterLogin]: {pendingAction: null},
-        };
-
-        const failureMembersState: OnyxCollectionInputValue<PolicyEmployee> = {
-            [submitterLogin]: {
-                errors: ErrorUtils.getMicroSecondOnyxErrorWithTranslationKey('workspace.people.error.genericAdd'),
-            },
-        };
-
-        // Add employee list update to optimistic data
-        optimisticData.push({
-            onyxMethod: Onyx.METHOD.MERGE,
-            key: policyKey,
-            value: {
-                employeeList: optimisticMembersState,
-            },
-        });
-
-        // Add success and failure data
-        successData.push({
-            onyxMethod: Onyx.METHOD.MERGE,
-            key: policyKey,
-            value: {
-                employeeList: successMembersState,
-            },
-        });
-
-        failureData.push({
-            onyxMethod: Onyx.METHOD.MERGE,
-            key: policyKey,
-            value: {
-                employeeList: failureMembersState,
-            },
-        });
-
-        // Add personal details and chat data
-        optimisticData.push(...newPersonalDetailsOnyxData.optimisticData, ...membersChats.onyxOptimisticData, ...announceRoomMembers.optimisticData);
-
-        successData.push(...newPersonalDetailsOnyxData.finallyData, ...membersChats.onyxSuccessData, ...announceRoomMembers.successData);
-
-        failureData.push(...membersChats.onyxFailureData, ...announceRoomMembers.failureData);
-    }
-
     const parameters: MoveIOUReportToPolicyAndInviteSubmitterParams = {
-        iouReportID,
+        iouReportID: reportID,
         policyID,
         policyExpenseChatReportID: optimisticPolicyExpenseChatReportID ?? String(CONST.DEFAULT_NUMBER_ID),
         policyExpenseCreatedReportActionID: optimisticPolicyExpenseChatCreatedReportActionID ?? String(CONST.DEFAULT_NUMBER_ID),

@ikevin127
Copy link
Contributor Author

@luacmartins Thanks for the refactor diff, I applied it and things look good, couldn't find any issues 👍

Copy link
Contributor

@luacmartins luacmartins left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ikevin127 please remove the diff for Mobile-Expensify. You can do that by running git submodule update and committing the changes

@ikevin127
Copy link
Contributor Author

@ikevin127 please remove the diff for Mobile-Expensify. You can do that by running git submodule update and committing the changes

🟢 Done!

Copy link
Contributor

@luacmartins luacmartins left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM! All yours @dukenv0307

@dukenv0307
Copy link
Contributor

@ZhenjaHorbach I reviewed this PR before. Can I continue?

@dukenv0307
Copy link
Contributor

Reviewer Checklist

  • I have verified the author checklist is complete (all boxes are checked off).
  • I verified the correct issue is linked in the ### Fixed Issues section above
  • I verified testing steps are clear and they cover the changes made in this PR
    • I verified the steps for local testing are in the Tests section
    • I verified the steps for Staging and/or Production testing are in the QA steps section
    • I verified the steps cover any possible failure scenarios (i.e. verify an input displays the correct error message if the entered data is not correct)
    • I turned off my network connection and tested it while offline to ensure it matches the expected behavior (i.e. verify the default avatar icon is displayed if app is offline)
  • I checked that screenshots or videos are included for tests on all platforms
  • I included screenshots or videos for tests on all platforms
  • I verified tests pass on all platforms & I tested again on:
    • Android: Native
    • Android: mWeb Chrome
    • iOS: Native
    • iOS: mWeb Safari
    • MacOS: Chrome / Safari
    • MacOS: Desktop
  • If there are any errors in the console that are unrelated to this PR, I either fixed them (preferred) or linked to where I reported them in Slack
  • I verified proper code patterns were followed (see Reviewing the code)
    • I verified that any callback methods that were added or modified are named for what the method does and never what callback they handle (i.e. toggleReport and not onIconClick).
    • I verified that the left part of a conditional rendering a React component is a boolean and NOT a string, e.g. myBool && <MyComponent />.
    • I verified that comments were added to code that is not self explanatory
    • I verified that any new or modified comments were clear, correct English, and explained "why" the code was doing something instead of only explaining "what" the code was doing.
    • I verified any copy / text shown in the product is localized by adding it to src/languages/* files and using the translation method
    • I verified all numbers, amounts, dates and phone numbers shown in the product are using the localization methods
    • I verified any copy / text that was added to the app is grammatically correct in English. It adheres to proper capitalization guidelines (note: only the first word of header/labels should be capitalized), and is either coming verbatim from figma or has been approved by marketing (in order to get marketing approval, ask the Bug Zero team member to add the Waiting for copy label to the issue)
    • I verified proper file naming conventions were followed for any new files or renamed files. All non-platform specific files are named after what they export and are not named "index.js". All platform-specific files are named for the platform the code supports as outlined in the README.
    • I verified the JSDocs style guidelines (in STYLE.md) were followed
  • If a new code pattern is added I verified it was agreed to be used by multiple Expensify engineers
  • I verified that this PR follows the guidelines as stated in the Review Guidelines
  • I verified other components that can be impacted by these changes have been tested, and I retested again (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar have been tested & I retested again)
  • I verified all code is DRY (the PR doesn't include any logic written more than once, with the exception of tests)
  • I verified any variables that can be defined as constants (ie. in CONST.js or at the top of the file that uses the constant) are defined as such
  • If a new component is created I verified that:
    • A similar component doesn't exist in the codebase
    • All props are defined accurately and each prop has a /** comment above it */
    • The file is named correctly
    • The component has a clear name that is non-ambiguous and the purpose of the component can be inferred from the name alone
    • The only data being stored in the state is data necessary for rendering and nothing else
    • For Class Components, any internal methods passed to components event handlers are bound to this properly so there are no scoping issues (i.e. for onClick={this.submit} the method this.submit should be bound to this in the constructor)
    • Any internal methods bound to this are necessary to be bound (i.e. avoid this.submit = this.submit.bind(this); if this.submit is never passed to a component event handler like onClick)
    • All JSX used for rendering exists in the render method
    • The component has the minimum amount of code necessary for its purpose, and it is broken down into smaller components in order to separate concerns and functions
  • If any new file was added I verified that:
    • The file has a description of what it does and/or why is needed at the top of the file if the code is not self explanatory
  • If a new CSS style is added I verified that:
    • A similar style doesn't already exist
    • The style can't be created with an existing StyleUtils function (i.e. StyleUtils.getBackgroundAndBorderStyle(theme.componentBG)
  • If the PR modifies code that runs when editing or sending messages, I tested and verified there is no unexpected behavior for all supported markdown - URLs, single line code, code blocks, quotes, headings, bold, strikethrough, and italic.
  • If the PR modifies a generic component, I tested and verified that those changes do not break usages of that component in the rest of the App (i.e. if a shared library or component like Avatar is modified, I verified that Avatar is working as expected in all cases)
  • If the PR modifies a component related to any of the existing Storybook stories, I tested and verified all stories for that component are still working as expected.
  • If the PR modifies a component or page that can be accessed by a direct deeplink, I verified that the code functions as expected when the deeplink is used - from a logged in and logged out account.
  • If the PR modifies the UI (e.g. new buttons, new UI components, changing the padding/spacing/sizing, moving components, etc) or modifies the form input styles:
    • I verified that all the inputs inside a form are aligned with each other.
    • I added Design label and/or tagged @Expensify/design so the design team can review the changes.
  • If a new page is added, I verified it's using the ScrollView component to make it scrollable when more elements are added to the page.
  • If the main branch was merged into this PR after a review, I tested again and verified the outcome was still expected according to the Test steps.
  • I have checked off every checkbox in the PR reviewer checklist, including those that don't apply to this PR.

Screenshots/Videos

Android: Native
Screen.Recording.2025-03-31.at.23.42.05.mov
Android: mWeb Chrome
Screen.Recording.2025-03-31.at.23.27.50.mov
iOS: Native
Screen.Recording.2025-03-31.at.23.39.20.mov
iOS: mWeb Safari
Screen.Recording.2025-03-31.at.23.31.34.mov
MacOS: Chrome / Safari
Screen.Recording.2025-03-31.at.23.23.15.mov
MacOS: Desktop
Screen.Recording.2025-03-31.at.23.47.41.mov

@melvin-bot melvin-bot bot requested a review from luacmartins March 31, 2025 16:50
@luacmartins luacmartins merged commit 495e374 into Expensify:main Mar 31, 2025
17 of 18 checks passed
@luacmartins luacmartins removed the request for review from ZhenjaHorbach March 31, 2025 18:24
@OSBotify
Copy link
Contributor

✋ This PR was not deployed to staging yet because QA is ongoing. It will be automatically deployed to staging after the next production release.

@github-actions
Copy link
Contributor

github-actions bot commented Apr 1, 2025

🚀 Deployed to staging by https://github.com/luacmartins in version: 9.1.22-0 🚀

platform result
🖥 desktop 🖥 success ✅
🕸 web 🕸 success ✅
🤖 android 🤖 success ✅
🍎 iOS 🍎 success ✅

@github-actions
Copy link
Contributor

github-actions bot commented Apr 3, 2025

🚀 Deployed to production by https://github.com/grgia in version: 9.1.22-10 🚀

platform result
🖥 desktop 🖥 success ✅
🕸 web 🕸 success ✅
🤖 android 🤖 failure ❌
🍎 iOS 🍎 success ✅

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants