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
37 changes: 37 additions & 0 deletions src/hooks/useDuplicateTransactionsAndViolations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ import type {Transaction, TransactionViolation, TransactionViolations} from '@sr
import type {OnyxCollection} from 'react-native-onyx';

import {useMemo} from 'react';
// Use the original useOnyx hook to get the real-time data from Onyx and not from the snapshot
// eslint-disable-next-line no-restricted-imports
import {useOnyx as useOnyxWithoutSnapshots} from 'react-native-onyx';

import useOnyx from './useOnyx';

Expand Down Expand Up @@ -143,4 +146,38 @@ function useDuplicateTransactionsAndViolations(transactionIDs: string[]): Duplic
);
}

/**
* Same as {@link useDuplicateTransactionsAndViolations}, but reads the transaction and violation collections from live
* Onyx rather than the Search snapshot.
* More info: https://github.com/Expensify/App/pull/99279#discussion_r3892786625
* @param transactionIDs - Array of transaction IDs to check for duplicates.
* @returns - An object containing duplicate transactions and their violations.
*/
function useLiveDuplicateTransactionsAndViolations(transactionIDs: string[]): DuplicateTransactionsAndViolations {
const violationsSelectorMemo = useMemo(() => {
return (allTransactionsViolations: OnyxCollection<TransactionViolations>) => selectViolationsWithDuplicates(transactionIDs, allTransactionsViolations);
}, [transactionIDs]);

const [duplicateTransactionViolations] = useOnyxWithoutSnapshots(ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS, {
selector: violationsSelectorMemo,
});

const transactionSelector = useMemo(() => {
return (allTransactions: OnyxCollection<Transaction>) => selectTransactionsWithDuplicates(transactionIDs, allTransactions, duplicateTransactionViolations);
}, [transactionIDs, duplicateTransactionViolations]);

const [duplicateTransactions] = useOnyxWithoutSnapshots(ONYXKEYS.COLLECTION.TRANSACTION, {
selector: transactionSelector,
});

return useMemo(
() => ({
duplicateTransactions,
duplicateTransactionViolations,
}),
[duplicateTransactions, duplicateTransactionViolations],
);
}

export {useLiveDuplicateTransactionsAndViolations};
export default useDuplicateTransactionsAndViolations;
25 changes: 23 additions & 2 deletions src/hooks/useTransactionInlineEdit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import {useOnyx as originalUseOnyx} from 'react-native-onyx';
import {useCurrencyListActions} from './useCurrencyList';
import useDelegateAccountID from './useDelegateAccountID';
import useDistanceRateOriginalPolicy from './useDistanceRateOriginalPolicy';
import {useLiveDuplicateTransactionsAndViolations} from './useDuplicateTransactionsAndViolations';
import useNetwork from './useNetwork';
import useOnyx from './useOnyx';
import usePersonalPolicy from './usePersonalPolicy';
Expand Down Expand Up @@ -94,6 +95,11 @@ function useTransactionInlineEdit({transactionID, hash, linkedReportAction}: Use
const effectiveParentReport = isUnreported ? selfDMReport : parentReport;
const effectiveParentReportID = effectiveParentReport?.reportID;

const [liveParentReport] = originalUseOnyx(`${ONYXKEYS.COLLECTION.REPORT}${getNonEmptyStringOnyxID(reportID)}`);
const [selfDMReportID] = useOnyx(ONYXKEYS.SELF_DM_REPORT_ID);
const [liveSelfDMReport] = originalUseOnyx(`${ONYXKEYS.COLLECTION.REPORT}${getNonEmptyStringOnyxID(selfDMReportID)}`);
const parentReportForAction = isUnreported ? (liveSelfDMReport ?? selfDMReport) : (effectiveParentReport ?? liveParentReport);

const linkedReportActionID = linkedReportAction?.reportActionID;

// Use original Onyx here because the useOnyx wrapper can read the partial Search snapshot report actions, which may miss
Expand Down Expand Up @@ -123,6 +129,7 @@ function useTransactionInlineEdit({transactionID, hash, linkedReportAction}: Use
});

