App icon indicating copy to clipboard operation
App copied to clipboard

[$250] Members - Removed user with secondary login is shown as "already a member" in search list

Open vincdargento opened this issue 2 weeks ago • 95 comments

If you haven’t already, check out our contributing guidelines for onboarding and email [email protected] to request to join our Slack channel!


Version Number: v9.5.36-0 Reproducible in staging?: Yes Reproducible in production?: Yes If this was caught during regression testing, add the test name, ID and link from TestRail: https://github.com/Expensify/Expensify/issues/579751 Email or phone of affected tester (no customers): N/A Issue reported by: Applause Internal Team

Action Performed:

  1. Go to staging.new.expensify.com
  2. Go to workspace settings > Members.
  3. Invite a member using their secondary login.
  4. Click Invite member.
  5. Enter the secondary login of the invited member.
  6. Close the RHP.
  7. Remove the invited member.
  8. Click Invite member.
  9. Enter the secondary login of the invited member.

Expected Result:

The removed user will appear in the search list.

Actual Result:

The removed user does not appear in the search list. It shows that the removed user is already a member of the workspace when the user has been removed.

Workaround:

N/A

Platforms:

  • [ ] Android: App
  • [ ] Android: mWeb Chrome
  • [ ] iOS: App
  • [ ] iOS: mWeb Safari
  • [ ] iOS: mWeb Chrome
  • [ ] Windows: Chrome
  • [x] MacOS: Chrome / Safari

Screenshots/Videos

https://github.com/user-attachments/assets/3db9d799-a595-4207-afcd-5856a0087ee0

Upwork Automation - Do Not Edit

vincdargento avatar Nov 11 '26 13:11 vincdargento

Triggered auto assignment to Contributor-plus team member for initial proposal review - @FitseTLT (External)

melvin-bot[bot] avatar Nov 11 '26 14:11 melvin-bot[bot]

Job added to Upwork: https://www.upwork.com/jobs/~022120517466941292149

melvin-bot[bot] avatar Nov 11 '26 14:11 melvin-bot[bot]

🤖 Web test steps verification results: ⚠️ partial

Blocked on dev NewDot web: no account with a verified secondary login was available. No substitute email was invited, and no product failure was observed.

Invite dialog awaiting the required verified secondary-login fixture
Step Status
Open workspace settings > MembersCreated a workspace and reached its invite panel, but not Members settings.
Invite dialog awaiting the required verified secondary-login fixture
⚠️
Invite a member using their secondary loginBlocked: verified secondary-login fixture unavailable. No invitation sent.
⚠️
Click Invite member againNot executed because the invitation was blocked.
⚠️
Search the invited secondary loginNot executed: required fixture unavailable.
⚠️
Close the RHPNot executed in the requested post-search state.
⚠️
Remove the invited memberNo fixture member was invited.
⚠️
Click Invite member again after removalNot executed in the requested post-removal state.
⚠️
Search the secondary login and verify reinvitation is availableBlocked by the missing fixture; behavior remains unverified.
⚠️

Preliminary analysis

⚠️ Low confidence in the complete root cause. The code explains the displayed message, but not why the reported sequence leaves the offending state.

Likely mechanism: A secondary-login entry remains in the workspace’s employee list after removal. Invite search treats that entry as membership—even if its value is an empty object.

Code evidence and hypothesis challenge
  • The exact “already a member” message comes from current employee-list exclusions, not a remembered search result: DynamicWorkspaceInvitePage.tsx:203–216.
  • The exclusion helper accepts empty employee entries, skipping only pending deletions and entries with errors: members.ts:210–225. An existing test documents empty secondary-login artifacts: WorkspaceMembersTest.tsx:634–657.
  • Counterevidence: The reported release already expands removal to include the secondary login when primaryLoginsInvited contains its pairing: Member.ts:398–426. Simply adding alias cleanup would duplicate existing behavior.
  • No client-side mapping cleanup was found in the intermediate open/search/close flow. Server responses clearing the pairing or reintroducing an alias remain unverified alternatives.

Required confirmation: With a verified secondary-login fixture, capture employeeList, primaryLoginsInvited, and response Onyx updates before and after the intermediate search, removal, and final reopening. This distinguishes an alias that was never deleted from one restored afterward. A specific code fix is not yet justified.

Possibly related: Secondary login can not be removed from workspace members reports overlapping removal symptoms; duplication is not confirmed.


Next Steps: Provide the verified secondary-login fixture or a sanitized state/response trace to establish the missing causal step.


view run · view recording

MelvinBot avatar Nov 11 '26 14:11 MelvinBot

Proposal

Please re-state the problem that we are trying to solve in this issue.

When a workspace member is invited using their secondary login and later removed from the workspace, searching for that secondary login in the "Invite member" search list does not show the user. Instead, the UI displays the message that the user is "already a member" of the workspace.

