Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix distance rate flow (when per diem is enabled as well) #51159

Merged
merged 5 commits into from
Oct 22, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
6 changes: 3 additions & 3 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,7 +302,7 @@ 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 distanceUnit = PolicyUtils.getDistanceRateCustomUnit(policy);
const customUnitRate = PolicyUtils.getCustomUnitRate(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 ?? 0) / 100) {
shubham1206agra marked this conversation as resolved.
Show resolved Hide resolved
errors.taxClaimableValue = Localize.translateLocal('workspace.taxes.error.updateTaxClaimableFailureMessage');
}
return errors;
Expand Down
8 changes: 4 additions & 4 deletions src/libs/PolicyUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,15 +126,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 {
shubham1206agra marked this conversation as resolved.
Show resolved Hide resolved
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 {
shubham1206agra marked this conversation as resolved.
Show resolved Hide resolved
const distanceUnit = getCustomUnit(policy);
const distanceUnit = getDistanceRateCustomUnit(policy);
return distanceUnit?.rates[customUnitRateID];
}

Expand Down Expand Up @@ -376,7 +376,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 @@ -1138,7 +1138,7 @@ export {
getSageIntacctNonReimbursableActiveDefaultVendor,
getSageIntacctCreditCards,
getSageIntacctBankAccounts,
getCustomUnit,
getDistanceRateCustomUnit,
getCustomUnitRate,
sortWorkspacesBySelected,
removePendingFieldsFromCustomUnit,
Expand Down
8 changes: 4 additions & 4 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,10 +128,10 @@ 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 distanceRateCustomUnit = getDistanceRateCustomUnit(policy);
shubham1206agra marked this conversation as resolved.
Show resolved Hide resolved
const customUnitID = distanceRateCustomUnit?.customUnitID ?? '';

const rateEntries = Object.entries(customUnit?.rates ?? {});
const rateEntries = Object.entries(distanceRateCustomUnit?.rates ?? {});
// find the rate to be enabled after disabling the distance rate feature
const rateEntryToBeEnabled = rateEntries.at(0);

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 @@ -1146,7 +1146,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(
shubham1206agra marked this conversation as resolved.
Show resolved Hide resolved
(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
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 distanceRateCustomUnit = getDistanceRateCustomUnit(policy);
shubham1206agra marked this conversation as resolved.
Show resolved Hide resolved
const customUnitID = distanceRateCustomUnit?.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(distanceRateCustomUnit?.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,19 +38,19 @@ 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 rate = customUnit?.rates[rateID];

const distanceRateCustomUnit = getDistanceRateCustomUnit(policy);
const rate = distanceRateCustomUnit?.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 isDistanceTrackTaxEnabled = !!distanceRateCustomUnit?.attributes?.taxEnabled;
const isPolicyTrackTaxEnabled = !!policy?.tax?.trackingEnabled;
const taxRate =
taxRateExternalID && policy?.taxRates?.taxes[taxRateExternalID] ? `${policy?.taxRates?.taxes[taxRateExternalID]?.name} (${policy?.taxRates?.taxes[taxRateExternalID]?.value})` : '';
// Rates can be disabled or deleted as long as in the remaining rates there is always at least one enabled rate and there are no pending delete action
const canDisableOrDeleteRate = Object.values(customUnit?.rates ?? {}).some(
const canDisableOrDeleteRate = Object.values(distanceRateCustomUnit?.rates ?? {}).some(
(distanceRate: Rate) => distanceRate?.enabled && rateID !== distanceRate?.customUnitRateID && distanceRate?.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE,
);
const errorFields = rate?.errorFields;
Expand All @@ -70,24 +71,24 @@ function PolicyDistanceRateDetailsPage({route}: PolicyDistanceRateDetailsPagePro

const toggleRate = () => {
if (!rate?.enabled || canDisableOrDeleteRate) {
DistanceRate.setPolicyDistanceRatesEnabled(policyID, customUnit, [{...rate, enabled: !rate?.enabled}]);
DistanceRate.setPolicyDistanceRatesEnabled(policyID, distanceRateCustomUnit, [{...rate, enabled: !rate?.enabled}]);
} else {
setIsWarningModalVisible(true);
}
};

const deleteRate = () => {
Navigation.goBack();
DistanceRate.deletePolicyDistanceRates(policyID, customUnit, [rateID]);
DistanceRate.deletePolicyDistanceRates(policyID, distanceRateCustomUnit, [rateID]);
setIsDeleteModalVisible(false);
};

const rateValueToDisplay = CurrencyUtils.convertAmountToDisplayString(rate?.rate, currency);
const taxClaimableValueToDisplay = taxClaimablePercentage && rate.rate ? CurrencyUtils.convertAmountToDisplayString(taxClaimablePercentage * rate.rate, currency) : '';
const unitToDisplay = translate(`common.${customUnit?.attributes?.unit ?? CONST.CUSTOM_UNITS.DISTANCE_UNIT_MILES}`);
const unitToDisplay = translate(`common.${distanceRateCustomUnit?.attributes?.unit ?? CONST.CUSTOM_UNITS.DISTANCE_UNIT_MILES}`);

const clearErrorFields = (fieldName: keyof Rate | keyof TaxRateAttributes) => {
DistanceRate.clearPolicyDistanceRateErrorFields(policyID, customUnit.customUnitID, rateID, {...errorFields, [fieldName]: null});
DistanceRate.clearPolicyDistanceRateErrorFields(policyID, distanceRateCustomUnit.customUnitID, rateID, {...errorFields, [fieldName]: null});
};

return (
Expand All @@ -101,7 +102,7 @@ function PolicyDistanceRateDetailsPage({route}: PolicyDistanceRateDetailsPagePro
includeSafeAreaPaddingBottom={false}
style={[styles.defaultModalContainer]}
>
<HeaderWithBackButton title={`${rateValueToDisplay} / ${translate(`common.${customUnit?.attributes?.unit ?? CONST.CUSTOM_UNITS.DISTANCE_UNIT_MILES}`)}`} />
<HeaderWithBackButton title={`${rateValueToDisplay} / ${translate(`common.${distanceRateCustomUnit?.attributes?.unit ?? CONST.CUSTOM_UNITS.DISTANCE_UNIT_MILES}`)}`} />
<ScrollView contentContainerStyle={styles.flexGrow1}>
<OfflineWithFeedback
errors={ErrorUtils.getLatestErrorField(rate ?? {}, 'enabled')}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import usePolicy from '@hooks/usePolicy';
import useThemeStyles from '@hooks/useThemeStyles';
import Navigation from '@libs/Navigation/Navigation';
import {validateRateValue} from '@libs/PolicyDistanceRatesUtils';
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 @@ -32,9 +33,8 @@ function PolicyDistanceRateEditPage({route}: PolicyDistanceRateEditPageProps) {
const policyID = route.params.policyID;
const rateID = route.params.rateID;
const policy = usePolicy(policyID);
const customUnits = policy?.customUnits ?? {};
const customUnit = customUnits[Object.keys(customUnits)[0]];
const rate = customUnit?.rates[rateID];
const distanceRateCustomUnit = getDistanceRateCustomUnit(policy);
const rate = distanceRateCustomUnit?.rates[rateID];
const currency = rate?.currency ?? CONST.CURRENCY.USD;
const currentRateValue = (parseFloat((rate?.rate ?? 0).toString()) / CONST.POLICY.CUSTOM_UNIT_RATE_BASE_OFFSET).toFixed(CONST.MAX_TAX_RATE_DECIMAL_PLACES);

Expand All @@ -43,7 +43,10 @@ function PolicyDistanceRateEditPage({route}: PolicyDistanceRateEditPageProps) {
Navigation.goBack();
return;
}
DistanceRate.updatePolicyDistanceRateValue(policyID, customUnit, [{...rate, rate: Number(values.rate) * CONST.POLICY.CUSTOM_UNIT_RATE_BASE_OFFSET}]);
if (!distanceRateCustomUnit) {
return;
}
DistanceRate.updatePolicyDistanceRateValue(policyID, distanceRateCustomUnit, [{...rate, rate: Number(values.rate) * CONST.POLICY.CUSTOM_UNIT_RATE_BASE_OFFSET}]);
Keyboard.dismiss();
Navigation.goBack();
};
Expand Down
Loading
Loading