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
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import {useCurrencyListActions} from '@hooks/useCurrencyList';
import useCurrentUserPersonalDetails from '@hooks/useCurrentUserPersonalDetails';
import useOnyx from '@hooks/useOnyx';
import useRulesPrefetch from '@hooks/useRulesPrefetch';

import {getMemberDefaultCategory} from '@libs/CategoryUtils';
import {convertToBackendAmount} from '@libs/CurrencyUtils';
import DistanceRequestUtils from '@libs/DistanceRequestUtils';
import {arePolicyRulesEnabled, getDistanceRateCustomUnit} from '@libs/PolicyUtils';
Expand Down Expand Up @@ -65,6 +67,7 @@ function useTaxAmount({
previousTransactionCurrency,
}: UseTaxAmountParams) {
const {getCurrencyDecimals} = useCurrencyListActions();
const {accountID: currentUserAccountID} = useCurrentUserPersonalDetails();
const [rules] = useOnyx(ONYXKEYS.COLLECTION.RULE);
const [policyCategories] = useOnyx(`${ONYXKEYS.COLLECTION.POLICY_CATEGORIES}${policy?.id}`);
// A category's tax default lives in the `rules_` collection, which only `GetRules` populates. Onyx hydrates it
Expand All @@ -80,7 +83,7 @@ function useTaxAmount({
// The rate is read into its own value so React Compiler can cache the lookup. The hooks below split the block
// it used to be cached in, which left it running on every render.
const distanceRateCustomUnit = isDistanceRequest ? getDistanceRateCustomUnit(policy) : undefined;
const category = transaction?.category || (distanceRateCustomUnit?.defaultCategory ?? '');
const category = transaction?.category || getMemberDefaultCategory(distanceRateCustomUnit?.defaultCategory, policyCategories, currentUserAccountID);
// The category whose rate the expense is currently carrying, which only moves on once a rate has been resolved
// for it. While the rules are loading nothing is resolved, so a category picked in that window stays pending
// here until they land. Tracking the last rendered category instead would let the change pass unseen, and the
Expand Down
16 changes: 15 additions & 1 deletion src/libs/CategoryUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import ONYXKEYS from '@src/ONYXKEYS';
import type {Policy, PolicyCategories, PolicyCategory} from '@src/types/onyx';
import type {ApprovalRule, MccGroup} from '@src/types/onyx/Policy';

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

import {Str} from 'expensify-common';

Expand Down Expand Up @@ -149,6 +149,19 @@ function isCategoryVisibleToMember(policyCategory: PolicyCategory | undefined, a
return !!policyCategory && (!policyCategory.visibleTo || !!policyCategory.visibleTo[accountID]);
}

/**
* A workspace default category, such as the distance or per diem one, only applies to members who can use it, so this
* returns an empty category for a member it's hidden from. The default is kept while the category isn't loaded, since
* its visibility isn't known yet.
*/
function getMemberDefaultCategory(defaultCategory: string | undefined, policyCategories: OnyxEntry<PolicyCategories>, accountID: number): string {
if (!defaultCategory) {
return '';
}
const policyCategory = policyCategories?.[defaultCategory];
return !policyCategory || isCategoryVisibleToMember(policyCategory, accountID) ? defaultCategory : '';
}

function isCategoryDescriptionRequired(policyCategories: PolicyCategories | undefined, category: string | undefined, areRulesEnabled: boolean | undefined): boolean {
if (!policyCategories || !category || !areRulesEnabled) {
return false;
Expand Down Expand Up @@ -375,4 +388,5 @@ export {
getDisabledCategoryKey,
canCreateCategoryFromSearch,
isCategoryVisibleToMember,
getMemberDefaultCategory,
};
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
import useCurrentUserPersonalDetails from '@hooks/useCurrentUserPersonalDetails';

import {getMemberDefaultCategory} from '@libs/CategoryUtils';

import {setMoneyRequestCategory} from '@userActions/IOU/MoneyRequest';

import CONST from '@src/CONST';
Expand All @@ -21,7 +25,7 @@ type CategoryDefaultsSetterProps = {
/**
* Side-effect-only component that handles two category-related effects:
* 1. Resets cleared categories back to their last saved value
* 2. Sets the default distance category for distance requests
* 2. Sets the default distance category for distance requests, unless the member can't use it
*/
function CategoryDefaultsSetter({
transactions,
Expand All @@ -33,6 +37,8 @@ function CategoryDefaultsSetter({
requestType,
isMovingTransactionFromTrackExpense,
}: CategoryDefaultsSetterProps) {
const {accountID} = useCurrentUserPersonalDetails();

useEffect(() => {
for (const item of transactions) {
if (!item.category) {
Expand All @@ -53,7 +59,7 @@ function CategoryDefaultsSetter({
}, [policy?.id, policyCategories, transactions.length]);

const policyDistance = Object.values(policy?.customUnits ?? {}).find((customUnit) => customUnit.name === CONST.CUSTOM_UNITS.NAME_DISTANCE);
const defaultCategory = policyDistance?.defaultCategory ?? '';
const defaultCategory = getMemberDefaultCategory(policyDistance?.defaultCategory, policyCategories, accountID);

useEffect(() => {
for (const item of transactions) {
Expand Down
103 changes: 103 additions & 0 deletions tests/ui/CategoryDefaultsSetterTest.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import {render} from '@testing-library/react-native';

import CategoryDefaultsSetter from '@pages/iou/request/step/confirmation/CategoryDefaultsSetter';

import {setMoneyRequestCategory} from '@userActions/IOU/MoneyRequest';

import CONST from '@src/CONST';
import type {Policy, PolicyCategories, Transaction} from '@src/types/onyx';

import React from 'react';

import createMock from '../utils/createMock';

const CURRENT_USER_ACCOUNT_ID = 1;
const OTHER_ACCOUNT_ID = 2;

jest.mock('@userActions/IOU/MoneyRequest', () => ({
setMoneyRequestCategory: jest.fn(),
}));

jest.mock('@hooks/useCurrentUserPersonalDetails', () => jest.fn(() => ({accountID: CURRENT_USER_ACCOUNT_ID})));

const setMoneyRequestCategoryMock = jest.mocked(setMoneyRequestCategory);

const policy = createMock<Policy>({
id: 'policy1',
customUnits: {
distance: {customUnitID: 'distance', name: CONST.CUSTOM_UNITS.NAME_DISTANCE, defaultCategory: 'Car', rates: {}},
perDiem: {customUnitID: 'perDiem', name: CONST.CUSTOM_UNITS.NAME_PER_DIEM_INTERNATIONAL, defaultCategory: 'Car', rates: {}},
},
});

function renderSetter({
category = '',
visibleTo,
isDistanceRequest = true,
requestType = CONST.IOU.REQUEST_TYPE.DISTANCE_MAP,
}: {
category?: string;
visibleTo: Record<number, boolean> | null;
isDistanceRequest?: boolean;
requestType?: string;
}) {
const transaction = createMock<Transaction>({transactionID: 'transaction1', category});
const policyCategories: PolicyCategories = {
Car: {name: 'Car', enabled: true, visibleTo},
Benefits: {name: 'Benefits', enabled: true, visibleTo: null},
};
return render(
<CategoryDefaultsSetter
transactions={[transaction]}
transactionIDs={[transaction.transactionID]}
existingTransaction={undefined}
policyCategories={policyCategories}
policy={policy}
isDistanceRequest={isDistanceRequest}
requestType={requestType}
isMovingTransactionFromTrackExpense={false}
/>,
);
}

describe('CategoryDefaultsSetter', () => {
beforeEach(() => {
jest.clearAllMocks();
});

it('applies the distance default category when the member can use it', () => {
// Given a distance expense on a workspace whose distance default, Car, is open to everyone
// When the confirmation page sets the defaults
renderSetter({visibleTo: null});

// Then the expense is coded to Car, as before category visibility
expect(setMoneyRequestCategoryMock).toHaveBeenCalledWith('transaction1', 'Car', policy, false);
});

it("doesn't apply the distance default category when it's hidden from the member", () => {
// Given a distance expense whose distance default, Car, is limited to another member
// When the confirmation page sets the defaults
renderSetter({visibleTo: {[OTHER_ACCOUNT_ID]: true}});

// Then the expense isn't coded to Car, since the member couldn't pick it
expect(setMoneyRequestCategoryMock).not.toHaveBeenCalledWith('transaction1', 'Car', expect.anything(), expect.anything());
});

it("keeps a category already on the expense even when it's hidden from the member", () => {
// Given a distance expense already coded to Car, which is limited to another member
// When the confirmation page sets the defaults
renderSetter({category: 'Car', visibleTo: {[OTHER_ACCOUNT_ID]: true}});

// Then Car stays, so a category set before the restriction isn't silently removed, and the "Category not allowed" violation flags it instead
expect(setMoneyRequestCategoryMock).not.toHaveBeenCalled();
});

it('keeps a default category the member can use', () => {
// Given a distance expense already coded to Car, which the member is on the list for
// When the confirmation page sets the defaults
renderSetter({category: 'Car', visibleTo: {[CURRENT_USER_ACCOUNT_ID]: true}});

// Then Car stays, since the member can use it
expect(setMoneyRequestCategoryMock).not.toHaveBeenCalled();
});
});
40 changes: 40 additions & 0 deletions tests/unit/CategoryUtilsTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
getCategoryNameError,
getDecodedFullCategoryName,
getDecodedLeafCategoryName,
getMemberDefaultCategory,
getMemberVisibleCategoryNames,
getMembersWithoutVisibleCategories,
getVisibleCategories,
Expand Down Expand Up @@ -730,3 +731,42 @@ describe('getVisibleCategories', () => {
expect(Object.keys(visibleCategories)).toEqual(['Travel', 'Meals', 'Software', 'Office']);
});
});

describe('getMemberDefaultCategory', () => {
const policyCategories: PolicyCategories = {
Car: {name: 'Car', enabled: true, visibleTo: buildVisibleTo(2)},
Travel: {name: 'Travel', enabled: true, visibleTo: null},
};

it('drops a default category hidden from the member', () => {
// Given a distance default of Car, which only member 2 can use
// When the default is resolved for member 1
const defaultCategory = getMemberDefaultCategory('Car', policyCategories, 1);

// Then no category is applied, so the expense isn't coded to a category the member can't pick
expect(defaultCategory).toBe('');
});

it('keeps a default category the member can use', () => {
// Given defaults that member 2 can use, one listing them and one open to everyone
// When the defaults are resolved for member 2
// Then both are applied as before
expect(getMemberDefaultCategory('Car', policyCategories, 2)).toBe('Car');
expect(getMemberDefaultCategory('Travel', policyCategories, 1)).toBe('Travel');
});

it("keeps the default while the category isn't loaded, since its visibility isn't known yet", () => {
// Given a default category that isn't in the loaded categories
// When the default is resolved
// Then it's kept, as it was before visibility existed
expect(getMemberDefaultCategory('Fuel', policyCategories, 1)).toBe('Fuel');
expect(getMemberDefaultCategory('Fuel', undefined, 1)).toBe('Fuel');
});

it('returns an empty category when the workspace has no default', () => {
// Given no default category
// When it's resolved
// Then nothing is applied
expect(getMemberDefaultCategory(undefined, policyCategories, 1)).toBe('');
});
});
Loading