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
85 changes: 85 additions & 0 deletions src/hooks/useApprovalWorkflows.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
/**
* Hook that derives a workspace's approval workflows from the source of truth and reports whether the workspace
* actually has a custom (advanced) approval workflow, so callers don't trust the stale `policy.approvalMode` flag.
*/
import {isHRAdvancedMode} from '@libs/merge/HRUtils';
import {isControlPolicy} from '@libs/PolicyUtils';
import {convertApprovalWorkflowRulesToWorkflows, convertPolicyEmployeesToApprovalWorkflows, filterRulesForPolicy, getApprovalWorkflowRulesForPolicy} from '@libs/WorkflowUtils';

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

import type {OnyxCollection, OnyxEntry} from 'react-native-onyx';

import useCurrentUserPersonalDetails from './useCurrentUserPersonalDetails';
import useLocalize from './useLocalize';
import useOnyx from './useOnyx';
import usePermissions from './usePermissions';
import {useAllPersonalDetails} from './usePersonalDetails';

type UseApprovalWorkflowsResult = {
/** Every approval workflow the workspace's data describes, derived from the policy employees or the approval-workflow rules */
approvalWorkflows: ApprovalWorkflow[];

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

❌ CONSISTENCY-13 (docs)

This is a new, non-trivial module file (a hook plus a result type), but its first non-import token is the UseApprovalWorkflowsResult type declaration with no header comment describing the file. A one-line header orients the next reader immediately instead of forcing them to scan down to the function JSDoc to learn the module's purpose.

Add a short header comment at the top (after the imports or above them), e.g.:

/**
 * Hook that derives a workspace's approval workflows from the source of truth and reports whether the
 * workspace actually has a custom (advanced) approval workflow, so callers don't trust the stale `policy.approvalMode` flag.
 */
type UseApprovalWorkflowsResult = {
    // ...
};

Reviewed at: 5bce7a5 | Please rate this suggestion with 👍 or 👎 to help us improve! Reactions are used to monitor reviewer efficiency.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Added a file header to useApprovalWorkflows.ts in 1b01fcf. It describes what the hook derives and why callers should use it instead of policy.approvalMode. Lint passes.


/** The subset of `approvalWorkflows` the Workflows tab displays: only the default workflow unless the workspace uses advanced approvals */
filteredApprovalWorkflows: ApprovalWorkflow[];

/** List of available members that can be selected in a workflow */
availableMembers: Member[];

/** Emails that are already used as approvers in the configured workflows */
usedApproverEmails: string[];

/** Whether the workspace has a custom (advanced) approval workflow on top of the plain default one */
isAdvanceApproval: boolean;

/** The workspace's approval-workflow rules, exposed so consumers don't need a second `RULE` subscription */
rulesCollection: OnyxCollection<Rule>;

/** Personal details, exposed so consumers don't need a second `PERSONAL_DETAILS_LIST` subscription */
personalDetails: OnyxEntry<PersonalDetailsList>;
};

