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
2 changes: 1 addition & 1 deletion config/eslint/eslint.seatbelt.tsv
Original file line number Diff line number Diff line change
Expand Up @@ -1735,7 +1735,7 @@
"../../tests/ui/hooks/useHtmlPasteTest/index.tsx" "@typescript-eslint/no-unsafe-type-assertion" 10
"../../tests/unit/APITest.ts" "@typescript-eslint/no-unsafe-type-assertion" 74
"../../tests/unit/AddExistingExpenseSearchTest.ts" "@typescript-eslint/no-unsafe-type-assertion" 6
"../../tests/unit/AgentActionTest.ts" "@typescript-eslint/no-unsafe-type-assertion" 57
"../../tests/unit/AgentActionTest.ts" "@typescript-eslint/no-unsafe-type-assertion" 61
"../../tests/unit/AgentZeroStatusContextTest.ts" "@typescript-eslint/no-unsafe-type-assertion" 5
"../../tests/unit/AvatarButtonWithIconTest.tsx" "@typescript-eslint/no-unsafe-type-assertion" 1
"../../tests/unit/AvatarUtilsTest.ts" "@typescript-eslint/no-unsafe-type-assertion" 2
Expand Down
2 changes: 2 additions & 0 deletions src/libs/WorkflowUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,8 @@ function calculateApprovers({employees, firstEmail, personalDetailsByEmail}: Get
approvalLimit: employee.approvalLimit,
overLimitForwardsTo: employee.overLimitForwardsTo,
overLimitForwardsToDisplayName: getOverLimitForwardsToDisplayName(employee.overLimitForwardsTo, personalDetailsByEmail),
pendingAction: employee.pendingAction,
Comment thread
NicolasBonet marked this conversation as resolved.
Resolved
Comment thread
NicolasBonet marked this conversation as resolved.
Resolved
errors: employee.errors,
});

// If we've already seen this approver, break to prevent infinite loop
Expand Down
30 changes: 29 additions & 1 deletion src/libs/actions/Agent.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import Onyx from 'react-native-onyx';
import type {OnyxCollection, OnyxCollectionInputValue} from 'react-native-onyx';
import {read, write} from '@libs/API';
import {READ_COMMANDS, WRITE_COMMANDS} from '@libs/API/types';
import {resolveAvatarURI} from '@libs/Avatars/PresetAvatarCatalog';
Expand All @@ -10,6 +11,8 @@ import type {AvatarSource} from '@libs/UserAvatarUtils';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import ROUTES from '@src/ROUTES';
import type {Policy} from '@src/types/onyx';
import type PolicyEmployee from '@src/types/onyx/PolicyEmployee';
import type {AnyOnyxUpdate} from '@src/types/onyx/Request';

