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
37 changes: 37 additions & 0 deletions src/libs/PolicyUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -611,6 +611,41 @@ function shouldFilterExpensifyTeam(policyOwner: string | undefined, currentUserL
return !!policyOwner && !!currentUserLogin && !isExpensifyTeam(policyOwner) && !isExpensifyTeam(currentUserLogin);
}

/**
* Creates a selector for useOnyx that computes the filtered member count.
* Returns a primitive number to prevent unnecessary re-renders when unrelated personal details change.
*/
function createFilteredMemberCountSelector(employeeList: PolicyEmployeeList | undefined, policyOwner: string | undefined, currentUserLogin: string | undefined) {
return (personalDetails: PersonalDetailsList | undefined): number => {
const shouldFilter = shouldFilterExpensifyTeam(policyOwner, currentUserLogin);
const policyMemberEmailsToAccountIDs = getMemberAccountIDsForWorkspace(employeeList, false, false);

return Object.keys(policyMemberEmailsToAccountIDs).reduce((count, email) => {
const accountID = policyMemberEmailsToAccountIDs[email];
const details = personalDetails?.[accountID];

if (shouldFilter && isExpensifyTeam(details?.login ?? details?.displayName)) {
return count;
}

return count + 1;
}, 0);
};
}

/**
* Creates a selector for useOnyx that returns formatted text for invoice configuration.
* Returns a primitive string to prevent unnecessary re-renders when unrelated bank account data changes.
* This matches the filtering logic used by PaymentMethodList with filterType=BUSINESS on the invoices page.
*/
function createInvoiceConfigurationTextSelector(translate: LocaleContextProps['translate'], invoiceCompany: string) {
return (bankAccountList: OnyxEntry<Record<string, {accountData?: {type?: string}}>>): string => {
const count = Object.values(bankAccountList ?? {}).filter((account) => account.accountData?.type === CONST.BANK_ACCOUNT.TYPE.BUSINESS).length;
const bankAccountsText = count > 0 ? `${count} ${translate('common.bankAccounts').toLowerCase()}` : '';
return [bankAccountsText, invoiceCompany].filter(Boolean).join(', ');
};
}

