diff --git a/src/components/MoneyRequestConfirmationList.tsx b/src/components/MoneyRequestConfirmationList.tsx index 13eb788d7e92..22c6c22be717 100755 --- a/src/components/MoneyRequestConfirmationList.tsx +++ b/src/components/MoneyRequestConfirmationList.tsx @@ -53,6 +53,7 @@ import { getTaxValue, hasMissingSmartscanFields, hasRoute as hasRouteUtil, + hasTaxRateWithMatchingValue, isMerchantMissing, isScanRequest as isScanRequestUtil, } from '@libs/TransactionUtils'; @@ -439,6 +440,7 @@ function MoneyRequestConfirmationList({ category: iouCategory, tag: getTag(transaction), taxCode: transaction?.taxCode, + taxValue: transaction?.taxValue, policyCategories, policyTagLists: policyTags, policyTaxRates: policy?.taxRates?.taxes, @@ -1017,7 +1019,7 @@ function MoneyRequestConfirmationList({ return; } - if (shouldShowTax && !!transaction.taxCode && !Object.keys(policy?.taxRates?.taxes ?? {}).some((key) => key === transaction.taxCode)) { + if (shouldShowTax && !!transaction.taxCode && !hasTaxRateWithMatchingValue(policy, transaction)) { setFormError('violations.taxOutOfPolicy'); return; } diff --git a/src/components/MoneyRequestConfirmationListFooter.tsx b/src/components/MoneyRequestConfirmationListFooter.tsx index 0aa71dbcdef0..61810fb55d90 100644 --- a/src/components/MoneyRequestConfirmationListFooter.tsx +++ b/src/components/MoneyRequestConfirmationListFooter.tsx @@ -34,7 +34,7 @@ import {getTagVisibility, hasEnabledTags} from '@libs/TagsOptionsListUtils'; import { getTagForDisplay, getTaxAmount, - getTaxName, + getTaxRateTitle, isAmountMissing, isCreatedMissing, isFetchingWaypointsFromServer, @@ -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'; diff --git a/src/libs/TransactionUtils/index.ts b/src/libs/TransactionUtils/index.ts index 2348aad087b7..b656bde1d0ba 100644 --- a/src/libs/TransactionUtils/index.ts +++ b/src/libs/TransactionUtils/index.ts @@ -2180,6 +2180,47 @@ function getTaxName(policy: OnyxEntry, transaction: OnyxEntry, transaction: OnyxEntry) { + 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, transaction: OnyxEntry, isMovingFromTrackExpense: boolean, policyForMovingExpenses?: OnyxEntry): string { + const currentTaxName = getTaxName(policy, transaction); + + 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>; type FieldsToChange = { category?: Array; @@ -2758,6 +2799,8 @@ export { transformedTaxRates, getTaxValue, getTaxName, + getTaxRateTitle, + hasTaxRateWithMatchingValue, getEnabledTaxRateCount, getUpdatedTransaction, getClearedPendingFields, diff --git a/src/libs/Violations/ViolationsUtils.ts b/src/libs/Violations/ViolationsUtils.ts index 94ffd0fb4aab..f9da781e2b1c 100644 --- a/src/libs/Violations/ViolationsUtils.ts +++ b/src/libs/Violations/ViolationsUtils.ts @@ -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 boolean> = { [`${CONST.VIOLATIONS_PREFIX}${CONST.VIOLATIONS.CATEGORY_OUT_OF_POLICY}`]: () => { @@ -267,8 +267,15 @@ function getIsViolationFixed(violationError: string, params: ViolationFixParams) return hasEnabledTags && hasMatchingTag; }, [`${CONST.VIOLATIONS_PREFIX}${CONST.VIOLATIONS.TAX_OUT_OF_POLICY}`]: () => { - // 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 diff --git a/src/libs/Violations/types.ts b/src/libs/Violations/types.ts index cd68502afb8f..e94e3514e0c5 100644 --- a/src/libs/Violations/types.ts +++ b/src/libs/Violations/types.ts @@ -1,4 +1,4 @@ -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'; @@ -6,9 +6,11 @@ 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; policyCategories: PolicyCategories | undefined; policyTagLists: PolicyTagLists | undefined; - policyTaxRates: Record | undefined; + policyTaxRates: TaxRates | undefined; iouAttendees: Attendee[] | undefined; currentUserPersonalDetails: CurrentUserPersonalDetails; isAttendeeTrackingEnabled: boolean | undefined; diff --git a/src/libs/actions/IOU/index.ts b/src/libs/actions/IOU/index.ts index c568914379c2..72ecf7db4923 100644 --- a/src/libs/actions/IOU/index.ts +++ b/src/libs/actions/IOU/index.ts @@ -12383,6 +12383,16 @@ function setMoneyRequestTaxAmount(transactionID: string, taxAmount: number | nul 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, @@ -12951,7 +12961,7 @@ function prepareRejectMoneyRequestData( movedToReport = existingOpenReport; rejectedToReportID = existingOpenReport.reportID; - const [, , iouAction, ,] = buildOptimisticMoneyRequestEntities({ + const [, , iouAction] = buildOptimisticMoneyRequestEntities({ iouReport: movedToReport, type: CONST.IOU.REPORT_ACTION_TYPE.CREATE, amount: transactionAmount, @@ -13042,7 +13052,7 @@ function prepareRejectMoneyRequestData( reportTransactions, betas, }); - const [, createdActionForExpenseReport, iouAction, ,] = buildOptimisticMoneyRequestEntities({ + const [, createdActionForExpenseReport, iouAction] = buildOptimisticMoneyRequestEntities({ iouReport: newExpenseReport, type: CONST.IOU.REPORT_ACTION_TYPE.CREATE, amount: transactionAmount, @@ -13840,6 +13850,7 @@ export { setMoneyRequestTag, setMoneyRequestTaxAmount, setMoneyRequestTaxRate, + setMoneyRequestTaxRateValues, startMoneyRequest, submitReport, trackExpense, diff --git a/src/pages/iou/request/step/IOURequestStepTaxRatePage.tsx b/src/pages/iou/request/step/IOURequestStepTaxRatePage.tsx index 673e64af8f1d..3de9660328cb 100644 --- a/src/pages/iou/request/step/IOURequestStepTaxRatePage.tsx +++ b/src/pages/iou/request/step/IOURequestStepTaxRatePage.tsx @@ -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'; @@ -62,6 +64,7 @@ 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); @@ -69,7 +72,7 @@ function IOURequestStepTaxRatePage({ Navigation.goBack(backTo); }; - const taxRateTitle = getTaxName(policy, currentTransaction); + const taxRateTitle = getTaxRateTitle(policy, currentTransaction, isMovingTransactionFromTrackExpense(action), policyForMovingExpenses); const currency = getCurrency(currentTransaction); const decimals = getCurrencyDecimals(currency); @@ -86,6 +89,7 @@ function IOURequestStepTaxRatePage({ setDraftSplitTransaction(currentTransaction.transactionID, splitDraftTransaction, { taxAmount: convertToBackendAmount(taxAmount ?? 0), taxCode: taxes.code, + taxValue, }); navigateBack(); return; @@ -117,8 +121,8 @@ function IOURequestStepTaxRatePage({ return; } const amountInSmallestCurrencyUnits = convertToBackendAmount(taxAmount); - setMoneyRequestTaxRate(currentTransaction?.transactionID, taxes?.code ?? ''); - setMoneyRequestTaxAmount(currentTransaction.transactionID, amountInSmallestCurrencyUnits); + + setMoneyRequestTaxRateValues(currentTransaction.transactionID, {taxCode: taxes?.code ?? '', taxAmount: amountInSmallestCurrencyUnits, taxValue}); navigateBack(); }; diff --git a/tests/unit/TransactionUtilsTest.ts b/tests/unit/TransactionUtilsTest.ts index 5a4283fd5f49..6bfde9a1217d 100644 --- a/tests/unit/TransactionUtilsTest.ts +++ b/tests/unit/TransactionUtilsTest.ts @@ -1801,6 +1801,158 @@ describe('TransactionUtils', () => { }); }); + describe('hasTaxRateWithMatchingValue', () => { + const policy: Policy = { + ...createRandomPolicy(0), + taxRates: CONST.DEFAULT_TAX, + }; + + it('should return true when transaction has no taxValue and a matching tax rate exists', () => { + const transaction = generateTransaction({ + taxCode: 'id_TAX_RATE_1', + taxValue: undefined, + }); + + const result = TransactionUtils.hasTaxRateWithMatchingValue(policy, transaction); + + expect(result).toBe(true); + }); + + it('should return false when transaction has no taxValue and no matching tax rate exists', () => { + const transaction = generateTransaction({ + taxCode: 'id_CUSTOM', + taxValue: undefined, + }); + + const result = TransactionUtils.hasTaxRateWithMatchingValue(policy, transaction); + + expect(result).toBe(false); + }); + + it('should return true when transaction has taxValue and the tax rate value matches exactly', () => { + const transaction = generateTransaction({ + taxCode: 'id_TAX_RATE_1', + taxValue: '5%', + }); + + const result = TransactionUtils.hasTaxRateWithMatchingValue(policy, transaction); + + expect(result).toBe(true); + }); + + it('should return false when transaction has taxValue but the tax rate value does not match', () => { + const transaction = generateTransaction({ + taxCode: 'id_TAX_RATE_1', + taxValue: '15%', + }); + + const result = TransactionUtils.hasTaxRateWithMatchingValue(policy, transaction); + + expect(result).toBe(false); + }); + + it('should return false when policy is undefined', () => { + const transaction = generateTransaction({ + taxCode: 'id_TAX_RATE_1', + taxValue: '10%', + }); + + const result = TransactionUtils.hasTaxRateWithMatchingValue(undefined, transaction); + + expect(result).toBe(false); + }); + + it('should return false when transaction is undefined', () => { + const result = TransactionUtils.hasTaxRateWithMatchingValue(policy, undefined); + + expect(result).toBe(false); + }); + + it('should return false when both policy and transaction are undefined', () => { + const result = TransactionUtils.hasTaxRateWithMatchingValue(undefined, undefined); + + expect(result).toBe(false); + }); + }); + + describe('getTaxRateTitle', () => { + const policy: Policy = { + ...createRandomPolicy(0), + taxRates: CONST.DEFAULT_TAX, + }; + + const policyForMovingExpenses: Policy = { + ...createRandomPolicy(1), + taxRates: { + ...CONST.DEFAULT_TAX, + taxes: { + ...CONST.DEFAULT_TAX.taxes, + // eslint-disable-next-line @typescript-eslint/naming-convention + id_TAX_RATE_1: { + name: 'Tax Rate 1 - Default Policy', + value: '15%', + code: 'id_TAX_RATE_1', + }, + }, + }, + }; + + it('should return tax name with fallback when tax exists and not moving from track expense', () => { + const transaction = generateTransaction({ + taxCode: 'id_TAX_RATE_1', + taxValue: '5%', + }); + + const result = TransactionUtils.getTaxRateTitle(policy, transaction, false, undefined); + + expect(result).toBe('Tax Rate 1 (5%)'); + }); + + it('should return default policy tax name when moving from track expense', () => { + const transaction = generateTransaction({ + taxCode: 'id_TAX_RATE_1', + taxValue: '15%', + }); + + const result = TransactionUtils.getTaxRateTitle(policy, transaction, true, policyForMovingExpenses); + + expect(result).toBe('Tax Rate 1 - Default Policy (15%)'); + }); + + it('should return chosen policy tax name with fallback when moving from track expense but tax rate value is the same', () => { + const transaction = generateTransaction({ + taxCode: 'id_TAX_RATE_1', + taxValue: '5%', + }); + + const result = TransactionUtils.getTaxRateTitle(policy, transaction, true, policyForMovingExpenses); + + expect(result).toBe('Tax Rate 1 (5%)'); + }); + + it('should return default tax name when transaction has empty taxCode', () => { + const transaction = generateTransaction({ + taxCode: '', + taxValue: undefined, + }); + + const result = TransactionUtils.getTaxRateTitle(policy, transaction, false, undefined); + + expect(result).toBe('Tax exempt (0%) • Default'); + }); + + it('should return empty string when policy is undefined', () => { + const transaction = generateTransaction({ + taxCode: 'id_TAX_RATE_1', + taxValue: '10%', + }); + + const result = TransactionUtils.getTaxRateTitle(undefined, transaction, false, undefined); + + expect(result).toBe(''); + }); + }); + describe('compareDuplicateTransactionFields', () => { const fakeReportID = 'fakeReportID'; const fakeReport = { diff --git a/tests/unit/ViolationUtilsTest.ts b/tests/unit/ViolationUtilsTest.ts index f5745ad45f52..fc83bdfe0588 100644 --- a/tests/unit/ViolationUtilsTest.ts +++ b/tests/unit/ViolationUtilsTest.ts @@ -1631,6 +1631,16 @@ describe('getIsViolationFixed', () => { }); expect(result).toBe(true); }); + + it("should return false when taxCodes match but the taxValues doesn't", () => { + const result = getIsViolationFixed('violations.taxOutOfPolicy', { + ...defaultParams, + taxCode: 'CUSTOM_TAX', + taxValue: '15', + policyTaxRates: {CUSTOM_TAX: {name: '10%', value: '10'}}, + }); + expect(result).toBe(false); + }); }); describe('violations.missingAttendees', () => {