function openAgentsPage() {
Expand Down Expand Up @@ -315,7 +318,7 @@ function updateAgentAvatar(
write(WRITE_COMMANDS.UPDATE_AGENT_AVATAR, params, {optimisticData, successData, failureData});
}

function deleteAgent(accountID: number) {
function deleteAgent(accountID: number, agentLogin?: string, allPolicies?: OnyxCollection<Policy>) {
const optimisticData: AnyOnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
Expand Down Expand Up @@ -348,6 +351,31 @@ function deleteAgent(accountID: number) {
},
];

// Mark the agent's row pending-delete on every policy it belongs to so workflow cards render
// the agent's approver row with strikethrough/RBR while DELETE_AGENT is in flight.
if (agentLogin && allPolicies) {
for (const policy of Object.values(allPolicies)) {
if (!policy?.id || !policy.employeeList?.[agentLogin]) {
continue;
}
const policyKey = `${ONYXKEYS.COLLECTION.POLICY}${policy.id}` as const;
const optimisticEmployees: OnyxCollectionInputValue<PolicyEmployee> = {
[agentLogin]: {pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE},
};
const successEmployees: OnyxCollectionInputValue<PolicyEmployee> = {[agentLogin]: null};
const failureEmployees: OnyxCollectionInputValue<PolicyEmployee> = {
[agentLogin]: {
pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE,
errors: getMicroSecondOnyxErrorWithTranslationKey('common.genericErrorMessage'),
},
};

optimisticData.push({onyxMethod: Onyx.METHOD.MERGE, key: policyKey, value: {employeeList: optimisticEmployees}});
successData.push({onyxMethod: Onyx.METHOD.MERGE, key: policyKey, value: {employeeList: successEmployees}});
failureData.push({onyxMethod: Onyx.METHOD.MERGE, key: policyKey, value: {employeeList: failureEmployees}});
}
}

write(WRITE_COMMANDS.DELETE_AGENT, {agentAccountID: accountID}, {optimisticData, successData, failureData});
Navigation.goBack(ROUTES.SETTINGS_AGENTS);
}
Expand Down
5 changes: 3 additions & 2 deletions src/pages/settings/Agents/EditAgentPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,14 @@ function EditAgentPage({route}: EditAgentPageProps) {
const accountID = route.params.accountID;
const [agent, agentMetadata] = useOnyx(`${ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT}${accountID}`);
const [personalDetails, personalDetailsMetadata] = useOnyx(ONYXKEYS.PERSONAL_DETAILS_LIST, {selector: (list) => list?.[accountID]});
const [allPolicies] = useOnyx(ONYXKEYS.COLLECTION.POLICY);
Comment thread
NicolasBonet marked this conversation as resolved.
Resolved
const {showConfirmModal} = useConfirmModal();
const chatWithAgent = useChatWithAgent();
const switchToDelegator = useSwitchToDelegator();
const isOnyxLoaded = agentMetadata.status === 'loaded' && personalDetailsMetadata.status === 'loaded';
const shouldShowNotFoundPage = isOnyxLoaded && !agent && !personalDetails;

const agentLogin = personalDetails?.login ?? '';
const handleBackPress = () => Navigation.goBack();
const handleEditAvatarPress = () => Navigation.navigate(ROUTES.SETTINGS_AGENTS_EDIT_AVATAR.getRoute(accountID));
const handleEditNamePress = () => Navigation.navigate(ROUTES.SETTINGS_AGENTS_EDIT_NAME.getRoute(accountID));
Expand All @@ -57,9 +59,8 @@ function EditAgentPage({route}: EditAgentPageProps) {
if (result.action !== ModalActions.CONFIRM) {
return;
}
deleteAgent(accountID);
deleteAgent(accountID, agentLogin, allPolicies);
};
const agentLogin = personalDetails?.login ?? '';
const isPendingAddOrDelete = agent?.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD || agent?.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE;
const areActionsDisabled = isPendingAddOrDelete || accountID <= 0 || !agentLogin;
const handleChatPress = () => {
Expand Down
79 changes: 79 additions & 0 deletions tests/unit/AgentActionTest.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import Onyx from 'react-native-onyx';
import type {OnyxCollection} from 'react-native-onyx';
import {write} from '@libs/API';
import {WRITE_COMMANDS} from '@libs/API/types';
import Navigation from '@libs/Navigation/Navigation';
import {clearAgentAvatarUpdateError, clearAgentUpdateError, createAgent, deleteAgent, updateAgentAvatar, updateAgentName, updateAgentPrompt} from '@userActions/Agent';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import type {Policy} from '@src/types/onyx';
import type {AnyOnyxUpdate} from '@src/types/onyx/Request';
import createRandomPolicy from '../utils/collections/policies';

jest.mock('@libs/API');
jest.mock('@libs/Navigation/Navigation', () => ({navigate: jest.fn(), goBack: jest.fn()}));
Expand Down Expand Up @@ -467,6 +470,82 @@ describe('deleteAgent', () => {

expect(mockGoBack).toHaveBeenCalledTimes(1);
});

describe('cascade to policies containing the agent', () => {
const AGENT_EMAIL = 'agent@expensifail.com';
const OTHER_EMAIL = 'submitter@expensifail.com';
const OWNER_EMAIL = 'owner@expensifail.com';
const POLICY_ID = 'POLICY1';
const policyKey = `${ONYXKEYS.COLLECTION.POLICY}${POLICY_ID}`;

const buildPolicies = (): OnyxCollection<Policy> => ({
[policyKey]: {
...createRandomPolicy(1),
id: POLICY_ID,
owner: OWNER_EMAIL,
approver: OWNER_EMAIL,
employeeList: {
[AGENT_EMAIL]: {email: AGENT_EMAIL, submitsTo: AGENT_EMAIL, forwardsTo: OWNER_EMAIL},
[OTHER_EMAIL]: {email: OTHER_EMAIL, submitsTo: AGENT_EMAIL},
},
},
});

it('marks agent employeeList entry as pending DELETE optimistically', () => {
deleteAgent(TEST_ACCOUNT_ID, AGENT_EMAIL, buildPolicies());

const {optimisticData} = getWriteOptions();
const policyUpdate = optimisticData.find((u) => u.key === policyKey);
const employees = (policyUpdate?.value as {employeeList: Record<string, {pendingAction: string}>})?.employeeList;
expect(employees?.[AGENT_EMAIL]).toEqual({pendingAction: 'delete'});
});

it('leaves other employees and approver chains untouched so the workflow card still renders', () => {
deleteAgent(TEST_ACCOUNT_ID, AGENT_EMAIL, buildPolicies());

const {optimisticData} = getWriteOptions();
const policyUpdate = optimisticData.find((u) => u.key === policyKey);
const value = policyUpdate?.value as {employeeList: Record<string, unknown>; approver?: string; rules?: unknown};
expect(value?.employeeList[OTHER_EMAIL]).toBeUndefined();
expect(value?.approver).toBeUndefined();
expect(value?.rules).toBeUndefined();
});

it('nulls the agent employeeList entry on success', () => {
deleteAgent(TEST_ACCOUNT_ID, AGENT_EMAIL, buildPolicies());

const {successData} = getWriteOptions();
const policyUpdate = successData.find((u) => u.key === policyKey);
const employees = (policyUpdate?.value as {employeeList: Record<string, unknown>})?.employeeList;
expect(employees?.[AGENT_EMAIL]).toBeNull();
});

it('restores agent pendingAction with errors on failure', () => {
deleteAgent(TEST_ACCOUNT_ID, AGENT_EMAIL, buildPolicies());

const {failureData} = getWriteOptions();
const policyUpdate = failureData.find((u) => u.key === policyKey);
const agentEntry = (policyUpdate?.value as {employeeList: Record<string, {pendingAction?: string; errors?: unknown}>})?.employeeList[AGENT_EMAIL];
expect(agentEntry?.pendingAction).toBe('delete');
expect(agentEntry?.errors).toBeTruthy();
});

it('skips policies that do not contain the agent', () => {
const policies: OnyxCollection<Policy> = {
[policyKey]: {
...createRandomPolicy(1),
id: POLICY_ID,
owner: OWNER_EMAIL,
approver: OWNER_EMAIL,
employeeList: {[OWNER_EMAIL]: {email: OWNER_EMAIL}},
},
};
deleteAgent(TEST_ACCOUNT_ID, AGENT_EMAIL, policies);

const {optimisticData} = getWriteOptions();
expect(optimisticData.find((u) => u.key === policyKey)).toBeUndefined();
});
});
});

describe('clearAgentUpdateError', () => {
Expand Down
18 changes: 18 additions & 0 deletions tests/unit/WorkflowUtilsTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,24 @@ describe('WorkflowUtils', () => {
]);
});

it('Should surface a DELETE pendingAction from the employee onto the approver row so the workflow card renders with strikethrough', () => {
const employees: PolicyEmployeeList = {
'1@example.com': {
email: '1@example.com',
forwardsTo: '2@example.com',
pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE,
},
'2@example.com': {
email: '2@example.com',
forwardsTo: undefined,
},
};

const approvers = calculateApprovers({employees, firstEmail: '1@example.com', personalDetailsByEmail});

expect(approvers).toEqual([buildApprover(1, {forwardsTo: '2@example.com', pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE}), buildApprover(2)]);
});

it('Should include approvalLimit and overLimitForwardsTo in approver objects', () => {
const employees: PolicyEmployeeList = {
'1@example.com': {
Expand Down
Loading