/**
* Checks if the current user is of the role "user" on the policy.
*/
Expand Down Expand Up @@ -2433,6 +2468,8 @@ export {
shouldShowTaxRateError,
isExpensifyTeam,
shouldFilterExpensifyTeam,
createFilteredMemberCountSelector,
createInvoiceConfigurationTextSelector,
isDeletedPolicyEmployee,
isInstantSubmitEnabled,
isDelayedSubmissionEnabled,
Expand Down
8 changes: 4 additions & 4 deletions src/pages/workspace/WorkspaceMembersPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ import {
isGroupPolicy,
isPaidGroupPolicy,
isPolicyApprover,
shouldFilterExpensifyTeam,
} from '@libs/PolicyUtils';
import {getDisplayNameForParticipant} from '@libs/ReportUtils';
import tokenizedSearch from '@libs/tokenizedSearch';
Expand Down Expand Up @@ -417,6 +418,7 @@ function WorkspaceMembersPage({personalDetails, route, policy}: WorkspaceMembers
const isControlPolicyWithWideLayout = !shouldUseNarrowLayout && isControlPolicy(policy);

const filteredMembers = useMemo(() => {
const shouldFilter = shouldFilterExpensifyTeam(policyOwner, currentUserLogin);
const result: Array<{email: string; policyEmployee: PolicyEmployee; accountID: number; details: PersonalDetails}> = [];

for (const [email, policyEmployee] of Object.entries(policy?.employeeList ?? {})) {
Expand All @@ -435,10 +437,8 @@ function WorkspaceMembersPage({personalDetails, route, policy}: WorkspaceMembers
// If this policy is owned by Expensify then show all support (expensify.com or team.expensify.com) emails
// We don't want to show guides as policy members unless the user is a guide. Some customers get confused when they
// see random people added to their policy, but guides having access to the policies help set them up.
if (isExpensifyTeam(details?.login ?? details?.displayName)) {
if (policyOwner && currentUserLogin && !isExpensifyTeam(policyOwner) && !isExpensifyTeam(currentUserLogin)) {
continue;
}
if (shouldFilter && isExpensifyTeam(details?.login ?? details?.displayName)) {
continue;
}

result.push({email, policyEmployee, accountID, details});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import MultiSelectListItem from '@components/SelectionList/ListItem/MultiSelectL
import type {ConfirmButtonOptions, ListItem} from '@components/SelectionList/types';
import Text from '@components/Text';
import useConfirmModal from '@hooks/useConfirmModal';
import useCurrentUserPersonalDetails from '@hooks/useCurrentUserPersonalDetails';
import useLocalize from '@hooks/useLocalize';
import useOnyx from '@hooks/useOnyx';
import useThemeStyles from '@hooks/useThemeStyles';
Expand All @@ -21,10 +22,9 @@ import {areAllTargetsAccountingCompatible, areAllTargetsCompatibleForAccountingP
import Navigation from '@libs/Navigation/Navigation';
import type {PlatformStackRouteProp} from '@libs/Navigation/PlatformStackNavigation/types';
import type {PolicyCopySettingsNavigatorParamList} from '@libs/Navigation/types';
import {getDistanceRateCustomUnit, getMemberAccountIDsForWorkspace, getPerDiemCustomUnit, isCollectPolicy} from '@libs/PolicyUtils';
import {createFilteredMemberCountSelector, createInvoiceConfigurationTextSelector, getDistanceRateCustomUnit, getPerDiemCustomUnit, isCollectPolicy} from '@libs/PolicyUtils';
import {formatAddressToString} from '@libs/ReportActionsUtils';
import {getReportFieldsByPolicyID} from '@libs/ReportUtils';
import {getEligibleExistingBusinessBankAccounts} from '@libs/WorkflowUtils';
import AccessOrNotFoundWrapper from '@pages/workspace/AccessOrNotFoundWrapper';
import {getAllValidConnectedIntegration, getWorkflowRules, getWorkspaceRules} from '@pages/workspace/duplicate/utils';
import CONST from '@src/CONST';
Expand Down Expand Up @@ -53,7 +53,7 @@ function CopyPolicySettingsSelectFeaturesPage() {
const [copyPolicySettings] = useOnyx(ONYXKEYS.COPY_POLICY_SETTINGS);
const [policyTags] = useOnyx(`${ONYXKEYS.COLLECTION.POLICY_TAGS}${sourcePolicyID}`);
const [policyCategories] = useOnyx(`${ONYXKEYS.COLLECTION.POLICY_CATEGORIES}${sourcePolicyID}`);
const [bankAccountList] = useOnyx(ONYXKEYS.BANK_ACCOUNT_LIST);
const currentUserPersonalDetails = useCurrentUserPersonalDetails();

const sourcePolicy = sourcePolicyID ? policies?.[`${ONYXKEYS.COLLECTION.POLICY}${sourcePolicyID}`] : undefined;
const targetPolicyIDs = copyPolicySettings?.targetPolicyIDs ?? [];
Expand All @@ -63,7 +63,13 @@ function CopyPolicySettingsSelectFeaturesPage() {
const isCodingCompatible = areAllTargetsAccountingCompatible(sourcePolicy, targetPolicies);
const isAccountingPartCompatible = areAllTargetsCompatibleForAccountingPart(sourcePolicy, targetPolicies);

const memberCount = Object.keys(getMemberAccountIDsForWorkspace(sourcePolicy?.employeeList, false, false)).length;
const [memberCount = 0] = useOnyx(ONYXKEYS.PERSONAL_DETAILS_LIST, {
selector: createFilteredMemberCountSelector(sourcePolicy?.employeeList, sourcePolicy?.owner, currentUserPersonalDetails.login),
});
const invoiceCompany = [sourcePolicy?.invoice?.companyName, sourcePolicy?.invoice?.companyWebsite].filter(Boolean).join(', ');
const [invoiceConfigurationText = ''] = useOnyx(ONYXKEYS.BANK_ACCOUNT_LIST, {
selector: createInvoiceConfigurationTextSelector(translate, invoiceCompany),
});
const categoriesCount = Object.values(policyCategories ?? {}).filter((c) => c?.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE).length;
const totalTags = policyTags
? Object.values(policyTags).reduce(
Expand All @@ -81,9 +87,6 @@ function CopyPolicySettingsSelectFeaturesPage() {
const formattedAddress = !isEmptyObject(sourcePolicy) && !isEmptyObject(sourcePolicy.address) ? formatAddressToString(sourcePolicy.address) : '';
const workflows = getWorkflowRules(sourcePolicy, translate);
const rules = getWorkspaceRules(sourcePolicy, translate);
const invoiceCompany = [sourcePolicy?.invoice?.companyName, sourcePolicy?.invoice?.companyWebsite].filter(Boolean).join(', ');

const workspaceBankAccountsCount = getEligibleExistingBusinessBankAccounts(bankAccountList, sourcePolicy?.outputCurrency).length;

const sourceFeatureContext = {
policy: sourcePolicy,
Expand All @@ -98,7 +101,7 @@ function CopyPolicySettingsSelectFeaturesPage() {
hasWorkflowRules: !!workflows?.length,
hasWorkspaceRules: !!rules?.length,
codingRulesCount,
hasInvoiceConfiguration: (!!sourcePolicy?.areInvoicesEnabled && workspaceBankAccountsCount > 0) || !!invoiceCompany,
hasInvoiceConfiguration: !!sourcePolicy?.areInvoicesEnabled && !!invoiceConfigurationText,
isCollectPolicy: isCollectPolicy(sourcePolicy),
};

Expand Down Expand Up @@ -163,13 +166,8 @@ function CopyPolicySettingsSelectFeaturesPage() {
return distanceRatesCount > 0 ? `${distanceRatesCount} ${translate('iou.rates').toLowerCase()}` : undefined;
case 'perDiem':
return perDiemCount > 0 ? `${perDiemCount} ${translate('workspace.common.perDiem').toLowerCase()}` : undefined;
case 'invoices': {
const bankAccountsText = workspaceBankAccountsCount > 0 ? `${workspaceBankAccountsCount} ${translate('common.bankAccounts').toLowerCase()}` : '';
if (bankAccountsText && invoiceCompany) {
return `${bankAccountsText}, ${invoiceCompany}`;
}
return bankAccountsText || invoiceCompany || undefined;
}
case 'invoices':
return invoiceConfigurationText || undefined;
default:
return undefined;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import useOnyx from '@hooks/useOnyx';
import usePolicy from '@hooks/usePolicy';
import useThemeStyles from '@hooks/useThemeStyles';
import {readFileAsync} from '@libs/fileDownload/FileUtils';
import {getDistanceRateCustomUnit, getMemberAccountIDsForWorkspace, getPerDiemCustomUnit, isCollectPolicy} from '@libs/PolicyUtils';
import {createFilteredMemberCountSelector, createInvoiceConfigurationTextSelector, getDistanceRateCustomUnit, getPerDiemCustomUnit, isCollectPolicy} from '@libs/PolicyUtils';
import {formatAddressToString} from '@libs/ReportActionsUtils';
import {getReportFieldsByPolicyID} from '@libs/ReportUtils';
import Navigation from '@navigation/Navigation';
Expand All @@ -39,8 +39,6 @@ function WorkspaceDuplicateSelectFeaturesForm({policyID}: WorkspaceDuplicateForm
const {showConfirmModal} = useConfirmModal();
const [duplicateWorkspace] = useOnyx(ONYXKEYS.DUPLICATE_WORKSPACE);
const [duplicatedWorkspaceAvatar, setDuplicatedWorkspaceAvatar] = useState<File | undefined>();
const allIds = getMemberAccountIDsForWorkspace(policy?.employeeList, false, false);
const totalMembers = Object.keys(allIds).length;
const [policyTags] = useOnyx(`${ONYXKEYS.COLLECTION.POLICY_TAGS}${policyID}`);
const taxesLength = Object.values(policy?.taxRates?.taxes ?? {}).filter((tax) => tax.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE).length ?? 0;
const [policyCategories] = useOnyx(`${ONYXKEYS.COLLECTION.POLICY_CATEGORIES}${policyID}`);
Expand All @@ -51,18 +49,20 @@ function WorkspaceDuplicateSelectFeaturesForm({policyID}: WorkspaceDuplicateForm
const customUnits = getPerDiemCustomUnit(policy);
const customUnitRates: Record<string, Rate> = customUnits?.rates ?? {};
const allRates = Object.values(customUnitRates)?.filter((rate) => rate.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE).length ?? 0;
const [bankAccountList] = useOnyx(ONYXKEYS.BANK_ACCOUNT_LIST);
const currentUserPersonalDetails = useCurrentUserPersonalDetails();
const [totalMembers = 0] = useOnyx(ONYXKEYS.PERSONAL_DETAILS_LIST, {
selector: createFilteredMemberCountSelector(policy?.employeeList, policy?.owner, currentUserPersonalDetails.login),
});
const invoiceCompany = [policy?.invoice?.companyName, policy?.invoice?.companyWebsite].filter(Boolean).join(', ');
const [invoiceConfigurationText = ''] = useOnyx(ONYXKEYS.BANK_ACCOUNT_LIST, {
selector: createInvoiceConfigurationTextSelector(translate, invoiceCompany),
});

const accountingIntegrations = CONST.POLICY.CONNECTIONS.ACCOUNTING_CONNECTION_NAMES;
const connectedIntegration = getAllValidConnectedIntegration(policy, accountingIntegrations);

const customUnit = getDistanceRateCustomUnit(policy);
const ratesCount = Object.values(customUnit?.rates ?? {}).filter((rate) => rate.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE).length;
const invoiceCompany =
policy?.invoice?.companyName && policy?.invoice?.companyWebsite
? `${policy?.invoice?.companyName}, ${policy?.invoice?.companyWebsite}`
: (policy?.invoice?.companyName ?? policy?.invoice?.companyWebsite ?? '');

const totalTags = useMemo(() => {
if (!policyTags) {
Expand Down Expand Up @@ -166,11 +166,11 @@ function WorkspaceDuplicateSelectFeaturesForm({policyID}: WorkspaceDuplicateForm
}
: undefined,

policy?.areInvoicesEnabled && ((bankAccountList && Object.keys(bankAccountList).length) || !!invoiceCompany)
policy?.areInvoicesEnabled && !!invoiceConfigurationText
? {
translation: translate('workspace.common.invoices'),
value: 'invoices',
alternateText: bankAccountList ? `${Object.keys(bankAccountList).length} ${translate('common.bankAccounts').toLowerCase()}, ${invoiceCompany}` : invoiceCompany,
alternateText: invoiceConfigurationText,
}
: undefined,
policy?.isTravelEnabled
Expand All @@ -195,8 +195,7 @@ function WorkspaceDuplicateSelectFeaturesForm({policyID}: WorkspaceDuplicateForm
ratesCount,
isCollect,
allRates,
bankAccountList,
invoiceCompany,
invoiceConfigurationText,
codingRulesCount,
]);

Expand Down
Loading
Loading