From 03d3003ea27d7f76144c01d1ee87c2a7582095b9 Mon Sep 17 00:00:00 2001 From: Mukher Date: Fri, 21 Aug 2026 16:10:51 +0500 Subject: [PATCH 1/7] Fix inline category edit not saving on the first attempt On Search surfaces useOnyx resolves a transaction_ read against the search snapshot, but getUpdateMoneyRequestParams read the live TRANSACTION collection, which has no entry for a row the user has not opened. The transaction came back undefined, dataToIncludeInParams came out empty, and UpdateMoneyRequestCategory went out with no category field, clearing any category the expense already had. Pass the transaction the hook already holds down to the write and keep the cache lookup as the fallback so other callers are unaffected. --- src/hooks/useTransactionInlineEdit.ts | 1 + src/libs/actions/IOU/UpdateMoneyRequest.ts | 9 +- src/libs/actions/TransactionInlineEdit.ts | 4 +- .../TransactionInlineEditCategory.test.ts | 110 ++++++++++++++++++ 4 files changed, 122 insertions(+), 2 deletions(-) create mode 100644 tests/unit/inlineEditing/TransactionInlineEditCategory.test.ts diff --git a/src/hooks/useTransactionInlineEdit.ts b/src/hooks/useTransactionInlineEdit.ts index 55f11977f151..ebcace4e93f4 100644 --- a/src/hooks/useTransactionInlineEdit.ts +++ b/src/hooks/useTransactionInlineEdit.ts @@ -178,6 +178,7 @@ function useTransactionInlineEdit({transactionID, hash, linkedReportAction}: Use return { hash, transactionID, + transaction, parentReport: effectiveParentReport, parentReportAction, transactionThreadReport, diff --git a/src/libs/actions/IOU/UpdateMoneyRequest.ts b/src/libs/actions/IOU/UpdateMoneyRequest.ts index 792e0b588733..247687a8f080 100644 --- a/src/libs/actions/IOU/UpdateMoneyRequest.ts +++ b/src/libs/actions/IOU/UpdateMoneyRequest.ts @@ -1167,6 +1167,7 @@ function updateMoneyRequestDistance({ /** Updates the category of an expense */ function updateMoneyRequestCategory({ transactionID, + transaction, transactionThreadReport, parentReport, iouReportOwnerLogin, @@ -1186,6 +1187,7 @@ function updateMoneyRequestCategory({ getCurrencySymbol, }: { transactionID: string; + transaction?: OnyxEntry; transactionThreadReport: OnyxEntry; parentReport: OnyxEntry; iouReportOwnerLogin: string | undefined; @@ -1210,6 +1212,7 @@ function updateMoneyRequestCategory({ const {params, onyxData} = getUpdateMoneyRequestParams({ transactionID, + transaction, transactionThreadReport, iouReport: parentReport, iouReportOwnerLogin, @@ -1536,6 +1539,9 @@ function updateMoneyRequestAmountAndCurrency({ type GetUpdateMoneyRequestParamsType = { transactionID: string | undefined; + + /** The transaction being edited, when the caller holds it. Search rows live in the snapshot, not the TRANSACTION collection the cache lookup below reads. */ + transaction?: OnyxEntry; transactionThreadReport: OnyxEntry; transactionChanges: TransactionChanges; policy: OnyxEntry; @@ -1582,6 +1588,7 @@ type UpdateMoneyRequestDataKeys = function getUpdateMoneyRequestParams(params: GetUpdateMoneyRequestParamsType): UpdateMoneyRequestData { const { transactionID, + transaction: transactionFromCaller, transactionThreadReport, transactionChanges, policy, @@ -1645,7 +1652,7 @@ function getUpdateMoneyRequestParams(params: GetUpdateMoneyRequestParamsType): U > = []; // Step 1: Get the transaction being updated - const transaction = getAllTransactions()?.[`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`]; + const transaction = transactionFromCaller ?? getAllTransactions()?.[`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`]; // The manual-distance submit path always sends waypoints to keep the BE in sync, even when the user // only edited the distance number. Detect whether the addresses actually changed so we can skip the diff --git a/src/libs/actions/TransactionInlineEdit.ts b/src/libs/actions/TransactionInlineEdit.ts index 5b5e79492482..b08c7323eb0c 100644 --- a/src/libs/actions/TransactionInlineEdit.ts +++ b/src/libs/actions/TransactionInlineEdit.ts @@ -178,6 +178,7 @@ type TransactionEditPermissionsParams = { type GetIouParamsInput = { transactionID: string; + transaction: OnyxEntry; parentReport: OnyxEntry; parentReportAction: OnyxEntry; transactionThreadReport: OnyxEntry; @@ -212,6 +213,7 @@ type TransactionInlineEditParams = GetIouParamsInput & { */ function getIouParamsForTransaction({ transactionID, + transaction: transactionFromView, parentReport, parentReportAction, transactionThreadReport, @@ -230,7 +232,7 @@ function getIouParamsForTransaction({ getCurrencyDecimals, getCurrencySymbol, }: GetIouParamsInput) { - const transaction = allTransactions[`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`]; + const transaction = transactionFromView ?? allTransactions[`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`]; const transactionViolations = allTransactionViolations[`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${transactionID}`]; const isUnreportedExpense = !transaction?.reportID || transaction.reportID === CONST.REPORT.UNREPORTED_REPORT_ID; diff --git a/tests/unit/inlineEditing/TransactionInlineEditCategory.test.ts b/tests/unit/inlineEditing/TransactionInlineEditCategory.test.ts new file mode 100644 index 000000000000..77eb95e5f8ab --- /dev/null +++ b/tests/unit/inlineEditing/TransactionInlineEditCategory.test.ts @@ -0,0 +1,110 @@ +import type {TransactionInlineEditParams} from '@libs/actions/TransactionInlineEdit'; +import {editTransactionCategoryInline} from '@libs/actions/TransactionInlineEdit'; +import {write} from '@libs/API'; +import {WRITE_COMMANDS} from '@libs/API/types'; + +import CONST from '@src/CONST'; +import ONYXKEYS from '@src/ONYXKEYS'; +import type {PolicyCategories, Report, Transaction} from '@src/types/onyx'; + +import Onyx from 'react-native-onyx'; + +import waitForBatchedUpdates from '../../utils/waitForBatchedUpdates'; + +jest.mock('@libs/API'); +jest.mock('@libs/Network/enhanceParameters', () => ({ + __esModule: true, + default: (_: string, params: Record) => params, +})); + +const mockWrite = jest.mocked(write); + +const TRANSACTION_ID = '7777777777777777777'; +const SELF_DM_REPORT_ID = '4242424242'; + +/** An unreported expense as the Search table renders it, i.e. straight out of the search snapshot. */ +const snapshotTransaction: Transaction = { + transactionID: TRANSACTION_ID, + reportID: CONST.REPORT.UNREPORTED_REPORT_ID, + amount: -10000, + currency: 'USD', + merchant: 'Coffee', + created: '2026-08-12', + comment: {}, +}; + +const selfDMReport: Report = { + reportID: SELF_DM_REPORT_ID, + chatType: CONST.REPORT.CHAT_TYPE.SELF_DM, + type: CONST.REPORT.TYPE.CHAT, +}; + +const policyCategories: PolicyCategories = { + Benefits: {name: 'Benefits', enabled: true}, + Travel: {name: 'Travel', enabled: true}, +}; + +function buildParams(transaction: TransactionInlineEditParams['transaction']): TransactionInlineEditParams { + return { + hash: 123456, + isOffline: false, + transactionID: TRANSACTION_ID, + transaction, + parentReport: selfDMReport, + parentReportAction: undefined, + transactionThreadReport: undefined, + policy: undefined, + policyCategories, + policyTags: undefined, + reportPolicyTags: undefined, + policyRecentlyUsedCategories: undefined, + policyRecentlyUsedTags: undefined, + isSelfTourViewed: true, + hasCompletedGuidedSetupFlow: true, + personalDetailsList: undefined, + delegateAccountID: undefined, + isTrackIntentUser: false, + getCurrencyDecimals: () => 2, + getCurrencySymbol: () => '$', + }; +} + +function getLastWrittenParams(): Record { + const call = mockWrite.mock.calls.at(-1); + expect(call?.at(0)).toBe(WRITE_COMMANDS.UPDATE_MONEY_REQUEST_CATEGORY); + return (call?.at(1) ?? {}) as Record; +} + +describe('editTransactionCategoryInline', () => { + beforeAll(() => { + Onyx.init({keys: ONYXKEYS}); + }); + + beforeEach(async () => { + jest.clearAllMocks(); + await Onyx.clear(); + await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${SELF_DM_REPORT_ID}`, selfDMReport); + await waitForBatchedUpdates(); + }); + + it('sends the selected category when the transaction is only in the search snapshot', async () => { + // Search stores its results under snapshot_ only, so right after a fresh sign-in the + // live TRANSACTION collection has no entry for a row the user can already see and edit. + expect(await new Promise((resolve) => Onyx.connectWithoutView({key: `${ONYXKEYS.COLLECTION.TRANSACTION}${TRANSACTION_ID}`, callback: resolve}))).toBeUndefined(); + + editTransactionCategoryInline(buildParams(snapshotTransaction), 'Benefits'); + await waitForBatchedUpdates(); + + expect(getLastWrittenParams()).toEqual(expect.objectContaining({transactionID: TRANSACTION_ID, category: 'Benefits'})); + }); + + it('still falls back to the live transaction when the caller has none', async () => { + await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION}${TRANSACTION_ID}`, snapshotTransaction); + await waitForBatchedUpdates(); + + editTransactionCategoryInline(buildParams(undefined), 'Travel'); + await waitForBatchedUpdates(); + + expect(getLastWrittenParams()).toEqual(expect.objectContaining({transactionID: TRANSACTION_ID, category: 'Travel'})); + }); +}); From b83259ffe1cea1bec897891ec282af42d9cc6f0e Mon Sep 17 00:00:00 2001 From: Mukher Date: Fri, 21 Aug 2026 16:57:10 +0500 Subject: [PATCH 2/7] Prefer the live transaction and fall back to the caller's copy Resolving the caller's copy first let a render-time transaction win even when the live TRANSACTION collection had a fresher entry. That matters because the optimistic update merges the whole resolved transaction back into the live Onyx key, so a stale copy would overwrite live fields. The live lookup returns undefined for the Search rows this fixes, so the behaviour there is unchanged. Also pass the transaction in the existing inline-edit test now that the param is required, and drop an unsafe cast and a promise-executor return in the new regression test. --- src/libs/actions/IOU/UpdateMoneyRequest.ts | 4 +--- src/libs/actions/TransactionInlineEdit.ts | 2 +- .../actions/IOUTest/UpdateMoneyRequestTest.ts | 1 + .../TransactionInlineEditCategory.test.ts | 21 +++++++++++++++---- 4 files changed, 20 insertions(+), 8 deletions(-) diff --git a/src/libs/actions/IOU/UpdateMoneyRequest.ts b/src/libs/actions/IOU/UpdateMoneyRequest.ts index 247687a8f080..e9ac896f95c9 100644 --- a/src/libs/actions/IOU/UpdateMoneyRequest.ts +++ b/src/libs/actions/IOU/UpdateMoneyRequest.ts @@ -1539,8 +1539,6 @@ function updateMoneyRequestAmountAndCurrency({ type GetUpdateMoneyRequestParamsType = { transactionID: string | undefined; - - /** The transaction being edited, when the caller holds it. Search rows live in the snapshot, not the TRANSACTION collection the cache lookup below reads. */ transaction?: OnyxEntry; transactionThreadReport: OnyxEntry; transactionChanges: TransactionChanges; @@ -1652,7 +1650,7 @@ function getUpdateMoneyRequestParams(params: GetUpdateMoneyRequestParamsType): U > = []; // Step 1: Get the transaction being updated - const transaction = transactionFromCaller ?? getAllTransactions()?.[`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`]; + const transaction = getAllTransactions()?.[`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`] ?? transactionFromCaller; // The manual-distance submit path always sends waypoints to keep the BE in sync, even when the user // only edited the distance number. Detect whether the addresses actually changed so we can skip the diff --git a/src/libs/actions/TransactionInlineEdit.ts b/src/libs/actions/TransactionInlineEdit.ts index b08c7323eb0c..45c34b1c9642 100644 --- a/src/libs/actions/TransactionInlineEdit.ts +++ b/src/libs/actions/TransactionInlineEdit.ts @@ -232,7 +232,7 @@ function getIouParamsForTransaction({ getCurrencyDecimals, getCurrencySymbol, }: GetIouParamsInput) { - const transaction = transactionFromView ?? allTransactions[`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`]; + const transaction = allTransactions[`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`] ?? transactionFromView; const transactionViolations = allTransactionViolations[`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${transactionID}`]; const isUnreportedExpense = !transaction?.reportID || transaction.reportID === CONST.REPORT.UNREPORTED_REPORT_ID; diff --git a/tests/actions/IOUTest/UpdateMoneyRequestTest.ts b/tests/actions/IOUTest/UpdateMoneyRequestTest.ts index 91171e1363be..86912c6765f0 100644 --- a/tests/actions/IOUTest/UpdateMoneyRequestTest.ts +++ b/tests/actions/IOUTest/UpdateMoneyRequestTest.ts @@ -2779,6 +2779,7 @@ describe('actions/IOU/UpdateMoneyRequest', () => { { hash: undefined, transactionID, + transaction: fakeTransaction, parentReport, parentReportAction: undefined, transactionThreadReport, diff --git a/tests/unit/inlineEditing/TransactionInlineEditCategory.test.ts b/tests/unit/inlineEditing/TransactionInlineEditCategory.test.ts index 77eb95e5f8ab..f625b6c5c815 100644 --- a/tests/unit/inlineEditing/TransactionInlineEditCategory.test.ts +++ b/tests/unit/inlineEditing/TransactionInlineEditCategory.test.ts @@ -69,10 +69,23 @@ function buildParams(transaction: TransactionInlineEditParams['transaction']): T }; } -function getLastWrittenParams(): Record { +function getLastWrittenParams() { const call = mockWrite.mock.calls.at(-1); - expect(call?.at(0)).toBe(WRITE_COMMANDS.UPDATE_MONEY_REQUEST_CATEGORY); - return (call?.at(1) ?? {}) as Record; + expect(call?.[0]).toBe(WRITE_COMMANDS.UPDATE_MONEY_REQUEST_CATEGORY); + return call?.[1]; +} + +/** Reads the live TRANSACTION entry, disconnecting so the subscription does not outlive the test. */ +function readLiveTransaction() { + return new Promise((resolve) => { + const connection = Onyx.connectWithoutView({ + key: `${ONYXKEYS.COLLECTION.TRANSACTION}${TRANSACTION_ID}`, + callback: (value) => { + Onyx.disconnect(connection); + resolve(value); + }, + }); + }); } describe('editTransactionCategoryInline', () => { @@ -90,7 +103,7 @@ describe('editTransactionCategoryInline', () => { it('sends the selected category when the transaction is only in the search snapshot', async () => { // Search stores its results under snapshot_ only, so right after a fresh sign-in the // live TRANSACTION collection has no entry for a row the user can already see and edit. - expect(await new Promise((resolve) => Onyx.connectWithoutView({key: `${ONYXKEYS.COLLECTION.TRANSACTION}${TRANSACTION_ID}`, callback: resolve}))).toBeUndefined(); + expect(await readLiveTransaction()).toBeUndefined(); editTransactionCategoryInline(buildParams(snapshotTransaction), 'Benefits'); await waitForBatchedUpdates(); From 16a2cfc83311008324595305e8b99cce23c93d2d Mon Sep 17 00:00:00 2001 From: Mukher Date: Mon, 24 Aug 2026 09:23:34 +0500 Subject: [PATCH 3/7] Apply the transaction fix to every inline edit field Only the category edit forwarded the caller's transaction, so date, merchant, description, amount and tag still resolved it from the live TRANSACTION collection and went out missing their field on a Search row the user had not opened. All six now forward it, and the param wins over the cache lookup, which stays as the fallback for the callers that pass only a transactionID. getIouParamsForTransaction takes the transaction directly: it is a required param and the only caller is the inline edit hook, so the cache lookup was dead code. Two related failures fixed by the same threading: - isValidMerchant only permits an empty merchant on an unreported expense, which it reads off the transaction. Without one, clearing a merchant was discarded before any API call. - getUpdateTrackExpenseParams repeated the same lookup, so date, merchant, description and amount edits on a self-DM expense stayed broken even once the other path was fixed. Its currency context now carries the transaction too. --- src/libs/actions/IOU/UpdateMoneyRequest.ts | 62 ++++++++++++++++++---- src/libs/actions/TransactionInlineEdit.ts | 7 +-- 2 files changed, 54 insertions(+), 15 deletions(-) diff --git a/src/libs/actions/IOU/UpdateMoneyRequest.ts b/src/libs/actions/IOU/UpdateMoneyRequest.ts index e9ac896f95c9..230cf0ed92f1 100644 --- a/src/libs/actions/IOU/UpdateMoneyRequest.ts +++ b/src/libs/actions/IOU/UpdateMoneyRequest.ts @@ -69,6 +69,7 @@ type UpdateMoneyRequestData = { type UpdateMoneyRequestDateParams = { transactionID: string; + transaction?: OnyxEntry; transactionThreadReport: OnyxEntry; parentReport: OnyxEntry; iouReportOwnerLogin: string | undefined; @@ -219,6 +220,7 @@ function getRecalculatedDistanceRateIDForExpenseDate({ /** Updates the created date of an expense */ function updateMoneyRequestDate({ transactionID, + transaction: transactionFromCaller, transactionThreadReport, parentReport, iouReportOwnerLogin, @@ -242,7 +244,7 @@ function updateMoneyRequestDate({ getCurrencyDecimals, getCurrencySymbol, }: UpdateMoneyRequestDateParams) { - const transaction = getAllTransactions()[`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`]; + const transaction = transactionFromCaller ?? getAllTransactions()[`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`]; const isTrackExpense = isTrackExpenseReport(transactionThreadReport) && isSelfDM(parentReport); const effectivePolicy = isTrackExpense ? policyForTrackExpense : policy; const currentTransactionViolations = transactionViolations?.[`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${transactionID}`] ?? []; @@ -306,7 +308,7 @@ function updateMoneyRequestDate({ transactionChanges, effectivePolicy, delegateAccountID, - {getCurrencyDecimals, getCurrencySymbol}, + {getCurrencyDecimals, getCurrencySymbol, transaction}, hash, undefined, distanceOriginalPolicy, @@ -315,6 +317,7 @@ function updateMoneyRequestDate({ } else { data = getUpdateMoneyRequestParams({ transactionID, + transaction, transactionThreadReport, iouReport: parentReport, iouReportOwnerLogin, @@ -475,6 +478,7 @@ function updateMoneyRequestReimbursable({ /** Updates the merchant field of an expense */ function updateMoneyRequestMerchant({ transactionID, + transaction, transactionThreadReport, parentReport, iouReportOwnerLogin, @@ -494,6 +498,7 @@ function updateMoneyRequestMerchant({ getCurrencySymbol, }: { transactionID: string; + transaction?: OnyxEntry; transactionThreadReport: OnyxEntry; parentReport: OnyxEntry; iouReportOwnerLogin: string | undefined; @@ -518,10 +523,19 @@ function updateMoneyRequestMerchant({ let data: UpdateMoneyRequestData; if (isTrackExpenseReport(transactionThreadReport) && isSelfDM(parentReport)) { - data = getUpdateTrackExpenseParams(transactionID, transactionThreadReport?.reportID, transactionChanges, policy, delegateAccountID, {getCurrencyDecimals, getCurrencySymbol}, hash); + data = getUpdateTrackExpenseParams( + transactionID, + transactionThreadReport?.reportID, + transactionChanges, + policy, + delegateAccountID, + {getCurrencyDecimals, getCurrencySymbol, transaction}, + hash, + ); } else { data = getUpdateMoneyRequestParams({ transactionID, + transaction, transactionThreadReport, iouReport: parentReport, iouReportOwnerLogin, @@ -799,6 +813,7 @@ function updateMoneyRequestVendor({ type UpdateMoneyRequestTagParams = { transactionID: string; + transaction?: OnyxEntry; transactionThreadReport: OnyxEntry; parentReport: OnyxEntry; iouReportOwnerLogin: string | undefined; @@ -822,6 +837,7 @@ type UpdateMoneyRequestTagParams = { /** Updates the tag of an expense */ function updateMoneyRequestTag({ transactionID, + transaction, transactionThreadReport, parentReport, iouReportOwnerLogin, @@ -846,6 +862,7 @@ function updateMoneyRequestTag({ }; const {params, onyxData} = getUpdateMoneyRequestParams({ transactionID, + transaction, transactionThreadReport, iouReport: parentReport, iouReportOwnerLogin, @@ -1237,6 +1254,7 @@ function updateMoneyRequestCategory({ /** Updates the description of an expense */ function updateMoneyRequestDescription({ transactionID, + transaction, transactionThreadReport, parentReport, iouReportOwnerLogin, @@ -1255,6 +1273,7 @@ function updateMoneyRequestDescription({ getCurrencySymbol, }: { transactionID: string; + transaction?: OnyxEntry; transactionThreadReport: OnyxEntry; parentReport: OnyxEntry; iouReportOwnerLogin: string | undefined; @@ -1279,10 +1298,19 @@ function updateMoneyRequestDescription({ let data: UpdateMoneyRequestData; if (isTrackExpenseReport(transactionThreadReport) && isSelfDM(parentReport)) { - data = getUpdateTrackExpenseParams(transactionID, transactionThreadReport?.reportID, transactionChanges, policy, delegateAccountID, {getCurrencyDecimals, getCurrencySymbol}, hash); + data = getUpdateTrackExpenseParams( + transactionID, + transactionThreadReport?.reportID, + transactionChanges, + policy, + delegateAccountID, + {getCurrencyDecimals, getCurrencySymbol, transaction}, + hash, + ); } else { data = getUpdateMoneyRequestParams({ transactionID, + transaction, transactionThreadReport, iouReport: parentReport, iouReportOwnerLogin, @@ -1443,6 +1471,7 @@ function updateMoneyRequestDistanceRate({ type UpdateMoneyRequestAmountAndCurrencyParams = { transactionID: string; + transaction?: OnyxEntry; transactionThreadReport: OnyxEntry; parentReport: OnyxEntry; iouReportOwnerLogin: string | undefined; @@ -1472,6 +1501,7 @@ type UpdateMoneyRequestAmountAndCurrencyParams = { /** Updates the amount and currency fields of an expense */ function updateMoneyRequestAmountAndCurrency({ transactionID, + transaction, transactionThreadReport, parentReport, iouReportOwnerLogin, @@ -1508,10 +1538,19 @@ function updateMoneyRequestAmountAndCurrency({ let data: UpdateMoneyRequestData; if (isTrackExpenseReport(transactionThreadReport) && isSelfDM(parentReport)) { - data = getUpdateTrackExpenseParams(transactionID, transactionThreadReport?.reportID, transactionChanges, policy, delegateAccountID, {getCurrencyDecimals, getCurrencySymbol}, hash); + data = getUpdateTrackExpenseParams( + transactionID, + transactionThreadReport?.reportID, + transactionChanges, + policy, + delegateAccountID, + {getCurrencyDecimals, getCurrencySymbol, transaction}, + hash, + ); } else { data = getUpdateMoneyRequestParams({ transactionID, + transaction, transactionThreadReport, iouReport: parentReport, iouReportOwnerLogin, @@ -1650,7 +1689,7 @@ function getUpdateMoneyRequestParams(params: GetUpdateMoneyRequestParamsType): U > = []; // Step 1: Get the transaction being updated - const transaction = getAllTransactions()?.[`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`] ?? transactionFromCaller; + const transaction = transactionFromCaller ?? getAllTransactions()?.[`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`]; // The manual-distance submit path always sends waypoints to keep the BE in sync, even when the user // only edited the distance number. Detect whether the addresses actually changed so we can skip the @@ -2245,10 +2284,13 @@ function getUpdateMoneyRequestParams(params: GetUpdateMoneyRequestParamsType): U * @param policy May be undefined, an empty object, or an object matching the Policy type (src/types/onyx/Policy.ts) * @param [shouldBuildOptimisticModifiedExpenseReportAction=true] When true, build an optimistic MODIFIED_EXPENSE report action. */ -type TrackExpenseCurrencyContext = { +type TrackExpenseContext = { personalPolicyOutputCurrency?: string; getCurrencyDecimals: CurrencyListActionsContextType['getCurrencyDecimals']; getCurrencySymbol: CurrencyListActionsContextType['getCurrencySymbol']; + + /** Transaction supplied by the caller, e.g. a Search row read from the snapshot rather than the live collection. */ + transaction?: OnyxEntry; }; function getUpdateTrackExpenseParams( @@ -2257,7 +2299,7 @@ function getUpdateTrackExpenseParams( transactionChanges: TransactionChanges, policy: OnyxEntry, delegateAccountID: number | undefined, - currencyContext: TrackExpenseCurrencyContext, + trackExpenseContext: TrackExpenseContext, hash?: number, shouldBuildOptimisticModifiedExpenseReportAction = true, distanceOriginalPolicy?: OnyxEntry, @@ -2270,7 +2312,7 @@ function getUpdateTrackExpenseParams( | typeof ONYXKEYS.COLLECTION.SNAPSHOT | typeof ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS > { - const {personalPolicyOutputCurrency, getCurrencyDecimals, getCurrencySymbol} = currencyContext; + const {personalPolicyOutputCurrency, getCurrencyDecimals, getCurrencySymbol, transaction: transactionFromCaller} = trackExpenseContext; const optimisticData: Array< OnyxUpdate< | typeof ONYXKEYS.COLLECTION.REPORT_ACTIONS @@ -2300,7 +2342,7 @@ function getUpdateTrackExpenseParams( // Step 2: Get all the collections being updated const transactionThread = getAllReports()?.[`${ONYXKEYS.COLLECTION.REPORT}${transactionThreadReportID}`] ?? null; - const transaction = getAllTransactions()?.[`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`]; + const transaction = transactionFromCaller ?? getAllTransactions()?.[`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`]; const chatReport = getAllReports()?.[`${ONYXKEYS.COLLECTION.REPORT}${transactionThread?.parentReportID}`] ?? null; const policyForTransaction = distanceOriginalPolicy ?? policy; const updatedTransaction = transaction diff --git a/src/libs/actions/TransactionInlineEdit.ts b/src/libs/actions/TransactionInlineEdit.ts index 45c34b1c9642..e32c2b940d53 100644 --- a/src/libs/actions/TransactionInlineEdit.ts +++ b/src/libs/actions/TransactionInlineEdit.ts @@ -213,7 +213,7 @@ type TransactionInlineEditParams = GetIouParamsInput & { */ function getIouParamsForTransaction({ transactionID, - transaction: transactionFromView, + transaction, parentReport, parentReportAction, transactionThreadReport, @@ -232,7 +232,6 @@ function getIouParamsForTransaction({ getCurrencyDecimals, getCurrencySymbol, }: GetIouParamsInput) { - const transaction = allTransactions[`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`] ?? transactionFromView; const transactionViolations = allTransactionViolations[`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${transactionID}`]; const isUnreportedExpense = !transaction?.reportID || transaction.reportID === CONST.REPORT.UNREPORTED_REPORT_ID; @@ -326,9 +325,7 @@ function editTransactionDateInline(params: TransactionInlineEditParams, newDate: /** Updates the merchant of an expense from the Search results table or the Expense Report page. */ function editTransactionMerchantInline(params: TransactionInlineEditParams, newMerchant: string) { - const transaction = allTransactions[`${ONYXKEYS.COLLECTION.TRANSACTION}${params.transactionID}`]; - - if (!isValidMerchant(newMerchant, transaction, params.parentReport)) { + if (!isValidMerchant(newMerchant, params.transaction, params.parentReport)) { return; } From eae7fa146e64996cb6a6b91178ddbed1f95df55e Mon Sep 17 00:00:00 2001 From: Mukher Date: Mon, 24 Aug 2026 09:23:47 +0500 Subject: [PATCH 4/7] Fold the inline edit tests into the existing suite Moves the category regression test into TransactionInlineEdit.test.ts and widens it to all six fields, each asserting its delegate receives the forwarded transaction. Adds a case for clearing a merchant, which was previously dropped before the API call. The delegates are mocked rather than the API layer: editTransaction*Inline only builds params and calls through, so that boundary is the assertion point. That also removes the need for Onyx setup, since an uninitialised transaction cache is exactly the state being tested. --- .../TransactionInlineEdit.test.ts | 851 ++++++++++-------- .../TransactionInlineEditCategory.test.ts | 123 --- 2 files changed, 476 insertions(+), 498 deletions(-) delete mode 100644 tests/unit/inlineEditing/TransactionInlineEditCategory.test.ts diff --git a/tests/unit/inlineEditing/TransactionInlineEdit.test.ts b/tests/unit/inlineEditing/TransactionInlineEdit.test.ts index 88053123d8f7..ef2f4d7c8370 100644 --- a/tests/unit/inlineEditing/TransactionInlineEdit.test.ts +++ b/tests/unit/inlineEditing/TransactionInlineEdit.test.ts @@ -1,451 +1,552 @@ -import type {TransactionEditPermissions, TransactionEditPermissionsParams} from '@libs/actions/TransactionInlineEdit'; -import {getTransactionEditPermissions} from '@libs/actions/TransactionInlineEdit'; +import type {TransactionEditPermissions, TransactionEditPermissionsParams, TransactionInlineEditParams} from '@libs/actions/TransactionInlineEdit'; +import { + editTransactionAmountInline, + editTransactionCategoryInline, + editTransactionDateInline, + editTransactionDescriptionInline, + editTransactionMerchantInline, + editTransactionTagInline, + getTransactionEditPermissions, +} from '@libs/actions/TransactionInlineEdit'; + +import { + updateMoneyRequestAmountAndCurrency, + updateMoneyRequestCategory, + updateMoneyRequestDate, + updateMoneyRequestDescription, + updateMoneyRequestMerchant, + updateMoneyRequestTag, +} from '@userActions/IOU/UpdateMoneyRequest'; import CONST from '@src/CONST'; import type {Policy, PolicyCategories, PolicyTagLists, Report, ReportAction, ReportNameValuePairs, Transaction} from '@src/types/onyx'; -describe('getTransactionEditPermissions', () => { - // Use unreported transaction by default to bypass most permission checks - const baseTransaction: Transaction = { - transactionID: '1', - reportID: CONST.REPORT.UNREPORTED_REPORT_ID, - amount: 1000, - currency: 'USD', - merchant: 'Test Merchant', - created: '2024-01-01', - comment: { - comment: 'Test comment', - }, - }; - - const baseParentReportAction: ReportAction = { - reportActionID: '1', - actionName: CONST.REPORT.ACTIONS.TYPE.IOU, - actorAccountID: 1, - created: '2024-01-01', - message: [], - originalMessage: { - IOUTransactionID: '1', +// The delegate boundary is the assertion point: editTransaction*Inline only builds params and calls through. +jest.mock('@userActions/IOU/UpdateMoneyRequest', () => ({ + updateMoneyRequestDate: jest.fn(), + updateMoneyRequestMerchant: jest.fn(), + updateMoneyRequestDescription: jest.fn(), + updateMoneyRequestCategory: jest.fn(), + updateMoneyRequestAmountAndCurrency: jest.fn(), + updateMoneyRequestTag: jest.fn(), +})); + +describe('TransactionInlineEdit', () => { + describe('getTransactionEditPermissions', () => { + // Use unreported transaction by default to bypass most permission checks + const baseTransaction: Transaction = { + transactionID: '1', + reportID: CONST.REPORT.UNREPORTED_REPORT_ID, amount: 1000, currency: 'USD', - type: CONST.IOU.REPORT_ACTION_TYPE.CREATE, - }, - }; - - const baseParentReport: Report = { - reportID: '100', - ownerAccountID: 1, - managerID: 1, - policyID: '1', - type: CONST.REPORT.TYPE.EXPENSE, - statusNum: CONST.REPORT.STATUS_NUM.OPEN, - }; - - const basePolicy: Policy = { - id: '1', - name: 'Test Policy', - role: 'admin', - type: CONST.POLICY.TYPE.TEAM, - owner: '', - outputCurrency: 'USD', - isPolicyExpenseChatEnabled: false, - areCategoriesEnabled: true, - }; - - const baseParams: TransactionEditPermissionsParams = { - transaction: baseTransaction, - parentReportAction: baseParentReportAction, - parentReport: baseParentReport, - policy: basePolicy, - }; - - const policyCategories: PolicyCategories = { - Food: {name: 'Food', enabled: true}, - Travel: {name: 'Travel', enabled: true}, - }; - - const singleLevelTags: PolicyTagLists = { - Tag: { - name: 'Tag', - required: false, - orderWeight: 1, - tags: { - Project1: {name: 'Project1', enabled: true}, - Project2: {name: 'Project2', enabled: true}, + merchant: 'Test Merchant', + created: '2024-01-01', + comment: { + comment: 'Test comment', }, - }, - }; - - const baseUnreportedParams: TransactionEditPermissionsParams = { - ...baseParams, - parentReportAction: undefined, - parentReport: undefined, - policyCategories, - policyTags: singleLevelTags, - }; - - const allFalsePermissions: TransactionEditPermissions = { - canEditDate: false, - canEditMerchant: false, - canEditDescription: false, - canEditCategory: false, - canEditAmount: false, - canEditTag: false, - } as const; - - describe('disabled flag', () => { - it('should return all false when disabled is true', () => { - const permissions = getTransactionEditPermissions({ - ...baseParams, - disabled: true, - }); + }; - expect(permissions).toEqual(allFalsePermissions); - }); - }); + const baseParentReportAction: ReportAction = { + reportActionID: '1', + actionName: CONST.REPORT.ACTIONS.TYPE.IOU, + actorAccountID: 1, + created: '2024-01-01', + message: [], + originalMessage: { + IOUTransactionID: '1', + amount: 1000, + currency: 'USD', + type: CONST.IOU.REPORT_ACTION_TYPE.CREATE, + }, + }; - describe('missing transaction', () => { - it('should return all false when transaction is undefined', () => { - const permissions = getTransactionEditPermissions({ - ...baseParams, - transaction: undefined, - }); + const baseParentReport: Report = { + reportID: '100', + ownerAccountID: 1, + managerID: 1, + policyID: '1', + type: CONST.REPORT.TYPE.EXPENSE, + statusNum: CONST.REPORT.STATUS_NUM.OPEN, + }; - expect(permissions).toEqual(allFalsePermissions); - }); - }); + const basePolicy: Policy = { + id: '1', + name: 'Test Policy', + role: 'admin', + type: CONST.POLICY.TYPE.TEAM, + owner: '', + outputCurrency: 'USD', + isPolicyExpenseChatEnabled: false, + areCategoriesEnabled: true, + }; - describe('scanning transactions', () => { - it('should handle field permissions correctly while transaction is scanning', () => { - const scanningTransaction: Transaction = { - ...baseTransaction, - reportID: CONST.REPORT.UNREPORTED_REPORT_ID, - merchant: CONST.TRANSACTION.PARTIAL_TRANSACTION_MERCHANT, - amount: 0, - receipt: { - state: CONST.IOU.RECEIPT_STATE.SCANNING, + const baseParams: TransactionEditPermissionsParams = { + transaction: baseTransaction, + parentReportAction: baseParentReportAction, + parentReport: baseParentReport, + policy: basePolicy, + }; + + const policyCategories: PolicyCategories = { + Food: {name: 'Food', enabled: true}, + Travel: {name: 'Travel', enabled: true}, + }; + + const singleLevelTags: PolicyTagLists = { + Tag: { + name: 'Tag', + required: false, + orderWeight: 1, + tags: { + Project1: {name: 'Project1', enabled: true}, + Project2: {name: 'Project2', enabled: true}, }, - }; + }, + }; - const permissions = getTransactionEditPermissions({ - ...baseUnreportedParams, - transaction: scanningTransaction, - }); + const baseUnreportedParams: TransactionEditPermissionsParams = { + ...baseParams, + parentReportAction: undefined, + parentReport: undefined, + policyCategories, + policyTags: singleLevelTags, + }; - expect(permissions).toMatchObject({ - canEditCategory: true, - canEditDate: true, - canEditDescription: true, - canEditTag: true, - // Amount and merchant editing should be disabled for scanning transactions - canEditAmount: false, - canEditMerchant: false, - } satisfies TransactionEditPermissions); + const allFalsePermissions: TransactionEditPermissions = { + canEditDate: false, + canEditMerchant: false, + canEditDescription: false, + canEditCategory: false, + canEditAmount: false, + canEditTag: false, + } as const; + + describe('disabled flag', () => { + it('should return all false when disabled is true', () => { + const permissions = getTransactionEditPermissions({ + ...baseParams, + disabled: true, + }); + + expect(permissions).toEqual(allFalsePermissions); + }); }); - }); - describe('distance requests', () => { - it('should handle field permissions correctly for distance requests', () => { - const distanceTransaction: Transaction = { - ...baseTransaction, - reportID: CONST.REPORT.UNREPORTED_REPORT_ID, - iouRequestType: CONST.IOU.REQUEST_TYPE.DISTANCE, - comment: { - type: CONST.TRANSACTION.TYPE.CUSTOM_UNIT, - customUnit: { - name: CONST.CUSTOM_UNITS.NAME_DISTANCE, - }, - }, - }; + describe('missing transaction', () => { + it('should return all false when transaction is undefined', () => { + const permissions = getTransactionEditPermissions({ + ...baseParams, + transaction: undefined, + }); - const permissions = getTransactionEditPermissions({ - ...baseUnreportedParams, - transaction: distanceTransaction, + expect(permissions).toEqual(allFalsePermissions); }); - - expect(permissions).toMatchObject({ - canEditCategory: true, - canEditDate: true, - canEditDescription: true, - canEditTag: true, - canEditAmount: true, - // Merchant editing should be disabled for distance requests - canEditMerchant: false, - } satisfies TransactionEditPermissions); }); - }); - describe('per diem requests', () => { - it('should disable amount and merchant for per diem requests', () => { - const perDiemTransaction: Transaction = { - ...baseTransaction, - reportID: CONST.REPORT.UNREPORTED_REPORT_ID, - iouRequestType: CONST.IOU.REQUEST_TYPE.PER_DIEM, - comment: { - type: CONST.TRANSACTION.TYPE.CUSTOM_UNIT, - customUnit: { - name: CONST.CUSTOM_UNITS.NAME_PER_DIEM_INTERNATIONAL, + describe('scanning transactions', () => { + it('should handle field permissions correctly while transaction is scanning', () => { + const scanningTransaction: Transaction = { + ...baseTransaction, + reportID: CONST.REPORT.UNREPORTED_REPORT_ID, + merchant: CONST.TRANSACTION.PARTIAL_TRANSACTION_MERCHANT, + amount: 0, + receipt: { + state: CONST.IOU.RECEIPT_STATE.SCANNING, }, - }, - }; - - const permissions = getTransactionEditPermissions({ - ...baseUnreportedParams, - transaction: perDiemTransaction, + }; + + const permissions = getTransactionEditPermissions({ + ...baseUnreportedParams, + transaction: scanningTransaction, + }); + + expect(permissions).toMatchObject({ + canEditCategory: true, + canEditDate: true, + canEditDescription: true, + canEditTag: true, + // Amount and merchant editing should be disabled for scanning transactions + canEditAmount: false, + canEditMerchant: false, + } satisfies TransactionEditPermissions); }); - - expect(permissions).toMatchObject({ - canEditCategory: true, - canEditDate: true, - canEditDescription: true, - canEditTag: true, - // Amount and merchant are derived from the rate and cannot be edited - canEditAmount: false, - canEditMerchant: false, - } satisfies TransactionEditPermissions); }); - }); - - describe('split expenses', () => { - it('should handle field permissions correctly for split expense children', () => { - const splitTransaction: Transaction = { - ...baseTransaction, - reportID: CONST.REPORT.UNREPORTED_REPORT_ID, - comment: { - originalTransactionID: 'original123', - source: CONST.IOU.TYPE.SPLIT, - }, - }; - const originalTransaction: Transaction = { - ...baseTransaction, - transactionID: 'original123', - reportID: CONST.REPORT.UNREPORTED_REPORT_ID, - comment: {}, - }; + describe('distance requests', () => { + it('should handle field permissions correctly for distance requests', () => { + const distanceTransaction: Transaction = { + ...baseTransaction, + reportID: CONST.REPORT.UNREPORTED_REPORT_ID, + iouRequestType: CONST.IOU.REQUEST_TYPE.DISTANCE, + comment: { + type: CONST.TRANSACTION.TYPE.CUSTOM_UNIT, + customUnit: { + name: CONST.CUSTOM_UNITS.NAME_DISTANCE, + }, + }, + }; + + const permissions = getTransactionEditPermissions({ + ...baseUnreportedParams, + transaction: distanceTransaction, + }); + + expect(permissions).toMatchObject({ + canEditCategory: true, + canEditDate: true, + canEditDescription: true, + canEditTag: true, + canEditAmount: true, + // Merchant editing should be disabled for distance requests + canEditMerchant: false, + } satisfies TransactionEditPermissions); + }); + }); - const permissions = getTransactionEditPermissions({ - ...baseUnreportedParams, - transaction: splitTransaction, - originalTransaction, + describe('per diem requests', () => { + it('should disable amount and merchant for per diem requests', () => { + const perDiemTransaction: Transaction = { + ...baseTransaction, + reportID: CONST.REPORT.UNREPORTED_REPORT_ID, + iouRequestType: CONST.IOU.REQUEST_TYPE.PER_DIEM, + comment: { + type: CONST.TRANSACTION.TYPE.CUSTOM_UNIT, + customUnit: { + name: CONST.CUSTOM_UNITS.NAME_PER_DIEM_INTERNATIONAL, + }, + }, + }; + + const permissions = getTransactionEditPermissions({ + ...baseUnreportedParams, + transaction: perDiemTransaction, + }); + + expect(permissions).toMatchObject({ + canEditCategory: true, + canEditDate: true, + canEditDescription: true, + canEditTag: true, + // Amount and merchant are derived from the rate and cannot be edited + canEditAmount: false, + canEditMerchant: false, + } satisfies TransactionEditPermissions); }); + }); - expect(permissions).toMatchObject({ - canEditCategory: true, - canEditDate: true, - canEditDescription: true, - canEditTag: true, - canEditMerchant: true, - // Amount editing should be disabled for split expense children - canEditAmount: false, - } satisfies TransactionEditPermissions); + describe('split expenses', () => { + it('should handle field permissions correctly for split expense children', () => { + const splitTransaction: Transaction = { + ...baseTransaction, + reportID: CONST.REPORT.UNREPORTED_REPORT_ID, + comment: { + originalTransactionID: 'original123', + source: CONST.IOU.TYPE.SPLIT, + }, + }; + + const originalTransaction: Transaction = { + ...baseTransaction, + transactionID: 'original123', + reportID: CONST.REPORT.UNREPORTED_REPORT_ID, + comment: {}, + }; + + const permissions = getTransactionEditPermissions({ + ...baseUnreportedParams, + transaction: splitTransaction, + originalTransaction, + }); + + expect(permissions).toMatchObject({ + canEditCategory: true, + canEditDate: true, + canEditDescription: true, + canEditTag: true, + canEditMerchant: true, + // Amount editing should be disabled for split expense children + canEditAmount: false, + } satisfies TransactionEditPermissions); + }); }); - }); - describe('category permissions', () => { - it('should disable category editing when categories are not enabled on policy', () => { - const policyWithoutCategories: Policy = { - ...basePolicy, - areCategoriesEnabled: false, - }; + describe('category permissions', () => { + it('should disable category editing when categories are not enabled on policy', () => { + const policyWithoutCategories: Policy = { + ...basePolicy, + areCategoriesEnabled: false, + }; + + const permissions = getTransactionEditPermissions({ + ...baseUnreportedParams, + policy: policyWithoutCategories, + }); - const permissions = getTransactionEditPermissions({ - ...baseUnreportedParams, - policy: policyWithoutCategories, + expect(permissions.canEditCategory).toBe(false); }); - expect(permissions.canEditCategory).toBe(false); - }); + it('should enable category editing when transaction already has a category', () => { + const transactionWithCategory: Transaction = { + ...baseTransaction, + reportID: CONST.REPORT.UNREPORTED_REPORT_ID, + category: 'Food', + }; - it('should enable category editing when transaction already has a category', () => { - const transactionWithCategory: Transaction = { - ...baseTransaction, - reportID: CONST.REPORT.UNREPORTED_REPORT_ID, - category: 'Food', - }; + const permissions = getTransactionEditPermissions({ + ...baseUnreportedParams, + transaction: transactionWithCategory, + }); - const permissions = getTransactionEditPermissions({ - ...baseUnreportedParams, - transaction: transactionWithCategory, + expect(permissions.canEditCategory).toBe(true); }); - - expect(permissions.canEditCategory).toBe(true); }); - }); - describe('tag permissions', () => { - it('should disable tag editing for multi-level tags', () => { - const multiLevelTags: PolicyTagLists = { - Department: { - name: 'Department', - required: false, - orderWeight: 1, - tags: { - Engineering: {name: 'Engineering', enabled: true}, + describe('tag permissions', () => { + it('should disable tag editing for multi-level tags', () => { + const multiLevelTags: PolicyTagLists = { + Department: { + name: 'Department', + required: false, + orderWeight: 1, + tags: { + Engineering: {name: 'Engineering', enabled: true}, + }, }, - }, - Team: { - name: 'Team', - required: false, - orderWeight: 2, - tags: { - Frontend: {name: 'Frontend', enabled: true}, + Team: { + name: 'Team', + required: false, + orderWeight: 2, + tags: { + Frontend: {name: 'Frontend', enabled: true}, + }, }, - }, - }; + }; + + const permissions = getTransactionEditPermissions({ + ...baseUnreportedParams, + policyTags: multiLevelTags, + }); - const permissions = getTransactionEditPermissions({ - ...baseUnreportedParams, - policyTags: multiLevelTags, + expect(permissions.canEditTag).toBe(false); }); - expect(permissions.canEditTag).toBe(false); + it('should enable tag editing when transaction already has a tag', () => { + const transactionWithTag: Transaction = { + ...baseTransaction, + reportID: CONST.REPORT.UNREPORTED_REPORT_ID, + tag: 'Project1', + }; + + const permissions = getTransactionEditPermissions({ + ...baseUnreportedParams, + transaction: transactionWithTag, + policyTags: undefined, + }); + + expect(permissions.canEditTag).toBe(true); + }); }); - it('should enable tag editing when transaction already has a tag', () => { - const transactionWithTag: Transaction = { + describe('unreported expenses', () => { + const unreportedTransaction: Transaction = { ...baseTransaction, reportID: CONST.REPORT.UNREPORTED_REPORT_ID, - tag: 'Project1', }; - const permissions = getTransactionEditPermissions({ - ...baseUnreportedParams, - transaction: transactionWithTag, - policyTags: undefined, + it('should allow editing all fields', () => { + const permissions = getTransactionEditPermissions({ + ...baseUnreportedParams, + transaction: unreportedTransaction, + }); + + expect(permissions).toMatchObject({ + canEditAmount: true, + canEditDate: true, + canEditDescription: true, + canEditMerchant: true, + canEditCategory: true, + canEditTag: true, + } satisfies TransactionEditPermissions); }); - expect(permissions.canEditTag).toBe(true); - }); - }); - - describe('unreported expenses', () => { - const unreportedTransaction: Transaction = { - ...baseTransaction, - reportID: CONST.REPORT.UNREPORTED_REPORT_ID, - }; - - it('should allow editing all fields', () => { - const permissions = getTransactionEditPermissions({ - ...baseUnreportedParams, - transaction: unreportedTransaction, + it('should disable category and tag editing without available options', () => { + const permissions = getTransactionEditPermissions({ + ...baseUnreportedParams, + transaction: unreportedTransaction, + policyCategories: undefined, + policyTags: undefined, + }); + + expect(permissions).toMatchObject({ + canEditAmount: true, + canEditDate: true, + canEditDescription: true, + canEditMerchant: true, + canEditCategory: false, + canEditTag: false, + } satisfies TransactionEditPermissions); }); - expect(permissions).toMatchObject({ - canEditAmount: true, - canEditDate: true, - canEditDescription: true, - canEditMerchant: true, - canEditCategory: true, - canEditTag: true, - } satisfies TransactionEditPermissions); - }); + it('should respect scanning restrictions', () => { + const permissions = getTransactionEditPermissions({ + ...baseUnreportedParams, + transaction: { + ...unreportedTransaction, + merchant: CONST.TRANSACTION.PARTIAL_TRANSACTION_MERCHANT, + amount: 0, + receipt: {state: CONST.IOU.RECEIPT_STATE.SCANNING}, + }, + }); - it('should disable category and tag editing without available options', () => { - const permissions = getTransactionEditPermissions({ - ...baseUnreportedParams, - transaction: unreportedTransaction, - policyCategories: undefined, - policyTags: undefined, + expect(permissions).toMatchObject({ + canEditAmount: false, + canEditMerchant: false, + } satisfies Partial); }); - expect(permissions).toMatchObject({ - canEditAmount: true, - canEditDate: true, - canEditDescription: true, - canEditMerchant: true, - canEditCategory: false, - canEditTag: false, - } satisfies TransactionEditPermissions); - }); + it('should respect distance request restrictions', () => { + const permissions = getTransactionEditPermissions({ + ...baseUnreportedParams, + transaction: { + ...unreportedTransaction, + iouRequestType: CONST.IOU.REQUEST_TYPE.DISTANCE, + comment: { + type: CONST.TRANSACTION.TYPE.CUSTOM_UNIT, + customUnit: {name: CONST.CUSTOM_UNITS.NAME_DISTANCE}, + }, + }, + }); - it('should respect scanning restrictions', () => { - const permissions = getTransactionEditPermissions({ - ...baseUnreportedParams, - transaction: { - ...unreportedTransaction, - merchant: CONST.TRANSACTION.PARTIAL_TRANSACTION_MERCHANT, - amount: 0, - receipt: {state: CONST.IOU.RECEIPT_STATE.SCANNING}, - }, + expect(permissions).toMatchObject({ + canEditMerchant: false, + } satisfies Partial); }); - expect(permissions).toMatchObject({ - canEditAmount: false, - canEditMerchant: false, - } satisfies Partial); - }); - - it('should respect distance request restrictions', () => { - const permissions = getTransactionEditPermissions({ - ...baseUnreportedParams, - transaction: { - ...unreportedTransaction, - iouRequestType: CONST.IOU.REQUEST_TYPE.DISTANCE, - comment: { - type: CONST.TRANSACTION.TYPE.CUSTOM_UNIT, - customUnit: {name: CONST.CUSTOM_UNITS.NAME_DISTANCE}, + it('should respect per diem request restrictions', () => { + const permissions = getTransactionEditPermissions({ + ...baseUnreportedParams, + transaction: { + ...unreportedTransaction, + iouRequestType: CONST.IOU.REQUEST_TYPE.PER_DIEM, + comment: { + type: CONST.TRANSACTION.TYPE.CUSTOM_UNIT, + customUnit: {name: CONST.CUSTOM_UNITS.NAME_PER_DIEM_INTERNATIONAL}, + }, }, - }, + }); + + expect(permissions).toMatchObject({ + canEditAmount: false, + canEditMerchant: false, + } satisfies Partial); }); - expect(permissions).toMatchObject({ - canEditMerchant: false, - } satisfies Partial); + it('should disable category editing when workspace selection is required', () => { + const permissions = getTransactionEditPermissions({ + ...baseUnreportedParams, + transaction: unreportedTransaction, + // No policy context yet since workspace selection is pending + policy: undefined, + shouldSelectPolicyForUnreported: true, + }); + + expect(permissions).toMatchObject({ + canEditCategory: false, + } satisfies Partial); + }); }); - it('should respect per diem request restrictions', () => { - const permissions = getTransactionEditPermissions({ - ...baseUnreportedParams, - transaction: { - ...unreportedTransaction, - iouRequestType: CONST.IOU.REQUEST_TYPE.PER_DIEM, - comment: { - type: CONST.TRANSACTION.TYPE.CUSTOM_UNIT, - customUnit: {name: CONST.CUSTOM_UNITS.NAME_PER_DIEM_INTERNATIONAL}, - }, - }, - }); + describe('archived reports', () => { + it('should disable all editing when chat report is archived', () => { + const reportedTransaction: Transaction = { + ...baseTransaction, + reportID: '100', + }; - expect(permissions).toMatchObject({ - canEditAmount: false, - canEditMerchant: false, - } satisfies Partial); - }); + const chatReportNVP: ReportNameValuePairs = { + private_isArchived: 'true', + }; - it('should disable category editing when workspace selection is required', () => { - const permissions = getTransactionEditPermissions({ - ...baseUnreportedParams, - transaction: unreportedTransaction, - // No policy context yet since workspace selection is pending - policy: undefined, - shouldSelectPolicyForUnreported: true, - }); + const permissions = getTransactionEditPermissions({ + ...baseParams, + transaction: reportedTransaction, + chatReportNVP, + }); - expect(permissions).toMatchObject({ - canEditCategory: false, - } satisfies Partial); + expect(permissions).toEqual(allFalsePermissions); + }); }); }); - describe('archived reports', () => { - it('should disable all editing when chat report is archived', () => { - const reportedTransaction: Transaction = { - ...baseTransaction, - reportID: '100', - }; + describe('editTransaction*Inline', () => { + const TRANSACTION_ID = '7777777777777777777'; + const SELF_DM_REPORT_ID = '4242424242'; - const chatReportNVP: ReportNameValuePairs = { - private_isArchived: 'true', + /** An unreported expense as the Search table renders it, i.e. straight out of the search snapshot. */ + const snapshotTransaction: Transaction = { + transactionID: TRANSACTION_ID, + reportID: CONST.REPORT.UNREPORTED_REPORT_ID, + amount: -10000, + currency: 'USD', + merchant: 'Coffee', + created: '2026-08-12', + comment: {}, + }; + + const selfDMReport: Report = { + reportID: SELF_DM_REPORT_ID, + chatType: CONST.REPORT.CHAT_TYPE.SELF_DM, + type: CONST.REPORT.TYPE.CHAT, + }; + + function buildParams(): TransactionInlineEditParams { + return { + hash: 123456, + isOffline: false, + transactionID: TRANSACTION_ID, + transaction: snapshotTransaction, + parentReport: selfDMReport, + parentReportAction: undefined, + transactionThreadReport: undefined, + policy: undefined, + policyCategories: {}, + policyTags: undefined, + reportPolicyTags: undefined, + policyRecentlyUsedCategories: undefined, + policyRecentlyUsedTags: undefined, + isSelfTourViewed: true, + hasCompletedGuidedSetupFlow: true, + personalDetailsList: undefined, + delegateAccountID: undefined, + isTrackIntentUser: false, + getCurrencyDecimals: () => 2, + getCurrencySymbol: () => '$', }; + } + + beforeEach(() => jest.clearAllMocks()); + + // Onyx is never initialised here, so the module-level transaction cache is empty. That is exactly + // the state of a Search row the user has not opened: it exists only in the search snapshot. + it.each([ + ['date', () => editTransactionDateInline(buildParams(), '2026-01-15', undefined), () => updateMoneyRequestDate, {value: '2026-01-15'}], + ['merchant', () => editTransactionMerchantInline(buildParams(), 'Cafe'), () => updateMoneyRequestMerchant, {value: 'Cafe'}], + ['description', () => editTransactionDescriptionInline(buildParams(), 'Lunch'), () => updateMoneyRequestDescription, {comment: 'Lunch'}], + ['category', () => editTransactionCategoryInline(buildParams(), 'Benefits'), () => updateMoneyRequestCategory, {category: 'Benefits'}], + ['amount', () => editTransactionAmountInline(buildParams(), 500), () => updateMoneyRequestAmountAndCurrency, {amount: 500}], + ['tag', () => editTransactionTagInline(buildParams(), 'Project1'), () => updateMoneyRequestTag, {tag: 'Project1'}], + ])('forwards the caller transaction when editing %s', (_field, edit, getDelegate, expectedChange) => { + edit(); + + expect(getDelegate()).toHaveBeenCalledWith(expect.objectContaining({transactionID: TRANSACTION_ID, transaction: snapshotTransaction, ...expectedChange})); + }); - const permissions = getTransactionEditPermissions({ - ...baseParams, - transaction: reportedTransaction, - chatReportNVP, - }); + it('clears the merchant instead of discarding the edit', () => { + // isValidMerchant only allows an empty merchant on an unreported expense, which it can only + // tell from the transaction. Without one the edit was dropped before any API call. + editTransactionMerchantInline(buildParams(), ''); - expect(permissions).toEqual(allFalsePermissions); + expect(updateMoneyRequestMerchant).toHaveBeenCalledWith(expect.objectContaining({value: CONST.TRANSACTION.PARTIAL_TRANSACTION_MERCHANT})); }); }); }); diff --git a/tests/unit/inlineEditing/TransactionInlineEditCategory.test.ts b/tests/unit/inlineEditing/TransactionInlineEditCategory.test.ts deleted file mode 100644 index f625b6c5c815..000000000000 --- a/tests/unit/inlineEditing/TransactionInlineEditCategory.test.ts +++ /dev/null @@ -1,123 +0,0 @@ -import type {TransactionInlineEditParams} from '@libs/actions/TransactionInlineEdit'; -import {editTransactionCategoryInline} from '@libs/actions/TransactionInlineEdit'; -import {write} from '@libs/API'; -import {WRITE_COMMANDS} from '@libs/API/types'; - -import CONST from '@src/CONST'; -import ONYXKEYS from '@src/ONYXKEYS'; -import type {PolicyCategories, Report, Transaction} from '@src/types/onyx'; - -import Onyx from 'react-native-onyx'; - -import waitForBatchedUpdates from '../../utils/waitForBatchedUpdates'; - -jest.mock('@libs/API'); -jest.mock('@libs/Network/enhanceParameters', () => ({ - __esModule: true, - default: (_: string, params: Record) => params, -})); - -const mockWrite = jest.mocked(write); - -const TRANSACTION_ID = '7777777777777777777'; -const SELF_DM_REPORT_ID = '4242424242'; - -/** An unreported expense as the Search table renders it, i.e. straight out of the search snapshot. */ -const snapshotTransaction: Transaction = { - transactionID: TRANSACTION_ID, - reportID: CONST.REPORT.UNREPORTED_REPORT_ID, - amount: -10000, - currency: 'USD', - merchant: 'Coffee', - created: '2026-08-12', - comment: {}, -}; - -const selfDMReport: Report = { - reportID: SELF_DM_REPORT_ID, - chatType: CONST.REPORT.CHAT_TYPE.SELF_DM, - type: CONST.REPORT.TYPE.CHAT, -}; - -const policyCategories: PolicyCategories = { - Benefits: {name: 'Benefits', enabled: true}, - Travel: {name: 'Travel', enabled: true}, -}; - -function buildParams(transaction: TransactionInlineEditParams['transaction']): TransactionInlineEditParams { - return { - hash: 123456, - isOffline: false, - transactionID: TRANSACTION_ID, - transaction, - parentReport: selfDMReport, - parentReportAction: undefined, - transactionThreadReport: undefined, - policy: undefined, - policyCategories, - policyTags: undefined, - reportPolicyTags: undefined, - policyRecentlyUsedCategories: undefined, - policyRecentlyUsedTags: undefined, - isSelfTourViewed: true, - hasCompletedGuidedSetupFlow: true, - personalDetailsList: undefined, - delegateAccountID: undefined, - isTrackIntentUser: false, - getCurrencyDecimals: () => 2, - getCurrencySymbol: () => '$', - }; -} - -function getLastWrittenParams() { - const call = mockWrite.mock.calls.at(-1); - expect(call?.[0]).toBe(WRITE_COMMANDS.UPDATE_MONEY_REQUEST_CATEGORY); - return call?.[1]; -} - -/** Reads the live TRANSACTION entry, disconnecting so the subscription does not outlive the test. */ -function readLiveTransaction() { - return new Promise((resolve) => { - const connection = Onyx.connectWithoutView({ - key: `${ONYXKEYS.COLLECTION.TRANSACTION}${TRANSACTION_ID}`, - callback: (value) => { - Onyx.disconnect(connection); - resolve(value); - }, - }); - }); -} - -describe('editTransactionCategoryInline', () => { - beforeAll(() => { - Onyx.init({keys: ONYXKEYS}); - }); - - beforeEach(async () => { - jest.clearAllMocks(); - await Onyx.clear(); - await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${SELF_DM_REPORT_ID}`, selfDMReport); - await waitForBatchedUpdates(); - }); - - it('sends the selected category when the transaction is only in the search snapshot', async () => { - // Search stores its results under snapshot_ only, so right after a fresh sign-in the - // live TRANSACTION collection has no entry for a row the user can already see and edit. - expect(await readLiveTransaction()).toBeUndefined(); - - editTransactionCategoryInline(buildParams(snapshotTransaction), 'Benefits'); - await waitForBatchedUpdates(); - - expect(getLastWrittenParams()).toEqual(expect.objectContaining({transactionID: TRANSACTION_ID, category: 'Benefits'})); - }); - - it('still falls back to the live transaction when the caller has none', async () => { - await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION}${TRANSACTION_ID}`, snapshotTransaction); - await waitForBatchedUpdates(); - - editTransactionCategoryInline(buildParams(undefined), 'Travel'); - await waitForBatchedUpdates(); - - expect(getLastWrittenParams()).toEqual(expect.objectContaining({transactionID: TRANSACTION_ID, category: 'Travel'})); - }); -}); From 89e749145ceded557b4270d9ef8aa6c99de09986 Mon Sep 17 00:00:00 2001 From: Mukher Date: Mon, 24 Aug 2026 09:32:42 +0500 Subject: [PATCH 5/7] Use US spelling in a test comment cspell flagged "initialised" in the CI spell check. --- tests/unit/inlineEditing/TransactionInlineEdit.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/unit/inlineEditing/TransactionInlineEdit.test.ts b/tests/unit/inlineEditing/TransactionInlineEdit.test.ts index ef2f4d7c8370..eca545631752 100644 --- a/tests/unit/inlineEditing/TransactionInlineEdit.test.ts +++ b/tests/unit/inlineEditing/TransactionInlineEdit.test.ts @@ -526,7 +526,7 @@ describe('TransactionInlineEdit', () => { beforeEach(() => jest.clearAllMocks()); - // Onyx is never initialised here, so the module-level transaction cache is empty. That is exactly + // Onyx is never initialized here, so the module-level transaction cache is empty. That is exactly // the state of a Search row the user has not opened: it exists only in the search snapshot. it.each([ ['date', () => editTransactionDateInline(buildParams(), '2026-01-15', undefined), () => updateMoneyRequestDate, {value: '2026-01-15'}], From 60d8a5a2e5bcd72059c075d7e9dc26700f4be0f4 Mon Sep 17 00:00:00 2001 From: Mukher Date: Mon, 24 Aug 2026 13:04:55 +0500 Subject: [PATCH 6/7] Pass the transaction as its own parameter to getUpdateTrackExpenseParams --- src/libs/actions/IOU/UpdateMoneyRequest.ts | 58 ++++++++++--------- src/libs/actions/MergeTransaction.ts | 3 +- .../actions/IOUTest/UpdateMoneyRequestTest.ts | 8 +-- 3 files changed, 37 insertions(+), 32 deletions(-) diff --git a/src/libs/actions/IOU/UpdateMoneyRequest.ts b/src/libs/actions/IOU/UpdateMoneyRequest.ts index 230cf0ed92f1..bd6133fc8604 100644 --- a/src/libs/actions/IOU/UpdateMoneyRequest.ts +++ b/src/libs/actions/IOU/UpdateMoneyRequest.ts @@ -220,7 +220,7 @@ function getRecalculatedDistanceRateIDForExpenseDate({ /** Updates the created date of an expense */ function updateMoneyRequestDate({ transactionID, - transaction: transactionFromCaller, + transaction: transactionParam, transactionThreadReport, parentReport, iouReportOwnerLogin, @@ -244,7 +244,7 @@ function updateMoneyRequestDate({ getCurrencyDecimals, getCurrencySymbol, }: UpdateMoneyRequestDateParams) { - const transaction = transactionFromCaller ?? getAllTransactions()[`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`]; + const transaction = transactionParam ?? getAllTransactions()[`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`]; const isTrackExpense = isTrackExpenseReport(transactionThreadReport) && isSelfDM(parentReport); const effectivePolicy = isTrackExpense ? policyForTrackExpense : policy; const currentTransactionViolations = transactionViolations?.[`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${transactionID}`] ?? []; @@ -304,15 +304,14 @@ function updateMoneyRequestDate({ if (isTrackExpense) { data = getUpdateTrackExpenseParams( transactionID, + transaction, transactionThreadReport?.reportID, transactionChanges, effectivePolicy, delegateAccountID, - {getCurrencyDecimals, getCurrencySymbol, transaction}, + {getCurrencyDecimals, getCurrencySymbol}, hash, - undefined, - distanceOriginalPolicy, - currentTransactionViolations, + {distanceOriginalPolicy, currentTransactionViolations}, ); } else { data = getUpdateMoneyRequestParams({ @@ -525,11 +524,12 @@ function updateMoneyRequestMerchant({ if (isTrackExpenseReport(transactionThreadReport) && isSelfDM(parentReport)) { data = getUpdateTrackExpenseParams( transactionID, + transaction, transactionThreadReport?.reportID, transactionChanges, policy, delegateAccountID, - {getCurrencyDecimals, getCurrencySymbol, transaction}, + {getCurrencyDecimals, getCurrencySymbol}, hash, ); } else { @@ -1088,15 +1088,14 @@ function updateMoneyRequestDistance({ if (isTrackExpenseReport(transactionThreadReport) && isSelfDM(parentReport)) { data = getUpdateTrackExpenseParams( transaction?.transactionID, + transaction, transactionThreadReport?.reportID, transactionChanges, policy, delegateAccountID, {personalPolicyOutputCurrency, getCurrencyDecimals, getCurrencySymbol}, undefined, - undefined, - distanceOriginalPolicy, - undefined, + {distanceOriginalPolicy}, ); } else { data = getUpdateMoneyRequestParams({ @@ -1300,11 +1299,12 @@ function updateMoneyRequestDescription({ if (isTrackExpenseReport(transactionThreadReport) && isSelfDM(parentReport)) { data = getUpdateTrackExpenseParams( transactionID, + transaction, transactionThreadReport?.reportID, transactionChanges, policy, delegateAccountID, - {getCurrencyDecimals, getCurrencySymbol, transaction}, + {getCurrencyDecimals, getCurrencySymbol}, hash, ); } else { @@ -1423,15 +1423,14 @@ function updateMoneyRequestDistanceRate({ if (isTrackExpenseReport(transactionThreadReport) && isSelfDM(parentReport)) { data = getUpdateTrackExpenseParams( transaction?.transactionID, + transaction, transactionThreadReport?.reportID, transactionChanges, policy, delegateAccountID, {personalPolicyOutputCurrency, getCurrencyDecimals, getCurrencySymbol}, hash, - shouldBuildOptimisticModifiedExpenseReportAction, - distanceOriginalPolicy, - currentTransactionViolations, + {shouldBuildOptimisticModifiedExpenseReportAction, distanceOriginalPolicy, currentTransactionViolations}, ); } else { data = getUpdateMoneyRequestParams({ @@ -1540,11 +1539,12 @@ function updateMoneyRequestAmountAndCurrency({ if (isTrackExpenseReport(transactionThreadReport) && isSelfDM(parentReport)) { data = getUpdateTrackExpenseParams( transactionID, + transaction, transactionThreadReport?.reportID, transactionChanges, policy, delegateAccountID, - {getCurrencyDecimals, getCurrencySymbol, transaction}, + {getCurrencyDecimals, getCurrencySymbol}, hash, ); } else { @@ -1625,7 +1625,7 @@ type UpdateMoneyRequestDataKeys = function getUpdateMoneyRequestParams(params: GetUpdateMoneyRequestParamsType): UpdateMoneyRequestData { const { transactionID, - transaction: transactionFromCaller, + transaction: transactionParam, transactionThreadReport, transactionChanges, policy, @@ -1689,7 +1689,7 @@ function getUpdateMoneyRequestParams(params: GetUpdateMoneyRequestParamsType): U > = []; // Step 1: Get the transaction being updated - const transaction = transactionFromCaller ?? getAllTransactions()?.[`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`]; + const transaction = transactionParam ?? getAllTransactions()?.[`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`]; // The manual-distance submit path always sends waypoints to keep the BE in sync, even when the user // only edited the distance number. Detect whether the addresses actually changed so we can skip the @@ -2284,26 +2284,29 @@ function getUpdateMoneyRequestParams(params: GetUpdateMoneyRequestParamsType): U * @param policy May be undefined, an empty object, or an object matching the Policy type (src/types/onyx/Policy.ts) * @param [shouldBuildOptimisticModifiedExpenseReportAction=true] When true, build an optimistic MODIFIED_EXPENSE report action. */ -type TrackExpenseContext = { +/** Rarely-set extras, grouped so the parameter list stays within the max-params limit. */ +type TrackExpenseParamsOptions = { + shouldBuildOptimisticModifiedExpenseReportAction?: boolean; + distanceOriginalPolicy?: OnyxEntry; + currentTransactionViolations?: OnyxEntry; +}; + +type TrackExpenseCurrencyContext = { personalPolicyOutputCurrency?: string; getCurrencyDecimals: CurrencyListActionsContextType['getCurrencyDecimals']; getCurrencySymbol: CurrencyListActionsContextType['getCurrencySymbol']; - - /** Transaction supplied by the caller, e.g. a Search row read from the snapshot rather than the live collection. */ - transaction?: OnyxEntry; }; function getUpdateTrackExpenseParams( transactionID: string | undefined, + transactionParam: OnyxEntry, transactionThreadReportID: string | undefined, transactionChanges: TransactionChanges, policy: OnyxEntry, delegateAccountID: number | undefined, - trackExpenseContext: TrackExpenseContext, + currencyContext: TrackExpenseCurrencyContext, hash?: number, - shouldBuildOptimisticModifiedExpenseReportAction = true, - distanceOriginalPolicy?: OnyxEntry, - currentTransactionViolations?: OnyxEntry, + options: TrackExpenseParamsOptions = {}, ): UpdateMoneyRequestData< | typeof ONYXKEYS.COLLECTION.REPORT_ACTIONS | typeof ONYXKEYS.COLLECTION.TRANSACTION @@ -2312,7 +2315,8 @@ function getUpdateTrackExpenseParams( | typeof ONYXKEYS.COLLECTION.SNAPSHOT | typeof ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS > { - const {personalPolicyOutputCurrency, getCurrencyDecimals, getCurrencySymbol, transaction: transactionFromCaller} = trackExpenseContext; + const {personalPolicyOutputCurrency, getCurrencyDecimals, getCurrencySymbol} = currencyContext; + const {shouldBuildOptimisticModifiedExpenseReportAction = true, distanceOriginalPolicy, currentTransactionViolations} = options; const optimisticData: Array< OnyxUpdate< | typeof ONYXKEYS.COLLECTION.REPORT_ACTIONS @@ -2342,7 +2346,7 @@ function getUpdateTrackExpenseParams( // Step 2: Get all the collections being updated const transactionThread = getAllReports()?.[`${ONYXKEYS.COLLECTION.REPORT}${transactionThreadReportID}`] ?? null; - const transaction = transactionFromCaller ?? getAllTransactions()?.[`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`]; + const transaction = transactionParam ?? getAllTransactions()?.[`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`]; const chatReport = getAllReports()?.[`${ONYXKEYS.COLLECTION.REPORT}${transactionThread?.parentReportID}`] ?? null; const policyForTransaction = distanceOriginalPolicy ?? policy; const updatedTransaction = transaction diff --git a/src/libs/actions/MergeTransaction.ts b/src/libs/actions/MergeTransaction.ts index e11fea8bfa39..d2bdc9c4881d 100644 --- a/src/libs/actions/MergeTransaction.ts +++ b/src/libs/actions/MergeTransaction.ts @@ -330,13 +330,14 @@ function getOnyxTargetTransactionData({ if (isUnreportedExpense) { data = getUpdateTrackExpenseParams( targetTransaction.transactionID, + targetTransaction, targetTransactionThreadReport?.reportID, filteredTransactionChanges, policy, delegateAccountID, {getCurrencyDecimals, getCurrencySymbol}, undefined, - shouldBuildOptimisticModifiedExpenseReportAction, + {shouldBuildOptimisticModifiedExpenseReportAction}, ); } else { data = getUpdateMoneyRequestParams({ diff --git a/tests/actions/IOUTest/UpdateMoneyRequestTest.ts b/tests/actions/IOUTest/UpdateMoneyRequestTest.ts index 86912c6765f0..1160de5e2386 100644 --- a/tests/actions/IOUTest/UpdateMoneyRequestTest.ts +++ b/tests/actions/IOUTest/UpdateMoneyRequestTest.ts @@ -582,6 +582,7 @@ describe('actions/IOU/UpdateMoneyRequest', () => { const {onyxData} = getUpdateTrackExpenseParams( transactionID, + undefined, transactionThreadReport.reportID, {amount: 20000}, createRandomPolicy(1), @@ -2018,7 +2019,7 @@ describe('actions/IOU/UpdateMoneyRequest', () => { await waitForBatchedUpdates(); // When the caller passes a higher-precision distance than what `customUnit.quantity` would round to - const {params} = getUpdateTrackExpenseParams(transactionID, transactionThreadReportID, {distance: 5.555}, fakePolicy, undefined, { + const {params} = getUpdateTrackExpenseParams(transactionID, undefined, transactionThreadReportID, {distance: 5.555}, fakePolicy, undefined, { getCurrencyDecimals: getCurrencyDecimalsLocal, getCurrencySymbol: getCurrencySymbolLocal, }); @@ -2091,15 +2092,14 @@ describe('actions/IOU/UpdateMoneyRequest', () => { const {onyxData} = getUpdateTrackExpenseParams( transactionID, + undefined, transactionThreadReportID, {created: '2026-06-15'}, fakePolicy, undefined, {getCurrencyDecimals: getCurrencyDecimalsLocal, getCurrencySymbol: getCurrencySymbolLocal}, snapshotHash, - undefined, - undefined, - [], + {currentTransactionViolations: []}, ); const snapshotKey = `${ONYXKEYS.COLLECTION.SNAPSHOT}${snapshotHash}` as const; From 8b21fe6430f819341a91d6e3cf44281f2582afa8 Mon Sep 17 00:00:00 2001 From: Mukher Date: Mon, 24 Aug 2026 13:54:45 +0500 Subject: [PATCH 7/7] Take a single params object in getUpdateTrackExpenseParams --- src/libs/actions/IOU/UpdateMoneyRequest.ts | 109 ++++++++++-------- src/libs/actions/MergeTransaction.ts | 17 ++- .../actions/IOUTest/UpdateMoneyRequestTest.ts | 44 +++---- 3 files changed, 92 insertions(+), 78 deletions(-) diff --git a/src/libs/actions/IOU/UpdateMoneyRequest.ts b/src/libs/actions/IOU/UpdateMoneyRequest.ts index bd6133fc8604..09a17ff63ae4 100644 --- a/src/libs/actions/IOU/UpdateMoneyRequest.ts +++ b/src/libs/actions/IOU/UpdateMoneyRequest.ts @@ -302,17 +302,18 @@ function updateMoneyRequestDate({ let data: UpdateMoneyRequestData; if (isTrackExpense) { - data = getUpdateTrackExpenseParams( + data = getUpdateTrackExpenseParams({ transactionID, transaction, - transactionThreadReport?.reportID, + transactionThreadReportID: transactionThreadReport?.reportID, transactionChanges, - effectivePolicy, + policy: effectivePolicy, delegateAccountID, - {getCurrencyDecimals, getCurrencySymbol}, + currencyContext: {getCurrencyDecimals, getCurrencySymbol}, hash, - {distanceOriginalPolicy, currentTransactionViolations}, - ); + distanceOriginalPolicy, + currentTransactionViolations, + }); } else { data = getUpdateMoneyRequestParams({ transactionID, @@ -522,16 +523,16 @@ function updateMoneyRequestMerchant({ let data: UpdateMoneyRequestData; if (isTrackExpenseReport(transactionThreadReport) && isSelfDM(parentReport)) { - data = getUpdateTrackExpenseParams( + data = getUpdateTrackExpenseParams({ transactionID, transaction, - transactionThreadReport?.reportID, + transactionThreadReportID: transactionThreadReport?.reportID, transactionChanges, policy, delegateAccountID, - {getCurrencyDecimals, getCurrencySymbol}, + currencyContext: {getCurrencyDecimals, getCurrencySymbol}, hash, - ); + }); } else { data = getUpdateMoneyRequestParams({ transactionID, @@ -1086,17 +1087,16 @@ function updateMoneyRequestDistance({ let data: UpdateMoneyRequestData; if (isTrackExpenseReport(transactionThreadReport) && isSelfDM(parentReport)) { - data = getUpdateTrackExpenseParams( - transaction?.transactionID, + data = getUpdateTrackExpenseParams({ + transactionID: transaction?.transactionID, transaction, - transactionThreadReport?.reportID, + transactionThreadReportID: transactionThreadReport?.reportID, transactionChanges, policy, delegateAccountID, - {personalPolicyOutputCurrency, getCurrencyDecimals, getCurrencySymbol}, - undefined, - {distanceOriginalPolicy}, - ); + currencyContext: {personalPolicyOutputCurrency, getCurrencyDecimals, getCurrencySymbol}, + distanceOriginalPolicy, + }); } else { data = getUpdateMoneyRequestParams({ transactionID: transaction?.transactionID, @@ -1297,16 +1297,16 @@ function updateMoneyRequestDescription({ let data: UpdateMoneyRequestData; if (isTrackExpenseReport(transactionThreadReport) && isSelfDM(parentReport)) { - data = getUpdateTrackExpenseParams( + data = getUpdateTrackExpenseParams({ transactionID, transaction, - transactionThreadReport?.reportID, + transactionThreadReportID: transactionThreadReport?.reportID, transactionChanges, policy, delegateAccountID, - {getCurrencyDecimals, getCurrencySymbol}, + currencyContext: {getCurrencyDecimals, getCurrencySymbol}, hash, - ); + }); } else { data = getUpdateMoneyRequestParams({ transactionID, @@ -1421,17 +1421,19 @@ function updateMoneyRequestDistanceRate({ currentTransactionViolationsParam ?? (transaction?.transactionID ? transactionViolations?.[`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${transaction.transactionID}`] : undefined); if (isTrackExpenseReport(transactionThreadReport) && isSelfDM(parentReport)) { - data = getUpdateTrackExpenseParams( - transaction?.transactionID, + data = getUpdateTrackExpenseParams({ + transactionID: transaction?.transactionID, transaction, - transactionThreadReport?.reportID, + transactionThreadReportID: transactionThreadReport?.reportID, transactionChanges, policy, delegateAccountID, - {personalPolicyOutputCurrency, getCurrencyDecimals, getCurrencySymbol}, + currencyContext: {personalPolicyOutputCurrency, getCurrencyDecimals, getCurrencySymbol}, hash, - {shouldBuildOptimisticModifiedExpenseReportAction, distanceOriginalPolicy, currentTransactionViolations}, - ); + shouldBuildOptimisticModifiedExpenseReportAction, + distanceOriginalPolicy, + currentTransactionViolations, + }); } else { data = getUpdateMoneyRequestParams({ transactionID: transaction?.transactionID, @@ -1537,16 +1539,16 @@ function updateMoneyRequestAmountAndCurrency({ let data: UpdateMoneyRequestData; if (isTrackExpenseReport(transactionThreadReport) && isSelfDM(parentReport)) { - data = getUpdateTrackExpenseParams( + data = getUpdateTrackExpenseParams({ transactionID, transaction, - transactionThreadReport?.reportID, + transactionThreadReportID: transactionThreadReport?.reportID, transactionChanges, policy, delegateAccountID, - {getCurrencyDecimals, getCurrencySymbol}, + currencyContext: {getCurrencyDecimals, getCurrencySymbol}, hash, - ); + }); } else { data = getUpdateMoneyRequestParams({ transactionID, @@ -2284,29 +2286,28 @@ function getUpdateMoneyRequestParams(params: GetUpdateMoneyRequestParamsType): U * @param policy May be undefined, an empty object, or an object matching the Policy type (src/types/onyx/Policy.ts) * @param [shouldBuildOptimisticModifiedExpenseReportAction=true] When true, build an optimistic MODIFIED_EXPENSE report action. */ -/** Rarely-set extras, grouped so the parameter list stays within the max-params limit. */ -type TrackExpenseParamsOptions = { - shouldBuildOptimisticModifiedExpenseReportAction?: boolean; - distanceOriginalPolicy?: OnyxEntry; - currentTransactionViolations?: OnyxEntry; -}; - type TrackExpenseCurrencyContext = { personalPolicyOutputCurrency?: string; getCurrencyDecimals: CurrencyListActionsContextType['getCurrencyDecimals']; getCurrencySymbol: CurrencyListActionsContextType['getCurrencySymbol']; }; +type GetUpdateTrackExpenseParamsType = { + transactionID: string | undefined; + transaction?: OnyxEntry; + transactionThreadReportID: string | undefined; + transactionChanges: TransactionChanges; + policy: OnyxEntry; + delegateAccountID: number | undefined; + currencyContext: TrackExpenseCurrencyContext; + hash?: number; + shouldBuildOptimisticModifiedExpenseReportAction?: boolean; + distanceOriginalPolicy?: OnyxEntry; + currentTransactionViolations?: OnyxEntry; +}; + function getUpdateTrackExpenseParams( - transactionID: string | undefined, - transactionParam: OnyxEntry, - transactionThreadReportID: string | undefined, - transactionChanges: TransactionChanges, - policy: OnyxEntry, - delegateAccountID: number | undefined, - currencyContext: TrackExpenseCurrencyContext, - hash?: number, - options: TrackExpenseParamsOptions = {}, + params: GetUpdateTrackExpenseParamsType, ): UpdateMoneyRequestData< | typeof ONYXKEYS.COLLECTION.REPORT_ACTIONS | typeof ONYXKEYS.COLLECTION.TRANSACTION @@ -2315,8 +2316,20 @@ function getUpdateTrackExpenseParams( | typeof ONYXKEYS.COLLECTION.SNAPSHOT | typeof ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS > { + const { + transactionID, + transaction: transactionParam, + transactionThreadReportID, + transactionChanges, + policy, + delegateAccountID, + currencyContext, + hash, + shouldBuildOptimisticModifiedExpenseReportAction = true, + distanceOriginalPolicy, + currentTransactionViolations, + } = params; const {personalPolicyOutputCurrency, getCurrencyDecimals, getCurrencySymbol} = currencyContext; - const {shouldBuildOptimisticModifiedExpenseReportAction = true, distanceOriginalPolicy, currentTransactionViolations} = options; const optimisticData: Array< OnyxUpdate< | typeof ONYXKEYS.COLLECTION.REPORT_ACTIONS diff --git a/src/libs/actions/MergeTransaction.ts b/src/libs/actions/MergeTransaction.ts index d2bdc9c4881d..2f05e638c36b 100644 --- a/src/libs/actions/MergeTransaction.ts +++ b/src/libs/actions/MergeTransaction.ts @@ -328,17 +328,16 @@ function getOnyxTargetTransactionData({ const shouldBuildOptimisticModifiedExpenseReportAction = false; if (isUnreportedExpense) { - data = getUpdateTrackExpenseParams( - targetTransaction.transactionID, - targetTransaction, - targetTransactionThreadReport?.reportID, - filteredTransactionChanges, + data = getUpdateTrackExpenseParams({ + transactionID: targetTransaction.transactionID, + transaction: targetTransaction, + transactionThreadReportID: targetTransactionThreadReport?.reportID, + transactionChanges: filteredTransactionChanges, policy, delegateAccountID, - {getCurrencyDecimals, getCurrencySymbol}, - undefined, - {shouldBuildOptimisticModifiedExpenseReportAction}, - ); + currencyContext: {getCurrencyDecimals, getCurrencySymbol}, + shouldBuildOptimisticModifiedExpenseReportAction, + }); } else { data = getUpdateMoneyRequestParams({ transactionID: targetTransaction.transactionID, diff --git a/tests/actions/IOUTest/UpdateMoneyRequestTest.ts b/tests/actions/IOUTest/UpdateMoneyRequestTest.ts index 1160de5e2386..e6af5d5d4be6 100644 --- a/tests/actions/IOUTest/UpdateMoneyRequestTest.ts +++ b/tests/actions/IOUTest/UpdateMoneyRequestTest.ts @@ -580,16 +580,15 @@ describe('actions/IOU/UpdateMoneyRequest', () => { await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`, transaction); await waitForBatchedUpdates(); - const {onyxData} = getUpdateTrackExpenseParams( + const {onyxData} = getUpdateTrackExpenseParams({ transactionID, - undefined, - transactionThreadReport.reportID, - {amount: 20000}, - createRandomPolicy(1), - undefined, - {getCurrencyDecimals: getCurrencyDecimalsLocal, getCurrencySymbol: getCurrencySymbolLocal}, - snapshotHash, - ); + transactionThreadReportID: transactionThreadReport.reportID, + transactionChanges: {amount: 20000}, + policy: createRandomPolicy(1), + delegateAccountID: undefined, + currencyContext: {getCurrencyDecimals: getCurrencyDecimalsLocal, getCurrencySymbol: getCurrencySymbolLocal}, + hash: snapshotHash, + }); const snapshotKey = `${ONYXKEYS.COLLECTION.SNAPSHOT}${snapshotHash}` as const; const transactionKey: keyof SearchResults['data'] = `${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`; type SnapshotUpdate = Extract, {onyxMethod: typeof Onyx.METHOD.SET | typeof Onyx.METHOD.MERGE}>; @@ -2019,9 +2018,13 @@ describe('actions/IOU/UpdateMoneyRequest', () => { await waitForBatchedUpdates(); // When the caller passes a higher-precision distance than what `customUnit.quantity` would round to - const {params} = getUpdateTrackExpenseParams(transactionID, undefined, transactionThreadReportID, {distance: 5.555}, fakePolicy, undefined, { - getCurrencyDecimals: getCurrencyDecimalsLocal, - getCurrencySymbol: getCurrencySymbolLocal, + const {params} = getUpdateTrackExpenseParams({ + transactionID, + transactionThreadReportID, + transactionChanges: {distance: 5.555}, + policy: fakePolicy, + delegateAccountID: undefined, + currencyContext: {getCurrencyDecimals: getCurrencyDecimalsLocal, getCurrencySymbol: getCurrencySymbolLocal}, }); // Then the raw caller value flows into the API params instead of the rounded display value (5.56). @@ -2090,17 +2093,16 @@ describe('actions/IOU/UpdateMoneyRequest', () => { await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${transactionID}`, []); await waitForBatchedUpdates(); - const {onyxData} = getUpdateTrackExpenseParams( + const {onyxData} = getUpdateTrackExpenseParams({ transactionID, - undefined, transactionThreadReportID, - {created: '2026-06-15'}, - fakePolicy, - undefined, - {getCurrencyDecimals: getCurrencyDecimalsLocal, getCurrencySymbol: getCurrencySymbolLocal}, - snapshotHash, - {currentTransactionViolations: []}, - ); + transactionChanges: {created: '2026-06-15'}, + policy: fakePolicy, + delegateAccountID: undefined, + currencyContext: {getCurrencyDecimals: getCurrencyDecimalsLocal, getCurrencySymbol: getCurrencySymbolLocal}, + hash: snapshotHash, + currentTransactionViolations: [], + }); const snapshotKey = `${ONYXKEYS.COLLECTION.SNAPSHOT}${snapshotHash}` as const; const violationsKey = `${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${transactionID}` as const;