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 cycle dependencies in metro console #53852

Open
wants to merge 49 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
49 commits
Select commit Hold shift + click to select a range
ab2ef10
fix: attempt to use named export to fix cycular dependecies
kubabutkiewicz Nov 25, 2024
3b05f56
fix more files
kubabutkiewicz Nov 26, 2024
1eee276
lint
kubabutkiewicz Nov 26, 2024
f28bce0
Merge branch 'main' of github.com:callstack-internal/Expensify-App in…
kubabutkiewicz Nov 26, 2024
765e46d
refactor imports in ReportUtils for PolicyUtils and ReportActionsUtils
kubabutkiewicz Nov 27, 2024
09bffc4
refacort imports in ReportUtils and actions/IOU
kubabutkiewicz Nov 28, 2024
09b1e4c
refactor imports in ReportUtils, SearchQueryUtils, App, IOU, Priority…
kubabutkiewicz Dec 2, 2024
f490ddc
Merge branch 'main' of github.com:callstack-internal/Expensify-App in…
kubabutkiewicz Dec 2, 2024
4d0d477
fix imports in OnyxUpdateManager
kubabutkiewicz Dec 2, 2024
625283a
fixing rest of dependecy cycles
kubabutkiewicz Dec 2, 2024
43398e7
Merge branch 'main' of github.com:callstack-internal/Expensify-App in…
kubabutkiewicz Dec 4, 2024
9795ed6
Merge branch 'main' of github.com:callstack-internal/Expensify-App in…
kubabutkiewicz Dec 5, 2024
f1c0869
fix: import in Report.ts
kubabutkiewicz Dec 6, 2024
a03dc83
Merge branch 'main' of github.com:callstack-internal/Expensify-App in…
kubabutkiewicz Dec 9, 2024
31847ee
fix: two cyclic dependecies
kubabutkiewicz Dec 10, 2024
68f4b4e
Merge branch 'main' of github.com:callstack-internal/Expensify-App in…
kubabutkiewicz Dec 10, 2024
4711615
fix: tests
kubabutkiewicz Dec 11, 2024
642f272
Merge branch 'main' of github.com:callstack-internal/Expensify-App in…
kubabutkiewicz Dec 11, 2024
fd30e2a
fix: resolve comments
kubabutkiewicz Dec 12, 2024
f688e6c
fix: resolve comment
kubabutkiewicz Dec 12, 2024
d76caa2
Merge branch 'main' of github.com:callstack-internal/Expensify-App in…
kubabutkiewicz Dec 12, 2024
10d59cd
rerun of workflows
kubabutkiewicz Dec 12, 2024
c64f181
revert commit
kubabutkiewicz Dec 12, 2024
75e9499
Merge branch 'main' of github.com:callstack-internal/Expensify-App in…
kubabutkiewicz Dec 12, 2024
e296606
fix: lint
kubabutkiewicz Dec 12, 2024
eb23bac
Merge branch 'main' of github.com:callstack-internal/Expensify-App in…
kubabutkiewicz Dec 12, 2024
9d79515
Merge branch 'main' of github.com:callstack-internal/Expensify-App in…
kubabutkiewicz Dec 16, 2024
e334c63
Merge branch 'main' of github.com:callstack-internal/Expensify-App in…
kubabutkiewicz Dec 16, 2024
69dbbab
Merge branch 'main' of github.com:callstack-internal/Expensify-App in…
kubabutkiewicz Dec 17, 2024
3b6abbe
Merge branch 'main' of github.com:callstack-internal/Expensify-App in…
kubabutkiewicz Dec 17, 2024
cb7bfbc
remove changes from package-lock.json
kubabutkiewicz Dec 17, 2024
c748699
Merge branch 'main' of github.com:callstack-internal/Expensify-App in…
kubabutkiewicz Dec 18, 2024
b736f16
fix eslint problems
kubabutkiewicz Dec 18, 2024
721bb16
Merge branch 'main' of github.com:callstack-internal/Expensify-App in…
kubabutkiewicz Dec 18, 2024
4516381
Merge branch 'main' of github.com:callstack-internal/Expensify-App in…
kubabutkiewicz Dec 18, 2024
b772902
fix lint and ts problems
kubabutkiewicz Dec 18, 2024
60a6a84
Merge branch 'main' of github.com:callstack-internal/Expensify-App in…
kubabutkiewicz Dec 18, 2024
bcb22a3
ts fixes
kubabutkiewicz Dec 18, 2024
b39b7ae
adjusted check
kubabutkiewicz Dec 18, 2024
1ac0dda
fix lint
kubabutkiewicz Dec 18, 2024
2249f9a
Merge branch 'main' of github.com:callstack-internal/Expensify-App in…
kubabutkiewicz Dec 19, 2024
969a338
Merge branch 'main' of github.com:callstack-internal/Expensify-App in…
kubabutkiewicz Dec 19, 2024
21f10eb
fix resolve comments
kubabutkiewicz Dec 19, 2024
7a8f142
remove unnecessary changes
kubabutkiewicz Dec 19, 2024
63b3f05
Merge branch 'main' of github.com:callstack-internal/Expensify-App in…
kubabutkiewicz Dec 19, 2024
c7f3bdc
fix: another cycle dependecy
kubabutkiewicz Dec 19, 2024
6211c2a
Merge branch 'main' of github.com:callstack-internal/Expensify-App in…
kubabutkiewicz Dec 20, 2024
b8d4975
adjusted types
kubabutkiewicz Dec 20, 2024
b90ad7b
fixes
kubabutkiewicz Dec 20, 2024
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
9 changes: 9 additions & 0 deletions metro.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,15 @@ const config = {
// When we run the e2e tests we want files that have the extension e2e.js to be resolved as source files
sourceExts: [...(isE2ETesting ? e2eSourceExts : []), ...defaultSourceExts, 'jsx'],
},
// We are merging the default config from Expo and React Native and expo one is overriding the React Native one so inlineRequires is set to false so we want to set it to true
// for fix cycling dependencies and improve performance of app startup
transformer: {
getTransformOptions: async () => ({
transform: {
inlineRequires: true,
kubabutkiewicz marked this conversation as resolved.
Show resolved Hide resolved
},
}),
},
};

