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
4 changes: 3 additions & 1 deletion src/components/MoneyRequestConfirmationList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ import {
getTaxValue,
hasMissingSmartscanFields,
hasRoute as hasRouteUtil,
hasTaxRateWithMatchingValue,
isMerchantMissing,
isScanRequest as isScanRequestUtil,
} from '@libs/TransactionUtils';
Expand Down Expand Up @@ -439,6 +440,7 @@ function MoneyRequestConfirmationList({
category: iouCategory,
tag: getTag(transaction),
taxCode: transaction?.taxCode,
taxValue: transaction?.taxValue,
policyCategories,
policyTagLists: policyTags,
policyTaxRates: policy?.taxRates?.taxes,
Expand Down Expand Up @@ -1017,7 +1019,7 @@ function MoneyRequestConfirmationList({
return;
}
Comment thread
koko57 marked this conversation as resolved.
Resolved

if (shouldShowTax && !!transaction.taxCode && !Object.keys(policy?.taxRates?.taxes ?? {}).some((key) => key === transaction.taxCode)) {
if (shouldShowTax && !!transaction.taxCode && !hasTaxRateWithMatchingValue(policy, transaction)) {
setFormError('violations.taxOutOfPolicy');
Comment thread
koko57 marked this conversation as resolved.
Resolved
return;
}
Expand Down
12 changes: 3 additions & 9 deletions src/components/MoneyRequestConfirmationListFooter.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ import {getTagVisibility, hasEnabledTags} from '@libs/TagsOptionsListUtils';
import {
getTagForDisplay,
getTaxAmount,
getTaxName,
getTaxRateTitle,
isAmountMissing,
isCreatedMissing,
isFetchingWaypointsFromServer,
Expand Down Expand Up @@ -418,14 +418,8 @@ function MoneyRequestConfirmationListFooter({
const taxAmount = getTaxAmount(transaction, false);
const formattedTaxAmount = convertToDisplayString(taxAmount, iouCurrencyCode);
// Get the tax rate title based on the policy and transaction
let taxRateTitle;
if (getTaxName(policy, transaction)) {
taxRateTitle = getTaxName(policy, transaction);
} else if (isMovingCurrentTransactionFromTrackExpense) {
taxRateTitle = getTaxName(policyForMovingExpenses, transaction);
} else {
taxRateTitle = '';
}
const taxRateTitle = getTaxRateTitle(policy, transaction, isMovingCurrentTransactionFromTrackExpense, policyForMovingExpenses);

// Determine if the merchant error should be displayed
const shouldDisplayMerchantError = isMerchantRequired && (shouldDisplayFieldError || formError === 'iou.error.invalidMerchant') && isMerchantEmpty;
const shouldDisplayDistanceRateError = formError === 'iou.error.invalidRate';
Expand Down
43 changes: 43 additions & 0 deletions src/libs/TransactionUtils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2180,6 +2180,47 @@ function getTaxName(policy: OnyxEntry<Policy>, transaction: OnyxEntry<Transactio
return taxRate?.modifiedName;
}

/**
* Checks if the tax rate with matching transaction's tax rate value exists in the policy tax rates
*/
function hasTaxRateWithMatchingValue(policy: OnyxEntry<Policy>, transaction: OnyxEntry<Transaction>) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

❌ PERF-2 (docs)

The function performs expensive work (transformedTaxRates() and Object.values().find()) before checking if transaction?.taxValue exists. This validation should happen earlier to avoid wasted computation.

Suggested fix:

function hasTaxRateWithMatchingValue(policy: OnyxEntry<Policy>, transaction: OnyxEntry<Transaction>) {
    const transactionTaxCode = getTaxCode(transaction);
    const transactionTaxValue = transaction?.taxValue;
    
    // Early return: if no tax code, no point in checking rates
    if (!transactionTaxCode) {
        return false;
    }
    
    const taxRate = Object.values(transformedTaxRates(policy, transaction)).find((rate) => rate.code === transactionTaxCode);
    
    if (!transactionTaxValue) {
        return !!taxRate;
    }
    
    return taxRate?.value === transactionTaxValue;
}

Please rate this suggestion with 👍 or 👎 to help us improve! Reactions are used to monitor reviewer efficiency.

Comment thread
koko57 marked this conversation as resolved.
Resolved
Comment thread
koko57 marked this conversation as resolved.
Resolved
if (!policy || !transaction) {
return false;
}

const transactionTaxCode = getTaxCode(transaction);
const transformedRates = transformedTaxRates(policy, transaction);
const taxRate = Object.values(transformedRates).find((rate) => rate.code === transactionTaxCode);

if (!transaction?.taxValue) {
return !!taxRate;
}

return taxRate?.value === transaction?.taxValue;
}

/**
* Gets the tax rate title for display, handling the case when moving expenses from track to submit
*/
function getTaxRateTitle(policy: OnyxEntry<Policy>, transaction: OnyxEntry<Transaction>, isMovingFromTrackExpense: boolean, policyForMovingExpenses?: OnyxEntry<Policy>): string {
Comment thread
koko57 marked this conversation as resolved.
Resolved
const currentTaxName = getTaxName(policy, transaction);
Comment thread
koko57 marked this conversation as resolved.
Resolved

if (currentTaxName) {
// If moving from track expense show the tax name from the moving policy
if (isMovingFromTrackExpense && !hasTaxRateWithMatchingValue(policy, transaction)) {
return getTaxName(policyForMovingExpenses, transaction) ?? '';
}
return getTaxName(policy, transaction, true) ?? '';
}

// If no tax name on current policy but moving from track expense, use the moving policy
if (isMovingFromTrackExpense) {
return getTaxName(policyForMovingExpenses, transaction, true) ?? '';
}

return '';
}

type FieldsToCompare = Record<string, Array<keyof Transaction>>;
type FieldsToChange = {
category?: Array<string | undefined>;
Expand Down Expand Up @@ -2758,6 +2799,8 @@ export {
transformedTaxRates,
getTaxValue,
getTaxName,
getTaxRateTitle,
hasTaxRateWithMatchingValue,
getEnabledTaxRateCount,
getUpdatedTransaction,
getClearedPendingFields,
Expand Down
13 changes: 10 additions & 3 deletions src/libs/Violations/ViolationsUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,7 @@ function extractErrorMessages(errors: Errors | ReceiptErrors, errorActions: Repo
* Returns true if the violation should be cleared, false if it should persist.
*/
function getIsViolationFixed(violationError: string, params: ViolationFixParams): boolean {
const {category, tag, taxCode, policyCategories, policyTagLists, policyTaxRates, iouAttendees, currentUserPersonalDetails, isAttendeeTrackingEnabled, isControlPolicy} = params;
const {category, tag, taxCode, taxValue, policyCategories, policyTagLists, policyTaxRates, iouAttendees, currentUserPersonalDetails, isAttendeeTrackingEnabled, isControlPolicy} = params;

const violationValidators: Record<string, () => boolean> = {
[`${CONST.VIOLATIONS_PREFIX}${CONST.VIOLATIONS.CATEGORY_OUT_OF_POLICY}`]: () => {
Expand All @@ -267,8 +267,15 @@ function getIsViolationFixed(violationError: string, params: ViolationFixParams)
return hasEnabledTags && hasMatchingTag;
},
[`${CONST.VIOLATIONS_PREFIX}${CONST.VIOLATIONS.TAX_OUT_OF_POLICY}`]: () => {
Comment thread
koko57 marked this conversation as resolved.
Resolved
// Tax is fixed if it's empty or exists in policy tax rates
return !taxCode || Object.keys(policyTaxRates ?? {}).some((key) => key === taxCode);
if (!taxCode || !policyTaxRates) {
return !taxCode;
}
const matchingTaxRate = policyTaxRates[taxCode];
if (!matchingTaxRate) {
return false;
}
// If taxValue is provided, check that it matches the policy tax rate. If taxValue is not provided, just check that the tax code exists in the policy.
return taxValue !== undefined ? matchingTaxRate.value === taxValue : true;
},
[`${CONST.VIOLATIONS_PREFIX}${CONST.VIOLATIONS.MISSING_ATTENDEES}`]: () => {
// Attendees violation is fixed if getIsMissingAttendeesViolation returns false
Expand Down
6 changes: 4 additions & 2 deletions src/libs/Violations/types.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
import type {PolicyCategories, PolicyTagLists} from '@src/types/onyx';
import type {PolicyCategories, PolicyTagLists, TaxRates} from '@src/types/onyx';
import type {Attendee} from '@src/types/onyx/IOU';
import type {CurrentUserPersonalDetails} from '@src/types/onyx/PersonalDetails';

type ViolationFixParams = {
category: string;
tag: string;
taxCode: string | undefined;
/** Tax value as a percentage string (e.g., "5%", "10%") or undefined if not set */
taxValue?: string;
Comment thread
koko57 marked this conversation as resolved.
Resolved
policyCategories: PolicyCategories | undefined;
policyTagLists: PolicyTagLists | undefined;
policyTaxRates: Record<string, unknown> | undefined;
policyTaxRates: TaxRates | undefined;
iouAttendees: Attendee[] | undefined;
currentUserPersonalDetails: CurrentUserPersonalDetails;
isAttendeeTrackingEnabled: boolean | undefined;
Expand Down
15 changes: 13 additions & 2 deletions src/libs/actions/IOU/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -806,7 +806,7 @@
};

let allPersonalDetails: OnyxTypes.PersonalDetailsList = {};
Onyx.connect({

Check warning on line 809 in src/libs/actions/IOU/index.ts

View workflow job for this annotation

GitHub Actions / Changed files ESLint check

Onyx.connect() is deprecated. Use useOnyx() hook instead and pass the data as parameters to a pure function
key: ONYXKEYS.PERSONAL_DETAILS_LIST,
callback: (value) => {
allPersonalDetails = value ?? {};
Expand Down Expand Up @@ -899,7 +899,7 @@
};

let allTransactions: NonNullable<OnyxCollection<OnyxTypes.Transaction>> = {};
Onyx.connect({

Check warning on line 902 in src/libs/actions/IOU/index.ts

View workflow job for this annotation

GitHub Actions / Changed files ESLint check

Onyx.connect() is deprecated. Use useOnyx() hook instead and pass the data as parameters to a pure function
key: ONYXKEYS.COLLECTION.TRANSACTION,
waitForCollectionCallback: true,
callback: (value) => {
Expand All @@ -913,7 +913,7 @@
});

let allTransactionDrafts: NonNullable<OnyxCollection<OnyxTypes.Transaction>> = {};
Onyx.connect({

Check warning on line 916 in src/libs/actions/IOU/index.ts

View workflow job for this annotation

GitHub Actions / Changed files ESLint check

Onyx.connect() is deprecated. Use useOnyx() hook instead and pass the data as parameters to a pure function
key: ONYXKEYS.COLLECTION.TRANSACTION_DRAFT,
waitForCollectionCallback: true,
callback: (value) => {
Expand All @@ -922,7 +922,7 @@
});

let allTransactionViolations: NonNullable<OnyxCollection<OnyxTypes.TransactionViolations>> = {};
Onyx.connect({

Check warning on line 925 in src/libs/actions/IOU/index.ts

View workflow job for this annotation

GitHub Actions / Changed files ESLint check

Onyx.connect() is deprecated. Use useOnyx() hook instead and pass the data as parameters to a pure function
key: ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS,
waitForCollectionCallback: true,
callback: (value) => {
Expand All @@ -936,7 +936,7 @@
});

let allPolicyTags: OnyxCollection<OnyxTypes.PolicyTagLists> = {};
Onyx.connect({

Check warning on line 939 in src/libs/actions/IOU/index.ts

View workflow job for this annotation

GitHub Actions / Changed files ESLint check

Onyx.connect() is deprecated. Use useOnyx() hook instead and pass the data as parameters to a pure function
key: ONYXKEYS.COLLECTION.POLICY_TAGS,
waitForCollectionCallback: true,
callback: (value) => {
Expand All @@ -949,7 +949,7 @@
});

let allReports: OnyxCollection<OnyxTypes.Report>;
Onyx.connect({

Check warning on line 952 in src/libs/actions/IOU/index.ts

View workflow job for this annotation

GitHub Actions / Changed files ESLint check

Onyx.connect() is deprecated. Use useOnyx() hook instead and pass the data as parameters to a pure function
key: ONYXKEYS.COLLECTION.REPORT,
waitForCollectionCallback: true,
callback: (value) => {
Expand All @@ -958,7 +958,7 @@
});

let allReportNameValuePairs: OnyxCollection<OnyxTypes.ReportNameValuePairs>;
Onyx.connect({

Check warning on line 961 in src/libs/actions/IOU/index.ts

View workflow job for this annotation

GitHub Actions / Changed files ESLint check

Onyx.connect() is deprecated. Use useOnyx() hook instead and pass the data as parameters to a pure function
key: ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS,
waitForCollectionCallback: true,
callback: (value) => {
Expand All @@ -968,7 +968,7 @@

let userAccountID = -1;
let currentUserEmail = '';
Onyx.connect({

Check warning on line 971 in src/libs/actions/IOU/index.ts

View workflow job for this annotation

GitHub Actions / Changed files ESLint check

Onyx.connect() is deprecated. Use useOnyx() hook instead and pass the data as parameters to a pure function
key: ONYXKEYS.SESSION,
callback: (value) => {
currentUserEmail = value?.email ?? '';
Expand All @@ -977,7 +977,7 @@
});

let deprecatedCurrentUserPersonalDetails: OnyxEntry<OnyxTypes.PersonalDetails>;
Onyx.connect({

Check warning on line 980 in src/libs/actions/IOU/index.ts

View workflow job for this annotation

GitHub Actions / Changed files ESLint check

Onyx.connect() is deprecated. Use useOnyx() hook instead and pass the data as parameters to a pure function
key: ONYXKEYS.PERSONAL_DETAILS_LIST,
callback: (value) => {
deprecatedCurrentUserPersonalDetails = value?.[userAccountID] ?? undefined;
Expand All @@ -985,7 +985,7 @@
});

let allReportActions: OnyxCollection<OnyxTypes.ReportActions>;
Onyx.connect({

Check warning on line 988 in src/libs/actions/IOU/index.ts

View workflow job for this annotation

GitHub Actions / Changed files ESLint check

Onyx.connect() is deprecated. Use useOnyx() hook instead and pass the data as parameters to a pure function
key: ONYXKEYS.COLLECTION.REPORT_ACTIONS,
waitForCollectionCallback: true,
callback: (actions) => {
Expand Down Expand Up @@ -12383,6 +12383,16 @@
Onyx.merge(`${isDraft ? ONYXKEYS.COLLECTION.TRANSACTION_DRAFT : ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`, {taxAmount});
}

type TaxRateValues = {
taxCode: string | null;
taxAmount: number | null;
taxValue: string | null;
};

function setMoneyRequestTaxRateValues(transactionID: string, taxRateValues: TaxRateValues, isDraft = true) {
Onyx.merge(`${isDraft ? ONYXKEYS.COLLECTION.TRANSACTION_DRAFT : ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`, {...taxRateValues});
}

// eslint-disable-next-line rulesdir/no-negated-variables
function navigateToStartStepIfScanFileCannotBeRead(
receiptFilename: string | undefined,
Expand Down Expand Up @@ -12951,7 +12961,7 @@
movedToReport = existingOpenReport;
rejectedToReportID = existingOpenReport.reportID;

const [, , iouAction, ,] = buildOptimisticMoneyRequestEntities({
const [, , iouAction] = buildOptimisticMoneyRequestEntities({
iouReport: movedToReport,
type: CONST.IOU.REPORT_ACTION_TYPE.CREATE,
amount: transactionAmount,
Expand Down Expand Up @@ -13042,7 +13052,7 @@
reportTransactions,
betas,
});
const [, createdActionForExpenseReport, iouAction, ,] = buildOptimisticMoneyRequestEntities({
const [, createdActionForExpenseReport, iouAction] = buildOptimisticMoneyRequestEntities({
iouReport: newExpenseReport,
type: CONST.IOU.REPORT_ACTION_TYPE.CREATE,
amount: transactionAmount,
Expand Down Expand Up @@ -13840,6 +13850,7 @@
setMoneyRequestTag,
setMoneyRequestTaxAmount,
setMoneyRequestTaxRate,
setMoneyRequestTaxRateValues,
startMoneyRequest,
submitReport,
trackExpense,
Expand Down
14 changes: 9 additions & 5 deletions src/pages/iou/request/step/IOURequestStepTaxRatePage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,16 @@ import useCurrentUserPersonalDetails from '@hooks/useCurrentUserPersonalDetails'
import useLocalize from '@hooks/useLocalize';
import useOnyx from '@hooks/useOnyx';
import usePermissions from '@hooks/usePermissions';
import usePolicyForMovingExpenses from '@hooks/usePolicyForMovingExpenses';
import usePolicyForTransaction from '@hooks/usePolicyForTransaction';
import useRestartOnReceiptFailure from '@hooks/useRestartOnReceiptFailure';
import {convertToBackendAmount} from '@libs/CurrencyUtils';
import getNonEmptyStringOnyxID from '@libs/getNonEmptyStringOnyxID';
import {isMovingTransactionFromTrackExpense} from '@libs/IOUUtils';
import Navigation from '@libs/Navigation/Navigation';
import type {TaxRatesOption} from '@libs/TaxOptionsListUtils';
import {calculateTaxAmount, getAmount, getCurrency, getTaxName, getTaxValue} from '@libs/TransactionUtils';
import {setMoneyRequestTaxAmount, setMoneyRequestTaxRate, updateMoneyRequestTaxRate} from '@userActions/IOU';
import {calculateTaxAmount, getAmount, getCurrency, getTaxRateTitle, getTaxValue} from '@libs/TransactionUtils';
import {setMoneyRequestTaxRateValues, updateMoneyRequestTaxRate} from '@userActions/IOU';
import {setDraftSplitTransaction} from '@userActions/IOU/Split';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
Expand Down Expand Up @@ -62,14 +64,15 @@ function IOURequestStepTaxRatePage({
const currentUserPersonalDetails = useCurrentUserPersonalDetails();
const currentUserAccountIDParam = currentUserPersonalDetails.accountID;
const currentUserEmailParam = currentUserPersonalDetails.login ?? '';
const {policyForMovingExpenses} = usePolicyForMovingExpenses();
const {isBetaEnabled} = usePermissions();
const isASAPSubmitBetaEnabled = isBetaEnabled(CONST.BETAS.ASAP_SUBMIT);

const navigateBack = () => {
Navigation.goBack(backTo);
};

const taxRateTitle = getTaxName(policy, currentTransaction);
const taxRateTitle = getTaxRateTitle(policy, currentTransaction, isMovingTransactionFromTrackExpense(action), policyForMovingExpenses);
const currency = getCurrency(currentTransaction);
const decimals = getCurrencyDecimals(currency);

Expand All @@ -86,6 +89,7 @@ function IOURequestStepTaxRatePage({
setDraftSplitTransaction(currentTransaction.transactionID, splitDraftTransaction, {
taxAmount: convertToBackendAmount(taxAmount ?? 0),
taxCode: taxes.code,
taxValue,
});
navigateBack();
return;
Expand Down Expand Up @@ -117,8 +121,8 @@ function IOURequestStepTaxRatePage({
return;
Comment thread
koko57 marked this conversation as resolved.
Resolved
}
const amountInSmallestCurrencyUnits = convertToBackendAmount(taxAmount);
setMoneyRequestTaxRate(currentTransaction?.transactionID, taxes?.code ?? '');
setMoneyRequestTaxAmount(currentTransaction.transactionID, amountInSmallestCurrencyUnits);

setMoneyRequestTaxRateValues(currentTransaction.transactionID, {taxCode: taxes?.code ?? '', taxAmount: amountInSmallestCurrencyUnits, taxValue});

navigateBack();
};
Expand Down
Loading
Loading