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
121 changes: 78 additions & 43 deletions src/libs/actions/Policy/Policy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@
};

const deprecatedAllPolicies: OnyxCollection<Policy> = {};
Onyx.connect({

Check warning on line 229 in src/libs/actions/Policy/Policy.ts

View workflow job for this annotation

GitHub Actions / Changed files ESLint check

Onyx.connect() is deprecated. Use useOnyx() hook instead and pass the data as parameters to a pure function
key: ONYXKEYS.COLLECTION.POLICY,
callback: (val, key) => {
if (!key) {
Expand All @@ -242,7 +242,7 @@
});

let deprecatedAllReportActions: OnyxCollection<ReportActions>;
Onyx.connect({

Check warning on line 245 in src/libs/actions/Policy/Policy.ts

View workflow job for this annotation

GitHub Actions / Changed files ESLint check

Onyx.connect() is deprecated. Use useOnyx() hook instead and pass the data as parameters to a pure function
key: ONYXKEYS.COLLECTION.REPORT_ACTIONS,
waitForCollectionCallback: true,
callback: (actions) => {
Expand All @@ -252,7 +252,7 @@

let deprecatedSessionEmail = '';
let deprecatedSessionAccountID = 0;
Onyx.connect({

Check warning on line 255 in src/libs/actions/Policy/Policy.ts

View workflow job for this annotation

GitHub Actions / Changed files ESLint check

Onyx.connect() is deprecated. Use useOnyx() hook instead and pass the data as parameters to a pure function
key: ONYXKEYS.SESSION,
callback: (val) => {
deprecatedSessionEmail = val?.email ?? '';
Expand All @@ -261,7 +261,7 @@
});

let deprecatedAllPersonalDetails: OnyxEntry<PersonalDetailsList>;
Onyx.connect({

Check warning on line 264 in src/libs/actions/Policy/Policy.ts

View workflow job for this annotation

GitHub Actions / Changed files ESLint check

Onyx.connect() is deprecated. Use useOnyx() hook instead and pass the data as parameters to a pure function
key: ONYXKEYS.PERSONAL_DETAILS_LIST,
callback: (val) => (deprecatedAllPersonalDetails = val),
});
Expand Down Expand Up @@ -1173,7 +1173,7 @@
API.write(WRITE_COMMANDS.SET_WORKSPACE_REIMBURSEMENT, params, {optimisticData, failureData, successData});
}

function leaveWorkspace(policyID?: string) {
function leaveWorkspace(currentUserAccountID: number, policyID?: string) {
if (!policyID) {
return;
}
Expand All @@ -1197,14 +1197,16 @@
},
];

const successData: Array<OnyxUpdate<typeof ONYXKEYS.COLLECTION.POLICY | typeof ONYXKEYS.COLLECTION.REPORT_METADATA>> = [
const successData: Array<OnyxUpdate<typeof ONYXKEYS.COLLECTION.POLICY | typeof ONYXKEYS.COLLECTION.REPORT_METADATA | typeof ONYXKEYS.COLLECTION.REPORT>> = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.POLICY}${policyID}`,
value: null,
},
];
const failureData: Array<OnyxUpdate<typeof ONYXKEYS.COLLECTION.POLICY | typeof ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS | typeof ONYXKEYS.COLLECTION.REPORT_METADATA>> = [
const failureData: Array<
OnyxUpdate<typeof ONYXKEYS.COLLECTION.POLICY | typeof ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS | typeof ONYXKEYS.COLLECTION.REPORT_METADATA | typeof ONYXKEYS.COLLECTION.REPORT>
> = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.POLICY}${policyID}`,
Expand All @@ -1223,62 +1225,95 @@
const pendingChatMembers = ReportUtils.getPendingChatMembers([deprecatedSessionAccountID], [], CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE);

for (const report of workspaceChats) {
if (!report?.reportID) {
continue;
}

const parentReport = ReportUtils.getRootParentReport({report});
const reportToCheckOwner = isEmptyObject(parentReport) ? report : parentReport;

if (ReportUtils.isPolicyExpenseChat(report) && !ReportUtils.isReportOwner(reportToCheckOwner)) {
continue;
}

optimisticData.push(
{
// Use merge instead of set to avoid deleting the report too quickly, which could cause a brief "not found" page to appear.
// The remaining parts of the report object will be removed after the API call is successful.
optimisticData.push({
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT}${report?.reportID}`,
value: {
statusNum: CONST.REPORT.STATUS_NUM.CLOSED,
reportID: null,
stateNum: CONST.REPORT.STATE_NUM.APPROVED,
oldPolicyName: policy?.name ?? '',
isPinned: false,
statusNum: CONST.REPORT.STATUS_NUM.CLOSED,
participants: {
[currentUserAccountID]: {
notificationPreference: CONST.REPORT.NOTIFICATION_PREFERENCE.HIDDEN,
},
},
},
},
{
});

// Ensure that any remaining data is removed upon successful completion, even if the server sends a report removal response.
// This is done to prevent the removal update from lingering in the applyHTTPSOnyxUpdates function.
successData.push({
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT}${report?.reportID}`,
value: null,
});

failureData.push({
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT}${report?.reportID}`,
value: report,
});
} else {
optimisticData.push(
{
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT}${report?.reportID}`,
value: {
statusNum: CONST.REPORT.STATUS_NUM.CLOSED,
stateNum: CONST.REPORT.STATE_NUM.APPROVED,
oldPolicyName: policy?.name ?? '',
isPinned: false,
},
},
{
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT_METADATA}${report?.reportID}`,
value: {
pendingChatMembers,
},
},
{
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS}${report?.reportID}`,
value: {
private_isArchived: currentTime,
},
},
);

// Restore archived flag on failure
failureData.push({
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS}${report?.reportID}`,
value: {
private_isArchived: null,
},
});
successData.push({
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT_METADATA}${report?.reportID}`,
value: {
pendingChatMembers,
pendingChatMembers: null,
},
},
{
});
failureData.push({
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS}${report?.reportID}`,
key: `${ONYXKEYS.COLLECTION.REPORT_METADATA}${report?.reportID}`,
value: {
private_isArchived: currentTime,
pendingChatMembers: null,
},
},
);

// Restore archived flag on failure
failureData.push({
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS}${report?.reportID}`,
value: {
private_isArchived: null,
},
});
successData.push({
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT_METADATA}${report?.reportID}`,
value: {
pendingChatMembers: null,
},
});
failureData.push({
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.REPORT_METADATA}${report?.reportID}`,
value: {
pendingChatMembers: null,
},
});
});
}
}