module.exports = wrapWithReanimatedMetroConfig(mergeConfig(defaultConfig, expoConfig, config));
4 changes: 2 additions & 2 deletions src/CONST.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import type {ValueOf} from 'type-fest';
import type {Video} from './libs/actions/Report';
import type {MileageRate} from './libs/DistanceRequestUtils';
import BankAccount from './libs/models/BankAccount';
import * as Url from './libs/Url';
import {addTrailingForwardSlash} from './libs/Url';
import SCREENS from './SCREENS';
import type PlaidBankAccount from './types/onyx/PlaidBankAccount';

Expand All @@ -18,7 +18,7 @@ const EMPTY_OBJECT = Object.freeze({});

const CLOUDFRONT_DOMAIN = 'cloudfront.net';
const CLOUDFRONT_URL = `https://d2k5nsl2zxldvw.${CLOUDFRONT_DOMAIN}`;
const ACTIVE_EXPENSIFY_URL = Url.addTrailingForwardSlash(Config?.NEW_EXPENSIFY_URL ?? 'https://new.expensify.com');
const ACTIVE_EXPENSIFY_URL = addTrailingForwardSlash(Config?.NEW_EXPENSIFY_URL ?? 'https://new.expensify.com');
const USE_EXPENSIFY_URL = 'https://use.expensify.com';
const EXPENSIFY_URL = 'https://www.expensify.com';
const PLATFORM_OS_MACOS = 'Mac OS';
Expand Down
18 changes: 10 additions & 8 deletions src/components/ReportActionItem/ReportPreview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ type ReportPreviewProps = {
chatReportID: string;

/** The active IOUReport, used for Onyx subscription */
iouReportID: string;
iouReportID: string | undefined;

/** The report's policyID, used for Onyx subscription */
policyID: string;
Expand Down Expand Up @@ -103,7 +103,7 @@ function ReportPreview({
const [transactionViolations] = useOnyx(ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS);
const [userWallet] = useOnyx(ONYXKEYS.USER_WALLET);
const [invoiceReceiverPolicy] = useOnyx(
`${ONYXKEYS.COLLECTION.POLICY}${chatReport?.invoiceReceiver && 'policyID' in chatReport.invoiceReceiver ? chatReport.invoiceReceiver.policyID : -1}`,
`${ONYXKEYS.COLLECTION.POLICY}${chatReport?.invoiceReceiver && 'policyID' in chatReport.invoiceReceiver ? chatReport.invoiceReceiver.policyID : CONST.DEFAULT_NUMBER_ID}`,
);
const theme = useTheme();
const styles = useThemeStyles();
Expand Down Expand Up @@ -144,10 +144,10 @@ function ReportPreview({
const shouldDisableApproveButton = shouldShowApproveButton && !ReportUtils.isAllowedToApproveExpenseReport(iouReport);

const {nonHeldAmount, fullAmount, hasValidNonHeldAmount} = ReportUtils.getNonHeldAndFullAmount(iouReport, shouldShowPayButton);
const hasOnlyHeldExpenses = ReportUtils.hasOnlyHeldExpenses(iouReport?.reportID ?? '');
const hasHeldExpenses = ReportUtils.hasHeldExpenses(iouReport?.reportID ?? '');
const hasOnlyHeldExpenses = ReportUtils.hasOnlyHeldExpenses(iouReport?.reportID);
const hasHeldExpenses = ReportUtils.hasHeldExpenses(iouReport?.reportID);

const managerID = iouReport?.managerID ?? action.childManagerAccountID ?? 0;
const managerID = iouReport?.managerID ?? action.childManagerAccountID ?? CONST.DEFAULT_NUMBER_ID;
const {totalDisplaySpend, reimbursableSpend} = ReportUtils.getMoneyRequestSpendBreakdown(iouReport);

const iouSettled = ReportUtils.isSettled(iouReportID) || action?.childStatusNum === CONST.REPORT.STATUS_NUM.REIMBURSED;
Expand Down Expand Up @@ -189,9 +189,8 @@ function ReportPreview({
const lastThreeReceipts = lastThreeTransactions.map((transaction) => ({...ReceiptUtils.getThumbnailAndImageURIs(transaction), transaction}));
const showRTERViolationMessage =
numberOfRequests === 1 &&
TransactionUtils.hasPendingUI(allTransactions.at(0), TransactionUtils.getTransactionViolations(allTransactions.at(0)?.transactionID ?? '-1', transactionViolations));
const shouldShowBrokenConnectionViolation =
numberOfRequests === 1 && TransactionUtils.shouldShowBrokenConnectionViolation(allTransactions.at(0)?.transactionID ?? '-1', iouReport, policy);
TransactionUtils.hasPendingUI(allTransactions.at(0), TransactionUtils.getTransactionViolations(allTransactions.at(0)?.transactionID, transactionViolations));
const shouldShowBrokenConnectionViolation = numberOfRequests === 1 && TransactionUtils.shouldShowBrokenConnectionViolation(allTransactions.at(0)?.transactionID, iouReport, policy);
let formattedMerchant = numberOfRequests === 1 ? TransactionUtils.getMerchant(allTransactions.at(0)) : null;
const formattedDescription = numberOfRequests === 1 ? TransactionUtils.getDescription(allTransactions.at(0)) : null;

Expand Down Expand Up @@ -477,6 +476,9 @@ function ReportPreview({
}, [isApproved, isApprovedAnimationRunning, thumbsUpScale]);

const openReportFromPreview = useCallback(() => {
if (!iouReportID) {
return;
}
Performance.markStart(CONST.TIMING.OPEN_REPORT_FROM_PREVIEW);
Timing.start(CONST.TIMING.OPEN_REPORT_FROM_PREVIEW);
Navigation.navigate(ROUTES.REPORT_WITH_ID.getRoute(iouReportID));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {PressableWithFeedback} from '@components/Pressable';
import useStyleUtils from '@hooks/useStyleUtils';
import useTheme from '@hooks/useTheme';
import useThemeStyles from '@hooks/useThemeStyles';
import * as SearchUIUtils from '@libs/SearchUIUtils';
import {isCorrectSearchUserName} from '@libs/SearchUIUtils';
import variables from '@styles/variables';
import CONST from '@src/CONST';
import type {SearchPersonalDetails, SearchTransactionAction} from '@src/types/onyx/SearchResults';
Expand Down Expand Up @@ -54,7 +54,7 @@ function ExpenseItemHeaderNarrow({
const theme = useTheme();

// It might happen that we are missing display names for `From` or `To`, we only display arrow icon if both names exist
const shouldDisplayArrowIcon = SearchUIUtils.isCorrectSearchUserName(participantFromDisplayName) && SearchUIUtils.isCorrectSearchUserName(participantToDisplayName);
const shouldDisplayArrowIcon = isCorrectSearchUserName(participantFromDisplayName) && isCorrectSearchUserName(participantToDisplayName);

return (
<View style={[styles.flex1, styles.flexRow, styles.alignItemsCenter, styles.justifyContentBetween, styles.mb3, styles.gap2, containerStyle]}>
Expand Down
4 changes: 2 additions & 2 deletions src/components/SelectionList/Search/UserInfoCell.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import Avatar from '@components/Avatar';
import Text from '@components/Text';
import useResponsiveLayout from '@hooks/useResponsiveLayout';
import useThemeStyles from '@hooks/useThemeStyles';
import * as SearchUIUtils from '@libs/SearchUIUtils';
import {isCorrectSearchUserName} from '@libs/SearchUIUtils';
import CONST from '@src/CONST';
import type {SearchPersonalDetails} from '@src/types/onyx/SearchResults';

Expand All @@ -18,7 +18,7 @@ function UserInfoCell({participant, displayName}: UserInfoCellProps) {
const {isLargeScreenWidth} = useResponsiveLayout();
const avatarURL = participant?.avatar;

if (!SearchUIUtils.isCorrectSearchUserName(displayName)) {
if (!isCorrectSearchUserName(displayName)) {
return null;
}

Expand Down
36 changes: 18 additions & 18 deletions src/libs/API/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ import type {OnyxUpdate} from 'react-native-onyx';
import Onyx from 'react-native-onyx';
import type {SetRequired} from 'type-fest';
import Log from '@libs/Log';
import * as Middleware from '@libs/Middleware';
import * as SequentialQueue from '@libs/Network/SequentialQueue';
import * as Pusher from '@libs/Pusher/pusher';
import * as Request from '@libs/Request';
import * as PersistedRequests from '@userActions/PersistedRequests';
import {HandleUnusedOptimisticID, Logging, Pagination, Reauthentication, RecheckConnection, SaveResponseInOnyx} from '@libs/Middleware';
import {push as pushToSequentialQueue, waitForIdle as waitForSequentialQueueIdle} from '@libs/Network/SequentialQueue';
import {getPusherSocketID} from '@libs/Pusher/pusher';
import {processWithMiddleware, use} from '@libs/Request';
import {getLength as getPersistedRequestsLength} from '@userActions/PersistedRequests';
import CONST from '@src/CONST';
import type OnyxRequest from '@src/types/onyx/Request';
import type {PaginatedRequest, PaginationConfig, RequestConflictResolver} from '@src/types/onyx/Request';
Expand All @@ -18,22 +18,22 @@ import type {ApiCommand, ApiRequestCommandParameters, ApiRequestType, CommandOfT
// e.g. an error thrown in Logging or Reauthenticate logic will be caught by the next middleware or the SequentialQueue which retries failing requests.

// Logging - Logs request details and errors.
Request.use(Middleware.Logging);
use(Logging);

// RecheckConnection - Sets a timer for a request that will "recheck" if we are connected to the internet if time runs out. Also triggers the connection recheck when we encounter any error.
Request.use(Middleware.RecheckConnection);
use(RecheckConnection);

// Reauthentication - Handles jsonCode 407 which indicates an expired authToken. We need to reauthenticate and get a new authToken with our stored credentials.
Request.use(Middleware.Reauthentication);
use(Reauthentication);

// If an optimistic ID is not used by the server, this will update the remaining serialized requests using that optimistic ID to use the correct ID instead.
Request.use(Middleware.HandleUnusedOptimisticID);
use(HandleUnusedOptimisticID);

Request.use(Middleware.Pagination);
use(Pagination);

// SaveResponseInOnyx - Merges either the successData or failureData (or finallyData, if included in place of the former two values) into Onyx depending on if the call was successful or not. This needs to be the LAST middleware we use, don't add any
// middlewares after this, because the SequentialQueue depends on the result of this middleware to pause the queue (if needed) to bring the app to an up-to-date state.
Request.use(Middleware.SaveResponseInOnyx);
use(SaveResponseInOnyx);

type OnyxData = {
optimisticData?: OnyxUpdate[];
Expand Down Expand Up @@ -69,7 +69,7 @@ function prepareRequest<TCommand extends ApiCommand>(

// We send the pusherSocketID with all write requests so that the api can include it in push events to prevent Pusher from sending the events to the requesting client. The push event
// is sent back to the requesting client in the response data instead, which prevents a replay effect in the UI. See https://github.com/Expensify/App/issues/12775.
pusherSocketID: isWriteRequest ? Pusher.getPusherSocketID() : undefined,
pusherSocketID: isWriteRequest ? getPusherSocketID() : undefined,
};

// Assemble all request metadata (used by middlewares, and for persisted requests stored in Onyx)
Expand All @@ -95,18 +95,18 @@ function prepareRequest<TCommand extends ApiCommand>(
function processRequest(request: OnyxRequest, type: ApiRequestType): Promise<void | Response> {
// Write commands can be saved and retried, so push it to the SequentialQueue
if (type === CONST.API_REQUEST_TYPE.WRITE) {
SequentialQueue.push(request);
pushToSequentialQueue(request);
return Promise.resolve();
}

// Read requests are processed right away, but don't return the response to the caller
if (type === CONST.API_REQUEST_TYPE.READ) {
Request.processWithMiddleware(request);
processWithMiddleware(request);
return Promise.resolve();
}

// Requests with side effects process right away, and return the response to the caller
return Request.processWithMiddleware(request);
return processWithMiddleware(request);
}

/**
Expand Down Expand Up @@ -172,10 +172,10 @@ function makeRequestWithSideEffects<TCommand extends SideEffectRequestCommand>(
* write requests that use the same Onyx keys and haven't responded yet.
*/
function waitForWrites<TCommand extends ReadCommand>(command: TCommand) {
if (PersistedRequests.getLength() > 0) {
Log.info(`[API] '${command}' is waiting on ${PersistedRequests.getLength()} write commands`);
if (getPersistedRequestsLength() > 0) {
Log.info(`[API] '${command}' is waiting on ${getPersistedRequestsLength()} write commands`);
}
return SequentialQueue.waitForIdle();
return waitForSequentialQueueIdle();
}

/**
Expand Down
2 changes: 1 addition & 1 deletion src/libs/API/parameters/ResolveDuplicatesParams.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
type ResolveDuplicatesParams = {
/** The ID of the transaction that we want to keep */
transactionID: string;
transactionID: string | undefined;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are you sure that the api call can be called without valid transactionID?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Checked it and looks fine when I am passing undefined I am getting same error from API when passing empty string, which say that there are missing information to proceed


/** The list of other duplicated transactions */
transactionIDList: string[];
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
type VerifyIdentityForBankAccountParams = {
bankAccountID: number;
onfidoData: string;
policyID: string;
policyID: string | undefined;
};
export default VerifyIdentityForBankAccountParams;
39 changes: 20 additions & 19 deletions src/libs/DistanceRequestUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@ import type {LastSelectedDistanceRates, OnyxInputOrEntry, Report, Transaction} f
import type {Unit} from '@src/types/onyx/Policy';
import type Policy from '@src/types/onyx/Policy';
import {isEmptyObject} from '@src/types/utils/EmptyObject';
import * as CurrencyUtils from './CurrencyUtils';
import * as PolicyUtils from './PolicyUtils';
import * as ReportUtils from './ReportUtils';
import * as TransactionUtils from './TransactionUtils';
import {getCurrencySymbol} from './CurrencyUtils';
import {getDistanceRateCustomUnit, getDistanceRateCustomUnitRate, getPersonalPolicy, getPolicy, getUnitRateValue} from './PolicyUtils';
import {isPolicyExpenseChat} from './ReportUtils';
import {getCurrency, getRateID, isCustomUnitRateIDForP2P} from './TransactionUtils';

type MileageRate = {
customUnitRateID?: string;
Expand Down Expand Up @@ -48,7 +48,7 @@ function getMileageRates(policy: OnyxInputOrEntry<Policy>, includeDisabledRates
return mileageRates;
}

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

const distanceUnit = PolicyUtils.getDistanceRateCustomUnit(policy);
const distanceUnit = getDistanceRateCustomUnit(policy);
if (!distanceUnit?.rates || !distanceUnit.attributes) {
return;
}
Expand Down Expand Up @@ -162,9 +162,9 @@ function getRateForDisplay(
}

const singularDistanceUnit = unit === CONST.CUSTOM_UNITS.DISTANCE_UNIT_MILES ? translate('common.mile') : translate('common.kilometer');
const formattedRate = PolicyUtils.getUnitRateValue(toLocaleDigit, {rate}, useShortFormUnit);
const formattedRate = getUnitRateValue(toLocaleDigit, {rate}, useShortFormUnit);
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
const currencySymbol = CurrencyUtils.getCurrencySymbol(currency) || `${currency} `;
const currencySymbol = getCurrencySymbol(currency) || `${currency} `;

return `${currencySymbol}${formattedRate} / ${useShortFormUnit ? unit : singularDistanceUnit}`;
}
Expand Down Expand Up @@ -250,7 +250,7 @@ function getRateForP2P(currency: string, transaction: OnyxEntry<Transaction>): M
ensureRateDefined(mileageRate.rate);

// Ensure the rate is updated when the currency changes, otherwise use the stored rate
const rate = TransactionUtils.getCurrency(transaction) === currency ? transaction?.comment?.customUnit?.defaultP2PRate ?? mileageRate.rate : mileageRate.rate;
const rate = getCurrency(transaction) === currency ? transaction?.comment?.customUnit?.defaultP2PRate ?? mileageRate.rate : mileageRate.rate;
return {
...mileageRate,
currency: currencyWithExistingRate,
Expand Down Expand Up @@ -292,14 +292,14 @@ function convertToDistanceInMeters(distance: number, unit: Unit): number {
function getCustomUnitRateID(reportID: string) {
const report = allReports?.[`${ONYXKEYS.COLLECTION.REPORT}${reportID}`];
const parentReport = allReports?.[`${ONYXKEYS.COLLECTION.REPORT}${report?.parentReportID}`];
const policy = PolicyUtils.getPolicy(report?.policyID ?? parentReport?.policyID);
const policy = getPolicy(report?.policyID ?? parentReport?.policyID);
let customUnitRateID: string = CONST.CUSTOM_UNITS.FAKE_P2P_ID;

if (isEmptyObject(policy)) {
return customUnitRateID;
}

if (ReportUtils.isPolicyExpenseChat(report) || ReportUtils.isPolicyExpenseChat(parentReport)) {
if (isPolicyExpenseChat(report) || isPolicyExpenseChat(parentReport)) {
const distanceUnit = Object.values(policy.customUnits ?? {}).find((unit) => unit.name === CONST.CUSTOM_UNITS.NAME_DISTANCE);
const lastSelectedDistanceRateID = lastSelectedDistanceRates?.[policy.id];
const lastSelectedDistanceRate = lastSelectedDistanceRateID ? distanceUnit?.rates[lastSelectedDistanceRateID] : undefined;
Expand All @@ -321,15 +321,15 @@ function getCustomUnitRateID(reportID: string) {
* 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.getDistanceRateCustomUnit(policy);
const customUnitRate = PolicyUtils.getDistanceRateCustomUnitRate(policy, customUnitRateID);
if (!distanceUnit || !distanceUnit?.customUnitID || !customUnitRate) {
const distanceUnit = getDistanceRateCustomUnit(policy);
const customUnitRate = getDistanceRateCustomUnitRate(policy, customUnitRateID);
if (!distanceUnit?.customUnitID || !customUnitRate) {
return 0;
}
const unit = distanceUnit?.attributes?.unit ?? CONST.CUSTOM_UNITS.DISTANCE_UNIT_MILES;
const rate = customUnitRate?.rate ?? 0;
const rate = customUnitRate?.rate ?? CONST.DEFAULT_NUMBER_ID;
const amount = getDistanceRequestAmount(distance, unit, rate);
const taxClaimablePercentage = customUnitRate.attributes?.taxClaimablePercentage ?? 0;
const taxClaimablePercentage = customUnitRate.attributes?.taxClaimablePercentage ?? CONST.DEFAULT_NUMBER_ID;
return amount * taxClaimablePercentage;
}

Expand All @@ -356,10 +356,11 @@ function getRate({
if (isEmptyObject(mileageRates) && policyDraft) {
mileageRates = getMileageRates(policyDraft, true, transaction?.comment?.customUnit?.customUnitRateID);
}
const policyCurrency = policy?.outputCurrency ?? PolicyUtils.getPersonalPolicy()?.outputCurrency ?? CONST.CURRENCY.USD;
const policyCurrency = policy?.outputCurrency ?? getPersonalPolicy()?.outputCurrency ?? CONST.CURRENCY.USD;
const defaultMileageRate = getDefaultMileageRate(policy);
const customUnitRateID = TransactionUtils.getRateID(transaction) ?? '';
const mileageRate = TransactionUtils.isCustomUnitRateIDForP2P(transaction) ? getRateForP2P(policyCurrency, transaction) : mileageRates?.[customUnitRateID] ?? defaultMileageRate;
const customUnitRateID = getRateID(transaction);
const customMileageRate = customUnitRateID ? mileageRates?.[customUnitRateID] : defaultMileageRate;
const mileageRate = isCustomUnitRateIDForP2P(transaction) ? getRateForP2P(policyCurrency, transaction) : customMileageRate;
const unit = getDistanceUnit(useTransactionDistanceUnit ? transaction : undefined, mileageRate);
return {
...mileageRate,
Expand Down
Loading
Loading