Skip to content

Commit

Permalink
Merge pull request #51159 from shubham1206agra/fix-distance-rate-flow
Browse files Browse the repository at this point in the history
Fix distance rate flow (when per diem is enabled as well)
  • Loading branch information
Gonals authored Oct 22, 2024
2 parents f3d92ce + 6f38eed commit 24de4c7
Show file tree
Hide file tree
Showing 17 changed files with 103 additions and 97 deletions.
4 changes: 2 additions & 2 deletions src/components/MoneyRequestConfirmationList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import * as MoneyRequestUtils from '@libs/MoneyRequestUtils';
import Navigation from '@libs/Navigation/Navigation';
import * as OptionsListUtils from '@libs/OptionsListUtils';
import * as PolicyUtils from '@libs/PolicyUtils';
import {getCustomUnitRate, isTaxTrackingEnabled} from '@libs/PolicyUtils';
import {getDistanceRateCustomUnitRate, isTaxTrackingEnabled} from '@libs/PolicyUtils';
import * as ReportUtils from '@libs/ReportUtils';
import playSound, {SOUNDS} from '@libs/Sound';
import * as TransactionUtils from '@libs/TransactionUtils';
Expand Down Expand Up @@ -358,7 +358,7 @@ function MoneyRequestConfirmationList({
let taxableAmount: number;
let taxCode: string;
if (isDistanceRequest) {
const customUnitRate = getCustomUnitRate(policy, customUnitRateID);
const customUnitRate = getDistanceRateCustomUnitRate(policy, customUnitRateID);
taxCode = customUnitRate?.attributes?.taxRateExternalID ?? '';
taxableAmount = DistanceRequestUtils.getTaxableAmount(policy, customUnitRateID, distance);
} else {
Expand Down
8 changes: 4 additions & 4 deletions src/libs/DistanceRequestUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ function getMileageRates(policy: OnyxInputOrEntry<Policy>, includeDisabledRates
return mileageRates;
}

const distanceUnit = PolicyUtils.getCustomUnit(policy);
const distanceUnit = PolicyUtils.getDistanceRateCustomUnit(policy);
if (!distanceUnit?.rates) {
return mileageRates;
}
Expand Down Expand Up @@ -78,7 +78,7 @@ function getDefaultMileageRate(policy: OnyxInputOrEntry<Policy>): MileageRate |
return undefined;
}

const distanceUnit = PolicyUtils.getCustomUnit(policy);
const distanceUnit = PolicyUtils.getDistanceRateCustomUnit(policy);
if (!distanceUnit?.rates) {
return;
}
Expand Down Expand Up @@ -302,8 +302,8 @@ function getCustomUnitRateID(reportID: string, shouldUseDefault?: boolean) {
* Get taxable amount from a specific distance rate, taking into consideration the tax claimable amount configured for the distance rate
*/
function getTaxableAmount(policy: OnyxEntry<Policy>, customUnitRateID: string, distance: number) {
const distanceUnit = PolicyUtils.getCustomUnit(policy);
const customUnitRate = PolicyUtils.getCustomUnitRate(policy, customUnitRateID);
const distanceUnit = PolicyUtils.getDistanceRateCustomUnit(policy);
const customUnitRate = PolicyUtils.getDistanceRateCustomUnitRate(policy, customUnitRateID);
if (!distanceUnit || !distanceUnit?.customUnitID || !customUnitRate) {
return 0;
}
Expand Down
4 changes: 2 additions & 2 deletions src/libs/PolicyDistanceRatesUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,10 @@ function validateRateValue(values: FormOnyxValues<RateValueForm>, currency: stri
return errors;
}

function validateTaxClaimableValue(values: FormOnyxValues<TaxReclaimableForm>, rate: Rate): FormInputErrors<TaxReclaimableForm> {
function validateTaxClaimableValue(values: FormOnyxValues<TaxReclaimableForm>, rate: Rate | undefined): FormInputErrors<TaxReclaimableForm> {
const errors: FormInputErrors<TaxReclaimableForm> = {};

if (rate.rate && Number(values.taxClaimableValue) > rate.rate / 100) {
if (rate?.rate && Number(values.taxClaimableValue) > rate.rate / 100) {
errors.taxClaimableValue = Localize.translateLocal('workspace.taxes.error.updateTaxClaimableFailureMessage');
}
return errors;
Expand Down
12 changes: 6 additions & 6 deletions src/libs/PolicyUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,15 +132,15 @@ function getNumericValue(value: number | string, toLocaleDigit: (arg: string) =>
/**
* Retrieves the distance custom unit object for the given policy
*/
function getCustomUnit(policy: OnyxEntry<Policy>): CustomUnit | undefined {
function getDistanceRateCustomUnit(policy: OnyxEntry<Policy>): CustomUnit | undefined {
return Object.values(policy?.customUnits ?? {}).find((unit) => unit.name === CONST.CUSTOM_UNITS.NAME_DISTANCE);
}

/**
* Retrieves custom unit rate object from the given customUnitRateID
*/
function getCustomUnitRate(policy: OnyxEntry<Policy>, customUnitRateID: string): Rate | undefined {
const distanceUnit = getCustomUnit(policy);
function getDistanceRateCustomUnitRate(policy: OnyxEntry<Policy>, customUnitRateID: string): Rate | undefined {
const distanceUnit = getDistanceRateCustomUnit(policy);
return distanceUnit?.rates[customUnitRateID];
}

Expand Down Expand Up @@ -382,7 +382,7 @@ function isControlPolicy(policy: OnyxEntry<Policy>): boolean {
}

function isTaxTrackingEnabled(isPolicyExpenseChat: boolean, policy: OnyxEntry<Policy>, isDistanceRequest: boolean): boolean {
const distanceUnit = getCustomUnit(policy);
const distanceUnit = getDistanceRateCustomUnit(policy);
const customUnitID = distanceUnit?.customUnitID ?? 0;
const isPolicyTaxTrackingEnabled = isPolicyExpenseChat && policy?.tax?.trackingEnabled;
const isTaxEnabledForDistance = isPolicyTaxTrackingEnabled && policy?.customUnits?.[customUnitID]?.attributes?.taxEnabled;
Expand Down Expand Up @@ -1148,8 +1148,8 @@ export {
getSageIntacctNonReimbursableActiveDefaultVendor,
getSageIntacctCreditCards,
getSageIntacctBankAccounts,
getCustomUnit,
getCustomUnitRate,
getDistanceRateCustomUnit,
getDistanceRateCustomUnitRate,
sortWorkspacesBySelected,
removePendingFieldsFromCustomUnit,
navigateWhenEnableFeature,
Expand Down
4 changes: 2 additions & 2 deletions src/libs/TransactionUtils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import {toLocaleDigit} from '@libs/LocaleDigitUtils';
import * as Localize from '@libs/Localize';
import * as NumberUtils from '@libs/NumberUtils';
import Permissions from '@libs/Permissions';
import {getCleanedTagName, getCustomUnitRate} from '@libs/PolicyUtils';
import {getCleanedTagName, getDistanceRateCustomUnitRate} from '@libs/PolicyUtils';
import * as PolicyUtils from '@libs/PolicyUtils';
// eslint-disable-next-line import/no-cycle
import * as ReportActionsUtils from '@libs/ReportActionsUtils';
Expand Down Expand Up @@ -903,7 +903,7 @@ function getRateID(transaction: OnyxInputOrEntry<Transaction>): string | undefin
function getDefaultTaxCode(policy: OnyxEntry<Policy>, transaction: OnyxEntry<Transaction>, currency?: string | undefined): string | undefined {
if (isDistanceRequest(transaction)) {
const customUnitRateID = getRateID(transaction) ?? '';
const customUnitRate = getCustomUnitRate(policy, customUnitRateID);
const customUnitRate = getDistanceRateCustomUnitRate(policy, customUnitRateID);
return customUnitRate?.attributes?.taxRateExternalID ?? '';
}
const defaultExternalID = policy?.taxRates?.defaultExternalID;
Expand Down
4 changes: 2 additions & 2 deletions src/libs/Violations/ViolationsUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import reject from 'lodash/reject';
import Onyx from 'react-native-onyx';
import type {OnyxUpdate} from 'react-native-onyx';
import type {LocaleContextProps} from '@components/LocaleContextProvider';
import {getCustomUnitRate, getSortedTagKeys} from '@libs/PolicyUtils';
import {getDistanceRateCustomUnitRate, getSortedTagKeys} from '@libs/PolicyUtils';
import * as TransactionUtils from '@libs/TransactionUtils';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
Expand Down Expand Up @@ -218,7 +218,7 @@ const ViolationsUtils = {
: getTagViolationsForMultiLevelTags(updatedTransaction, newTransactionViolations, policyTagList, hasDependentTags);
}

if (updatedTransaction?.comment?.customUnit?.customUnitRateID && !!getCustomUnitRate(policy, updatedTransaction?.comment?.customUnit?.customUnitRateID)) {
if (updatedTransaction?.comment?.customUnit?.customUnitRateID && !!getDistanceRateCustomUnitRate(policy, updatedTransaction?.comment?.customUnit?.customUnitRateID)) {
newTransactionViolations = reject(newTransactionViolations, {name: CONST.VIOLATIONS.CUSTOM_UNIT_OUT_OF_POLICY});
}

Expand Down
6 changes: 3 additions & 3 deletions src/libs/actions/Policy/DistanceRate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import type {
import {READ_COMMANDS, WRITE_COMMANDS} from '@libs/API/types';
import * as ErrorUtils from '@libs/ErrorUtils';
import getIsNarrowLayout from '@libs/getIsNarrowLayout';
import {navigateWhenEnableFeature, removePendingFieldsFromCustomUnit} from '@libs/PolicyUtils';
import {getDistanceRateCustomUnit, navigateWhenEnableFeature, removePendingFieldsFromCustomUnit} from '@libs/PolicyUtils';
import * as ReportUtils from '@libs/ReportUtils';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
Expand Down Expand Up @@ -128,8 +128,8 @@ function enablePolicyDistanceRates(policyID: string, enabled: boolean) {

if (!enabled) {
const policy = allPolicies?.[`${ONYXKEYS.COLLECTION.POLICY}${policyID}`];
const customUnitID = Object.keys(policy?.customUnits ?? {}).at(0) ?? '';
const customUnit = customUnitID ? policy?.customUnits?.[customUnitID] : undefined;
const customUnit = getDistanceRateCustomUnit(policy);
const customUnitID = customUnit?.customUnitID ?? '';

const rateEntries = Object.entries(customUnit?.rates ?? {});
// find the rate to be enabled after disabling the distance rate feature
Expand Down
2 changes: 1 addition & 1 deletion src/libs/actions/Policy/Policy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1139,7 +1139,7 @@ function updateGeneralSettings(policyID: string, name: string, currencyValue?: s
return;
}

const distanceUnit = PolicyUtils.getCustomUnit(policy);
const distanceUnit = PolicyUtils.getDistanceRateCustomUnit(policy);
const customUnitID = distanceUnit?.customUnitID;
const currency = currencyValue ?? policy?.outputCurrency ?? CONST.CURRENCY.USD;

Expand Down
59 changes: 25 additions & 34 deletions src/libs/actions/TaxRate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import type {
} from '@libs/API/parameters';
import {WRITE_COMMANDS} from '@libs/API/types';
import {translateLocal} from '@libs/Localize';
import * as PolicyUtils from '@libs/PolicyUtils';
import * as ValidationUtils from '@libs/ValidationUtils';
import CONST from '@src/CONST';
import * as ErrorUtils from '@src/libs/ErrorUtils';
Expand All @@ -21,7 +22,7 @@ import INPUT_IDS from '@src/types/form/WorkspaceNewTaxForm';
import {default as INPUT_IDS_TAX_CODE} from '@src/types/form/WorkspaceTaxCodeForm';
import type {Policy, TaxRate, TaxRates} from '@src/types/onyx';
import type * as OnyxCommon from '@src/types/onyx/OnyxCommon';
import type {CustomUnit, Rate} from '@src/types/onyx/Policy';
import type {Rate} from '@src/types/onyx/Policy';
import type {OnyxData} from '@src/types/onyx/Request';

let allPolicies: OnyxCollection<Policy>;
Expand Down Expand Up @@ -288,9 +289,9 @@ function deletePolicyTaxes(policyID: string, taxesToDelete: string[]) {
const firstTaxID = Object.keys(policyTaxRates ?? {})
.sort((a, b) => a.localeCompare(b))
.at(0);
const customUnits = policy?.customUnits ?? {};
const customUnitID = Object.keys(customUnits).at(0) ?? '-1';
const ratesToUpdate = Object.values(customUnits?.[customUnitID]?.rates ?? {}).filter(
const distanceRateCustomUnit = PolicyUtils.getDistanceRateCustomUnit(policy);
const customUnitID = distanceRateCustomUnit?.customUnitID ?? '-1';
const ratesToUpdate = Object.values(distanceRateCustomUnit?.rates ?? {}).filter(
(rate) => !!rate.attributes?.taxRateExternalID && taxesToDelete.includes(rate.attributes?.taxRateExternalID),
);

Expand Down Expand Up @@ -342,7 +343,7 @@ function deletePolicyTaxes(policyID: string, taxesToDelete: string[]) {
return acc;
}, {}),
},
customUnits: customUnits && {
customUnits: distanceRateCustomUnit && {
[customUnitID]: {
rates: optimisticRates,
},
Expand All @@ -362,7 +363,7 @@ function deletePolicyTaxes(policyID: string, taxesToDelete: string[]) {
return acc;
}, {}),
},
customUnits: customUnits && {
customUnits: distanceRateCustomUnit && {
[customUnitID]: {
rates: successRates,
},
Expand All @@ -386,7 +387,7 @@ function deletePolicyTaxes(policyID: string, taxesToDelete: string[]) {
return acc;
}, {}),
},
customUnits: customUnits && {
customUnits: distanceRateCustomUnit && {
[customUnitID]: {
rates: failureRates,
},
Expand Down Expand Up @@ -537,33 +538,23 @@ function renamePolicyTax(policyID: string, taxID: string, newName: string) {
function setPolicyTaxCode(policyID: string, oldTaxCode: string, newTaxCode: string) {
const policy = allPolicies?.[`${ONYXKEYS.COLLECTION.POLICY}${policyID}`];
const originalTaxRate = {...policy?.taxRates?.taxes[oldTaxCode]};
const customUnits = Object.values(policy?.customUnits ?? {});
const optimisticCustomUnit = {
customUnits: {
...customUnits.reduce((units, customUnit) => {
// eslint-disable-next-line no-param-reassign
units[customUnit.customUnitID] = {
rates: {
...Object.keys(customUnit.rates).reduce((rates, rateID) => {
if (customUnit.rates[rateID].attributes?.taxRateExternalID === oldTaxCode) {
// eslint-disable-next-line no-param-reassign
rates[rateID] = {
attributes: {
taxRateExternalID: newTaxCode,
},
};
}
return rates;
}, {} as Record<string, Rate>),
},
};
return units;
}, {} as Record<string, Partial<CustomUnit>>),
const distanceRateCustomUnit = PolicyUtils.getDistanceRateCustomUnit(policy);
const optimisticDistanceRateCustomUnit = distanceRateCustomUnit && {
...distanceRateCustomUnit,
rates: {
...Object.keys(distanceRateCustomUnit.rates).reduce((rates, rateID) => {
if (distanceRateCustomUnit.rates[rateID].attributes?.taxRateExternalID === oldTaxCode) {
// eslint-disable-next-line no-param-reassign
rates[rateID] = {
attributes: {
taxRateExternalID: newTaxCode,
},
};
}
return rates;
}, {} as Record<string, Rate>),
},
};
const failureCustomUnit = {
customUnits: policy?.customUnits,
};
const oldDefaultExternalID = policy?.taxRates?.defaultExternalID;
const oldForeignTaxDefault = policy?.taxRates?.foreignTaxDefault;
const onyxData: OnyxData = {
Expand All @@ -586,7 +577,7 @@ function setPolicyTaxCode(policyID: string, oldTaxCode: string, newTaxCode: stri
},
},
},
...(!!customUnits && optimisticCustomUnit),
...(!!distanceRateCustomUnit && {customUnits: {[distanceRateCustomUnit.customUnitID]: optimisticDistanceRateCustomUnit}}),
},
},
],
Expand Down Expand Up @@ -631,7 +622,7 @@ function setPolicyTaxCode(policyID: string, oldTaxCode: string, newTaxCode: stri
},
},
},
...(!!customUnits && failureCustomUnit),
...(!!distanceRateCustomUnit && {customUnits: {[distanceRateCustomUnit.customUnitID]: distanceRateCustomUnit}}),
},
},
],
Expand Down
4 changes: 2 additions & 2 deletions src/pages/iou/request/step/IOURequestStepDistanceRate.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import * as IOU from '@libs/actions/IOU';
import * as CurrencyUtils from '@libs/CurrencyUtils';
import DistanceRequestUtils from '@libs/DistanceRequestUtils';
import Navigation from '@libs/Navigation/Navigation';
import {getCustomUnitRate, isTaxTrackingEnabled} from '@libs/PolicyUtils';
import {getDistanceRateCustomUnitRate, isTaxTrackingEnabled} from '@libs/PolicyUtils';
import * as ReportUtils from '@libs/ReportUtils';
import * as TransactionUtils from '@libs/TransactionUtils';
import CONST from '@src/CONST';
Expand Down Expand Up @@ -83,7 +83,7 @@ function IOURequestStepDistanceRate({
let taxAmount;
let taxRateExternalID;
if (shouldShowTax) {
const policyCustomUnitRate = getCustomUnitRate(policy, customUnitRateID);
const policyCustomUnitRate = getDistanceRateCustomUnitRate(policy, customUnitRateID);
taxRateExternalID = policyCustomUnitRate?.attributes?.taxRateExternalID ?? '-1';
const unit = DistanceRequestUtils.getDistanceUnit(transaction, rates[customUnitRateID]);
const taxableAmount = DistanceRequestUtils.getTaxableAmount(policy, customUnitRateID, TransactionUtils.getDistanceInMeters(transaction, unit));
Expand Down
7 changes: 4 additions & 3 deletions src/pages/workspace/distanceRates/CreateDistanceRatePage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import useLocalize from '@hooks/useLocalize';
import usePolicy from '@hooks/usePolicy';
import useThemeStyles from '@hooks/useThemeStyles';
import {getOptimisticRateName, validateRateValue} from '@libs/PolicyDistanceRatesUtils';
import {getDistanceRateCustomUnit} from '@libs/PolicyUtils';
import Navigation from '@navigation/Navigation';
import type {SettingsNavigatorParamList} from '@navigation/types';
import AccessOrNotFoundWrapper from '@pages/workspace/AccessOrNotFoundWrapper';
Expand All @@ -32,8 +33,8 @@ function CreateDistanceRatePage({route}: CreateDistanceRatePageProps) {
const policyID = route.params.policyID;
const policy = usePolicy(policyID);
const currency = policy?.outputCurrency ?? CONST.CURRENCY.USD;
const customUnits = policy?.customUnits ?? {};
const customUnitID = customUnits[Object.keys(customUnits)[0]]?.customUnitID ?? '';
const customUnit = getDistanceRateCustomUnit(policy);
const customUnitID = customUnit?.customUnitID ?? '';
const customUnitRateID = generateCustomUnitID();
const {inputCallbackRef} = useAutoFocusInput();

Expand All @@ -47,7 +48,7 @@ function CreateDistanceRatePage({route}: CreateDistanceRatePageProps) {
const submit = (values: FormOnyxValues<typeof ONYXKEYS.FORMS.POLICY_CREATE_DISTANCE_RATE_FORM>) => {
const newRate: Rate = {
currency,
name: getOptimisticRateName(customUnits[customUnitID]?.rates),
name: getOptimisticRateName(customUnit?.rates ?? {}),
rate: parseFloat(values.rate) * CONST.POLICY.CUSTOM_UNIT_RATE_BASE_OFFSET,
customUnitRateID,
enabled: true,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import useThemeStyles from '@hooks/useThemeStyles';
import * as CurrencyUtils from '@libs/CurrencyUtils';
import * as ErrorUtils from '@libs/ErrorUtils';
import Navigation from '@libs/Navigation/Navigation';
import {getDistanceRateCustomUnit} from '@libs/PolicyUtils';
import type {SettingsNavigatorParamList} from '@navigation/types';
import NotFoundPage from '@pages/ErrorPage/NotFoundPage';
import AccessOrNotFoundWrapper from '@pages/workspace/AccessOrNotFoundWrapper';
Expand All @@ -37,12 +38,12 @@ function PolicyDistanceRateDetailsPage({route}: PolicyDistanceRateDetailsPagePro
const policyID = route.params.policyID;
const [policy] = useOnyx(`${ONYXKEYS.COLLECTION.POLICY}${route.params.policyID}`);
const rateID = route.params.rateID;
const customUnits = policy?.customUnits ?? {};
const customUnit = customUnits[Object.keys(customUnits)[0]];

const customUnit = getDistanceRateCustomUnit(policy);
const rate = customUnit?.rates[rateID];
const currency = rate?.currency ?? CONST.CURRENCY.USD;
const taxClaimablePercentage = rate.attributes?.taxClaimablePercentage;
const taxRateExternalID = rate.attributes?.taxRateExternalID;
const taxClaimablePercentage = rate?.attributes?.taxClaimablePercentage;
const taxRateExternalID = rate?.attributes?.taxRateExternalID;

const isDistanceTrackTaxEnabled = !!customUnit?.attributes?.taxEnabled;
const isPolicyTrackTaxEnabled = !!policy?.tax?.trackingEnabled;
Expand Down
Loading

0 comments on commit 24de4c7

Please sign in to comment.