const params: LeavePolicyParams = {
Expand Down
4 changes: 2 additions & 2 deletions src/pages/workspace/WorkspaceOverviewPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -279,10 +279,10 @@ function WorkspaceOverviewPage({policyDraft, policy: policyProp, route}: Workspa
return;
}

leaveWorkspace(policyID);
leaveWorkspace(currentUserPersonalDetails.accountID, policyID);
setIsLeaveModalOpen(false);
goBackFromInvalidPolicy();
}, [policyID]);
}, [currentUserPersonalDetails.accountID, policyID]);

const hideDeleteWorkspaceErrorModal = () => {
setIsDeleteWorkspaceErrorModalOpen(false);
Expand Down
2 changes: 1 addition & 1 deletion src/pages/workspace/WorkspacesListPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,7 @@ function WorkspacesListPage() {
return;
}

leaveWorkspace(policyIDToLeave);
leaveWorkspace(currentUserPersonalDetails.accountID, policyIDToLeave);
setIsLeaveModalOpen(false);
};

Expand Down
126 changes: 126 additions & 0 deletions tests/actions/PolicyTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -819,6 +819,132 @@ describe('actions/Policy', () => {
});
});

describe('leaveWorkspace', () => {
it("should remove all non-owned workspace chats and keep the user's own workspace chat when leaving a workspace", async () => {
await Onyx.set(ONYXKEYS.SESSION, {email: ESH_EMAIL, accountID: ESH_ACCOUNT_ID});
const policyID = Policy.generatePolicyID();
await Onyx.set(`${ONYXKEYS.COLLECTION.POLICY}${policyID}`, {
...createRandomPolicy(0, CONST.POLICY.TYPE.TEAM),
id: policyID,
name: WORKSPACE_NAME,
});
await waitForBatchedUpdates();

const ownWorkspaceChat: Report = {
...createRandomReport(100, CONST.REPORT.CHAT_TYPE.POLICY_EXPENSE_CHAT),
reportID: '100',
policyID,
ownerAccountID: ESH_ACCOUNT_ID,
type: CONST.REPORT.TYPE.CHAT,
};
const nonOwnedWorkspaceChat1: Report = {
...createRandomReport(101, CONST.REPORT.CHAT_TYPE.POLICY_EXPENSE_CHAT),
reportID: '101',
policyID,
ownerAccountID: ESH_ACCOUNT_ID + 1,
type: CONST.REPORT.TYPE.CHAT,
};
const nonOwnedWorkspaceChat2: Report = {
...createRandomReport(102, CONST.REPORT.CHAT_TYPE.POLICY_EXPENSE_CHAT),
reportID: '102',
policyID,
ownerAccountID: ESH_ACCOUNT_ID + 2,
type: CONST.REPORT.TYPE.CHAT,
};
const nonOwnedWorkspaceChats = [nonOwnedWorkspaceChat1, nonOwnedWorkspaceChat2];

const getAllWorkspaceReportsSpy = jest.spyOn(ReportUtils, 'getAllWorkspaceReports').mockReturnValue([ownWorkspaceChat, ...nonOwnedWorkspaceChats]);
const apiWriteSpy = jest.spyOn(require('@libs/API'), 'write').mockImplementation(() => Promise.resolve());

Policy.leaveWorkspace(ESH_ACCOUNT_ID, policyID);
await waitForBatchedUpdates();

expect(apiWriteSpy).toHaveBeenCalledWith(
WRITE_COMMANDS.LEAVE_POLICY,
expect.objectContaining({
policyID,
email: ESH_EMAIL,
}),
expect.anything(),
);

const writeOptions = apiWriteSpy.mock.calls.at(0)?.at(2) as {
optimisticData?: Array<{key?: string; value?: Record<string, unknown> | null}>;
successData?: Array<{key?: string; value?: Record<string, unknown> | null}>;
failureData?: Array<{key?: string; value?: Record<string, unknown> | null}>;
};

expect(writeOptions?.optimisticData).toEqual(
expect.arrayContaining(
nonOwnedWorkspaceChats.map((workspaceChat) =>
expect.objectContaining({
key: `${ONYXKEYS.COLLECTION.REPORT}${workspaceChat.reportID}`,
value: expect.objectContaining({
reportID: null,
stateNum: CONST.REPORT.STATE_NUM.APPROVED,
statusNum: CONST.REPORT.STATUS_NUM.CLOSED,
participants: {
[ESH_ACCOUNT_ID]: {
notificationPreference: CONST.REPORT.NOTIFICATION_PREFERENCE.HIDDEN,
},
},
}),
}),
),
),
);

const removedWorkspaceChatUpdates = (writeOptions?.optimisticData ?? []).filter((update) => (update.value as {reportID?: string | null} | undefined)?.reportID === null);
expect(removedWorkspaceChatUpdates).toHaveLength(nonOwnedWorkspaceChats.length);

expect(writeOptions?.optimisticData).not.toEqual(
expect.arrayContaining([
expect.objectContaining({
key: `${ONYXKEYS.COLLECTION.REPORT}${ownWorkspaceChat.reportID}`,
value: expect.objectContaining({
reportID: null,
}),
}),
]),
);

expect(writeOptions?.optimisticData).toEqual(
expect.arrayContaining([
expect.objectContaining({
key: `${ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS}${ownWorkspaceChat.reportID}`,
value: expect.objectContaining({
private_isArchived: expect.any(String) as unknown as string,
}),
}),
]),
);

expect(writeOptions?.successData).toEqual(
expect.arrayContaining(
nonOwnedWorkspaceChats.map((workspaceChat) =>
expect.objectContaining({
key: `${ONYXKEYS.COLLECTION.REPORT}${workspaceChat.reportID}`,
value: null,
}),
),
),
);
expect(writeOptions?.failureData).toEqual(
expect.arrayContaining(
nonOwnedWorkspaceChats.map((workspaceChat) =>
expect.objectContaining({
key: `${ONYXKEYS.COLLECTION.REPORT}${workspaceChat.reportID}`,
value: workspaceChat,
}),
),
),
);

apiWriteSpy.mockRestore();
getAllWorkspaceReportsSpy.mockRestore();
});
});

describe('createDraftInitialWorkspace', () => {
it('creates a policy draft with disabled workflows when onboarding choice does not enable workflows', async () => {
await Onyx.set(ONYXKEYS.SESSION, {email: ESH_EMAIL, accountID: ESH_ACCOUNT_ID});
Expand Down
Loading