What is the root cause of that problem?

  1. In src/pages/workspace/DynamicWorkspaceInvitePage.tsx (lines 85–92):

    const ineligibleInvites = getIneligibleInvitees(policy?.employeeList);
    const excludedUsers = ineligibleInvites.reduce(
        (acc, login) => {
            acc[login] = true;
            return acc;
        },
        {} as Record<string, boolean>,
    );
    

    The excludedUsers map for invite search is computed directly from getIneligibleInvitees(policy?.employeeList). When typing in the search box, lines 210–213 evaluate:

    } else if (
        excludedUsers[parsePhoneNumber(appendCountryCode(searchValue, countryCode)).possible ? addSMSDomainIfPhoneNumber(appendCountryCode(searchValue, countryCode)) : searchValue]
    ) {
        headerMessage = translate('messages.userIsAlreadyMember', searchValue, policyName);
    }
    

    and usePersonalDetailSearchSelector suppresses the user from the available options via excludeLogins: excludedUsers.

  2. In src/libs/PolicyUtils/members.ts (lines 210–226):

    function getIneligibleInvitees(employeeList?: PolicyEmployeeList): string[] {
        const policyEmployeeList = employeeList ?? {};
        const memberEmailsToExclude: string[] = [...CONST.EXPENSIFY_EMAILS];
        for (const email of Object.keys(policyEmployeeList)) {
            const policyEmployee = policyEmployeeList?.[email];
            // Policy members that are pending delete or have errors are not valid and we should show them in the invite options (don't exclude them).
            if (policyEmployee?.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE || Object.keys(policyEmployee?.errors ?? {}).length > 0) {
                continue;
            }
            if (!email) {
                continue;
            }
            memberEmailsToExclude.push(email);
        }
    
        return memberEmailsToExclude;
    }
    

    getIneligibleInvitees loops through all keys in policyEmployeeList and only skips entries if pendingAction === 'delete' or if errors exist.

  3. When a member is invited using a secondary login, the backend associates the membership under their primary login, leaving an empty object / nullified artifact {pendingAction: null} under the secondary email in policy.employeeList (as documented in WorkspaceMembersTest.tsx:634–657 and handled in useWorkspaceMembers.ts:30–35).

  4. Similarly, when members are removed (Member.removeMembers), successMembersState[email] = null is merged into Onyx.

  5. In getIneligibleInvitees:

    • For an empty employee artifact ({}, {pendingAction: null}, or null), policyEmployee?.pendingAction is null/undefined (not 'delete') and errors is empty.
    • Crucially, getIneligibleInvitees does not check isEmptyValueObject(policyEmployee) or !policyEmployee?.role (unlike useWorkspaceMembers.ts which skips isEmptyValueObject(policyEmployee), or PolicyUtils/members.ts:42 which requires employee.role).
    • Consequently, memberEmailsToExclude.push(email) pushes the secondary login (or any empty/nullified artifact), marking it as an active member and triggering the "user is already a member" message.
  6. Furthermore, in src/libs/actions/Policy/Member.ts (removeMembers, lines 554–576):

    • primaryLoginsInvited: null is only pushed to optimisticData and omitted from successData.
    • When only one of multiple secondary-invited members is deleted, individual entries in policy.primaryLoginsInvited are never cleared.
    • remainingLogins filters on selectedMemberEmails instead of selectedMemberEmailsWithDuplicates, failing to discount the paired secondary login.

