Skip to content
Closed
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
5 changes: 2 additions & 3 deletions src/components/ReportActionItem/MoneyRequestView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@ import {getDecodedCategoryName, isCategoryMissing} from '@libs/CategoryUtils';
import {convertToDisplayString} from '@libs/CurrencyUtils';
import DistanceRequestUtils from '@libs/DistanceRequestUtils';
import getNonEmptyStringOnyxID from '@libs/getNonEmptyStringOnyxID';
import {getRateFromMerchant} from '@libs/MergeTransactionUtils';
import {hasEnabledOptions} from '@libs/OptionsListUtils';
import Parser from '@libs/Parser';
import {
Expand Down Expand Up @@ -423,7 +422,7 @@ function MoneyRequestView({
const isCustomUnitOutOfPolicy = transactionViolations.some((violation) => violation.name === CONST.VIOLATIONS.CUSTOM_UNIT_OUT_OF_POLICY) || (isDistanceRequest && !rate);
let rateToDisplay = isCustomUnitOutOfPolicy
? translate('common.rateOutOfPolicy')
: DistanceRequestUtils.getRateForDisplay(unit, rate, currency, translate, toLocaleDigit, getCurrencySymbol, isOffline);
: DistanceRequestUtils.getStoredRateForDisplay(updatedTransaction ?? transaction, unit, rate, currency, translate, toLocaleDigit, getCurrencySymbol, isOffline);
const distanceToDisplay = DistanceRequestUtils.getDistanceForDisplay(hasRoute, distance, unit, rate, translate, undefined, isManualDistanceRequest);
let merchantTitle = isEmptyMerchant ? '' : transactionMerchant;
let amountTitle = formattedTransactionAmount?.toString() || '';
Expand Down Expand Up @@ -515,7 +514,7 @@ function MoneyRequestView({
// Because we lack the necessary data in policy.customUnits to determine the rate in merge flow,
// We need to extract the rate from the merchant string
// See https://github.com/Expensify/App/pull/71675#issuecomment-3425488228 for more information
rateToDisplay = getRateFromMerchant(updatedMerchantTitle);
rateToDisplay = DistanceRequestUtils.getRateFromMerchant(updatedMerchantTitle);
}

const hasErrors = hasMissingSmartscanFields(transaction, transactionReport);
Expand Down
41 changes: 41 additions & 0 deletions src/libs/DistanceRequestUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -362,6 +362,45 @@ function getDistanceUnit(transaction: OnyxEntry<Transaction>, mileageRate: OnyxE
return transaction?.comment?.customUnit?.distanceUnit ?? mileageRate?.unit ?? CONST.CUSTOM_UNITS.DISTANCE_UNIT_MILES;
}

/**
* Extract the rate display portion from a merchant string.
* The merchant format is "<distance> @ <rate>" (e.g., "10.00 mi @ $0.70 / mi").
* Returns the rate portion (e.g., "$0.70 / mi"), or empty string if not present.
*/
function getRateFromMerchant(merchant: string | undefined): string {
if (!merchant) {
return '';
}

return merchant.split(CONST.DISTANCE_MERCHANT_SEPARATOR).at(-1)?.trim() ?? '';
}

/**
* Get the rate display string for a distance transaction.
* Extracts the rate from the stored merchant string if it matches the expected format (contains '@'),
* otherwise falls back to computing the display string from the current policy rate.
*/
function getStoredRateForDisplay(
transaction: OnyxEntry<Transaction>,
unit: Unit | undefined,
rate: number | undefined,
currency: string | undefined,
translate: LocaleContextProps['translate'],
toLocaleDigit: LocaleContextProps['toLocaleDigit'],
getCurrencySymbol: CurrencyListActionsContextType['getCurrencySymbol'],
isOffline?: boolean,
): string {
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
const storedMerchant = transaction?.modifiedMerchant || transaction?.merchant;
if (storedMerchant?.includes(CONST.DISTANCE_MERCHANT_SEPARATOR)) {
const parsed = getRateFromMerchant(storedMerchant);
if (parsed) {
return parsed;
}
}
return getRateForDisplay(unit, rate, currency, translate, toLocaleDigit, getCurrencySymbol, isOffline);
}

/**
* Get the selected rate for a transaction, from the policy or P2P default rate.
* Use the distanceUnit stored on the transaction by default to prevent policy changes modifying existing transactions. Otherwise, get the unit from the rate.
Expand Down Expand Up @@ -436,6 +475,8 @@ export default {
getRateByCustomUnitRateID,
getDistanceForDisplayLabel,
convertDistanceUnit,
getStoredRateForDisplay,
getRateFromMerchant,
};

export type {MileageRate};
9 changes: 0 additions & 9 deletions src/libs/MergeTransactionUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -569,14 +569,6 @@ function getMergeFieldUpdatedValues<K extends MergeFieldKey>(
return updatedValues;
}

function getRateFromMerchant(merchant: string | undefined): string {
if (!merchant) {
return '';
}

return merchant.split(CONST.DISTANCE_MERCHANT_SEPARATOR).at(-1)?.trim() ?? '';
}

export {
getTransactionFromMergeTransaction,
shouldNavigateToReceiptReview,
Expand All @@ -593,7 +585,6 @@ export {
getReportIDForExpense,
getMergeFieldErrorText,
areTransactionsEligibleForMerge,
getRateFromMerchant,
getMergeFieldUpdatedValues,
getTransactionsAndReportsFromSearch,
MERGE_FIELDS,
Expand Down
9 changes: 9 additions & 0 deletions src/libs/TransactionUtils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1138,6 +1138,15 @@ function isUnreportedAndHasInvalidDistanceRateTransaction(transaction: OnyxInput
*/
function getMerchant(transaction: OnyxInputOrEntry<Transaction>, policyParam: OnyxEntry<Policy> = undefined): string {
if (transaction && isDistanceRequest(transaction)) {
// Prefer the stored merchant string if it contains rate info (has the '@' separator).
// The stored merchant was set when the expense was created/edited, so it preserves the original rate.
// This prevents policy rate changes from retroactively altering historical distance expense display.
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
const storedMerchant = transaction.modifiedMerchant || transaction.merchant;
if (storedMerchant?.includes(CONST.DISTANCE_MERCHANT_SEPARATOR)) {
return storedMerchant;
}

const report = getReportOrDraftReport(transaction.reportID);
// This will be fixed as part of https://github.com/Expensify/Expensify/issues/507850
// eslint-disable-next-line @typescript-eslint/no-deprecated
Expand Down
93 changes: 93 additions & 0 deletions tests/unit/DistanceRequestUtilsTest.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import DistanceRequestUtils from '@libs/DistanceRequestUtils';
import CONST from '@src/CONST';
import type {Transaction} from '@src/types/onyx';
import type {Unit} from '@src/types/onyx/Policy';
import type Policy from '@src/types/onyx/Policy';
import {translateLocal} from '../utils/TestHelper';
Expand Down Expand Up @@ -178,4 +179,96 @@ describe('DistanceRequestUtils', () => {
expect(result).toBe('0.00 mi @ $0.67 / mi');
});
});

describe('getRateFromMerchant', () => {
it('should return empty string for undefined merchant', () => {
const result = DistanceRequestUtils.getRateFromMerchant(undefined);
expect(result).toBe('');
});

it('should return empty string for empty merchant', () => {
const result = DistanceRequestUtils.getRateFromMerchant('');
expect(result).toBe('');
});

it('should extract rate from distance merchant string', () => {
const result = DistanceRequestUtils.getRateFromMerchant('5.2 mi @ $0.50 / mi');
expect(result).toBe('$0.50 / mi');
});

it('should extract rate from km merchant string', () => {
const result = DistanceRequestUtils.getRateFromMerchant('10.00 km @ $0.33 / km');
expect(result).toBe('$0.33 / km');
});

it('should return full string when no separator present', () => {
const result = DistanceRequestUtils.getRateFromMerchant('Uber ride');
expect(result).toBe('Uber ride');
});
});

describe('getStoredRateForDisplay', () => {
const toLocaleDigitMock = (dot: string): string => dot;
const getCurrencySymbolMock = (currency: string): string | undefined => {
if (currency === 'USD') {
return '$';
}
return undefined;
};

const callGetStoredRateForDisplay = (transaction: Transaction | undefined, unit?: Unit, rate?: number, currency?: string, isOffline?: boolean) =>
DistanceRequestUtils.getStoredRateForDisplay(
transaction,
unit ?? CONST.CUSTOM_UNITS.DISTANCE_UNIT_MILES,
rate ?? 67,
currency ?? 'USD',
translateLocal,
toLocaleDigitMock,
getCurrencySymbolMock,
isOffline,
);

it('should fall back to policy rate when transaction is undefined', () => {
const result = callGetStoredRateForDisplay(undefined);
const expectedFallback = DistanceRequestUtils.getRateForDisplay(CONST.CUSTOM_UNITS.DISTANCE_UNIT_MILES, 67, 'USD', translateLocal, toLocaleDigitMock, getCurrencySymbolMock);
expect(result).toBe(expectedFallback);
});

it('should fall back to policy rate when merchant has no separator', () => {
const transaction = {merchant: 'Uber ride'} as Transaction;
const result = callGetStoredRateForDisplay(transaction);
const expectedFallback = DistanceRequestUtils.getRateForDisplay(CONST.CUSTOM_UNITS.DISTANCE_UNIT_MILES, 67, 'USD', translateLocal, toLocaleDigitMock, getCurrencySymbolMock);
expect(result).toBe(expectedFallback);
});

it('should extract rate from merchant with separator', () => {
const transaction = {merchant: '10.00 mi @ $0.70 / mi'} as Transaction;
const result = callGetStoredRateForDisplay(transaction);
expect(result).toBe('$0.70 / mi');
});

it('should prefer modifiedMerchant over merchant', () => {
const transaction = {
merchant: '10.00 mi @ $0.50 / mi',
modifiedMerchant: '10.00 mi @ $1.00 / mi',
} as Transaction;
const result = callGetStoredRateForDisplay(transaction);
expect(result).toBe('$1.00 / mi');
});

it('should fall back to merchant when modifiedMerchant is empty', () => {
const transaction = {
merchant: '10.00 mi @ $0.70 / mi',
modifiedMerchant: '',
} as Transaction;
const result = callGetStoredRateForDisplay(transaction);
expect(result).toBe('$0.70 / mi');
});

it('should return stored rate even when policy rate differs', () => {
const transaction = {merchant: '10.00 mi @ $0.50 / mi'} as Transaction;
const result = callGetStoredRateForDisplay(transaction, CONST.CUSTOM_UNITS.DISTANCE_UNIT_MILES, 100, 'USD');
expect(result).toBe('$0.50 / mi');
});
});
});
25 changes: 0 additions & 25 deletions tests/unit/MergeTransactionUtilsTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import {
getMergeFieldTranslationKey,
getMergeFieldUpdatedValues,
getMergeFieldValue,
getRateFromMerchant,
isEmptyMergeValue,
selectTargetAndSourceTransactionsForMerge,
shouldNavigateToReceiptReview,
Expand Down Expand Up @@ -1230,28 +1229,4 @@ describe('MergeTransactionUtils', () => {
expect(result2).toBe(false);
});
});

describe('getRateFromMerchant', () => {
it('should return empty string for undefined merchant', () => {
// Given an undefined merchant
const merchant = undefined;

// When we get rate from merchant
const result = getRateFromMerchant(merchant);

// Then it should return empty string
expect(result).toBe('');
});

it('should extract rate from distance merchant string', () => {
// Given a distance merchant string with rate
const merchant = '5.2 mi @ $0.50 / mi';

// When we get rate from merchant
const result = getRateFromMerchant(merchant);

// Then it should return the rate portion
expect(result).toBe('$0.50 / mi');
});
});
});
94 changes: 94 additions & 0 deletions tests/unit/TransactionUtilsTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -688,6 +688,100 @@ describe('TransactionUtils', () => {
expect(merchant).toBe('100.00 mi @ USD 1.00 / mi');
});
});

