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
42 changes: 16 additions & 26 deletions src/libs/MoneyRequestUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,9 @@ import type {ValueOf} from 'type-fest';

import {convertToBackendAmount, convertToFrontendAmountAsInteger} from './CurrencyUtils';
import replaceAllDigits from './replaceAllDigits';
import {isInvoiceReport, isIOUReport} from './ReportUtils';
import StringUtils from './StringUtils';
import {isExpenseReport, isExpenseRequest, isPolicyExpenseChat} from './ReportUtils';
import {doesMoneyRequestDraftHaveUserInput, haveWaypointAddressesChanged, isExpenseUnreported} from './TransactionUtils';
import {isInvalidMerchantValue} from './ValidationUtils';
import {getMerchantError} from './ValidationUtils';

/**
* Strip comma from the amount
Expand Down Expand Up @@ -159,6 +158,18 @@ function isTaxAmountInvalid(currentAmount: string, maxTaxAmount: number, decimal
return Number.parseFloat(currentAmount) > convertToFrontendAmountAsInteger(Math.abs(maxTaxAmount), decimals);
}

/**
* Determines whether a merchant value is required for the given report/transaction — i.e. whether leaving the
* merchant empty is disallowed. Workspace expenses require a merchant; unreported expenses, IOU requests,
* and invoices allow an empty merchant.
*/
function isMerchantRequired(report: OnyxEntry<Report>, transaction: OnyxEntry<Transaction>): boolean {
if (transaction && isExpenseUnreported(transaction)) {
return false;
}
return isExpenseReport(report) || isPolicyExpenseChat(report) || isExpenseRequest(report) || !!transaction?.participants?.some((participant) => !!participant.isPolicyExpenseChat);
}

/**
* Validates a merchant value according to business rules.
*
Expand All @@ -168,29 +179,7 @@ function isTaxAmountInvalid(currentAmount: string, maxTaxAmount: number, decimal
* @returns Whether the merchant value is valid
*/
function isValidMerchant(merchant: string | undefined, transaction?: OnyxEntry<Transaction>, report?: OnyxEntry<Report>): boolean {
const trimmedMerchant = merchant?.trim() ?? '';
const isEmpty = !trimmedMerchant;

// Unreported expenses, IOU requests, and invoices can have empty merchants (allows clearing)
const isUnreported = transaction ? isExpenseUnreported(transaction) : false;
const isIOU = !!report && isIOUReport(report);
const isInvoice = !!report && isInvoiceReport(report);
if (isEmpty && (isUnreported || isIOU || isInvoice)) {
return true;
}

// Reported transactions or non-empty merchants must pass validation
if (isEmpty) {
return false;
}

// Check if it's an invalid merchant value (PARTIAL or DEFAULT constants)
if (isInvalidMerchantValue(trimmedMerchant)) {
return false;
}

const valueByteLength = StringUtils.getUTF8ByteLength(trimmedMerchant);
return valueByteLength <= CONST.MERCHANT_NAME_MAX_BYTES;
return !getMerchantError(merchant, isMerchantRequired(report, transaction));
}