const [transactionThreadReport] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${getNonEmptyStringOnyxID(transactionThreadReportID)}`);
const [liveTransactionThreadReport] = originalUseOnyx(`${ONYXKEYS.COLLECTION.REPORT}${getNonEmptyStringOnyxID(transactionThreadReportID)}`);
const [policyCategories] = useOnyx(`${ONYXKEYS.COLLECTION.POLICY_CATEGORIES}${getNonEmptyStringOnyxID(policyID)}`);
const [policyTags] = useOnyx(`${ONYXKEYS.COLLECTION.POLICY_TAGS}${getNonEmptyStringOnyxID(policyID)}`);
const [reportPolicyTags] = useOnyx(`${ONYXKEYS.COLLECTION.POLICY_TAGS}${getNonEmptyStringOnyxID(reportPolicyID)}`);
Expand All @@ -139,6 +146,14 @@ function useTransactionInlineEdit({transactionID, hash, linkedReportAction}: Use
const [originalTransaction] = useOnyx(`${ONYXKEYS.COLLECTION.TRANSACTION}${getNonEmptyStringOnyxID(originalTransactionID)}`);
const [personalDetailsList] = useOnyx(ONYXKEYS.PERSONAL_DETAILS_LIST);
const [isTrackIntentUser] = useOnyx(ONYXKEYS.NVP_INTRO_SELECTED, {selector: isTrackIntentUserSelector});
const [introSelected] = useOnyx(ONYXKEYS.NVP_INTRO_SELECTED);
const [session] = useOnyx(ONYXKEYS.SESSION);
const [betas] = useOnyx(ONYXKEYS.BETAS);

// Scoped transaction/violation collections (the edited transaction plus any duplicates) are read here and
// passed into the pure edit actions, which need them to resolve duplicate-transaction violations. This mirrors
// the non-inline edit flow (see DynamicIOURequestStepDate) and avoids subscribing to the full collections.
const {duplicateTransactions, duplicateTransactionViolations} = useLiveDuplicateTransactionsAndViolations([transactionID]);

const {hasSelectedTransactions} = useSearchSelectionContext();

Expand Down Expand Up @@ -179,9 +194,9 @@ function useTransactionInlineEdit({transactionID, hash, linkedReportAction}: Use
hash,
transactionID,
transaction,
parentReport: effectiveParentReport,
parentReport: parentReportForAction,
parentReportAction,
transactionThreadReport,
transactionThreadReport: transactionThreadReport ?? liveTransactionThreadReport,
policy: completePolicy ?? policy,
policyForTrackExpense: isTrackExpense ? policyForMovingExpenses : undefined,
policyCategories,
Expand All @@ -198,6 +213,12 @@ function useTransactionInlineEdit({transactionID, hash, linkedReportAction}: Use
isTrackIntentUser,
getCurrencyDecimals,
getCurrencySymbol,
transactions: duplicateTransactions,
transactionViolations: duplicateTransactionViolations,
betas,
introSelected,
currentUserAccountID: session?.accountID ?? CONST.DEFAULT_NUMBER_ID,
currentUserEmail: session?.email ?? '',
};
};

Expand Down
175 changes: 57 additions & 118 deletions src/libs/actions/TransactionInlineEdit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,8 @@ import {hasEnabledOptions} from '@libs/OptionsListUtils';
import Permissions from '@libs/Permissions';
import {getLoginByAccountID} from '@libs/PersonalDetailsUtils';
import {getTagLists, isGroupPolicy, isMultiLevelTags, resolveCurrentTaxCode} from '@libs/PolicyUtils';
import {getIOUActionForTransactionID, isMoneyRequestAction} from '@libs/ReportActionsUtils';
import {
canEditFieldOfMoneyRequest,
canEditMoneyRequest,
canUserPerformWriteAction,
findSelfDMReportID,
isArchivedReport,
isInvoiceReport,
isIOUReport,
shouldEnableNegative,
} from '@libs/ReportUtils';
import {isMoneyRequestAction} from '@libs/ReportActionsUtils';
import {canEditFieldOfMoneyRequest, canEditMoneyRequest, canUserPerformWriteAction, isArchivedReport, isInvoiceReport, isIOUReport, shouldEnableNegative} from '@libs/ReportUtils';
import {hasEnabledTags} from '@libs/TagsOptionsListUtils';
import {
calculateTaxAmount,
Expand Down Expand Up @@ -55,11 +46,12 @@ import type {ValueOf} from 'type-fest';
/**
* Actions for inline editing of transactions from the Search results table and the Expense Report page.
*
* Each function delegates to the corresponding IOU action which owns the canonical Onyx record,
* the API write, failure rollback, and snapshot updates (when a hash is provided).
* These functions are pure: every Onyx value they need (the transaction and violation
* collections, the resolved reports/report action, session, betas, etc.) is passed in by
* the caller (`useTransactionInlineEdit`), which reads it via `useOnyx`. Each function
* delegates to the corresponding IOU action which owns the canonical Onyx record, the API
* write, failure rollback, and snapshot updates (when a hash is provided).
*/
import Onyx from 'react-native-onyx';

import {
updateMoneyRequestAmountAndCurrency,
updateMoneyRequestCategory,
Expand All @@ -79,64 +71,6 @@ type TransactionEditPermissions = {
canEditTag: boolean;
};

let allTransactions: NonNullable<OnyxCollection<Transaction>> = {};
Onyx.connectWithoutView({
key: ONYXKEYS.COLLECTION.TRANSACTION,
callback: (value) => {
allTransactions = value ?? {};
},
});

let allTransactionViolations: NonNullable<OnyxCollection<TransactionViolations>> = {};
Onyx.connectWithoutView({
key: ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS,
callback: (value) => {
allTransactionViolations = value ?? {};
},
});

let allReports: NonNullable<OnyxCollection<Report>> = {};
Onyx.connectWithoutView({
key: ONYXKEYS.COLLECTION.REPORT,
callback: (value) => {
allReports = value ?? {};
},
});

let allReportActions: NonNullable<OnyxCollection<ReportActions>> = {};
Onyx.connectWithoutView({
key: ONYXKEYS.COLLECTION.REPORT_ACTIONS,
callback: (value) => {
allReportActions = value ?? {};
},
});

let currentUserAccountID: number = CONST.DEFAULT_NUMBER_ID;
let currentUserEmail = '';
Onyx.connectWithoutView({
key: ONYXKEYS.SESSION,
callback: (value) => {
currentUserEmail = value?.email ?? '';
currentUserAccountID = value?.accountID ?? CONST.DEFAULT_NUMBER_ID;
},
});

let allBetas: Beta[] | undefined;
Onyx.connectWithoutView({
key: ONYXKEYS.BETAS,
callback: (value) => {
allBetas = value ?? undefined;
},
});

let introSelected: OnyxEntry<IntroSelected>;
Onyx.connectWithoutView({
key: ONYXKEYS.NVP_INTRO_SELECTED,
callback: (value) => {
introSelected = value;
},
});

const NO_EDIT: Readonly<TransactionEditPermissions> = Object.freeze({
canEditDate: false,
canEditMerchant: false,
Expand Down Expand Up @@ -200,6 +134,24 @@ type GetIouParamsInput = {
isTrackIntentUser: boolean | undefined;
getCurrencyDecimals: CurrencyListActionsContextType['getCurrencyDecimals'];
getCurrencySymbol: CurrencyListActionsContextType['getCurrencySymbol'];

/** The transaction being edited plus any of its duplicates, scoped by the caller. */
transactions: OnyxCollection<Transaction>;

/** Violations for the transaction being edited plus any of its duplicates, scoped by the caller. */
transactionViolations: OnyxCollection<TransactionViolations>;

/** Betas the current user has access to, used to gate ASAP submit behavior. */
betas: Beta[] | undefined;

/** Onboarding intro data, needed to build a transaction thread report when one doesn't exist yet. */
introSelected: OnyxEntry<IntroSelected>;

/** The current user's account ID. */
currentUserAccountID: number;

/** The current user's email/login. */
currentUserEmail: string;
};

type TransactionInlineEditParams = GetIouParamsInput & {
Expand Down Expand Up @@ -234,52 +186,32 @@ function getIouParamsForTransaction({
isTrackIntentUser,
getCurrencyDecimals,
getCurrencySymbol,
transactionViolations,
betas,
introSelected,
currentUserAccountID,
currentUserEmail,
}: GetIouParamsInput) {
const transactionViolations = allTransactionViolations[`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${transactionID}`];
const isUnreportedExpense = !transaction?.reportID || transaction.reportID === CONST.REPORT.UNREPORTED_REPORT_ID;

let resolvedParentReport = parentReport;
if (!resolvedParentReport?.reportID && transaction?.reportID && transaction.reportID !== CONST.REPORT.UNREPORTED_REPORT_ID) {
resolvedParentReport = allReports[`${ONYXKEYS.COLLECTION.REPORT}${transaction.reportID}`];
}

let resolvedParentReportAction = parentReportAction;
if (!resolvedParentReportAction && resolvedParentReport?.reportID) {
const reportActions = allReportActions[`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${resolvedParentReport.reportID}`] ?? {};
resolvedParentReportAction = getIOUActionForTransactionID(Object.values(reportActions), transactionID);
}

if (isUnreportedExpense) {
const selfDMReportID = findSelfDMReportID(allReports);
if (selfDMReportID) {
resolvedParentReport = allReports[`${ONYXKEYS.COLLECTION.REPORT}${selfDMReportID}`] ?? resolvedParentReport;

if (!resolvedParentReportAction) {
const selfDMReportActions = allReportActions[`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${selfDMReportID}`] ?? {};
resolvedParentReportAction = getIOUActionForTransactionID(Object.values(selfDMReportActions), transactionID);
}
}
}
// transaction is passed in by the caller; only the scoped violations are derived here for the thread-report build.
const transactionViolationsForTransaction = transactionViolations?.[`${ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS}${transactionID}`];

// parentReport (already resolved to the self DM for unreported expenses), parentReportAction, and
// transactionThreadReport are resolved by the caller (useTransactionInlineEdit) via useOnyx, so they
// are used directly here. The only remaining resolution is building a transaction thread report when
// one doesn't exist in Onyx yet.
let resolvedTransactionThreadReport = transactionThreadReport;
const transactionThreadReportID = resolvedTransactionThreadReport?.reportID ?? transaction?.transactionThreadReportID ?? resolvedParentReportAction?.childReportID;

if (!resolvedTransactionThreadReport && transactionThreadReportID) {
resolvedTransactionThreadReport = allReports[`${ONYXKEYS.COLLECTION.REPORT}${transactionThreadReportID}`];
}

if (!resolvedTransactionThreadReport && resolvedParentReportAction && transaction) {
if (!resolvedTransactionThreadReport && parentReportAction && transaction) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Reuse an existing child thread before creating one

In Search snapshot mode, transactionThreadReport can be undefined even when parentReportAction.childReportID identifies an existing thread stored in live Onyx. This branch now creates a new thread with a generated ID and calls OpenReport instead of reusing that child thread; the removed allReports fallback previously recovered the live report. Editing such a Search row can therefore create a duplicate transaction thread and associate the update with the wrong optimistic report.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@MelvinBot Please fix this

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Good catch — fixed in 22be760.

Root cause: the hook already resolved transactionThreadReportID from parentReportAction.childReportID / transaction.transactionThreadReportID, but it read the report itself through the wrapped useOnyx, which serves the partial Search snapshot. In Search mode that snapshot often doesn't contain the child thread report, so transactionThreadReport came back undefined even though the thread exists in live Onyx — and the action then built a brand-new thread (generated ID + OpenReport) instead of reusing it, creating a duplicate. The pre-refactor allReports[...] fallback read from live global Onyx, so it never hit this.

Fix: read transactionThreadReport via originalUseOnyx (live Onyx) instead of the snapshot-aware wrapper — the same pattern already used a few lines up for parentReportActions and completePolicy. This restores the pre-refactor "reuse the live child thread" behavior while keeping the action pure. See src/hooks/useTransactionInlineEdit.ts:126-129.

Verified locally: ESLint ✅, React Compiler compliance ✅, npm run typecheck ✅, tests/unit/inlineEditing/TransactionInlineEdit.test.ts (26/26) ✅, tests/actions/IOUTest/UpdateMoneyRequestTest.ts (35/35) ✅.


view run

resolvedTransactionThreadReport = createTransactionThreadReport({
introSelected,
// Deferred: thread the real conciergeChat when this cascade is migrated (https://github.com/Expensify/App/issues/66411)
conciergeChat: undefined,
currentUserLogin: currentUserEmail,
currentUserAccountID,
betas: allBetas,
iouReport: resolvedParentReport,
iouReportAction: resolvedParentReportAction,
betas,
iouReport: parentReport,
iouReportAction: parentReportAction,
transaction,
transactionViolations: transactionViolations ?? undefined,
transactionViolations: transactionViolationsForTransaction ?? undefined,
personalDetails: personalDetailsList,
isSelfTourViewed,
hasCompletedGuidedSetupFlow,
Expand All @@ -289,14 +221,14 @@ function getIouParamsForTransaction({
return {
transactionID,
transactionThreadReport: resolvedTransactionThreadReport,
parentReport: resolvedParentReport,
iouReportOwnerLogin: getLoginByAccountID(resolvedParentReport?.ownerAccountID, personalDetailsList),
parentReport,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Resolve the parent report before dispatching edits

On a Search row whose partial snapshot contains the transaction/action but omits its report_<reportID> entry, the snapshot-aware hook passes parentReport as undefined even when the report exists in live Onyx. Editing can still be enabled because canEditMoneyRequest falls back to the live report internally, but this refactor no longer performs the corresponding fallback before dispatch: UpdateMoneyRequest consequently builds the API request with reportID: iouReport?.reportID as undefined and also applies the wrong optimistic report logic. Preserve the previous live-report resolution, or have the hook read and pass the complete parent report via the original Onyx hook.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Fixed! we fallback to live report in src/hooks/useTransactionInlineEdit.ts before pass to here

iouReportOwnerLogin: getLoginByAccountID(parentReport?.ownerAccountID, personalDetailsList),
policy,
policyForTrackExpense,
policyCategories,
currentUserAccountIDParam: currentUserAccountID,
currentUserEmailParam: currentUserEmail,
isASAPSubmitBetaEnabled: Permissions.isBetaEnabled(CONST.BETAS.ASAP_SUBMIT, allBetas),
isASAPSubmitBetaEnabled: Permissions.isBetaEnabled(CONST.BETAS.ASAP_SUBMIT, betas),
delegateAccountID,
isTrackIntentUser,
getCurrencyDecimals,
Expand All @@ -319,8 +251,8 @@ function editTransactionDateInline(params: TransactionInlineEditParams, newDate:
// updateMoneyRequestDate uses 'policyTags' (not policyTagList)
policyTags: iouParams.policyTagList,
value: newDate,
transactions: allTransactions,
transactionViolations: allTransactionViolations,
transactions: params.transactions,
transactionViolations: params.transactionViolations,
isOffline: params.isOffline,
hash: params.hash,
distanceOriginalPolicy: params.distanceOriginalPolicy,
Expand All @@ -330,6 +262,9 @@ 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) {
// Validate before building iouParams: getIouParamsForTransaction can call createTransactionThreadReport,
// which fires Onyx.merge + openReport (an API call). Building params first would optimistically create a
// thread report for an edit we're about to discard, so validate first.
if (!isValidMerchant(newMerchant, params.transaction, params.parentReport)) {
return;
}
Expand Down Expand Up @@ -366,15 +301,19 @@ function editTransactionCategoryInline(params: TransactionInlineEditParams, newC

/** Updates the amount and currency of an expense from the Search results table or the Expense Report page. */
function editTransactionAmountInline(params: TransactionInlineEditParams, newAmount: number) {
const iouParams = getIouParamsForTransaction(params);
// Validate before building iouParams: getIouParamsForTransaction can call createTransactionThreadReport,
// which fires Onyx.merge + openReport (an API call). Building params first would optimistically create a
// thread report for an edit we're about to discard, so validate against params directly first.
const iouType = isInvoiceReport(params.parentReport) ? CONST.IOU.TYPE.INVOICE : CONST.IOU.TYPE.SUBMIT;
const allowNegative = shouldEnableNegative(params.parentReport, iouParams.policy, iouType);
const allowNegative = shouldEnableNegative(params.parentReport, params.policy, iouType);
const isP2P = isIOUReport(params.parentReport);

if (!isValidMoneyRequestAmount(newAmount, iouType, allowNegative, isP2P)) {
return;
}

const iouParams = getIouParamsForTransaction(params);

// Keep the existing currency — only the amount is changing from the search table
const currency = iouParams.transaction?.modifiedCurrency ?? iouParams.transaction?.currency ?? CONST.CURRENCY.USD;
// Recalculate tax from the existing tax code and the new amount
Expand All @@ -390,8 +329,8 @@ function editTransactionAmountInline(params: TransactionInlineEditParams, newAmo
taxCode,
taxValue: taxPercentage,
allowNegative,
transactions: allTransactions,
transactionViolations: allTransactionViolations,
transactions: params.transactions,
transactionViolations: params.transactionViolations,
policyRecentlyUsedCurrencies: [],
hash: params.hash,
});
Expand Down
6 changes: 6 additions & 0 deletions tests/actions/IOUTest/UpdateMoneyRequestTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2798,6 +2798,12 @@ describe('actions/IOU/UpdateMoneyRequest', () => {
personalDetailsList: undefined,
getCurrencyDecimals: getCurrencyDecimalsLocal,
getCurrencySymbol: getCurrencySymbolLocal,
transactions: {[`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`]: fakeTransaction},
transactionViolations: {},
betas: undefined,
introSelected: undefined,
currentUserAccountID: RORY_ACCOUNT_ID,
currentUserEmail: RORY_EMAIL,
},
newMerchant,
);
Expand Down
Loading
Loading