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
3 changes: 1 addition & 2 deletions src/components/MoneyRequestConfirmationList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -275,7 +275,6 @@ function MoneyRequestConfirmationList({
selector: mileageRateSelector,
canBeMissing: true,
});
const {policyForMovingExpenses} = usePolicyForMovingExpenses();
const isMovingTransactionFromTrackExpense = isMovingTransactionFromTrackExpenseUtil(action);
const [defaultMileageRateReal] = useOnyx(`${ONYXKEYS.COLLECTION.POLICY}${policyID}`, {
selector: mileageRateSelector,
Expand Down Expand Up @@ -345,7 +344,7 @@ function MoneyRequestConfirmationList({
const prevCurrency = usePrevious(currency);
const prevSubRates = usePrevious(subRates);

const {shouldSelectPolicy} = usePolicyForMovingExpenses();
const {shouldSelectPolicy, policyForMovingExpenses} = usePolicyForMovingExpenses();

// A flag for showing the categories field
const shouldShowCategories = isTrackExpense
Expand Down
7 changes: 6 additions & 1 deletion src/hooks/usePolicyForMovingExpenses.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ function isPolicyValidForMovingExpenses(policy: OnyxEntry<Policy>, login: string
);
}

function usePolicyForMovingExpenses(isPerDiemRequest?: boolean, expensePolicyID?: string) {
function usePolicyForMovingExpenses(isPerDiemRequest?: boolean, expensePolicyID?: string, isTrackDistanceRequest?: boolean, isMovingFromTrackExpense?: boolean) {
const [allPolicies] = useOnyx(ONYXKEYS.COLLECTION.POLICY, {canBeMissing: true});
const [activePolicyID] = useOnyx(ONYXKEYS.NVP_ACTIVE_POLICY_ID, {canBeMissing: true});
const [activePolicy] = useOnyx(`${ONYXKEYS.COLLECTION.POLICY}${activePolicyID}`, {
Expand All @@ -41,6 +41,11 @@ function usePolicyForMovingExpenses(isPerDiemRequest?: boolean, expensePolicyID?
const session = useSession();
const login = session?.email ?? '';

// Creating a track distance request always uses the P2P custom unit, so we don't use the active policy
if (isTrackDistanceRequest && !isMovingFromTrackExpense) {
return {policyForMovingExpensesID: undefined, policyForMovingExpenses: undefined, shouldSelectPolicy: false};
}
Comment thread
mountiny marked this conversation as resolved.
Resolved

// Early exit optimization: only need to check if we have 0, 1, or >1 policies
let singleUserPolicy;
let isMemberOfMoreThanOnePolicy = false;
Expand Down
20 changes: 16 additions & 4 deletions src/hooks/usePolicyForTransaction.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import {useMemo} from 'react';
import type {OnyxEntry} from 'react-native-onyx';
import {isMovingTransactionFromTrackExpense as isMovingTransactionFromTrackExpenseIOUUtils} from '@libs/IOUUtils';
import {getPolicyByCustomUnitID} from '@libs/PolicyUtils';
import {isExpenseUnreported} from '@libs/TransactionUtils';
import {isDistanceRequest as isDistanceRequestTransactionUtils, isExpenseUnreported} from '@libs/TransactionUtils';
import CONST from '@src/CONST';
import type {IOUAction} from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import type {Policy, Transaction} from '@src/types/onyx';
import useOnyx from './useOnyx';
Expand All @@ -16,13 +18,19 @@ type UsePolicyForTransactionParams = {
reportPolicyID: string | undefined;

/** The current action being performed */
action: string;
action: IOUAction;

/** The type of IOU (split, track, submit, etc.) */
iouType: string;

/** Indicates if the request is a per diem request */
isPerDiemRequest?: boolean;

/** Indicates if the request is a track distance request */
isTrackDistanceRequest?: boolean;

/** Indicates if the transaction is a moving transaction from a track expense */
isMovingTransactionFromTrackExpense?: boolean;
};

type UsePolicyForTransactionResult = {
Expand All @@ -31,7 +39,12 @@ type UsePolicyForTransactionResult = {
};

function usePolicyForTransaction({transaction, reportPolicyID, action, iouType, isPerDiemRequest}: UsePolicyForTransactionParams): UsePolicyForTransactionResult {
const {policyForMovingExpenses} = usePolicyForMovingExpenses();
const isDistanceRequest = isDistanceRequestTransactionUtils(transaction);
const isCreatingTrackExpense = action === CONST.IOU.ACTION.CREATE && iouType === CONST.IOU.TYPE.TRACK;
const isTrackDistanceRequest = isCreatingTrackExpense && isDistanceRequest;
const isMovingTransactionFromTrackExpense = isMovingTransactionFromTrackExpenseIOUUtils(action);

const {policyForMovingExpenses} = usePolicyForMovingExpenses(undefined, undefined, isTrackDistanceRequest, isMovingTransactionFromTrackExpense);

const [allPolicies] = useOnyx(ONYXKEYS.COLLECTION.POLICY, {canBeMissing: true});

Expand All @@ -42,7 +55,6 @@ function usePolicyForTransaction({transaction, reportPolicyID, action, iouType,
const [reportPolicy] = useOnyx(`${ONYXKEYS.COLLECTION.POLICY}${reportPolicyID}`, {canBeMissing: true});

const isUnreportedExpense = isExpenseUnreported(transaction);
const isCreatingTrackExpense = action === CONST.IOU.ACTION.CREATE && iouType === CONST.IOU.TYPE.TRACK;

const policyForSelfDMExpense = isPerDiemRequest ? customUnitPolicy : policyForMovingExpenses;
const policy = isUnreportedExpense || isCreatingTrackExpense ? policyForSelfDMExpense : reportPolicy;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,7 @@ function IOURequestStepConfirmation({
const [selectedParticipantList, setSelectedParticipantList] = useState<Participant[]>([]);

const [receiptFiles, setReceiptFiles] = useState<Record<string, Receipt>>({});
const isMovingTransactionFromTrackExpense = isMovingTransactionFromTrackExpenseIOUUtils(action);
const isDistanceRequest = isDistanceRequestTransactionUtils(transaction);
const isManualDistanceRequest = isManualDistanceRequestTransactionUtils(transaction);
const isOdometerDistanceRequest = isOdometerDistanceRequestTransactionUtils(transaction);
Expand All @@ -272,7 +273,6 @@ function IOURequestStepConfirmation({
const transactionTaxAmount = transaction?.taxAmount ?? 0;
const isSharingTrackExpense = action === CONST.IOU.ACTION.SHARE;
const isCategorizingTrackExpense = action === CONST.IOU.ACTION.CATEGORIZE;
const isMovingTransactionFromTrackExpense = isMovingTransactionFromTrackExpenseIOUUtils(action);
const isTestTransaction = transaction?.participants?.some((participant) => isSelectedManagerMcTest(participant.login));

const gpsRequired = transaction?.amount === 0 && iouType !== CONST.IOU.TYPE.SPLIT && Object.values(receiptFiles).length && !isTestTransaction;
Expand Down
212 changes: 212 additions & 0 deletions tests/unit/usePolicyForMovingExpensesTest.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,212 @@
import {renderHook} from '@testing-library/react-native';
import Onyx from 'react-native-onyx';
import OnyxListItemProvider from '@components/OnyxListItemProvider';
import usePolicyForMovingExpenses from '@hooks/usePolicyForMovingExpenses';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import type {Policy} from '@src/types/onyx';
import waitForBatchedUpdates from '../utils/waitForBatchedUpdates';

const USER_EMAIL = 'user@example.com';

function createValidPolicyForMovingExpenses(id: string, overrides: Partial<Policy> = {}): Policy {
return {
id,
name: `Workspace ${id}`,
type: CONST.POLICY.TYPE.TEAM,
role: CONST.POLICY.ROLE.ADMIN,
pendingAction: undefined,
employeeList: {},
isPolicyExpenseChatEnabled: true,
customUnits: {},
outputCurrency: 'USD',
...overrides,
} as Policy;
}

describe('usePolicyForMovingExpenses', () => {
beforeAll(() => {
Onyx.init({
keys: ONYXKEYS,
});
return waitForBatchedUpdates();
});

beforeEach(async () => {
await Onyx.clear();
return waitForBatchedUpdates();
});

it('should return default values when no policies and no session', () => {
const {result} = renderHook(() => usePolicyForMovingExpenses(), {
wrapper: OnyxListItemProvider,
});

expect(result.current.policyForMovingExpensesID).toBeUndefined();
expect(result.current.policyForMovingExpenses).toBeUndefined();
expect(result.current.shouldSelectPolicy).toBe(false);
});

it('should return undefined policy when isTrackDistanceRequest is true and isMovingFromTrackExpense is false', async () => {
await Onyx.set(ONYXKEYS.SESSION, {email: USER_EMAIL});
const policy = createValidPolicyForMovingExpenses('1');
await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}${policy.id}`, policy);
await waitForBatchedUpdates();

const {result} = renderHook(() => usePolicyForMovingExpenses(false, undefined, true, false), {
wrapper: OnyxListItemProvider,
});

expect(result.current.policyForMovingExpensesID).toBeUndefined();
expect(result.current.policyForMovingExpenses).toBeUndefined();
expect(result.current.shouldSelectPolicy).toBe(false);
});

it('should return single valid policy when user is member of one policy', async () => {
await Onyx.set(ONYXKEYS.SESSION, {email: USER_EMAIL});
const policy = createValidPolicyForMovingExpenses('policy1');
await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}${policy.id}`, policy);
await waitForBatchedUpdates();

const {result} = renderHook(() => usePolicyForMovingExpenses(), {
wrapper: OnyxListItemProvider,
});

expect(result.current.policyForMovingExpensesID).toBe('policy1');
expect(result.current.policyForMovingExpenses?.id).toBe('policy1');
expect(result.current.shouldSelectPolicy).toBe(false);
});

it('should return shouldSelectPolicy true when user is member of more than one valid policy', async () => {
await Onyx.set(ONYXKEYS.SESSION, {email: USER_EMAIL});
const policy1 = createValidPolicyForMovingExpenses('policy1');
const policy2 = createValidPolicyForMovingExpenses('policy2');
await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}${policy1.id}`, policy1);
await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}${policy2.id}`, policy2);
await waitForBatchedUpdates();

const {result} = renderHook(() => usePolicyForMovingExpenses(), {
wrapper: OnyxListItemProvider,
});

expect(result.current.policyForMovingExpensesID).toBeUndefined();
expect(result.current.policyForMovingExpenses).toBeUndefined();
expect(result.current.shouldSelectPolicy).toBe(true);
});

it('should prefer expensePolicyID when provided and valid', async () => {
await Onyx.set(ONYXKEYS.SESSION, {email: USER_EMAIL});
await Onyx.set(ONYXKEYS.NVP_ACTIVE_POLICY_ID, 'activePolicy');
const activePolicy = createValidPolicyForMovingExpenses('activePolicy');
const expensePolicy = createValidPolicyForMovingExpenses('expensePolicy');
await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}${activePolicy.id}`, activePolicy);
await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}${expensePolicy.id}`, expensePolicy);
await waitForBatchedUpdates();

const {result} = renderHook(() => usePolicyForMovingExpenses(false, 'expensePolicy'), {
wrapper: OnyxListItemProvider,
});

expect(result.current.policyForMovingExpensesID).toBe('expensePolicy');
expect(result.current.policyForMovingExpenses?.id).toBe('expensePolicy');
expect(result.current.shouldSelectPolicy).toBe(false);
});

it('should return active policy when expensePolicyID not provided and active policy is valid', async () => {
await Onyx.set(ONYXKEYS.SESSION, {email: USER_EMAIL});
await Onyx.set(ONYXKEYS.NVP_ACTIVE_POLICY_ID, 'activePolicy');
const activePolicy = createValidPolicyForMovingExpenses('activePolicy');
await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}${activePolicy.id}`, activePolicy);
await waitForBatchedUpdates();

const {result} = renderHook(() => usePolicyForMovingExpenses(), {
wrapper: OnyxListItemProvider,
});

expect(result.current.policyForMovingExpensesID).toBe('activePolicy');
expect(result.current.policyForMovingExpenses?.id).toBe('activePolicy');
expect(result.current.shouldSelectPolicy).toBe(false);
});

it('should not return policy with pendingAction DELETE', async () => {
await Onyx.set(ONYXKEYS.SESSION, {email: USER_EMAIL});
const policy = createValidPolicyForMovingExpenses('policy1', {
pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE,
});
await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}${policy.id}`, policy);
await waitForBatchedUpdates();

const {result} = renderHook(() => usePolicyForMovingExpenses(), {
wrapper: OnyxListItemProvider,
});

expect(result.current.policyForMovingExpensesID).toBeUndefined();
expect(result.current.policyForMovingExpenses).toBeUndefined();
expect(result.current.shouldSelectPolicy).toBe(false);
});

it('should not return personal policy as valid for moving expenses', async () => {
await Onyx.set(ONYXKEYS.SESSION, {email: USER_EMAIL});
const policy = createValidPolicyForMovingExpenses('policy1', {
type: CONST.POLICY.TYPE.PERSONAL,
});
await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}${policy.id}`, policy);
await waitForBatchedUpdates();

const {result} = renderHook(() => usePolicyForMovingExpenses(), {
wrapper: OnyxListItemProvider,
});

expect(result.current.policyForMovingExpensesID).toBeUndefined();
expect(result.current.policyForMovingExpenses).toBeUndefined();
expect(result.current.shouldSelectPolicy).toBe(false);
});

it('should return single policy when only one of two policies is valid', async () => {
await Onyx.set(ONYXKEYS.SESSION, {email: USER_EMAIL});
const validPolicy = createValidPolicyForMovingExpenses('valid');
const invalidPolicy = createValidPolicyForMovingExpenses('invalid', {
type: CONST.POLICY.TYPE.PERSONAL,
});
await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}${validPolicy.id}`, validPolicy);
await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}${invalidPolicy.id}`, invalidPolicy);
await waitForBatchedUpdates();

const {result} = renderHook(() => usePolicyForMovingExpenses(), {
wrapper: OnyxListItemProvider,
});

expect(result.current.policyForMovingExpensesID).toBe('valid');
expect(result.current.shouldSelectPolicy).toBe(false);
});

it('should return undefined when expensePolicyID is provided but policy is invalid', async () => {
await Onyx.set(ONYXKEYS.SESSION, {email: USER_EMAIL});
const policy = createValidPolicyForMovingExpenses('policy1', {
type: CONST.POLICY.TYPE.PERSONAL,
});
await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}${policy.id}`, policy);
await waitForBatchedUpdates();

const {result} = renderHook(() => usePolicyForMovingExpenses(false, 'policy1'), {
wrapper: OnyxListItemProvider,
});

expect(result.current.policyForMovingExpensesID).toBeUndefined();
expect(result.current.policyForMovingExpenses).toBeUndefined();
});

it('should return policy when isTrackDistanceRequest is true but isMovingFromTrackExpense is true', async () => {
await Onyx.set(ONYXKEYS.SESSION, {email: USER_EMAIL});
const policy = createValidPolicyForMovingExpenses('policy1');
await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}${policy.id}`, policy);
await waitForBatchedUpdates();

const {result} = renderHook(() => usePolicyForMovingExpenses(false, undefined, true, true), {
wrapper: OnyxListItemProvider,
});

expect(result.current.policyForMovingExpensesID).toBe('policy1');
expect(result.current.shouldSelectPolicy).toBe(false);
});
});
Loading