it('should prefer stored merchant with rate info over recalculating from policy for distance requests', () => {
return waitForBatchedUpdates()
.then(async () => {
const fakePolicy: Policy = {
...createRandomPolicy(0),
customUnits: {
Unit1: {
customUnitID: 'Unit1',
name: CONST.CUSTOM_UNITS.NAME_DISTANCE,
rates: {
Rate1: {
customUnitRateID: 'Rate1',
currency: CONST.CURRENCY.USD,
rate: 200,
},
},
enabled: true,
attributes: {
unit: 'mi',
},
},
},
outputCurrency: CONST.CURRENCY.USD,
};
await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}${fakePolicy.id}`, fakePolicy);
await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${FAKE_OPEN_REPORT_ID}`, {policyID: fakePolicy.id});
})
.then(() => {
const transaction = generateTransaction({
merchant: '10.00 mi @ $0.70 / mi',
comment: {
type: CONST.TRANSACTION.TYPE.CUSTOM_UNIT,
customUnit: {
name: CONST.CUSTOM_UNITS.NAME_DISTANCE,
customUnitID: 'Unit1',
customUnitRateID: 'Rate1',
quantity: 10,
distanceUnit: CONST.CUSTOM_UNITS.DISTANCE_UNIT_MILES,
},
},
reportID: FAKE_OPEN_REPORT_ID,
});
const merchant = TransactionUtils.getMerchant(transaction);
expect(merchant).toBe('10.00 mi @ $0.70 / mi');
});
});