type AmountHasUnsavedChangesParams = {
Expand Down Expand Up @@ -262,6 +251,7 @@ export {
handleNegativeAmountFlipping,
isValidMoneyRequestAmount,
isTaxAmountInvalid,
isMerchantRequired,
isValidMerchant,
getAmountHasUnsavedChanges,
getStringFieldHasUnsavedChanges,
Expand Down
22 changes: 22 additions & 0 deletions src/libs/ValidationUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -818,6 +818,27 @@ function isInvalidMerchantValue(merchant?: string): boolean {
return merchant === '' || merchant === CONST.TRANSACTION.PARTIAL_TRANSACTION_MERCHANT || merchant === CONST.TRANSACTION.DEFAULT_MERCHANT;
}

type MerchantValidationError = {type: 'required'} | {type: 'invalidValue'} | {type: 'tooLong'; byteLength: number};

/**
* Returns the first merchant validation error (required, invalid value, or too long), or `undefined` if the merchant is valid.
*/
function getMerchantError(merchant: string | undefined, isMerchantRequired: boolean): MerchantValidationError | undefined {
const trimmedMerchant = merchant?.trim() ?? '';

if (isMerchantRequired && !trimmedMerchant) {
return {type: 'required'};
}
if (trimmedMerchant && isInvalidMerchantValue(trimmedMerchant)) {
return {type: 'invalidValue'};
}
const {isValid: isLengthValid, byteLength} = isValidInputLength(trimmedMerchant, CONST.MERCHANT_NAME_MAX_BYTES);
if (!isLengthValid) {
return {type: 'tooLong', byteLength};
}
return undefined;
}

/**
* Checks if a merchant is a placeholder the user never typed: the flow seeded the "Expense" / "(none)" value,
* so it should be treated as empty rather than as an invalid entry the user is responsible for.
Expand Down Expand Up @@ -934,6 +955,7 @@ export {
isValidInputLength,
isValidTaxIDEINNumber,
isInvalidMerchantValue,
getMerchantError,
isUntypedPlaceholderMerchant,
isValidPIN,
containsHtmlTag,
Expand Down
20 changes: 10 additions & 10 deletions src/pages/iou/request/step/DynamicIOURequestStepMerchant.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,10 @@ import useThemeStyles from '@hooks/useThemeStyles';

import focusComposerWithDelay from '@libs/focusComposerWithDelay';
import getNonEmptyStringOnyxID from '@libs/getNonEmptyStringOnyxID';
import {getTransactionDetails, isExpenseRequest, isPolicyExpenseChat} from '@libs/ReportUtils';
import {isMerchantRequired} from '@libs/MoneyRequestUtils';
import {getTransactionDetails} from '@libs/ReportUtils';
import {hasReceipt} from '@libs/TransactionUtils';
import {isInvalidMerchantValue, isValidInputLength} from '@libs/ValidationUtils';
import {getMerchantError, isInvalidMerchantValue} from '@libs/ValidationUtils';

import {clearMoneyRequestMerchant, setMoneyRequestMerchant} from '@userActions/IOU/MoneyRequest';
import {setDraftSplitTransaction} from '@userActions/IOU/Split';
Expand Down Expand Up @@ -90,27 +91,26 @@ function DynamicIOURequestStepMerchant({
const isASAPSubmitBetaEnabled = isBetaEnabled(CONST.BETAS.ASAP_SUBMIT);
const {isOffline} = useNetwork();

const isMerchantRequired = isPolicyExpenseChat(report) || isExpenseRequest(report) || transaction?.participants?.some((participant) => !!participant.isPolicyExpenseChat);
const isMerchantFieldRequired = isMerchantRequired(report, transaction);

const {navigateBack, armNavigateBack} = useNavigateBackOnSave(isSaved, backPath);

const validate = useCallback(
(value: FormOnyxValues<typeof ONYXKEYS.FORMS.MONEY_REQUEST_MERCHANT_FORM>) => {
const errors: FormInputErrors<typeof ONYXKEYS.FORMS.MONEY_REQUEST_MERCHANT_FORM> = {};
const {isValid, byteLength} = isValidInputLength(value.moneyRequestMerchant, CONST.MERCHANT_NAME_MAX_BYTES);
const merchantError = getMerchantError(value.moneyRequestMerchant, isMerchantFieldRequired);

const trimmedMerchant = value.moneyRequestMerchant?.trim();
if (isMerchantRequired && !trimmedMerchant) {
if (merchantError?.type === 'required') {
errors.moneyRequestMerchant = translate('common.error.fieldRequired');
} else if (trimmedMerchant && isInvalidMerchantValue(trimmedMerchant)) {
} else if (merchantError?.type === 'invalidValue') {
errors.moneyRequestMerchant = translate('iou.error.invalidMerchant');
} else if (!isValid) {
errors.moneyRequestMerchant = translate('common.error.characterLimitExceedCounter', byteLength, CONST.MERCHANT_NAME_MAX_BYTES);
} else if (merchantError?.type === 'tooLong') {
errors.moneyRequestMerchant = translate('common.error.characterLimitExceedCounter', merchantError.byteLength, CONST.MERCHANT_NAME_MAX_BYTES);
}

return errors;
},
[isMerchantRequired, translate],
[isMerchantFieldRequired, translate],
);

const updateMerchantRef = (value: string) => {
Expand Down
9 changes: 6 additions & 3 deletions tests/unit/MoneyRequestUtilsTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -297,12 +297,15 @@ describe('ReportActionsUtils', () => {
expect(isValidMerchant(undefined, reportedTransaction, iouReport)).toBe(true);
});

it('should return false for empty/undefined merchant when transaction is reported or missing', () => {
expect(isValidMerchant('', reportedTransaction)).toBe(false);
it('should return true for empty/undefined merchant when the report is missing, matching the normal edit flow', () => {
expect(isValidMerchant('', reportedTransaction)).toBe(true);
expect(isValidMerchant('')).toBe(true);
});

it('should return false for empty/undefined merchant on an expense report', () => {
expect(isValidMerchant('', reportedTransaction, expenseReport)).toBe(false);
expect(isValidMerchant(' ', reportedTransaction, expenseReport)).toBe(false);
expect(isValidMerchant(undefined, reportedTransaction, expenseReport)).toBe(false);
expect(isValidMerchant('')).toBe(false);
});
});

Expand Down
Loading