/**
* Derives approval workflows from policy employees or approval rules when `MULTIPLE_APPROVERS` is enabled.
*
* Prefer `isAdvanceApproval` over `policy.approvalMode`: the stored value is updated optimistically and can drift from the actual workflow structure.
*/
function useApprovalWorkflows(policy: OnyxEntry<Policy>): UseApprovalWorkflowsResult {
const policyID = policy?.id;
const {localeCompare} = useLocalize();
const {isBetaEnabled} = usePermissions();
const {login: currentUserLogin = ''} = useCurrentUserPersonalDetails();
const [personalDetails] = useAllPersonalDetails();
const [rulesCollection] = useOnyx(ONYXKEYS.COLLECTION.RULE, {selector: (rules: OnyxCollection<Rule>) => filterRulesForPolicy(rules, policyID)});

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Load workflow rules before deriving beta workflows

When a MULTIPLE_APPROVERS user enters the invite flow directly with a cold Rule collection, this hook treats the empty collection as authoritative and falls back to employeeList, even though beta workflow creation writes the configuration only to Rule records. The Members flow only calls openWorkspaceMembersPage() (WorkspaceMembersPage.tsx), while those records are fetched by openPolicyWorkflowsPage() on the Workflows page, so visiting Members first can incorrectly hide the Approver row and submit the invite without the chosen submitsTo; fetch the policy's workflow rules here or defer the derived result until they are loaded.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Valid — fixed in a938794.

Confirmed the mechanism: openPolicyWorkflowsPage is called only from WorkspaceWorkflowsPage.tsx:70 and WorkspaceWorkflowsPageRevamp.tsx:76, and with an empty rules map buildApproverChainFromRules falls back to employeeList.submitsTo — which the beta path never writes. So Members-first really did read an unfetched collection as "no custom workflow".

Went with the fetch rather than deferring: the collection is never fetched at all on that path, so deferring would hide the row indefinitely, and blocking submit would break enabledWhenOffline on the form. The invite component now fires the same read when the beta is on (WorkspaceInviteMessageComponent.tsx:121-130), and the hook's doc block now states the requirement for any future caller.


const isMultipleApproversBetaEnabled = isBetaEnabled(CONST.BETAS.MULTIPLE_APPROVERS);
const params = {
policy,
personalDetails: personalDetails ?? {},
localeCompare,
currentUserLogin,
rules: getApprovalWorkflowRulesForPolicy(rulesCollection, policyID),
};
const {approvalWorkflows, availableMembers, usedApproverEmails} = isMultipleApproversBetaEnabled
? convertApprovalWorkflowRulesToWorkflows(params)
: convertPolicyEmployeesToApprovalWorkflows(params);

const isAdvanceApproval = (approvalWorkflows.length > 1 || (approvalWorkflows?.at(0)?.approvers ?? []).length > 1) && isControlPolicy(policy);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Derive advanced state from the active workflows

For a non-beta Control workspace whose employeeList still contains a non-default submitsTo while approvalMode is BASIC, this counts the hidden legacy workflow and exposes the invite Approver picker. The same hook filters that workflow out at lines 74–80, and getManagerAccountEmail() deliberately ignores employeeList.submitsTo for BASIC policies (src/libs/PolicyUtils/index.ts:1907–1919), so the selected approver is sent with the invite but the member's reports will still route to the default approver. Compute this flag from filteredApprovalWorkflows (or otherwise require the active mode) so the invite surface agrees with effective routing.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The consequence is real but the premise state isn't reachable, so I don't think this needs a change.

The getManagerAccountEmail citation is accurate — PolicyUtils/index.ts#L1907-L1910 does return defaultApprover for BASIC/OPTIONAL and ignore submitsTo. But "employeeList still contains a non-default submitsTo while approvalMode is BASIC" is asserted without a path, and every writer that sets BASIC rules it out at the moment it writes:

  • Workflow.ts#L183 / #L189 — updateApprovalWorkflow writes BASIC only when hasMultipleWorkflows is false, i.e. no employee has a submitsTo other than the effective default approver, over the full merged list. #L251 has the same guard for remove.
  • The Approvals re-enable writes BASIC only after disabling flattened every chain to the owner (Policy.ts#L981-L1000).
  • CSV import promotes to ADVANCED whenever it sends a submitsTo on a Control policy (Member.ts#L1067).
  • addMembersToWorkspace only writes a non-default submitsTo when the Approver row was shown, which already requires isAdvanceApproval — circular.

Toggling Workflows off is also rejected by the backend when a custom workflow exists, which closes the other route into a non-ADVANCED mode with chains intact.

The suggested fix isn't clearly safer either: routing goes through getApprovalWorkflow, which defaults a missing approvalMode to ADVANCED (PolicyUtils/index.ts#L1680), while the filter tests the raw field for === ADVANCED. For a policy with approvalMode undefined and real chains, computing the flag from filteredApprovalWorkflows would hide a row that does match effective routing — and since the Workflows tab shares isAdvanceApproval, it would also undo the revert that keeps the tab identical to main.


const filteredApprovalWorkflows =
isMultipleApproversBetaEnabled ||
policy?.approvalMode === CONST.POLICY.APPROVAL_MODE.ADVANCED ||
policy?.approvalMode === CONST.POLICY.APPROVAL_MODE.DYNAMICEXTERNAL ||
isHRAdvancedMode(policy)
? approvalWorkflows
: approvalWorkflows.filter((workflow) => workflow.isDefault);

return {approvalWorkflows, filteredApprovalWorkflows, availableMembers, usedApproverEmails, isAdvanceApproval, rulesCollection, personalDetails};
}

export default useApprovalWorkflows;
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import ScreenWrapper from '@components/ScreenWrapper';
import Text from '@components/Text';
import TextInput from '@components/TextInput';

import useApprovalWorkflows from '@hooks/useApprovalWorkflows';
import useAutoFocusInput from '@hooks/useAutoFocusInput';
import useLocalize from '@hooks/useLocalize';
import useOnyx from '@hooks/useOnyx';
Expand All @@ -33,14 +34,13 @@ import {
getDefaultApprover,
getMemberAccountIDsForWorkspace,
goBackFromInvalidPolicy,
isControlPolicy,
isSubmitPolicy,
shouldHideDynamicExternalWorkflowPeople,
tryNavigateToSubmitWorkspaceUpgrade,
} from '@libs/PolicyUtils';
import {getAllPolicyExpenseChatReportActions} from '@libs/ReportUtils';
import updateMultilineInputRange from '@libs/updateMultilineInputRange';
import {getSearchParamFromPath} from '@libs/Url';
import {filterRulesForPolicy} from '@libs/WorkflowUtils';

import variables from '@styles/variables';

Expand All @@ -52,11 +52,10 @@ import type {Route as Routes} from '@src/ROUTES';
import INPUT_IDS from '@src/types/form/WorkspaceInviteMessageForm';
import type {CurrentUserPersonalDetails} from '@src/types/onyx/PersonalDetails';
import type Policy from '@src/types/onyx/Policy';
import type Rule from '@src/types/onyx/Rule';
import {isEmptyObject} from '@src/types/utils/EmptyObject';
import isLoadingOnyxValue from '@src/types/utils/isLoadingOnyxValue';

import type {OnyxCollection, OnyxEntry} from 'react-native-onyx';
import type {OnyxEntry} from 'react-native-onyx';
import type {GestureResponderEvent} from 'react-native/Libraries/Types/CoreEventTypes';

import {Str} from 'expensify-common';
Expand Down Expand Up @@ -88,6 +87,7 @@ function WorkspaceInviteMessageComponent({
}: WorkspaceInviteMessageComponentProps) {
const styles = useThemeStyles();
const {translate, formatPhoneNumber} = useLocalize();
const {isBetaEnabled} = usePermissions();
const policyName = policy?.name;

const backToPath = typeof backTo === 'string' ? (backTo.split('?').at(0) ?? '') : '';
Expand All @@ -101,9 +101,6 @@ function WorkspaceInviteMessageComponent({
const [allReportActions] = useOnyx(ONYXKEYS.COLLECTION.REPORT_ACTIONS);
// Only used when this page finishes a "+N more" workflow edit, which has no edit page behind it to save the workflow.
const [approvalWorkflow] = useOnyx(ONYXKEYS.APPROVAL_WORKFLOW);
const policyRulesSelector = useCallback((rules: OnyxCollection<Rule>) => filterRulesForPolicy(rules, policyID), [policyID]);
const [rulesCollection] = useOnyx(ONYXKEYS.COLLECTION.RULE, {selector: policyRulesSelector});
const {isBetaEnabled} = usePermissions();

const [welcomeNote, setWelcomeNote] = useState<string>();

Expand All @@ -127,8 +124,10 @@ function WorkspaceInviteMessageComponent({
const approverDetails = usePersonalDetailByLogin(workspaceInviteApproverDraft);
const employeePersonalDetails = usePersonalDetailsByLogins(Object.keys(policy?.employeeList ?? {}));

const isControl = isControlPolicy(policy);
const shouldShowApproverRow = isControl && policy?.approvalMode === CONST.POLICY.APPROVAL_MODE.ADVANCED && policy?.areWorkflowsEnabled;
// `approvalMode` can drift from the actual workflow structure because it is updated optimistically.
// Dynamic external workflows that hide people also have no selectable approver.
const {isAdvanceApproval, rulesCollection} = useApprovalWorkflows(policy);
const shouldShowApproverRow = isAdvanceApproval && !!policy?.areWorkflowsEnabled && !shouldHideDynamicExternalWorkflowPeople(policy);

const isApproverValid = !!workspaceInviteApproverDraft && workspaceInviteApproverDraft in (policy?.employeeList ?? {});
const validatedApprover = isApproverValid ? workspaceInviteApproverDraft : undefined;
Expand Down
45 changes: 6 additions & 39 deletions src/pages/workspace/workflows/tabs/WorkflowsApprovalsTab.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,14 @@ import SearchBar from '@components/SearchBar';
import Text from '@components/Text';
import TextLink from '@components/TextLink';

import useApprovalWorkflows from '@hooks/useApprovalWorkflows';
import useConfirmModal from '@hooks/useConfirmModal';
import useCurrentUserPersonalDetails from '@hooks/useCurrentUserPersonalDetails';
import useDebouncedAccessibilityAnnouncement from '@hooks/useDebouncedAccessibilityAnnouncement';
import {useMemoizedLazyExpensifyIcons} from '@hooks/useLazyAsset';
import useLocalize from '@hooks/useLocalize';
import useOnyx from '@hooks/useOnyx';
import usePermissions from '@hooks/usePermissions';
import {useAllPersonalDetails} from '@hooks/usePersonalDetails';
import usePolicy from '@hooks/usePolicy';
import usePolicyFeatureWriteAccess from '@hooks/usePolicyFeatureWriteAccess';
import useResponsiveLayout from '@hooks/useResponsiveLayout';
Expand All @@ -35,23 +35,12 @@ import Navigation from '@libs/Navigation/Navigation';
import {isTrackOnboardingChoice} from '@libs/OnboardingUtils';
import {getApprovalWorkflow, hasDynamicExternalWorkflow, isControlPolicy, isGroupPolicy, isSubmitPolicy, shouldHideDynamicExternalWorkflowPeople} from '@libs/PolicyUtils';
import tokenizedSearch from '@libs/tokenizedSearch';
import {
convertApprovalWorkflowRulesToWorkflows,
convertPolicyEmployeesToApprovalWorkflows,
filterRulesForPolicy,
getApprovalWorkflowRulesForPolicy,
getApprovalWorkflowSource,
INITIAL_APPROVAL_WORKFLOW,
isApprovalWorkflowLockedByIntegration,
} from '@libs/WorkflowUtils';
import {getApprovalWorkflowSource, INITIAL_APPROVAL_WORKFLOW, isApprovalWorkflowLockedByIntegration} from '@libs/WorkflowUtils';

import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import ROUTES, {DYNAMIC_ROUTES} from '@src/ROUTES';
import type ApprovalWorkflow from '@src/types/onyx/ApprovalWorkflow';
import type Rule from '@src/types/onyx/Rule';

import type {OnyxCollection} from 'react-native-onyx';

import {Str} from 'expensify-common';
import React, {useCallback, useEffect, useMemo, useState} from 'react';
Expand Down Expand Up @@ -116,23 +105,22 @@ function WorkflowsLoadMoreCard({count, onPress}: {count: number; onPress: () =>
}

function WorkflowsApprovalsTab({policyID}: WorkflowsApprovalsTabProps) {
const {translate, localeCompare, formatPhoneNumber} = useLocalize();
const {translate, formatPhoneNumber} = useLocalize();
const styles = useThemeStyles();
const theme = useTheme();
const {shouldUseNarrowLayout} = useResponsiveLayout();
const expensifyIcons = useMemoizedLazyExpensifyIcons(['Info', 'Plus']);
const policy = usePolicy(policyID);
const {showConfirmModal} = useConfirmModal();
const {isBetaEnabled, isBetaEnabledOrUnknown} = usePermissions();
const {isBetaEnabledOrUnknown} = usePermissions();

const isSmartLimitEnabled = policy?.areApprovalsLockedByExpensifyCard ?? false;
const [transactionViolations] = useOnyx(ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS);
const [personalDetails] = useAllPersonalDetails();
const [account] = useOnyx(ONYXKEYS.ACCOUNT);
const [introSelected] = useOnyx(ONYXKEYS.NVP_INTRO_SELECTED);
const accountManagerReportID = account?.accountManagerReportID;
const isTrackIntentUser = isTrackOnboardingChoice(introSelected?.choice);
const {accountID: currentUserAccountID, email: currentUserEmail = '', login: currentUserLogin = ''} = useCurrentUserPersonalDetails();
const {accountID: currentUserAccountID, email: currentUserEmail = ''} = useCurrentUserPersonalDetails();

const {
canWrite: canWriteApprovals,
Expand All @@ -142,21 +130,8 @@ function WorkflowsApprovalsTab({policyID}: WorkflowsApprovalsTabProps) {

const isSubmitPolicyWorkspace = isSubmitPolicy(policy);

const isMultipleApproversBetaEnabled = isBetaEnabled(CONST.BETAS.MULTIPLE_APPROVERS);
const policyRulesSelector = useCallback((rules: OnyxCollection<Rule>) => filterRulesForPolicy(rules, policyID), [policyID]);
const [rulesCollection] = useOnyx(ONYXKEYS.COLLECTION.RULE, {selector: policyRulesSelector});
const {approvalWorkflows, availableMembers, usedApproverEmails} = useMemo(() => {
const params = {
policy,
personalDetails: personalDetails ?? {},
localeCompare,
currentUserLogin,
rules: getApprovalWorkflowRulesForPolicy(rulesCollection, policyID),
};
return isMultipleApproversBetaEnabled ? convertApprovalWorkflowRulesToWorkflows(params) : convertPolicyEmployeesToApprovalWorkflows(params);
}, [policy, personalDetails, localeCompare, currentUserLogin, rulesCollection, policyID, isMultipleApproversBetaEnabled]);
const {approvalWorkflows, filteredApprovalWorkflows, availableMembers, usedApproverEmails, isAdvanceApproval, rulesCollection, personalDetails} = useApprovalWorkflows(policy);

const isAdvanceApproval = (approvalWorkflows.length > 1 || (approvalWorkflows?.at(0)?.approvers ?? []).length > 1) && isControlPolicy(policy);
const updateApprovalMode = isAdvanceApproval ? CONST.POLICY.APPROVAL_MODE.ADVANCED : CONST.POLICY.APPROVAL_MODE.BASIC;

const confirmDisableApprovals = useCallback(() => {
Expand Down Expand Up @@ -231,14 +206,6 @@ function WorkflowsApprovalsTab({policyID}: WorkflowsApprovalsTabProps) {
const isRecruitingAdvancedModeEnabled = isRecruitingAdvancedMode(policy);
const hrFinalApproverEmail = getHRFinalApprover(policy);

const filteredApprovalWorkflows =
isMultipleApproversBetaEnabled ||
policy?.approvalMode === CONST.POLICY.APPROVAL_MODE.ADVANCED ||
policy?.approvalMode === CONST.POLICY.APPROVAL_MODE.DYNAMICEXTERNAL ||
isHRAdvancedModeEnabled
? approvalWorkflows
: approvalWorkflows.filter((workflow) => workflow.isDefault);

const everyoneText = translate('workspace.common.everyone');

const filterWorkflow = (workflow: ApprovalWorkflow, searchInput: string) => {
Expand Down
Loading
Loading