it('should recalculate merchant from policy when stored merchant has no rate info', () => {
return waitForBatchedUpdates()
.then(async () => {
const fakePolicy: Policy = {
...createRandomPolicy(0),
customUnits: {
Unit1: {
customUnitID: 'Unit1',
name: CONST.CUSTOM_UNITS.NAME_DISTANCE,
rates: {
Rate1: {
customUnitRateID: 'Rate1',
currency: CONST.CURRENCY.USD,
rate: 100,
},
},
enabled: true,
attributes: {
unit: 'mi',
},
},
},
outputCurrency: CONST.CURRENCY.USD,
};
await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}${fakePolicy.id}`, fakePolicy);
await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${FAKE_OPEN_REPORT_ID}`, {policyID: fakePolicy.id});
})
.then(() => {
const transaction = generateTransaction({
merchant: 'Pending...',
comment: {
type: CONST.TRANSACTION.TYPE.CUSTOM_UNIT,
customUnit: {
name: CONST.CUSTOM_UNITS.NAME_DISTANCE,
customUnitID: 'Unit1',
customUnitRateID: 'Rate1',
quantity: 100,
distanceUnit: CONST.CUSTOM_UNITS.DISTANCE_UNIT_MILES,
},
},
reportID: FAKE_OPEN_REPORT_ID,
});
const merchant = TransactionUtils.getMerchant(transaction);
expect(merchant).toBe('100.00 mi @ USD 1.00 / mi');
});
});
});
describe('getTransactionPendingAction', () => {
it.each([
Expand Down
Loading