What changes do you think we should make in order to solve the problem?

  1. In src/libs/PolicyUtils/members.ts:

    • Import isEmptyValueObject from @src/types/utils/EmptyObject.
    • In getIneligibleInvitees, skip entries that are empty value objects or do not have an active role:
    --- a/src/libs/PolicyUtils/members.ts
    +++ b/src/libs/PolicyUtils/members.ts
    @@ -11,7 +11,7 @@ import CONST from '@src/CONST';
     import type {PersonalDetailsList, Policy, PolicyEmployeeList} from '@src/types/onyx';
     import type PolicyEmployee from '@src/types/onyx/PolicyEmployee';
    -import {isEmptyObject} from '@src/types/utils/EmptyObject';
    +import {isEmptyObject, isEmptyValueObject} from '@src/types/utils/EmptyObject';
    
     import type {OnyxCollection, OnyxEntry} from 'react-native-onyx';
    
    @@ -212,7 +212,12 @@ function getIneligibleInvitees(employeeList?: PolicyEmployeeList): string[] {
         const memberEmailsToExclude: string[] = [...CONST.EXPENSIFY_EMAILS];
         for (const email of Object.keys(policyEmployeeList)) {
             const policyEmployee = policyEmployeeList?.[email];
    -        // Policy members that are pending delete or have errors are not valid and we should show them in the invite options (don't exclude them).
    -        if (policyEmployee?.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE || Object.keys(policyEmployee?.errors ?? {}).length > 0) {
    +        // Policy members that are pending delete, empty artifacts, without an assigned role, or have errors
    +        // are not valid active members and we should show them in the invite options (don't exclude them).
    +        if (
    +            isEmptyValueObject(policyEmployee) ||
    +            !policyEmployee?.role ||
    +            policyEmployee?.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE ||
    +            Object.keys(policyEmployee?.errors ?? {}).length > 0
    +        ) {
                 continue;
             }
             if (!email) {
    
  2. In src/libs/actions/Policy/Member.ts (removeMembers):

    • Use selectedMemberEmailsWithDuplicates to compute remainingLogins.
    • Explicitly clear the removed member's secondary login from primaryLoginsInvited in both optimisticData and successData.
    • Also include primaryLoginsInvited: null in successData when all secondary-invited members have been removed.
  3. Add unit test coverage in tests/unit/PolicyUtilsTest.ts for getIneligibleInvitees:

    • Verifying that active members and Expensify team emails are excluded from invites.
    • Verifying that members pending delete or with errors are not excluded.
    • Verifying that empty employee objects ({}), {pendingAction: null}, and entries without a role are not excluded from invites.

andregrunert-ctrl avatar Nov 11 '26 14:11 andregrunert-ctrl

Proposal

Please re-state the problem that we are trying to solve in this issue.

When an admin invites a user to a workspace using their secondary login ([email protected]), removes that member from the workspace, and then opens Invite member and searches for the user's secondary login again, the removed user does not appear in the search list and instead displays the message that [email protected] is already a member of the workspace (messages.userIsAlreadyMember).

What is the root cause of that problem?

There is a two-part root cause across buildAddMembersToWorkspaceOnyxData / removeMembers (src/libs/actions/Policy/Member.ts) and getIneligibleInvitees (src/libs/PolicyUtils/members.ts):

  1. How inviting by secondary login leaves an empty {pendingAction: null} entry in policy.employeeList[secondaryLogin]:

    • When addMembersToWorkspace (src/libs/actions/Policy/Member.ts:898-952) invites secondaryLogin, optimisticData merges employeeList: {[secondaryLogin]: {email: secondaryLogin, pendingAction: 'add', role: ...}} and successData merges employeeList: {[secondaryLogin]: {pendingAction: null}} (line 906).
    • On the backend, AddMembersToWorkspace resolves secondaryLogin to the user's primary login (primaryLogin), adds employeeList[primaryLogin] = {email: primaryLogin, role: 'user', ...}, and sets employeeList[secondaryLogin] = null to clear the secondary login key.
    • However, because API.write applies successData after the server response onyxData, successData's Onyx.METHOD.MERGE (employeeList: {[secondaryLogin]: {pendingAction: null}}) re-creates policy.employeeList[secondaryLogin] as {pendingAction: null} (an empty-value object with no role or email, as documented in src/hooks/useWorkspaceMembers.ts:32-34).
  2. Why secondaryLogin remains in policy.employeeList and is marked ineligible in getIneligibleInvitees after the member is removed:

    • In DynamicWorkspaceInvitePage.tsx:85-92, 210-213, excludedUsers is built exclusively from getIneligibleInvitees(policy?.employeeList). When sections.length === 0 and excludedUsers[searchValue] is true, the page displays translate('messages.userIsAlreadyMember', searchValue, policyName).
    • In src/libs/PolicyUtils/members.ts:210-226, getIneligibleInvitees iterates over Object.keys(policyEmployeeList) and only skips entries where policyEmployee?.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE || Object.keys(policyEmployee?.errors ?? {}).length > 0. Unlike useWorkspaceMembers.ts:35 (which skips isEmptyValueObject(policyEmployee)) and getEligibleBankAccountShareRecipientEmails (src/libs/PolicyUtils/members.ts:42, which checks !employee.role), getIneligibleInvitees treats the {pendingAction: null} artifact at policy.employeeList[secondaryLogin] as an active workspace member.
    • When the member is removed in Step 7 (removeMembers in src/libs/actions/Policy/Member.ts:406-427), selectedMemberEmails only contains [primaryLogin] (because useWorkspaceMembers.ts:35 hid the empty secondaryLogin entry from the Members table). removeMembers only expands selectedMemberEmailsWithDuplicates to secondaryLogin if policy?.primaryLoginsInvited currently maps secondaryLogin -> primaryLogin. Whenever primaryLoginsInvited is absent, cleared (e.g. via dismissAddedWithPrimaryLoginMessages), or not populated on the policy when removeMembers runs (and even when primaryLoginsInvited is present, line 557 filters remainingLogins against selectedMemberEmails instead of selectedMemberEmailsWithDuplicates and only clears primaryLoginsInvited in optimisticData rather than successData), policy.employeeList[secondaryLogin] ({pendingAction: null}) is left behind in Onyx and getIneligibleInvitees continues to return secondaryLogin as an existing member.

What changes do you think we should make in order to solve the problem?

  1. Skip empty/role-less ghost entries in getIneligibleInvitees (src/libs/PolicyUtils/members.ts:210-226) while still respecting active primaryLoginsInvited pairings:

    • In getIneligibleInvitees, skip any policyEmployee entry that is an empty-value object (isEmptyValueObject(policyEmployee) || !policyEmployee?.role), matching the guard in useWorkspaceMembers.ts:35 and src/libs/PolicyUtils/members.ts:42.
    • Note on Step 5 (searching secondaryLogin while the user is still an active member of the workspace): when the user searches secondaryLogin in DynamicWorkspaceInvitePage, searchUserInServer(debouncedSearchTerm) (DynamicWorkspaceInvitePage.tsx:232) returns the user's personalDetails keyed by their accountID with login: primaryLogin. Because primaryLogin is an active member in excludedUsers, usePersonalDetailSearchSelector excludes that personalDetails option, and if secondaryLogin is also excluded while its paired primaryLogin is an active member (or if getIneligibleInvitees / DynamicWorkspaceInvitePage includes secondaryLogin from policy?.primaryLoginsInvited only while its mapped primaryLogin is an active member in policy.employeeList), Step 5 continues to show "already a member" while the user is in the workspace, and Step 9 (after primaryLogin is removed) no longer excludes secondaryLogin:
    function getIneligibleInvitees(policyEmployeeList?: PolicyEmployeeList, primaryLoginsInvited?: Record<string, string>): string[] {
        const policyEmployeeEmailsToExclude: string[] = [];
    
        for (const [email, policyEmployee] of Object.entries(policyEmployeeList ?? {})) {
            // Policy members that are pending delete or have errors aren't valid members so we shouldn't exclude them.
            // Also skip empty employeeList entries ({pendingAction: null}) left behind after inviting a secondary login.
            if (
                isEmptyValueObject(policyEmployee) ||
                !policyEmployee?.role ||
                policyEmployee?.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE ||
                Object.keys(policyEmployee?.errors ?? {}).length > 0
            ) {
                continue;
            }
            if (!email) {
                continue;
            }
            policyEmployeeEmailsToExclude.push(email);
        }
    
        // If a secondary login was invited and its resolved primary login is currently an active member, exclude the secondary login too
        if (primaryLoginsInvited) {
            const activeEmails = new Set(policyEmployeeEmailsToExclude);
            for (const [secondaryLogin, primaryLogin] of Object.entries(primaryLoginsInvited)) {
                if (activeEmails.has(primaryLogin) && !activeEmails.has(secondaryLogin)) {
                    policyEmployeeEmailsToExclude.push(secondaryLogin);
                }
            }
        }
    
        return policyEmployeeEmailsToExclude;
    }
    

    And pass policy?.primaryLoginsInvited where getIneligibleInvitees(policy?.employeeList, policy?.primaryLoginsInvited) is called in src/pages/workspace/DynamicWorkspaceInvitePage.tsx:85.

  2. Clean up orphaned empty {pendingAction: null} entries and primaryLoginsInvited in removeMembers (src/libs/actions/Policy/Member.ts:406-427, 554-576):

    • In removeMembers, in addition to expanding selectedMemberEmailsWithDuplicates via primaryLoginsInvited, also sweep any empty-value entry (isEmptyValueObject(employee)) in policy.employeeList into successMembersState[email] = null so stale {pendingAction: null} keys do not linger in policy.employeeList.
    • At line 557 of src/libs/actions/Policy/Member.ts, filter remainingLogins using selectedMemberEmailsWithDuplicates (and exclude isEmptyValueObject entries), and clear the removed member's entry from primaryLoginsInvited in both optimisticData and successData.

What alternative solutions did you explore? (Optional)

We also considered omitting successMembersState[email] = {pendingAction: null} in buildAddMembersToWorkspaceOnyxData (src/libs/actions/Policy/Member.ts:906). However, for normal primary-login invites, successData needs to clear the optimistic pendingAction: 'add' flag on employeeList[email] if the backend response does not overwrite pendingAction. Filtering isEmptyValueObject(policyEmployee) || !policyEmployee?.role in getIneligibleInvitees (paired with active primaryLoginsInvited lookup and removeMembers cleanup) safely handles the {pendingAction: null} secondary-login artifact without breaking primary-login optimistic pendingAction cleanup.


Contributor details

  • Your Expensify account email: [email protected]
  • Upwork Profile Link: https://www.upwork.com/freelancers/~013d295f05a578824b

— submitted with Antigravity on the contributor's behalf

HindsightWise avatar Nov 11 '26 16:11 HindsightWise

Proposal

Please re-state the problem that we are trying to solve in this issue.

In Workspace Members, after inviting a user using their secondary login, closing the panel, and then removing that invited member, re-inviting with the same secondary login fails because the search list incorrectly reports that the user is "already a member of the workspace".

What is the root cause of that problem?

In src/libs/actions/Policy/Member.ts (removeMembers) and src/libs/PolicyUtils/members.ts (getIneligibleInvitees):

  1. In src/libs/actions/Policy/Member.ts (lines 556–575): When removing members, remainingLogins is computed as: const remainingLogins = employeeListEmails.filter((email) => !selectedMemberEmails.includes(email)); It checks !selectedMemberEmails.includes(email) instead of selectedMemberEmailsWithDuplicates. When a member invited via secondary login is removed, selectedMemberEmails only contains one of the logins (primary or secondary), while the paired login was added to selectedMemberEmailsWithDuplicates. Because remainingLogins still contains the paired login, the cleanup condition !remainingLogins.some(...) evaluates to false, and policy.primaryLoginsInvited is never cleared.
  2. Additionally, in src/pages/workspace/DynamicWorkspaceInvitePage.tsx (lines 85–92 and 210–213) and getIneligibleInvitees: excludedUsers checks policy.employeeList and policy.primaryLoginsInvited. When the member is removed, if primaryLoginsInvited retains the secondaryLogin -> primaryLogin mapping or if employeeList[secondaryLogin] is not cleaned up in successData, excludedUsers[searchValue] evaluates to true, triggering messages.userIsAlreadyMember.

What changes do you think we should make in order to solve the problem?

  1. In src/libs/actions/Policy/Member.ts (removeMembers):
    • In lines 557–575, compute remainingLogins using selectedMemberEmailsWithDuplicates: const remainingLogins = employeeListEmails.filter((email) => !selectedMemberEmailsWithDuplicates.includes(email));
    • Explicitly delete the removed secondary login from policy.primaryLoginsInvited in both optimisticData and successData: primaryLoginsInvited: {[secondaryLogin]: null} so stale mappings do not persist after member deletion.
  2. In src/libs/PolicyUtils/members.ts (getIneligibleInvitees):
    • Ensure that if a primary login is deleted or pending delete (CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE), any associated secondary login from primaryLoginsInvited is also excluded from ineligibleInvitees.

What alternative solutions did you explore? (Optional)

Clearing the entire primaryLoginsInvited object whenever any member is deleted, which would inadvertently discard valid mappings for other members who were invited via secondary logins.

TassioSales avatar Nov 11 '26 19:11 TassioSales

Proposal

What is the root cause of that problem?

There are two interacting root causes across member invitation data persistence, member deletion cleanup, and invitee exclusion filtering:

  1. Orphaned {pendingAction: null} secondary login entry in policy.employeeList:

    • In buildAddMembersToWorkspaceOnyxData (src/libs/actions/Policy/Member.ts:898-906), inviting a member with a secondary login sets optimisticMembersState[secondaryLogin] = {email: secondaryLogin, pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD, role: ...} and successMembersState[secondaryLogin] = {pendingAction: null}.
    • When the backend responds, the backend stores the user under their primary login in employeeList[primaryLogin], stores the secondary-to-primary mapping in policy.primaryLoginsInvited, and nulls the secondary login key.
    • However, when successData merges, successMembersState[secondaryLogin] = {pendingAction: null} leaves an empty-value placeholder {pendingAction: null} in policy.employeeList[secondaryLogin].
    • In getIneligibleInvitees (src/libs/PolicyUtils/members.ts:210-226):
      for (const email of Object.keys(policyEmployeeList)) {
          const policyEmployee = policyEmployeeList?.[email];
          if (policyEmployee?.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE || Object.keys(policyEmployee?.errors ?? {}).length > 0) {
              continue;
          }
          if (!email) {
              continue;
          }
          memberEmailsToExclude.push(email);
      }
      
      getIneligibleInvitees only checks for pendingAction === 'delete' or errors; it does not check isEmptyValueObject(policyEmployee) or !policyEmployee?.role (unlike src/hooks/useWorkspaceMembers.ts:35, which explicitly ignores isEmptyValueObject(policyEmployee) to prevent rendering duplicate rows). As a result, the orphaned {pendingAction: null} entry is treated as an active member and added to memberEmailsToExclude.
  2. Incomplete member removal and missing primaryLoginsInvited cleanup in successData:

    • In removeMembers (src/libs/actions/Policy/Member.ts:554-575), line 557 computes remaining logins using selectedMemberEmails instead of selectedMemberEmailsWithDuplicates:
      const remainingLogins = employeeListEmails.filter((email) => !selectedMemberEmails.includes(email));
      
      Because the members table only renders the primary login (due to useWorkspaceMembers), selectedMemberEmails contains only [primaryLogin]. Thus, remainingLogins continues to contain secondaryLogin, causing remainingLogins.some((remainingLogin) => !!invitedPrimaryToSecondaryLogins[remainingLogin]) to evaluate to true.
    • Furthermore, lines 568-574 only push primaryLoginsInvited: null to optimisticData and never to successData. When DeleteMembersFromWorkspace completes and merges successData, stale secondary-to-primary mappings remain in Onyx.
    • On reopening the invite flow (DynamicWorkspaceInvitePage.tsx:210-213), excludedUsers[searchValue] evaluates to true, displaying messages.userIsAlreadyMember.

What changes do you think we should make in order to solve the problem?

1. Filter out empty-value placeholder entries and check active primary members in getIneligibleInvitees (src/libs/PolicyUtils/members.ts:210-226)

Skip placeholder entries (isEmptyValueObject(policyEmployee) or missing role), and forward primaryLoginsInvited so secondary logins are excluded only when their paired primary login is an active member:

 import type {OnyxCollection, OnyxEntry} from 'react-native-onyx';
 import Onyx from 'react-native-onyx';
import {isEmptyValueObject} from '@src/types/utils/EmptyObject';
 import CONST from '@src/CONST';
 
function getIneligibleInvitees(employeeList?: PolicyEmployeeList, primaryLoginsInvited?: Record<string, string>): string[] {
     const policyEmployeeList = employeeList ?? {};
     const memberEmailsToExclude: string[] = [...CONST.EXPENSIFY_EMAILS];
     for (const email of Object.keys(policyEmployeeList)) {
         const policyEmployee = policyEmployeeList?.[email];
        // Policy members that are pending delete, have errors, or are empty placeholder entries (e.g. secondary logins) are not valid active members
        if (isEmptyValueObject(policyEmployee) || !policyEmployee?.role || policyEmployee?.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE || Object.keys(policyEmployee?.errors ?? {}).length > 0) {
             continue;
         }
         if (!email) {
             continue;
         }
         memberEmailsToExclude.push(email);
     }

    if (primaryLoginsInvited) {
        for (const [secondaryLogin, primaryLogin] of Object.entries(primaryLoginsInvited)) {
            const primaryEmployee = policyEmployeeList?.[primaryLogin];
            if (primaryEmployee && !isEmptyValueObject(primaryEmployee) && !!primaryEmployee.role && primaryEmployee.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE && Object.keys(primaryEmployee.errors ?? {}).length === 0) {
                memberEmailsToExclude.push(secondaryLogin);
            }
        }
    }
 
     return memberEmailsToExclude;
 }

2. Pass policy?.primaryLoginsInvited in DynamicWorkspaceInvitePage.tsx:85

    const ineligibleInvites = getIneligibleInvitees(policy?.employeeList, policy?.primaryLoginsInvited);

3. Update removeMembers in src/libs/actions/Policy/Member.ts to clean up paired secondary logins and sync primaryLoginsInvited in both optimisticData and successData

     if (!isEmptyObject(policy?.primaryLoginsInvited ?? {})) {
         const employeeListEmails = Object.keys(policy?.employeeList ?? {});
        const remainingLogins = employeeListEmails.filter((email) => !selectedMemberEmailsWithDuplicates.includes(email));
         const invitedPrimaryToSecondaryLogins: Record<string, string> = {};
 
         if (policy?.primaryLoginsInvited) {
             for (const key of Object.keys(policy.primaryLoginsInvited)) {
                 invitedPrimaryToSecondaryLogins[policy.primaryLoginsInvited?.[key] ?? ''] = key;
             }
         }
 
        const removedSecondaryLogins: Record<string, null> = {};
        for (const [secondaryLogin, primaryLogin] of Object.entries(primaryLoginsInvited)) {
            if (selectedMemberEmailsWithDuplicates.includes(secondaryLogin) || selectedMemberEmailsWithDuplicates.includes(primaryLogin)) {
                removedSecondaryLogins[secondaryLogin] = null;
            }
        }

         if (!remainingLogins.some((remainingLogin) => !!invitedPrimaryToSecondaryLogins[remainingLogin])) {
             optimisticData.push({
                 onyxMethod: Onyx.METHOD.MERGE,
                 key: policyKey,
                 value: {
                     primaryLoginsInvited: null,
                 },
             });
            successData.push({
                onyxMethod: Onyx.METHOD.MERGE,
                key: policyKey,
                value: {
                    primaryLoginsInvited: null,
                },
            });
        } else if (!isEmptyObject(removedSecondaryLogins)) {
            optimisticData.push({
                onyxMethod: Onyx.METHOD.MERGE,
                key: policyKey,
                value: {
                    primaryLoginsInvited: removedSecondaryLogins,
                },
            });
            successData.push({
                onyxMethod: Onyx.METHOD.MERGE,
                key: policyKey,
                value: {
                    primaryLoginsInvited: removedSecondaryLogins,
                },
            });
         }
     }

What alternative solutions did you explore? (Optional)

  • Only filtering isEmptyValueObject in getIneligibleInvitees: Leaving primaryLoginsInvited uncleared in successData would leave stale secondary-to-primary mapping references in Onyx and could cause re-invitations or workspace arrangement helpers (WorkArrangementUtils.ts:30) to resolve against nonexistent primary members.
  • Clearing all primaryLoginsInvited unconditionally: Would inadvertently delete valid mappings for other workspace members who were invited via secondary logins and remain active in the workspace. Updating only removedSecondaryLogins ensures fine-grained precision.

What automated tests can you add to prevent this from re-occurring?

In tests/actions/PolicyMemberTest.ts: Add a unit test verifying that when a member invited with a secondary login is removed via removeMembers:

  1. Both primaryEmail and secondaryEmail entries are removed from policy.employeeList.
  2. The mapping in policy.primaryLoginsInvited is cleared in both optimistic and success Onyx data.
  3. getIneligibleInvitees(policy.employeeList, policy.primaryLoginsInvited) no longer contains secondaryEmail.

Contributor details

Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~0131dae36abcf59374

kevinjosh10 avatar Nov 12 '26 11:11 kevinjosh10

✅ Contributor details stored successfully. Thank you for contributing to Expensify!

melvin-bot[bot] avatar Nov 12 '26 11:11 melvin-bot[bot]

Proposal

Please re-state the problem that we are trying to solve in this issue.

When an admin invites a user to a workspace using their secondary login ([email protected]), searches that secondary login in Invite member, closes the RHP, removes the invited member from the workspace, and then opens Invite member and searches for [email protected] again, the removed user does not appear in the search list and the UI displays the message that [email protected] is already a member of the workspace (messages.userIsAlreadyMember).

What is the root cause of that problem?

The bug is caused by the interaction of three concrete mechanisms across the invitation flow, the intermediate Invite member RHP search (Steps 4–6), the member removal flow (Step 7), and the invite exclusion check (Steps 8–9):

  1. Inviting via secondary login leaves a role-less {pendingAction: null} ghost entry at policy.employeeList[secondaryLogin] (src/libs/actions/Policy/Member.ts:898-952):

    • In buildAddMembersToWorkspaceOnyxData, optimisticData merges employeeList: {[secondaryLogin]: {email: secondaryLogin, pendingAction: 'add', role: ...}} and successData merges employeeList: {[secondaryLogin]: {pendingAction: null}} (src/libs/actions/Policy/Member.ts:898-906).
    • On the server, AddMembersToWorkspace resolves secondaryLogin to the user's primary login (primaryLogin), adds employeeList[primaryLogin] = {email: primaryLogin, role: 'user', ...}, sets policy.primaryLoginsInvited = {[secondaryLogin]: primaryLogin}, and returns employeeList[secondaryLogin] = null in the command's onyxData.
    • Because Onyx.update applies the request's successData after the server's onyxData, successData's Onyx.METHOD.MERGE (employeeList: {[secondaryLogin]: {pendingAction: null}}) re-creates policy.employeeList[secondaryLogin] as {pendingAction: null} (an empty-value object with no role or email, as explicitly documented in src/hooks/useWorkspaceMembers.ts:32-35 and tests/ui/WorkspaceMembersTest.tsx:635-657).
  2. Why removeMembers in Step 7 fails to remove policy.employeeList[secondaryLogin] (and why Steps 4–6 matter):

    • On the Workspace Members page, useWorkspaceMembers (src/hooks/useWorkspaceMembers.ts:35) hides any policyEmployee where isEmptyValueObject(policyEmployee) is true, so only the primaryLogin row is rendered and selectable. When the admin removes the member in Step 7, selectedMemberEmails is [primaryLogin].
    • In removeMembers (src/libs/actions/Policy/Member.ts:406-418), selectedMemberEmailsWithDuplicates only expands primaryLogin to secondaryLogin if policy?.primaryLoginsInvited still contains [secondaryLogin]: primaryLogin at the moment removeMembers is called.
    • However, policy.primaryLoginsInvited is cleared whenever dismissAddedWithPrimaryLoginMessages(policyID) runs (src/libs/actions/Policy/Policy.ts:4650-4652) or when the policy object is refreshed by openWorkspaceInvitePage / openWorkspaceMembersPage in Steps 4–6 without primaryLoginsInvited. Once primaryLoginsInvited is absent/cleared, selectedMemberEmailsWithDuplicates contains only [primaryLogin], leaving policy.employeeList[secondaryLogin] ({pendingAction: null}) untouched in Onyx!
    • Even when policy.primaryLoginsInvited is present during removeMembers, src/libs/actions/Policy/Member.ts:557 filters remainingLogins against selectedMemberEmails instead of selectedMemberEmailsWithDuplicates (const remainingLogins = employeeListEmails.filter((email) => !selectedMemberEmails.includes(email))), and only merges primaryLoginsInvited: null into optimisticData (omitting successData and never clearing individual entries when other secondary-invited members remain).
  3. Why getIneligibleInvitees treats the empty {pendingAction: null} artifact as an active member in Step 9 (src/libs/PolicyUtils/members.ts:210-226):

    • In src/pages/workspace/DynamicWorkspaceInvitePage.tsx:85-92, 210-213, excludedUsers is built from getIneligibleInvitees(policy?.employeeList).
    • In src/libs/PolicyUtils/members.ts:210-226:
      function getIneligibleInvitees(employeeList?: PolicyEmployeeList): string[] {
          const policyEmployeeList = employeeList ?? {};
          const memberEmailsToExclude: string[] = [...CONST.EXPENSIFY_EMAILS];
          for (const email of Object.keys(policyEmployeeList)) {
              const policyEmployee = policyEmployeeList?.[email];
              if (policyEmployee?.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE || Object.keys(policyEmployee?.errors ?? {}).length > 0) {
                  continue;
              }
              if (!email) {
                  continue;
              }
              memberEmailsToExclude.push(email);
          }
      
          return memberEmailsToExclude;
      }
      
      Unlike useWorkspaceMembers.ts:35 (which skips isEmptyValueObject(policyEmployee)) and getEligibleBankAccountShareRecipientEmails (src/libs/PolicyUtils/members.ts:42, which checks !employee.role), getIneligibleInvitees does not skip empty-value objects (isEmptyValueObject(policyEmployee)). As a result, the leftover {pendingAction: null} entry under secondaryLogin is added to memberEmailsToExclude (excludedUsers[secondaryLogin] = true), which suppresses getUserToInviteOption in usePersonalDetailSearchSelector and causes DynamicWorkspaceInvitePage.tsx:213 to display translate('messages.userIsAlreadyMember', searchValue, policyName).

What changes do you think we should make in order to solve the problem?

  1. Skip empty-value employee artifacts in getIneligibleInvitees while still excluding secondaryLogin while its paired primaryLogin is an active member (src/libs/PolicyUtils/members.ts & src/pages/workspace/DynamicWorkspaceInvitePage.tsx):

    • Note why we must also check primaryLoginsInvited for active members: in Step 5 (while the invited user is still an active member under primaryLogin), typing secondaryLogin calls searchUserInServer, which returns personalDetails keyed by accountID with login: primaryLogin. While personalDetailsOptions excludes that contact because excludedUsers[primaryLogin] is true, filterUserToInvite (src/libs/PersonalDetailOptionsListUtils/index.ts:199-235, 427-434) checks loginsToExclude[searchValue] (loginsToExclude[secondaryLogin]). If secondaryLogin were not in excludedUsers while primaryLogin is an active member, filterUserToInvite would create a fallback userToInvite option for secondaryLogin in Step 5 instead of showing "already a member".
    • Therefore, in getIneligibleInvitees(employeeList?: PolicyEmployeeList, primaryLoginsInvited?: Record<string, string>):
      1. Skip any policyEmployee where isEmptyValueObject(policyEmployee) is true (matching useWorkspaceMembers.ts:35).
      2. For each [secondaryLogin, primaryLogin] in primaryLoginsInvited, include secondaryLogin in memberEmailsToExclude only if primaryLogin is currently an active (non-empty, non-pending-delete, error-free) member in policyEmployeeList.
    --- a/src/libs/PolicyUtils/members.ts
    +++ b/src/libs/PolicyUtils/members.ts
    @@ -11,7 +11,7 @@ import CONST from '@src/CONST';
     import type {PersonalDetailsList, Policy, PolicyEmployeeList} from '@src/types/onyx';
     import type PolicyEmployee from '@src/types/onyx/PolicyEmployee';
    -import {isEmptyObject} from '@src/types/utils/EmptyObject';
    +import {isEmptyObject, isEmptyValueObject} from '@src/types/utils/EmptyObject';
    @@ -210,10 +210,15 @@ function getAccountIDForSubmitManagerEmail(
     /**
      * Get login list that we should not show in the workspace invite options
      */
    -function getIneligibleInvitees(employeeList?: PolicyEmployeeList): string[] {
    +function getIneligibleInvitees(employeeList?: PolicyEmployeeList, primaryLoginsInvited?: Record<string, string>): string[] {
         const policyEmployeeList = employeeList ?? {};
         const memberEmailsToExclude: string[] = [...CONST.EXPENSIFY_EMAILS];
         for (const email of Object.keys(policyEmployeeList)) {
             const policyEmployee = policyEmployeeList?.[email];
             // Policy members that are pending delete, have errors, or are empty secondary-login artifacts are not valid members
    -        if (policyEmployee?.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE || Object.keys(policyEmployee?.errors ?? {}).length > 0) {
    +        if (
    +            isEmptyValueObject(policyEmployee) ||
    +            policyEmployee?.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE ||
    +            Object.keys(policyEmployee?.errors ?? {}).length > 0
    +        ) {
                 continue;
             }
             if (!email) {
                 continue;
             }
             memberEmailsToExclude.push(email);
         }
    +
    +    if (primaryLoginsInvited) {
    +        const activeMemberEmails = new Set(memberEmailsToExclude);
    +        for (const [secondaryLogin, primaryLogin] of Object.entries(primaryLoginsInvited)) {
    +            if (activeMemberEmails.has(primaryLogin) && !activeMemberEmails.has(secondaryLogin)) {
    +                memberEmailsToExclude.push(secondaryLogin);
    +            }
    +        }
    +    }
    
         return memberEmailsToExclude;
     }
    
    • Update getExcludedUsers in src/libs/PolicyUtils/members.ts:231 and the call site in src/pages/workspace/DynamicWorkspaceInvitePage.tsx:85 to pass policy?.primaryLoginsInvited:
      const ineligibleInvites = getIneligibleInvitees(policy?.employeeList, policy?.primaryLoginsInvited);
      
  2. Clean up empty {pendingAction: null} employeeList artifacts and primaryLoginsInvited entries in removeMembers (src/libs/actions/Policy/Member.ts:406-427, 554-576):

    • In removeMembers, sweep any empty-value entry (isEmptyValueObject(employeeList[email])) into successMembersState[email] = null so orphaned {pendingAction: null} keys do not accumulate in Onyx.
    • At line 557, compute remainingLogins using selectedMemberEmailsWithDuplicates (excluding isEmptyValueObject entries), and clear removed secondary-login mappings from primaryLoginsInvited in both optimisticData and successData.

What alternative solutions did you explore? (Optional)

  • Removing successMembersState[email] = {pendingAction: null} from buildAddMembersToWorkspaceOnyxData (src/libs/actions/Policy/Member.ts:906): Not sufficient on its own because for normal primary-login invitations or offline-to-online transitions where the server response does not overwrite pendingAction, successData must clear pendingAction: 'add'. Skipping isEmptyValueObject(policyEmployee) in getIneligibleInvitees (paired with active primaryLoginsInvited resolution and removeMembers cleanup) aligns getIneligibleInvitees with useWorkspaceMembers.ts:35 and handles both Step 5 (while active) and Step 9 (after removal).

cocvn157 avatar Nov 12 '26 13:11 cocvn157

I can not reproduce this

paulnjs avatar Nov 12 '26 17:11 paulnjs

I investigated the secondary-login invite bug and prepared a candidate fix and a proposal draft using Expensify's official proposal template.

  • Proposal draft + draft PR (in my fork, not upstream): https://github.com/HamzaZahid172/App/pull/1
  • Fix branch: https://github.com/HamzaZahid172/App/tree/fix/106630-secondary-login-invite

The proposed root cause is that a role-less employeeList placeholder left after inviting a secondary login is mistaken for an active member by getIneligibleInvitees. The candidate patch filters those placeholders while continuing to exclude a secondary login when its paired primary login is active. Four regression test cases were added.

Status: This is a proposal draft, not an official proposal submission or an upstream PR. I have not reproduced the complete nine-step scenario with a verified secondary-login account or run the full repository test suite. I also see that other proposals overlap with this approach.

Since the issue does not currently have a Help Wanted label and the contribution guidelines say not to submit proposals beforehand or open upstream PRs before acceptance, I am holding off on both. Could the assigned reviewer please confirm whether new proposals are being accepted and whether a verified secondary-login fixture or sanitized Onyx state trace can be provided? I can then validate the full flow and address any mapping-cleanup gaps before formal submission.

My Expensify/Upwork contributor details have already been registered in this issue.

HamzaZahid172 avatar Nov 15 '26 23:11 HamzaZahid172

📣 @HamzaZahid172! 📣 Hey, it seems we don’t have your contributor details yet! You'll only have to do this once, and this is how we'll hire you on Upwork. Please follow these steps:

  1. Make sure you've read and understood the contributing guidelines.
  2. Get the email address used to login to your Expensify account. If you don't already have an Expensify account, create one here. If you have multiple accounts (e.g. one for testing), please use your main account email.
  3. Get the link to your Upwork profile. It's necessary because we only pay via Upwork. You can access it by logging in, and then clicking on your name. It'll look like this. If you don't already have an account, sign up for one here.
  4. Copy the format below and paste it in a comment on this issue. Replace the placeholder text with your actual details. Screen Shot 2022-11-16 at 4 42 54 PM Format:
Contributor details
Your Expensify account email: <REPLACE EMAIL HERE>
Upwork Profile Link: <REPLACE LINK HERE>

melvin-bot[bot] avatar Nov 15 '26 23:11 melvin-bot[bot]

Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~0190813b8dab33818c

HamzaZahid172 avatar Nov 15 '26 23:11 HamzaZahid172

✅ Contributor details stored successfully. Thank you for contributing to Expensify!

melvin-bot[bot] avatar Nov 15 '26 23:11 melvin-bot[bot]

@FitseTLT Still overdue 6 days?! Let's take care of this!

Not overdue

FitseTLT avatar Nov 18 '26 22:11 FitseTLT

@MelvinBot proposal for this ?

FitseTLT avatar Nov 24 '26 16:11 FitseTLT

Proposal — preliminary, not ready for acceptance

What is the root cause of that problem?

A leftover secondary-login entry can incorrectly count as workspace membership, even when its value is {pendingAction: null}.

However, the complete reported sequence remains unverified: member removal already deletes both logins when their pairing is available. We still need to establish why the secondary entry survives.

Code evidence and important counterevidence
  • members.ts:210–225 excludes empty employee entries from invitation search.
  • Member.ts:424–453 already removes the paired secondary login.
  • Policy.ts:4649–4654 clears that pairing when its informational message is dismissed. This establishes a possible failure path, but not that opening/searching/closing Invite triggers it.

What changes do you think we should make in order to solve the problem?

A specific fix is not justified yet. Capture employeeList, primaryLoginsInvited, and response updates immediately before and after removal using a verified secondary-login account.

This must establish whether the alias was never deleted or was restored afterward. Any eventual fix must also keep the secondary login blocked while its primary account remains a member—simply ignoring empty entries could break that behavior.

Blocker: No verified secondary-login reproduction or sanitized state trace is available in the thread. Source review alone does not close that gap.


view run

MelvinBot avatar Nov 24 '26 17:11 MelvinBot

@MelvinBot What I can reproduce is when I delete it offline and search, it says it is already member but this doesn't happen for normal members only with the secondary login? Why?

FitseTLT avatar Nov 24 '26 17:11 FitseTLT

@FitseTLT Here is why this happens specifically for a secondary login (and not for normal members), even offline:

  1. Normal members: selectedMemberEmails contains their only login in policy.employeeList, so deleteMembersFromWorkspace sets employeeList[email] = {pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE} optimistically right away, and getIneligibleInvitees skips any entry with pendingAction === DELETE.
  2. Secondary login: When you invite by secondary login, the backend stores the member under their primary login, while the secondary login entry also remains in policy.employeeList (with {pendingAction: null}). When you remove the member in the UI, selectedMemberEmails only contains the primaryLogin.
  3. deleteMembersFromWorkspace (Member.ts#L432-L444) only expands selectedMemberEmailsWithDuplicates to include secondaryLogin if the pairing is still present in policy?.primaryLoginsInvited. Whenever primaryLoginsInvited has been cleared or is missing (e.g. after dismissing the invite flow / Onyx refresh), deleteMembersFromWorkspace only marks primaryLogin as pendingAction: DELETE, leaving employeeList[secondaryLogin] untouched (pendingAction: null), so getIneligibleInvitees still treats secondaryLogin as an active member and shows "already a member".

andregrunert-ctrl avatar Nov 24 '26 17:11 andregrunert-ctrl