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
Original file line number Diff line number Diff line change
Expand Up @@ -198,12 +198,16 @@ function WorkspaceDuplicateSelectFeaturesForm({policyID}: WorkspaceDuplicateForm
return result.filter((item): item is NonNullable<typeof item> => !!item);
})();

// Merchant rules live under Rules, so they are copied only along with it. The Rules row is hidden when the source has no workspace-level rules, and merchant rules can then be copied on their own.
const hasRulesItem = items.some((item) => item.value === 'rules');
const effectiveSelectedItems = hasRulesItem && !selectedItems.includes('rules') ? selectedItems.filter((value) => value !== 'codingRules') : selectedItems;

const featuresToCopy: ListItem[] = items.map((option) => {
const alternateText = option?.alternateText ? option.alternateText.trim().replaceAll(/,$/g, '') : undefined;
return {
text: option.translation,
keyForList: option.value,
isSelected: selectedItems.includes(option.value),
isSelected: effectiveSelectedItems.includes(option.value),
alternateText,
};
});
Expand All @@ -227,25 +231,25 @@ function WorkspaceDuplicateSelectFeaturesForm({policyID}: WorkspaceDuplicateForm
policyID: policy.id,
targetPolicyID: duplicateWorkspace.policyID,
welcomeNote: `${translate('workspace.duplicateWorkspace.welcomeNote')} ${duplicateWorkspace.name}`,
policyCategories: selectedItems.includes('categories') ? policyCategories : undefined,
policyCategories: effectiveSelectedItems.includes('categories') ? policyCategories : undefined,
personalDetailsByLogins: employeePersonalDetails,
parts: {
people: selectedItems.includes('members'),
reports: selectedItems.includes('reports'),
connections: selectedItems.includes('accounting'),
categories: selectedItems.includes('categories'),
tags: selectedItems.includes('tags'),
taxes: selectedItems.includes('taxes'),
perDiem: selectedItems.includes('perDiem'),
reimbursements: selectedItems.includes('invoices'),
expenses: selectedItems.includes('rules'),
distance: selectedItems.includes('distanceRates'),
invoices: selectedItems.includes('invoices'),
invoiceFields: selectedItems.includes('invoices'),
exportLayouts: selectedItems.includes('workflows'),
overview: selectedItems.includes('overview'),
travel: selectedItems.includes('travel'),
codingRules: selectedItems.includes('codingRules'),
people: effectiveSelectedItems.includes('members'),
reports: effectiveSelectedItems.includes('reports'),
connections: effectiveSelectedItems.includes('accounting'),
categories: effectiveSelectedItems.includes('categories'),
tags: effectiveSelectedItems.includes('tags'),
taxes: effectiveSelectedItems.includes('taxes'),
perDiem: effectiveSelectedItems.includes('perDiem'),
reimbursements: effectiveSelectedItems.includes('invoices'),
expenses: effectiveSelectedItems.includes('rules'),
distance: effectiveSelectedItems.includes('distanceRates'),
invoices: effectiveSelectedItems.includes('invoices'),
invoiceFields: effectiveSelectedItems.includes('invoices'),
exportLayouts: effectiveSelectedItems.includes('workflows'),
overview: effectiveSelectedItems.includes('overview'),
travel: effectiveSelectedItems.includes('travel'),
codingRules: effectiveSelectedItems.includes('codingRules'),
},
file: duplicatedWorkspaceAvatar,
localCurrency: currentUserPersonalDetails?.localCurrencyCode ?? CONST.CURRENCY.USD,
Expand All @@ -257,7 +261,7 @@ function WorkspaceDuplicateSelectFeaturesForm({policyID}: WorkspaceDuplicateForm
const duplicateWorkspaceName = duplicateWorkspace?.name;
const duplicateWorkspacePolicyID = duplicateWorkspace?.policyID;
const onConfirmSelectList = () => {
if (!totalMembers || totalMembers < 2 || !selectedItems.includes('members')) {
if (!totalMembers || totalMembers < 2 || !effectiveSelectedItems.includes('members')) {
confirmDuplicate();
return;
}
Expand Down Expand Up @@ -287,7 +291,7 @@ function WorkspaceDuplicateSelectFeaturesForm({policyID}: WorkspaceDuplicateForm
};

const toggleAllItems = () => {
if (selectedItems.length === items.length) {
if (effectiveSelectedItems.length === items.length) {
setSelectedItems([]);
} else {
setSelectedItems(items.map((i) => i.value));
Expand All @@ -296,15 +300,18 @@ function WorkspaceDuplicateSelectFeaturesForm({policyID}: WorkspaceDuplicateForm

const updateSelectedItems = (listItem: ListItem) => {
if (listItem.isSelected) {
setSelectedItems(selectedItems.filter((i) => i !== listItem.keyForList));
const deselectedItems = listItem.keyForList === 'rules' ? ['rules', 'codingRules'] : [listItem.keyForList];
setSelectedItems(selectedItems.filter((i) => !deselectedItems.includes(i)));
return;
}

const newItem = items.find((i) => i.value === listItem.keyForList)?.value;

if (newItem) {
setSelectedItems([...selectedItems, newItem]);
if (!newItem) {
return;
}

const newItems = newItem === 'codingRules' && hasRulesItem ? [newItem, 'rules'] : [newItem];
setSelectedItems(Array.from(new Set([...selectedItems, ...newItems])));
};

// When the component mounts, if there is a new avatar, see if the image can be read from the disk. If not, redirect the user to the starting step of the flow.
Expand Down Expand Up @@ -339,7 +346,7 @@ function WorkspaceDuplicateSelectFeaturesForm({policyID}: WorkspaceDuplicateForm
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

const isSelectAllChecked = selectedItems.length > 0 && selectedItems.length === items.length;
const isSelectAllChecked = effectiveSelectedItems.length > 0 && effectiveSelectedItems.length === items.length;

const confirmButtonOptions: ConfirmButtonOptions<ListItem> = {
showButton: true,
Expand All @@ -363,7 +370,7 @@ function WorkspaceDuplicateSelectFeaturesForm({policyID}: WorkspaceDuplicateForm
<Checkbox
accessibilityLabel={translate('accessibilityHints.selectAllFeatures')}
isChecked={isSelectAllChecked}
isIndeterminate={selectedItems.length > 0 && selectedItems.length !== items.length}
isIndeterminate={effectiveSelectedItems.length > 0 && effectiveSelectedItems.length !== items.length}
onPress={toggleAllItems}
disabled={items.length === 0}
shouldSelectOnPressEnter
Expand Down
55 changes: 55 additions & 0 deletions tests/actions/PolicyTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -733,6 +733,61 @@ describe('actions/Policy', () => {
await waitForBatchedUpdates();
});

it('duplicate workspace without the rules and codingRules options copies no merchant rules', async () => {
// Given a source workspace with a merchant rule
const fakePolicy = createRandomPolicy(16, CONST.POLICY.TYPE.CORPORATE);
const sourceRule: Rule = {
scope: CONST.RULES.SCOPE.POLICY,
scopeID: fakePolicy.id,
triggers: indexMap(CONST.RULES.TRIGGERS.CREATE_TRANSACTION),
filters: {left: CONST.RULES.EXPENSE_DEFAULT.FIELD.MERCHANT, operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, right: 'Acme'},
actions: indexMap({name: CONST.RULES.ACTIONS.SET, field: CONST.RULES.EXPENSE_DEFAULT.FIELD.CATEGORY, value: 'Travel'}),
};
// The request stays paused so the assertions read the optimistic data, which is where a wrongly copied rule would appear.
mockFetch?.pause?.();
await Onyx.set(`${ONYXKEYS.COLLECTION.POLICY}${fakePolicy.id}`, fakePolicy);
await waitForBatchedUpdates();

const policyID = Policy.generatePolicyID();

// When the workspace is duplicated with both the Rules and Merchant rules options unselected
Policy.duplicateWorkspace(fakePolicy, {
currentUserAccountID: ESH_ACCOUNT_ID,
currentUserEmail: ESH_EMAIL,
policyName: 'No Rules Workspace',
policyID: fakePolicy.id,
targetPolicyID: policyID,
welcomeNote: 'Join my policy',
parts: {
people: false,
reports: false,
connections: false,
categories: false,
tags: false,
taxes: false,
perDiem: false,
reimbursements: false,
expenses: false,
distance: false,
invoices: false,
exportLayouts: false,
codingRules: false,
},
localCurrency: 'USD',
rules: {[`${ONYXKEYS.COLLECTION.RULE}sourceRule`]: sourceRule},
});
await waitForBatchedUpdates();

// Then no merchant rule is scoped to the duplicate and the Rules feature stays off, because the admin chose not to copy either
const duplicatedRules = Object.values((await getRulesCollection()) ?? {}).filter((rule) => rule?.scopeID === policyID);
expect(duplicatedRules).toHaveLength(0);
const policy = await getOnyxValue(`${ONYXKEYS.COLLECTION.POLICY}${policyID}`);
expect(policy?.areRulesEnabled).toBe(false);

await mockFetch?.resume?.();
await waitForBatchedUpdates();
});

it('duplicate workspace with 3+ members creates optimistic announce chat using currentUserAccountID', async () => {
await Onyx.set(ONYXKEYS.SESSION, {email: ESH_EMAIL, accountID: ESH_ACCOUNT_ID});
const basePolicy = createRandomPolicy(16, CONST.POLICY.TYPE.TEAM);
Expand Down
209 changes: 209 additions & 0 deletions tests/unit/WorkspaceDuplicateSelectFeaturesFormTest.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,209 @@
import {act, render} from '@testing-library/react-native';

import OnyxListItemProvider from '@components/OnyxListItemProvider';
import type {ConfirmButtonOptions, ListItem} from '@components/SelectionList/types';

import {toIndexMap} from '@libs/RuleUtils';

import WorkspaceDuplicateSelectFeaturesForm from '@pages/workspace/duplicate/WorkspaceDuplicateSelectFeaturesForm';

import {duplicateWorkspace} from '@userActions/Policy/Policy';

import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import type {Policy} from '@src/types/onyx';
import type Rule from '@src/types/onyx/Rule';

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

import createRandomPolicy from '../utils/collections/policies';
import * as TestHelper from '../utils/TestHelper';
import waitForBatchedUpdates from '../utils/waitForBatchedUpdates';

const POLICY_ID = '1';
const TARGET_POLICY_ID = '2';

type CapturedSelectionListProps = {
data: ListItem[];
onSelectRow: (item: ListItem) => void;
confirmButtonOptions: ConfirmButtonOptions<ListItem>;
};
let mockSelectionListProps: CapturedSelectionListProps | undefined;

// The list itself isn't under test, so it is replaced by a stub that captures the rows, the row handler and the Continue button.
jest.mock('@components/SelectionList', () => ({
__esModule: true,
default: (props: CapturedSelectionListProps) => {
mockSelectionListProps = props;
return null;
},
}));

jest.mock('@react-navigation/native', () => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const actualNav = jest.requireActual('@react-navigation/native');
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return {
...actualNav,
useRoute: () => ({params: {policyID: POLICY_ID}}),
};
});

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

jest.mock('@hooks/useConfirmModal', () => ({
__esModule: true,
default: () => ({showConfirmModal: jest.fn(() => Promise.resolve({action: 'cancel'}))}),
}));

// The form fires openDuplicatePolicyPage on mount and duplicateWorkspace on Continue. Both are stubbed so the test can read the parts the form sends.
jest.mock('@userActions/Policy/Policy', () => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const actual = jest.requireActual('@userActions/Policy/Policy');
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return {
...actual,
openDuplicatePolicyPage: jest.fn(),
duplicateWorkspace: jest.fn(),
};
});

const MERCHANT_RULE: Rule = {
scope: CONST.RULES.SCOPE.POLICY,
scopeID: POLICY_ID,
triggers: toIndexMap([CONST.RULES.TRIGGERS.CREATE_TRANSACTION]),
filters: {left: CONST.RULES.EXPENSE_DEFAULT.FIELD.MERCHANT, operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, right: 'Acme'},
actions: toIndexMap([{name: CONST.RULES.ACTIONS.SET, field: CONST.RULES.EXPENSE_DEFAULT.FIELD.CATEGORY, value: 'Travel'}]),
};

/** A Control workspace whose only possible workspace-level rule is eReceipts, so the test decides whether the Rules row is shown. */
function createSourcePolicy(hasWorkspaceRules: boolean): Policy {
return {
...createRandomPolicy(Number(POLICY_ID), CONST.POLICY.TYPE.CORPORATE),
preventSelfApproval: false,
maxExpenseAmountNoReceipt: CONST.DISABLED_MAX_EXPENSE_VALUE,
maxExpenseAmount: CONST.DISABLED_MAX_EXPENSE_VALUE,
maxExpenseAge: CONST.DISABLED_MAX_EXPENSE_VALUE,
eReceipts: hasWorkspaceRules,
};
}

async function renderForm(hasWorkspaceRules: boolean) {
await Onyx.set(`${ONYXKEYS.COLLECTION.POLICY}${POLICY_ID}`, createSourcePolicy(hasWorkspaceRules));
await Onyx.set(`${ONYXKEYS.COLLECTION.RULE}merchantRule`, MERCHANT_RULE);
await Onyx.set(ONYXKEYS.RAM_ONLY_HAS_RULES_DATA_BEEN_FETCHED, true);
await Onyx.set(ONYXKEYS.DUPLICATE_WORKSPACE, {name: 'Duplicate', policyID: TARGET_POLICY_ID});
await waitForBatchedUpdates();

render(
<OnyxListItemProvider>
<WorkspaceDuplicateSelectFeaturesForm policyID={POLICY_ID} />
</OnyxListItemProvider>,
);
await waitForBatchedUpdates();
}

function getRow(key: string): ListItem | undefined {
return mockSelectionListProps?.data.find((item) => item.keyForList === key);
}

async function pressRow(key: string) {
const row = getRow(key);
expect(row).toBeDefined();
if (!row) {
return;
}
act(() => {
mockSelectionListProps?.onSelectRow(row);
});
await waitForBatchedUpdates();
}

function pressContinue() {
act(() => {
mockSelectionListProps?.confirmButtonOptions.onConfirm?.();
});
}

function getSentParts(): Record<string, boolean> | undefined {
return jest.mocked(duplicateWorkspace).mock.calls.at(0)?.[1].parts;
}

describe('WorkspaceDuplicateSelectFeaturesForm Rules and Merchant rules', () => {
beforeAll(() => {
Onyx.init({keys: ONYXKEYS});
});

beforeEach(() => {
// Without a fetch mock, background requests reach the real fetch and fail in the test environment.
global.fetch = TestHelper.createGlobalFetchMock();
mockSelectionListProps = undefined;
});

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

it('deselects Merchant rules when Rules is deselected, so neither is copied', async () => {
// Given a source with workspace-level rules and a merchant rule, where every row starts selected
await renderForm(true);
expect(getRow('rules')?.isSelected).toBe(true);
expect(getRow('codingRules')?.isSelected).toBe(true);

// When the admin deselects Rules and continues
await pressRow('rules');
pressContinue();

// Then Merchant rules is deselected too, because merchant rules live under Rules and can't be copied without it
expect(getRow('codingRules')?.isSelected).toBe(false);
expect(getSentParts()).toMatchObject({expenses: false, codingRules: false});
});

it('selects Rules when Merchant rules is selected while Rules is deselected', async () => {
// Given Rules and Merchant rules were both deselected
await renderForm(true);
await pressRow('rules');

// When the admin selects Merchant rules and continues
await pressRow('codingRules');
pressContinue();

// Then Rules is selected too, so the merchant rules are copied along with the Rules feature they belong to
expect(getRow('rules')?.isSelected).toBe(true);
expect(getRow('codingRules')?.isSelected).toBe(true);
expect(getSentParts()).toMatchObject({expenses: true, codingRules: true});
});

it('keeps Rules selected when only Merchant rules is deselected', async () => {
// Given every row starts selected
await renderForm(true);

// When the admin deselects only Merchant rules and continues
await pressRow('codingRules');
pressContinue();

// Then the workspace-level rules are still copied without the merchant rules, because Rules doesn't depend on Merchant rules
expect(getRow('rules')?.isSelected).toBe(true);
expect(getSentParts()).toMatchObject({expenses: true, codingRules: false});
});

it('copies merchant rules on their own when the source has no workspace-level rules', async () => {
// Given a source with a merchant rule but no workspace-level rules, so the Rules row is hidden
await renderForm(false);
expect(getRow('rules')).toBeUndefined();
expect(getRow('codingRules')?.isSelected).toBe(true);

// When the admin continues
pressContinue();

// Then the merchant rules are still copied, because there is no Rules row they could depend on
expect(getSentParts()).toMatchObject({expenses: false, codingRules: true});
});
});
Loading