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
17 changes: 3 additions & 14 deletions src/libs/PolicyUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@

let allPolicies: OnyxCollection<Policy>;

Onyx.connect({

Check warning on line 58 in src/libs/PolicyUtils.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,
waitForCollectionCallback: true,
callback: (value) => (allPolicies = value),
Expand Down Expand Up @@ -1388,22 +1388,12 @@
return policy.workspaceAccountID ?? CONST.DEFAULT_NUMBER_ID;
}

function hasVBBA(policyID: string | undefined) {
// This will be fixed as part of https://github.com/Expensify/Expensify/issues/507850
// eslint-disable-next-line @typescript-eslint/no-deprecated
const policy = getPolicy(policyID);
return !!policy?.achAccount?.bankAccountID;
}

function getTagApproverRule(policyOrID: string | OnyxEntry<Policy>, tagName: string) {
if (!policyOrID) {
function getTagApproverRule(policy: OnyxEntry<Policy>, tagName: string) {
if (!policy) {
return;
}
// This will be fixed as part of https://github.com/Expensify/Expensify/issues/507850
// eslint-disable-next-line @typescript-eslint/no-deprecated
const policy = typeof policyOrID === 'string' ? getPolicy(policyOrID) : policyOrID;

const approvalRules = policy?.rules?.approvalRules ?? [];
const approvalRules = policy.rules?.approvalRules ?? [];
const approverRule = approvalRules.find((rule) =>
rule.applyWhen.find(({condition, field, value}) => condition === CONST.POLICY.RULE_CONDITIONS.MATCHES && field === CONST.POLICY.FIELDS.TAG && value === tagName),
);
Expand Down Expand Up @@ -1664,7 +1654,6 @@
canSubmitPerDiemExpenseFromWorkspace,
canSendInvoice,
hasDependentTags,
hasVBBA,
getXeroTenants,
findCurrentXeroOrganization,
getCurrentXeroOrganizationName,
Expand Down
4 changes: 2 additions & 2 deletions src/libs/actions/Policy/Tag.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
import type {OnyxData} from '@src/types/onyx/Request';

let allPolicyTags: OnyxCollection<PolicyTagLists> = {};
Onyx.connect({

Check warning on line 39 in src/libs/actions/Policy/Tag.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_TAGS,
waitForCollectionCallback: true,
callback: (value) => {
Expand Down Expand Up @@ -574,7 +574,7 @@
const oldTagName = policyTag.oldName;
const newTagName = PolicyUtils.escapeTagName(policyTag.newName);

const policyTagRule = PolicyUtils.getTagApproverRule(policyID, oldTagName);
const policyTagRule = PolicyUtils.getTagApproverRule(policyData.policy, oldTagName);
const approvalRules = policyData.policy?.rules?.approvalRules ?? [];
const updatedApprovalRules: ApprovalRule[] = lodashCloneDeep(approvalRules);

Expand Down Expand Up @@ -1169,7 +1169,7 @@
// eslint-disable-next-line @typescript-eslint/no-deprecated
const policy = PolicyUtils.getPolicy(policyID);
const prevApprovalRules = policy?.rules?.approvalRules ?? [];
const approverRuleToUpdate = PolicyUtils.getTagApproverRule(policyID, tag);
const approverRuleToUpdate = PolicyUtils.getTagApproverRule(policy, tag);
const filteredApprovalRules = approverRuleToUpdate ? prevApprovalRules.filter((rule) => rule.id !== approverRuleToUpdate.id) : prevApprovalRules;
const toBeUnselected = approverRuleToUpdate?.approver === approver;

Expand Down
14 changes: 10 additions & 4 deletions src/pages/Search/SearchPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ import {navigateToParticipantPage} from '@libs/IOUUtils';
import Navigation from '@libs/Navigation/Navigation';
import type {PlatformStackScreenProps} from '@libs/Navigation/PlatformStackNavigation/types';
import type {SearchFullscreenNavigatorParamList} from '@libs/Navigation/types';
import {getActiveAdminWorkspaces, hasDynamicExternalWorkflow, hasOnlyPersonalPolicies as hasOnlyPersonalPoliciesUtil, hasVBBA, isPaidGroupPolicy} from '@libs/PolicyUtils';
import {getActiveAdminWorkspaces, hasDynamicExternalWorkflow, hasOnlyPersonalPolicies as hasOnlyPersonalPoliciesUtil, isPaidGroupPolicy} from '@libs/PolicyUtils';
import {getOriginalMessage, isMoneyRequestAction} from '@libs/ReportActionsUtils';
import {
canDeleteMoneyRequestReport,
Expand All @@ -84,7 +84,7 @@ import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import ROUTES from '@src/ROUTES';
import type SCREENS from '@src/SCREENS';
import type {Report, SearchResults, Transaction} from '@src/types/onyx';
import type {Policy, Report, SearchResults, Transaction} from '@src/types/onyx';
import type {FileObject} from '@src/types/utils/Attachment';
import SearchPageNarrow from './SearchPageNarrow';
import SearchPageWide from './SearchPageWide';
Expand Down Expand Up @@ -226,6 +226,12 @@ function SearchPage({route}: SearchPageProps) {
[queryJSON, selectedTransactionsKeys, areAllMatchingItemsSelected, selectedTransactionReportIDs],
);

const policyIDsWithVBBA = useMemo(() => {
return Object.values(policies ?? {})
.filter((policy): policy is Policy => !!policy?.achAccount?.bankAccountID)

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.

🟡 Potentially Inconsistent VBBA Check Pattern

Concern: This check only verifies bankAccountID exists but doesn't verify the bank account's state. Looking at SearchUIUtils.ts:

// SearchUIUtils.ts line 585 - More complete check
const hasVBBA = !!policy.achAccount?.bankAccountID && policy.achAccount.state === CONST.BANK_ACCOUNT.STATE.OPEN;

Bug Impact: A policy with a bank account in PENDING or VERIFYING state would incorrectly be considered as having a VBBA, potentially allowing payment options that shouldn't be available.

Suggested change
.filter((policy): policy is Policy => !!policy?.achAccount?.bankAccountID)
.filter((policy): policy is Policy => !!policy?.achAccount?.bankAccountID && policy?.achAccount?.state === CONST.BANK_ACCOUNT.STATE.OPEN)

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.

@ikevin127 Is this a blocker for merging the PR?

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.

@tgolen Not a blocker since the old / removed logic didn't check for account state open either, but thought I should mention it as a potential due to existing logic having that check.

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.

OK, thanks!

.map((policy) => policy.id);
}, [policies]);

const onBulkPaySelected = useCallback(
(paymentMethod?: PaymentMethodType, additionalData?: Record<string, unknown>) => {
if (!hash) {
Expand Down Expand Up @@ -257,7 +263,7 @@ function SearchPage({route}: SearchPageProps) {
return;
}

const hasPolicyVBBA = hasVBBA(itemPolicyID);
const hasPolicyVBBA = itemPolicyID ? policyIDsWithVBBA.includes(itemPolicyID) : false;

if (isExpenseReport && lastPolicyPaymentMethod !== CONST.IOU.PAYMENT_TYPE.ELSEWHERE && !hasPolicyVBBA) {
Navigation.navigate(
Expand Down Expand Up @@ -327,7 +333,7 @@ function SearchPage({route}: SearchPageProps) {
clearSelectedTransactions();
});
},
[clearSelectedTransactions, hash, isOffline, lastPaymentMethods, selectedReports, selectedTransactions, policies, formatPhoneNumber],
[clearSelectedTransactions, hash, isOffline, lastPaymentMethods, selectedReports, selectedTransactions, policies, formatPhoneNumber, policyIDsWithVBBA],
);

// Check if all selected transactions are from the submitter
Expand Down
5 changes: 3 additions & 2 deletions src/pages/workspace/duplicate/utils.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type {LocaleContextProps} from '@components/LocaleContextProvider';
import {getCorrectedAutoReportingFrequency, getWorkflowApprovalsUnavailable, hasVBBA} from '@libs/PolicyUtils';
import {getCorrectedAutoReportingFrequency, getWorkflowApprovalsUnavailable} from '@libs/PolicyUtils';
import {getAutoReportingFrequencyDisplayNames} from '@pages/workspace/workflows/WorkspaceAutoReportingFrequencyPage';
import {isAuthenticationError} from '@userActions/connections';
import CONST from '@src/CONST';
Expand All @@ -8,7 +8,8 @@ import type {ConnectionName} from '@src/types/onyx/Policy';

function getWorkspaceRules(policy: Policy | undefined, translate: LocaleContextProps['translate']) {
const workflowApprovalsUnavailable = getWorkflowApprovalsUnavailable(policy);
const autoPayApprovedReportsUnavailable = !policy?.areWorkflowsEnabled || policy?.reimbursementChoice !== CONST.POLICY.REIMBURSEMENT_CHOICES.REIMBURSEMENT_YES || !hasVBBA(policy?.id);
const autoPayApprovedReportsUnavailable =
!policy?.areWorkflowsEnabled || policy?.reimbursementChoice !== CONST.POLICY.REIMBURSEMENT_CHOICES.REIMBURSEMENT_YES || !policy?.achAccount?.bankAccountID;
const total: string[] = [];
if (policy?.maxExpenseAmountNoReceipt !== CONST.DISABLED_MAX_EXPENSE_VALUE) {
total.push(translate('workspace.rules.individualExpenseRules.receiptRequiredAmount'));
Expand Down
5 changes: 3 additions & 2 deletions src/pages/workspace/rules/ExpenseReportRulesSection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import usePolicy from '@hooks/usePolicy';
import useThemeStyles from '@hooks/useThemeStyles';
import {convertToDisplayString} from '@libs/CurrencyUtils';
import Navigation from '@libs/Navigation/Navigation';
import {getWorkflowApprovalsUnavailable, hasVBBA, isControlPolicy} from '@libs/PolicyUtils';
import {getWorkflowApprovalsUnavailable, isControlPolicy} from '@libs/PolicyUtils';
import ToggleSettingOptionRow from '@pages/workspace/workflows/ToggleSettingsOptionRow';
import {enableAutoApprovalOptions, enablePolicyAutoReimbursementLimit, setPolicyPreventSelfApproval} from '@userActions/Policy/Policy';
import CONST from '@src/CONST';
Expand All @@ -24,7 +24,8 @@ function ExpenseReportRulesSection({policyID}: ExpenseReportRulesSectionProps) {
const policy = usePolicy(policyID);
const {environmentURL} = useEnvironment();
const workflowApprovalsUnavailable = getWorkflowApprovalsUnavailable(policy);
const autoPayApprovedReportsUnavailable = !policy?.areWorkflowsEnabled || policy?.reimbursementChoice !== CONST.POLICY.REIMBURSEMENT_CHOICES.REIMBURSEMENT_YES || !hasVBBA(policyID);
const autoPayApprovedReportsUnavailable =
!policy?.areWorkflowsEnabled || policy?.reimbursementChoice !== CONST.POLICY.REIMBURSEMENT_CHOICES.REIMBURSEMENT_YES || !policy?.achAccount?.bankAccountID;

const renderFallbackSubtitle = ({featureName, variant = 'unlock'}: {featureName: string; variant?: 'unlock' | 'enable'}) => {
const moreFeaturesLink = `${environmentURL}/${ROUTES.WORKSPACE_MORE_FEATURES.getRoute(policyID)}`;
Expand Down
71 changes: 71 additions & 0 deletions tests/unit/PolicyUtilsTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
getPolicyNameByID,
getRateDisplayValue,
getSubmitToAccountID,
getTagApproverRule,
getTagList,
getTagListByOrderWeight,
getUberConnectionErrorDirectlyFromPolicy,
Expand Down Expand Up @@ -1566,4 +1567,74 @@ describe('PolicyUtils', () => {
expect(result).toBe(true);
});
});

describe('getTagApproverRule', () => {
it('should return undefined when no approval rules are present', () => {
const policy: Policy = {
...createRandomPolicy(1, CONST.POLICY.TYPE.TEAM),
rules: {
approvalRules: [],
},
};
const result = getTagApproverRule(policy, '');
expect(result).toBeUndefined();
});
});

it('should return undefined when no tag approver rule is present', () => {
const policy: Policy = {
...createRandomPolicy(1, CONST.POLICY.TYPE.TEAM),
rules: {
approvalRules: [
{
id: 'rule-1',
applyWhen: [
{
field: CONST.POLICY.FIELDS.TAG,
condition: CONST.POLICY.RULE_CONDITIONS.MATCHES,
value: 'Fake tag',
},
],
approver: 'lol@hhh.com',
},
],
},
};
const result = getTagApproverRule(policy, 'NonExistentTag');
expect(result).toBeUndefined();
});

it('should return the tag approver rule when present', () => {
const tagName = 'ImportantTag';
const policy: Policy = {
...createRandomPolicy(1, CONST.POLICY.TYPE.TEAM),
rules: {
approvalRules: [
{
id: 'rule-1',
applyWhen: [
{
field: CONST.POLICY.FIELDS.TAG,
condition: CONST.POLICY.RULE_CONDITIONS.MATCHES,
value: tagName,
},
],
approver: 'approver@example.com',
},
],
},
};
const result = getTagApproverRule(policy, tagName);
expect(result).toEqual({
id: 'rule-1',
applyWhen: [
{
field: CONST.POLICY.FIELDS.TAG,
condition: CONST.POLICY.RULE_CONDITIONS.MATCHES,
value: tagName,
},
],
approver: 'approver@example.com',
});
});
});
Loading