Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
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
1 change: 1 addition & 0 deletions src/libs/TransactionUtils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1848,6 +1848,7 @@ function isDuplicate(
if (!transaction) {
return false;
}

const duplicatedTransactionViolation = transactionViolation?.find((violation: TransactionViolation) => violation.name === CONST.VIOLATIONS.DUPLICATED_TRANSACTION);
const hasDuplicatedTransactionViolation = !!duplicatedTransactionViolation;
const isDuplicatedTransactionViolationDismissed = isViolationDismissed(transaction, duplicatedTransactionViolation, currentUserEmail, currentUserAccountID, iouReport, policy);
Expand Down
59 changes: 52 additions & 7 deletions src/libs/actions/IOU/Duplicate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,19 +12,21 @@ import {getMicroSecondOnyxErrorWithTranslationKey} from '@libs/ErrorUtils';
import {getExistingTransactionID} from '@libs/IOUUtils';
import * as NumberUtils from '@libs/NumberUtils';
import Parser from '@libs/Parser';
import {isPolicyAccessible} from '@libs/PolicyUtils';
import {isInstantSubmitEnabled, isPolicyAccessible, isSubmitAndClose} from '@libs/PolicyUtils';
import {getIOUActionForReportID, getOriginalMessage, isMoneyRequestAction} from '@libs/ReportActionsUtils';
import {
buildOptimisticCreatedReportAction,
buildOptimisticDismissedViolationReportAction,
buildOptimisticHoldReportAction,
buildOptimisticResolvedDuplicatesReportAction,
buildTransactionThread,
canAddTransaction,
generateReportID,
getTransactionDetails,
} from '@libs/ReportUtils';
import playSound, {SOUNDS} from '@libs/Sound';
import {
getReimbursable,
getRequestType,
getTransactionType,
hasCustomUnitOutOfPolicyViolation,
Expand Down Expand Up @@ -600,6 +602,7 @@ function createExpenseByType({
...(params.transactionParams ?? {}),
comment: {
...transaction.comment,
hold: undefined,
originalTransactionID: undefined,
source: undefined,
waypoints,
Expand Down Expand Up @@ -748,6 +751,7 @@ function duplicateExpenseTransaction({
...(params.transactionParams ?? {}),
comment: {
...transaction.comment,
hold: undefined,
originalTransactionID: undefined,
source: undefined,
waypoints,
Expand Down Expand Up @@ -998,8 +1002,12 @@ function bulkDuplicateExpenses({
}

const optimisticChatReportID = generateReportID();
const optimisticIOUReportID = generateReportID();
const sharedReportPreviewActionID = NumberUtils.rand64();

// These are mutable: when the current IOU report can't accept more
// transactions (e.g. instant-submit + submit-and-close with non-reimbursable
// expenses), we generate fresh IDs so each expense gets its own report.
let currentOptimisticIOUReportID = generateReportID();
let currentReportPreviewActionID = NumberUtils.rand64();

// After the first iteration creates a new optimistic IOU report, subsequent
// iterations must know its ID so getMoneyRequestInformation can find and
Expand All @@ -1011,6 +1019,19 @@ function bulkDuplicateExpenses({
let currentTargetReport = targetReport;
let optimisticIOUReport: OnyxEntry<OnyxTypes.Report>;

// When instant-submit + submit-and-close is active AND the duplicated
// expenses are all non-reimbursable (or the policy disables reimbursement
// entirely), canAddTransaction will reject the optimistic report after
// the first expense auto-submits and closes it. In that scenario every
// iteration will create a new report, so we must never defer auto-submit
// — otherwise the first expense's report stays in Draft because the
// server was told to wait for more expenses that will never arrive.
const allNonReimbursable = transactionsToDuplicate.every((t) => !getReimbursable(t));
const policyWillSplitReport =
isInstantSubmitEnabled(targetPolicy) &&
isSubmitAndClose(targetPolicy) &&
(allNonReimbursable || targetPolicy?.reimbursementChoice === CONST.POLICY.REIMBURSEMENT_CHOICES.REIMBURSEMENT_NO);

for (let i = 0; i < transactionsToDuplicate.length; i++) {
const item = transactionsToDuplicate.at(i);
if (!item) {
Expand All @@ -1020,10 +1041,34 @@ function bulkDuplicateExpenses({
const existingTransactionID = getExistingTransactionID(item.linkedTrackedExpenseReportAction);
const existingTransactionDraft = existingTransactionID ? transactionDrafts?.[existingTransactionID] : undefined;

// If the policy pre-check determined every expense must live on its
// own report, or the previous iteration's report can't accept more
// transactions, reset so this iteration creates its own independent
// report. policyWillSplitReport is needed because canAddTransaction
// reads transactions from Onyx, which hasn't been updated yet for
// optimistic reports (callbacks are deferred).
let reportWasSplit = false;
if (optimisticIOUReport && (policyWillSplitReport || !canAddTransaction(optimisticIOUReport))) {
Comment thread
Krishna2323 marked this conversation as resolved.
Resolved
optimisticIOUReport = undefined;
currentOptimisticIOUReportID = generateReportID();
currentReportPreviewActionID = NumberUtils.rand64();
reportWasSplit = true;
if (currentTargetReport) {
currentTargetReport = {...currentTargetReport, iouReportID: currentOptimisticIOUReportID};
}
}

// Defer auto-submit only when this isn't the last expense AND the
// report wasn't just split AND the policy won't force each expense
// onto its own report. Once a split happens every subsequent expense
// will also split (the policy closes reports immediately), so none of
// them should defer.
const shouldDeferAutoSubmit = !isLastExpense && !reportWasSplit && !policyWillSplitReport;

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 Do not defer auto-submit before a possible report split

In bulkDuplicateExpenses, shouldDeferAutoSubmit is computed as !isLastExpense && !reportWasSplit && !policyWillSplitReport, but reportWasSplit only reflects whether the current iteration split. In an instant-submit + submit-and-close workspace with a mixed batch where the first selected expense is non-reimbursable and a later one is reimbursable, the first request is sent with shouldDeferAutoSubmit: true, then the next iteration splits to a new report because canAddTransaction() becomes false for the first report. That leaves no later non-deferred request for the first report, so it can remain in Draft waiting for expenses that will never be added.

Useful? React with 👍 / 👎.

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.

Verified manually — in an instant-submit + submit-and-close workspace with reimbursement enabled and a mixed batch (reimbursable + non-reimbursable), canAddTransaction returns true on every subsequent iteration, so no split occurs. The deferral on iteration 0 is safe since the last iteration always finalizes the same report with shouldDeferAutoSubmit: false.

@MelvinBot Could you also take a fresh look at the concern raised by Codex?


const result = duplicateExpenseTransaction({
transaction: item,
optimisticChatReportID,
optimisticIOUReportID,
optimisticIOUReportID: currentOptimisticIOUReportID,
isASAPSubmitBetaEnabled,
introSelected,
activePolicyID,
Expand All @@ -1041,9 +1086,9 @@ function bulkDuplicateExpenses({
recentWaypoints,
targetPolicyTags,
shouldPlaySound: false,
shouldDeferAutoSubmit: !isLastExpense,
shouldDeferAutoSubmit,
existingIOUReport: optimisticIOUReport,
optimisticReportPreviewActionID: sharedReportPreviewActionID,
optimisticReportPreviewActionID: currentReportPreviewActionID,
currentUserAccountID: getUserAccountID(),
currentUserLogin: getCurrentUserEmail(),
});
Expand All @@ -1053,7 +1098,7 @@ function bulkDuplicateExpenses({
}

if (currentTargetReport && !currentTargetReport.iouReportID) {
currentTargetReport = {...currentTargetReport, iouReportID: optimisticIOUReportID};
currentTargetReport = {...currentTargetReport, iouReportID: currentOptimisticIOUReportID};
Comment thread
Krishna2323 marked this conversation as resolved.
Resolved
}
}

Expand Down
12 changes: 10 additions & 2 deletions tests/actions/IOUTest/DuplicateTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2402,7 +2402,13 @@ describe('actions/Duplicate', () => {
describe('bulkDuplicateExpenses', () => {
let writeSpy: jest.SpyInstance;

const mockPolicy = createRandomPolicy(1);
const mockPolicy: Policy = {
...createRandomPolicy(1),
type: CONST.POLICY.TYPE.TEAM,
autoReporting: false,
harvesting: {enabled: false},
approvalMode: CONST.POLICY.APPROVAL_MODE.BASIC,
};
const fakePolicyCategories = createRandomPolicyCategories(3);
const policyExpenseChat = createRandomReport(1, CONST.REPORT.CHAT_TYPE.POLICY_EXPENSE_CHAT);

Expand All @@ -2422,7 +2428,9 @@ describe('actions/Duplicate', () => {
}
return Promise.resolve();
});
return Onyx.clear();
await Onyx.clear();
await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}${mockPolicy.id}`, mockPolicy);
await waitForBatchedUpdates();
});

afterEach(() => {
Expand Down
Loading