App icon indicating copy to clipboard operation
App copied to clipboard

[Due for payment 2026-11-19] [$250] Expense - Both approved & held expenses' total is shown after approving

Open applause-bot[bot] opened this issue 1 month ago • 91 comments

If you haven’t already, check out our contributing guidelines for onboarding. To join our Slack channel, fill out this form.


Version Number: v9.5.9-0 Reproducible in staging?: Yes Reproducible in production?: Yes If this was caught during regression testing, add the test name, ID and link from BrowserStack: https://test-management.browserstack.com/projects/2219752/test-runs/78680856/folder/52723565/41236712/1861095397 Email or phone of affected tester (no customers): N/A Issue reported by: Applause Internal Team Bug source: Regression TC Execution Device used: Windows 11 / Chrome App Component: Chat Report View

Action Performed:

Setup: User A: Workspace owner User B: Workspace approver User C: Vacation delegate of User B User D: Expense submitter

  1. Navigate to https://staging.new.expensify.com/
  2. As User D, submit an expense report that contains two expenses
  3. As User C, Open one of the expenses > More > Split
  4. As User C, open one of the split expenses > More > Hold
  5. As User C, go back to the expense report > Click Approve > Approve only the unheld expenses
  6. As User C, click on the approved split expense > Go back to the report

Expected Result:

The total should only include unheld expenses (Expense 1 + Expense 2 [Split expense])

Actual Result:

Both approved and held expenses' total is shown instead of only approved expenses' total (Expense 1 + Expense 2 [Split expense] + Expense 3 [Split expense]). Once the user clicks on the approved split expense and then navigates back to the report, the correct total is shown.

Workaround:

Unknown

Platforms:

  • [ ] Android: App
  • [ ] Android: mWeb Chrome
  • [ ] iOS: App
  • [ ] iOS: mWeb Safari
  • [ ] iOS: mWeb Chrome
  • [x] Windows: Chrome
  • [x] MacOS: Chrome Safari

Screenshots/Videos

https://github.com/user-attachments/assets/065f1258-1e01-4ed5-a00d-df1ac8f7b199

View all open jobs on GitHub

Applause Internal Information Exported by: Nathan Lemma Bug ID: 7286552

Upwork Automation - Do Not Edit
Issue OwnerCurrent Issue Owner: @paulnjs

applause-bot[bot] avatar Oct 19 '26 10:10 applause-bot[bot]

While Applause doesn't embed attachments for this bug, here are the links for quick view: https://platform.applause.com/services/links/v1/external/1fa4350479122abb12a6761b53008e22ddced3f956542bb1bf7f4677ba4e0165

applause-bot[bot] avatar Oct 19 '26 10:10 applause-bot[bot]

Proposal

What is the root cause of that problem?

When you choose "Approve only the unheld expenses", the App does not recompute the approved report's total from its remaining expenses. Instead, it copies the cached unheldTotal / unheldReimbursableTotal fields onto total / reimbursableTotal (Hold.ts:970-979). The screen reads those fields, so if the cached unheld value is stale, the report keeps showing the full total (E1 + split A + held split B). Opening the split expense calls OpenReport, the server sends the correct totals, and the display fixes itself.

After a split, the cached unheld value goes stale in two ways:

  • The split flow overwrites unheldTotal with the full new report total and ignores any held amount (MoneyRequestBuilder.ts:1523-1532).
  • putOnHold is the only client code that lowers unheldTotal. It silently skips the update when the report is missing or its currency differs from the transaction's (Hold.ts:147-162). Split children inherit the original expense's currency.

What changes do you think we should make in order to solve the problem?

In getReportFromHoldRequestsOnyxData (Hold.ts), derive the totals from the holdTransactions it already collects. Do not trust iouReport.unheld*:

  1. Sum the held amounts (reimbursable and non-reimbursable separately), using convertedAmount when the currencies differ.
  2. Set the approved report's total, reimbursableTotal, nonReimbursableTotal, and unheld* fields to the current values minus those sums.
  3. Use the same sums for the new held report's amount, and drop the iouReport?.unheldTotal !== undefined gate.
  4. Use the same derived amount for the approve action's amount in ReportWorkflow.ts:179-184.

Add a unit test: split one expense, hold one split child, partially approve, and assert the approved report's total excludes the held split.

What alternative solutions did you explore? (Optional)

Fix the stale cache at its source instead: stop the split flow from assigning newReportTotal to unheldTotal, and make putOnHold use the converted amount instead of skipping. Both are worth doing, but they leave partial approve dependent on a cached value that other flows can still break.

Confidence and open questions

Confidence: medium. Code review confirms that partial approve copies cached unheld totals into total. I couldn't reproduce this case (four accounts plus a vacation delegate), so I haven't confirmed which upstream step makes the cache stale here. Two candidates:

  • A split or OpenReport server response lands after the optimistic hold and resets unheldTotal to the full total.
  • putOnHold skips the decrement because of the currency guard.

The proposed fix covers both because it no longer reads the cached value.

The display total comes from report fields, not a sum of transactions (ReportUtils.ts:5296-5311).

Possibly related: [$250] Hold - Approve modal displays same amount full report and pending expense. It shows the same stale unheldTotal symptom in the approve modal.


Next Steps for Contributor+ team: To accept: @MelvinBot implement [this](https://github.com/Expensify/App/issues/104341) to create a draft PR. To refine: @MelvinBot <your feedback> To reject: Explain why you are rejecting Melvin's proposal.


view run

MelvinBot avatar Oct 19 '26 10:10 MelvinBot

Triggered auto assignment to Contributor-plus team member for initial proposal review - @hoangzinh (External)

melvin-bot[bot] avatar Oct 19 '26 10:10 melvin-bot[bot]

Job added to Upwork: https://www.upwork.com/jobs/~022112136231790515292

melvin-bot[bot] avatar Oct 19 '26 10:10 melvin-bot[bot]


Proposal

What is the root cause of that problem?

When you choose "Approve only the unheld expenses", the App does not recompute the approved report's total from its remaining expenses. Instead it copies the cached unheldTotal / unheldReimbursableTotal fields onto total / reimbursableTotal (Hold.ts:970-979). That cached unheld value is stale at this point in the sequence (split, then hold, then approve), so the report keeps showing the full total (Expense 1 + unheld split + held split) until OpenReport refreshes the totals from the server - which matches the reported self-correction exactly.

What changes are needed to fix it?

In the approve-with-holds path, recompute total / reimbursableTotal from the report's actual remaining expenses (excluding held ones) after the approve action runs, and write those fresh values onto the report instead of copying the stale cached unheld totals. Cover the same recompute for any secondary totals fields shown on the report header.

What will I verify?

Run the exact repro on staging: submit 2 expenses, split one, hold one split, approve only unheld expenses. The report total should show only the unheld expenses, and navigating into the split expense and back should not change the total (no flash/self-correction).

Contributor details

GitHub: khizzcr7

khizzcr7 avatar Oct 19 '26 12:10 khizzcr7

Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/janithad

Proposal

Please re-state the problem that we are trying to solve in this issue.

When an expense report containing split expenses has one of the split expenses put on hold, and the user approves only the unheld expenses ("Approve only the unheld expenses"), the report's optimistic total incorrectly displays the sum of both approved and held expenses (full report total). Only when navigating away, opening the split expense, or refreshing from the server does the correct unheld total display.

What is the root cause of that problem?

This is caused by a compound issue between the split expense flow and the partial approval flow:

  1. Split flow corrupts cached unheld totals:
    In src/libs/actions/IOU/MoneyRequestBuilder.ts:1522-1532:

    if (typeof iouReport.unheldTotal === 'number') {
        if (hasReportTotalOverride) {
            iouReport.unheldTotal = newReportTotal;
        } else {
            iouReport.unheldTotal -= reportAmount;
        }
        if (reimbursable && newUnheldReimbursableTotal === undefined && isCurrencyMatching) {
            iouReport.unheldReimbursableTotal = previousUnheldReimbursableTotal - reportAmount;
        }
    }
    

    When an expense is split, hasReportTotalOverride is true. iouReport.unheldTotal is assigned newReportTotal, which represents the entire report total, inadvertently resetting unheldTotal and wiping out any distinction between held and unheld expenses.

  2. Partial approval blindly copies stale cached unheld totals:
    In src/libs/actions/IOU/Hold.ts:970-979 inside getReportFromHoldRequestsOnyxData:

    if (shouldUpdateOriginalReportTotals) {
        optimisticData.push({
            onyxMethod: Onyx.METHOD.MERGE,
            key: `${ONYXKEYS.COLLECTION.REPORT}${iouReport?.reportID}`,
            value: {
                total: iouReport?.unheldTotal ?? 0,
                nonReimbursableTotal: iouReport?.unheldNonReimbursableTotal ?? 0,
                reimbursableTotal: getUnheldReimbursableTotal(iouReport),
            },
        });
    }
    

    When the user chooses "Approve only the unheld expenses", the remaining approved report's total is simply overwritten with iouReport?.unheldTotal. Because unheldTotal was corrupted by the split flow (or any currency mismatch in putOnHold), the report receives the full total (E1 + split A + held split B) until OpenReport reconciles with backend calculations.

  3. Similarly, in src/libs/actions/IOU/ReportWorkflow.ts:174-179, approveMoneyRequest computes total = unheldTotal, directly depending on the corrupted cached value.

What changes do you think we should make in order to solve the problem?

We should apply a two-tier fix:

1. Derive totals from actual held transactions in getReportFromHoldRequestsOnyxData (src/libs/actions/IOU/Hold.ts & L970-L980):

Instead of relying on cached iouReport.unheld* values which are susceptible to drift across complex actions (like splits or currency conversions), calculate the held amount directly from the holdTransactions collection already gathered by getHoldReportActionsAndTransactions:

-    const holdReimbursable = getReimbursableTotal(iouReport) - getUnheldReimbursableTotal(iouReport);
-    const holdNonReimbursable = (iouReport?.nonReimbursableTotal ?? 0) - (iouReport?.unheldNonReimbursableTotal ?? 0);
+    const {holdReimbursable, holdNonReimbursable} = holdTransactions.reduce(
+        (acc, transaction) => {
+            const isExpense = isExpenseReport(iouReport);
+            const amount = getAmount(transaction, isExpense) * (isExpense ? -1 : 1);
+            if (transaction.reimbursable) {
+                acc.holdReimbursable += amount;
+            } else {
+                acc.holdNonReimbursable += amount;
+            }
+            return acc;
+        },
+        {holdReimbursable: 0, holdNonReimbursable: 0},
+    );

     const holdAmount = shouldMoveScanFailedTransactions ? 0 : (holdReimbursable + holdNonReimbursable) * coefficient;
     const holdNonReimbursableAmount = shouldMoveScanFailedTransactions ? 0 : holdNonReimbursable * coefficient;

And update the original approved report's optimistic totals by subtracting the computed held amounts:

     if (shouldUpdateOriginalReportTotals) {
+        const remainingReimbursable = getReimbursableTotal(iouReport) - holdReimbursable;
+        const remainingNonReimbursable = (iouReport?.nonReimbursableTotal ?? 0) - holdNonReimbursable;
+        const remainingTotal = remainingReimbursable + remainingNonReimbursable;
+
         optimisticData.push({
             onyxMethod: Onyx.METHOD.MERGE,
             key: `${ONYXKEYS.COLLECTION.REPORT}${iouReport?.reportID}`,
             value: {
-                total: iouReport?.unheldTotal ?? 0,
-                nonReimbursableTotal: iouReport?.unheldNonReimbursableTotal ?? 0,
-                reimbursableTotal: getUnheldReimbursableTotal(iouReport),
+                total: remainingTotal,
+                nonReimbursableTotal: remainingNonReimbursable,
+                reimbursableTotal: remainingReimbursable,
+                unheldTotal: remainingTotal,
+                unheldNonReimbursableTotal: remainingNonReimbursable,
+                unheldReimbursableTotal: remainingReimbursable,
             },
         });
     }

2. Ensure ReportWorkflow.ts uses the same derived amount (src/libs/actions/IOU/ReportWorkflow.ts:174-179):

Ensure that optimisticApprovedReportAction reflects the derived unheld total when held transactions are present.

What alternative solutions did you explore? (Optional)

Only patching MoneyRequestBuilder.ts to prevent hasReportTotalOverride from assigning newReportTotal to unheldTotal. While beneficial, patching only MoneyRequestBuilder leaves Hold.ts vulnerable whenever unheldTotal is desynced by currency mismatches, multi-currency splits, or offline race conditions. Deriving the unheld total directly from the active holdTransactions provides complete, self-contained resilience.

Tests

  1. Automated Unit Tests:

    • In tests/unit/HoldTest.ts:
      • Add a test case simulating an expense report with multiple transactions where an expense is split and one split transaction is put on hold.
      • Call getReportFromHoldRequestsOnyxData with isApprovalFlow: true.
      • Assert that the optimistic update for the approved report's total equals only the remaining unheld transactions' sum, and that the held report receives the exact amount of the held transaction.
  2. Manual QA Steps:

    1. Log in as a submitter and submit an expense report containing two expenses (e.g., $50 and $100).
    2. As an approver (or vacation delegate), open the $100 expense > select More > Split into two $50 expenses.
    3. Open one of the split $50 expenses > select More > Hold.
    4. Return to the main report view.
    5. Click Approve > choose "Approve only the unheld expenses".
    6. Verify that the report total immediately displays only the unheld expenses ($50 + $50 = $100), and does not include the held split expense ($50).
    7. Click into the approved split expense and navigate back to the report.
    8. Verify that the total remains consistent at $100 with no flickering or self-correction.

janiya2 avatar Oct 19 '26 13:10 janiya2

✅ Contributor details stored successfully. Thank you for contributing to Expensify!

melvin-bot[bot] avatar Oct 19 '26 13:10 melvin-bot[bot]

Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~011091133bbb09cd1c

Proposal

Please re-state the problem that we are trying to solve in this issue.

When an expense report contains both held and unheld expenses (such as after splitting an expense and putting one split on hold), choosing "Approve only the unheld expenses" causes the report total to optimistically display the full sum of all expenses (including the held split expense) instead of only the approved unheld expenses. Navigating into a split expense and back corrects the total once refreshed from the server.

What is the root cause of that problem?

There are two root causes that work in combination:

  1. In src/libs/actions/IOU/ReportWorkflow.ts:180-184, when hasHeldExpenses && !full, total = unheldTotal is calculated for buildOptimisticApprovedReportAction. However, in updatedExpenseReport (lines 240-271), total, reimbursableTotal, and nonReimbursableTotal are never overwritten with the unheld totals. Because ...expenseReport is spread into updatedExpenseReport, the optimistic data merged into ${ONYXKEYS.COLLECTION.REPORT}${expenseReport.reportID} retains the old full report total (combining both unheld and held split expenses).
  2. Furthermore, in src/libs/actions/IOU/MoneyRequestBuilder.ts:1523-1533, during split operations, when hasReportTotalOverride is true, iouReport.unheldTotal is assigned newReportTotal directly without deducting held amounts. In src/libs/actions/IOU/Hold.ts:970-980 (shouldUpdateOriginalReportTotals), the cached unheld values are copied directly onto total / reimbursableTotal without recomputing from remaining active unheld transactions, leading to stale unheld total values if transactions were held before or during split operations.

What changes do you think we should make in order to solve the problem?

  1. In src/libs/actions/IOU/ReportWorkflow.ts inside approveMoneyRequest: When hasHeldExpenses && !full, optimistically update the report total fields on updatedExpenseReport:
...(hasHeldExpenses && !full
    ? {
          total,
          reimbursableTotal: getUnheldReimbursableTotal(expenseReport),
          nonReimbursableTotal: expenseReport.unheldNonReimbursableTotal ?? 0,
      }
    : {}),
  1. In approveMoneyRequest, derive unheldTotal directly by summing the non-held transactions (reportTransactions.filter(t => !isOnHold(t))) using TransactionUtils or ReportUtils.getMoneyRequestSpendBreakdown, rather than relying solely on the cached expenseReport.unheldTotal.
  2. In src/libs/actions/IOU/MoneyRequestBuilder.ts:1523-1533, ensure that when hasReportTotalOverride is true during split creation, any existing held amounts on the report are subtracted when updating iouReport.unheldTotal and iouReport.unheldReimbursableTotal.

What alternative solutions did you explore? (Optional)

Centralize the unheld total computation in ReportUtils.getUnheldSpendBreakdown(report, reportTransactions) and invoke it across ReportWorkflow.ts, Hold.ts, and PayMoneyRequest.ts so that all partial approval/payment flows stay consistently synchronized with Onyx transaction states.

sijo0218 avatar Oct 19 '26 14:10 sijo0218

✅ Contributor details stored successfully. Thank you for contributing to Expensify!

melvin-bot[bot] avatar Oct 19 '26 14:10 melvin-bot[bot]

Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~0163955a2ba221e513

Proposal

Please re-state the problem that we are trying to solve in this issue.

When an expense report contains multiple expenses and an expense is split and then held, choosing "Approve only the unheld expenses" causes the original approved report's total to display the sum of both approved and held expenses rather than only the unheld expenses.

What is the root cause of that problem?

In src/libs/actions/IOU/Hold.ts:971-981: When moving held transactions out into a new report during "Approve only the unheld expenses", the original report's optimistic total is updated by copying cached unheld properties:

if (shouldUpdateOriginalReportTotals) {
    optimisticData.push({
        onyxMethod: Onyx.METHOD.MERGE,
        key: `${ONYXKEYS.COLLECTION.REPORT}${iouReport?.reportID}`,
        value: {
            total: iouReport?.unheldTotal ?? 0,
            nonReimbursableTotal: iouReport?.unheldNonReimbursableTotal ?? 0,
            reimbursableTotal: getUnheldReimbursableTotal(iouReport),
        },
    });
}
  1. iouReport.unheldTotal and iouReport.unheldReimbursableTotal are server-computed fields that were cached when the report was originally fetched.
  2. When an expense is split (Step 3: Open expense -> More -> Split) and then held (Step 4: Hold split expense), new optimistic transactions are created locally, but the server has not yet returned an updated unheldTotal for the report.
  3. Because iouReport.unheldTotal is stale, lines 976-978 write stale totals onto the original report. Furthermore, in src/libs/actions/IOU/Hold.ts:794-795, holdReimbursable is calculated as getReimbursableTotal(iouReport) - getUnheldReimbursableTotal(iouReport), which similarly produces an inaccurate delta when unheldReimbursableTotal is out of sync with optimistic client transactions.

What alternative solutions did you explore? (Optional)

Re-fetching the entire report was explored, but optimistic updates should be calculated immediately on the client using the real list of held transactions.

What changes do you think we should make in order to solve the problem?

In src/libs/actions/IOU/Hold.ts: Calculate the held transactions' amounts directly from holdTransactions instead of subtracting cached unheld fields:

let holdReimbursableAmount = 0;
let holdNonReimbursableAmount = 0;

for (const transaction of holdTransactions) {
    const amount = Math.abs(transaction.amount ?? 0);
    if (TransactionUtils.isReimbursable(transaction)) {
        holdReimbursableAmount += amount;
    } else {
        holdNonReimbursableAmount += amount;
    }
}

Then in the optimistic update for the original report:

--- a/src/libs/actions/IOU/Hold.ts
+++ b/src/libs/actions/IOU/Hold.ts
@@ -971,11 +971,11 @@
     if (shouldUpdateOriginalReportTotals) {
         optimisticData.push({
             onyxMethod: Onyx.METHOD.MERGE,
             key: `${ONYXKEYS.COLLECTION.REPORT}${iouReport?.reportID}`,
             value: {
-                total: iouReport?.unheldTotal ?? 0,
-                nonReimbursableTotal: iouReport?.unheldNonReimbursableTotal ?? 0,
-                reimbursableTotal: getUnheldReimbursableTotal(iouReport),
+                total: (iouReport?.total ?? 0) - (holdReimbursableAmount + holdNonReimbursableAmount) * coefficient,
+                nonReimbursableTotal: (iouReport?.nonReimbursableTotal ?? 0) - holdNonReimbursableAmount * coefficient,
+                reimbursableTotal: getReimbursableTotal(iouReport) - holdReimbursableAmount * coefficient,
             },
         });
     }

What automated tests can you add to prevent this from re-occurring?

Add a unit test in tests/actions/IOUTest/HoldTest.ts verifying that:

  1. When a report contains split transactions and a split transaction is held, approving only unheld expenses updates iouReport.total to reflect only the remaining unheld transactions.
  2. The optimistic report total never includes the amount of held transactions even when iouReport.unheldTotal is missing or stale.

jloa-dev avatar Oct 21 '26 01:10 jloa-dev

✅ Contributor details stored successfully. Thank you for contributing to Expensify!

melvin-bot[bot] avatar Oct 21 '26 01:10 melvin-bot[bot]

Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~018dd03e28202cc749

Proposal

What is the root cause of that problem?

When an approver or delegate selects "Approve only the unheld expenses", two code paths read the cached report-level unheld properties instead of calculating the delta from the moving transactions:

  1. Hold.ts:948-956 (getReportFromHoldRequestsOnyxData):

    if (shouldUpdateOriginalReportTotals) {
        optimisticData.push({
            onyxMethod: Onyx.METHOD.MERGE,
            key: `${ONYXKEYS.COLLECTION.REPORT}${iouReport?.reportID}`,
            value: {
                total: iouReport?.unheldTotal ?? 0,
                nonReimbursableTotal: iouReport?.unheldNonReimbursableTotal ?? 0,
                reimbursableTotal: getUnheldReimbursableTotal(iouReport),
            },
        });
    }
    

    Instead of subtracting the held transactions, it copies iouReport.unheldTotal and iouReport.unheldNonReimbursableTotal. If iouReport.unheldTotal is out of sync or undefined on the client, shouldUpdateOriginalReportTotals is either skipped or copies stale full totals. Furthermore, Hold.ts:768-769 calculates holdReimbursable as getReimbursableTotal(iouReport) - getUnheldReimbursableTotal(iouReport), which similarly relies on cached report-level fields rather than the actual transactions in holdTransactions.

  2. ReportWorkflow.ts:512-518 (approveMoneyRequest):

    const unheldTotal = getUnheldReimbursableTotal(expenseReport) + (expenseReport.unheldNonReimbursableTotal ?? 0);
    let total = getReimbursableTotal(expenseReport) + (expenseReport.nonReimbursableTotal ?? 0);
    if (hasHeldExpenses && !full && !!unheldTotal) {
        total = unheldTotal;
    }
    

    The optimistic approved action comment also derives its display amount from cached unheld fields.

What changes do you think we should make in order to solve the problem?

  1. In src/libs/actions/IOU/Hold.ts (getReportFromHoldRequestsOnyxData):

    • Calculate holdReimbursable and holdNonReimbursable by iterating over holdTransactions.
    • Multi-Currency Support: For transactions matching the report currency, use getTransactionAmount(transaction, isExpenseReport(iouReport)). For foreign currency transactions, use getConvertedAmount(transaction, isExpenseReport(iouReport)) to ensure amounts are denominated in the report currency before subtracting.
    • Update the original report totals in optimisticData by subtracting the computed held amounts:
      • total: (iouReport?.total ?? 0) - (holdReimbursable + holdNonReimbursable) * coefficient
      • reimbursableTotal: getReimbursableTotal(iouReport) - holdReimbursable * coefficient
      • nonReimbursableTotal: (iouReport?.nonReimbursableTotal ?? 0) - holdNonReimbursable * coefficient
    • Update line 892: const shouldUpdateOriginalReportTotals = !shouldMoveScanFailedTransactions && holdTransactions.length > 0;.
  2. In src/libs/actions/IOU/ReportWorkflow.ts (approveMoneyRequest):

    • Update the approved total calculation (lines 512-518) to subtract the held transactions' converted amounts from total rather than relying on cached unheldTotal.

What alternative solutions did you explore? (Optional)

Auditing every upstream mutation to guarantee cached unheldTotal is always updated was explored, but deriving the delta directly from holdTransactions with proper currency conversion is self-contained and avoids reliance on cached report-level totals.

Ishant5436 avatar Oct 21 '26 03:10 Ishant5436

✅ Contributor details stored successfully. Thank you for contributing to Expensify!

melvin-bot[bot] avatar Oct 21 '26 03:10 melvin-bot[bot]

@hoangzinh Uh oh! This issue is overdue by 2 days. Don't forget to update your issues!

melvin-bot[bot] avatar Oct 22 '26 21:10 melvin-bot[bot]

Can reproduce.

https://github.com/user-attachments/assets/b950e7e6-7414-4179-91cf-ae20b7b51955

nkdengineer avatar Oct 26 '26 12:10 nkdengineer

Reassign to @nkdengineer

hoangzinh avatar Oct 26 '26 12:10 hoangzinh

Proposal

Please re-state the problem that we are trying to solve in this issue.

When an expense report has two expenses, an approver (or vacation delegate) splits one of the expenses, puts one of the resulting split expenses on hold, and then clicks Approve > Approve only the unheld expenses, the approved report's total optimistically displays the sum of both approved and held expenses instead of only the approved unheld expenses (until navigating into the split expense and back refreshes the report from the server).

What is the root cause of that problem?

There are two bugs in how optimistic report totals are updated across the split -> hold -> partial-approve sequence:

  1. Splitting an expense overwrites iouReport.unheldTotal with the full report total (src/libs/actions/IOU/MoneyRequestBuilder.ts:1522-1532): During splitBill, hasReportTotalOverride is true, and MoneyRequestBuilder.ts sets iouReport.unheldTotal = newReportTotal and iouReport.unheldReimbursableTotal = newUnheldReimbursableTotal without accounting for held transactions or leaving unheldTotal out of sync on the client.
  2. Partial approval (Approve only the unheld expenses) in ReportWorkflow.ts and Hold.ts fails to update the report's total and reimbursableTotal from the moved held transactions:
    • In src/libs/actions/IOU/ReportWorkflow.ts (approveMoneyRequest, lines 180-184 and 240-271), when hasHeldExpenses && !full, unheldTotal is computed for the APPROVED report action message, but updatedExpenseReport (lines 240-271) spreads ...expenseReport without updating total, reimbursableTotal, or nonReimbursableTotal to the unheld totals.
    • In src/libs/actions/IOU/Hold.ts (getReportFromHoldRequestsOnyxData, lines 765-775 and 970-981), the original report's total and reimbursableTotal are only updated if shouldUpdateOriginalReportTotals (typeof iouReport?.unheldTotal === 'number') is true, and even then it blindly copies the stale cached iouReport.unheldTotal / getUnheldReimbursableTotal(iouReport) instead of subtracting the held transactions' amounts (holdTotal, holdReimbursable, holdNonReimbursable) that are being moved to the new held report!

What changes do you think we should make in order to solve the problem?

  1. In src/libs/actions/IOU/Hold.ts (getReportFromHoldRequestsOnyxData, lines 765-775 & 970-981):
    • Calculate the held transactions' sum (holdTotal, holdReimbursable, holdNonReimbursable) directly from movingTransactions (instead of relying solely on total - unheldTotal), and update the original report's total, reimbursableTotal, and nonReimbursableTotal by subtracting the moved held amounts ((iouReport?.total ?? 0) - holdTotal, etc.).
  2. In src/libs/actions/IOU/ReportWorkflow.ts (approveMoneyRequest, lines 240-271):
    • When hasHeldExpenses && !full, set total: unheldTotal, reimbursableTotal: unheldReimbursableTotal, and nonReimbursableTotal: unheldNonReimbursableTotal on updatedExpenseReport so the optimistic Onyx.METHOD.MERGE for ${ONYXKEYS.COLLECTION.REPORT}${expenseReport.reportID} immediately reflects only the approved unheld expenses.

What alternative solutions did you explore? (Optional)

We also considered recomputing unheldTotal and unheldReimbursableTotal from all report transactions inside MoneyRequestBuilder.ts during splitBill, which is a good defensive improvement alongside subtracting movingTransactions in Hold.ts.

Kabeer099 avatar Oct 29 '26 01:10 Kabeer099

The Melvin solution doesn't work, and the RCA is incorrect.

:sos: C+ Help Wanted

nkdengineer avatar Oct 29 '26 08:10 nkdengineer

🚨 Edited by proposal-police: This proposal was edited at 2026-10-29 09:29:14 UTC.

Proposal

Please re-state the problem that we are trying to solve in this issue.

After a vacation delegate approves only the unheld expenses, the report still shows the old total that includes the held expense. It corrects itself only after an OpenReport brings the report back from the server.

What is the root cause of that problem?

The bug only happens when the approver isn't in the submitter's workspace chat, which is always true for a vacation delegate. I reproduced it with three accounts (submitter, approver, approver's vacation delegate) on a same-currency workspace. With the owner approving their own report, the total came out right every time.

On partial approve, approveMoneyRequest builds the held-report data, including the update that sets the approved report's total / reimbursableTotal to the unheld values, only when the chat report is in Onyx:

https://github.com/Expensify/App/blob/67eb990d1d7c0a73e7d79d01dc4af502405aba4e/src/libs/actions/IOU/ReportWorkflow.ts#L436-L449

chatReport is the submitter's policy expense chat:

https://github.com/Expensify/App/blob/67eb990d1d7c0a73e7d79d01dc4af502405aba4e/src/libs/actions/IOU/ReportWorkflow.ts#L215

The delegate isn't a participant of that chat, so the whole block is skipped and the totals update in Hold.ts never runs:

https://github.com/Expensify/App/blob/67eb990d1d7c0a73e7d79d01dc4af502405aba4e/src/libs/actions/IOU/Hold.ts#L971-L981

What I watched on the delegate's client, on a $150 report with one $50 child on hold:

  • Before approving, the report had unheldTotal: -10000 and unheldReimbursableTotal: -10000. The dropdown read "Approve only $100.00", so the unheld cache was fine.
  • report_<chatReportID> was null in the delegate's Onyx, so getReportOrDraftReport returned nothing.
  • The only optimistic merge for the report was the generic approve merge. reimbursableTotal stayed at -15000.
  • The ApproveMoneyRequest response for the delegate only carried total: -10000. For the workspace owner, the same call also sends reimbursableTotal.
  • The footer reads reimbursableTotal, so it showed $150.00 above two $50 rows.
flowchart TD
    A["Delegate clicks Approve only $100"] -->|"report_chatReportID is null for the delegate"| B["chatReport undefined"]
    B -->|"!full && !!chatReport fails"| C["getReportFromHoldRequestsOnyxData skipped"]
    C -->|"no optimistic totals merge"| D["reimbursableTotal stays -15000"]
    D -->|"server response sets total -10000 only"| E["Footer reads reimbursableTotal: $150.00"]

Same currency on both sides (the reporter's video is INR on an INR workspace), and unheldTotal was already correct before approving. So neither the currency guard in putOnHold nor a stale unheld cache explains this case.

What changes do you think we should make in order to solve the problem?

When the partial approve can't build the held report because the chat isn't available, still drop the held amount from the approved report's totals optimistically, with the matching failure data. This mirrors what getReportFromHoldRequestsOnyxData already does for approvers who have the chat. The server still moves the held expense to the new report as it does today.

         optimisticReportActionCopyIDs = JSON.stringify(holdReportOnyxData.optimisticReportActionCopyIDs);
+    } else if (!full && hasHeldExpenses && expenseReport.unheldTotal !== undefined) {
+        optimisticData.push({
+            onyxMethod: Onyx.METHOD.MERGE,
+            key: `${ONYXKEYS.COLLECTION.REPORT}${expenseReport.reportID}`,
+            value: {
+                total: expenseReport.unheldTotal,
+                nonReimbursableTotal: expenseReport.unheldNonReimbursableTotal ?? 0,
+                reimbursableTotal: getUnheldReimbursableTotal(expenseReport),
+            },
+        });
+        // + failureData restoring total / nonReimbursableTotal / reimbursableTotal
     }

With this change, the delegate's report shows Total $100.00 right after approving, with reimbursableTotal going to -10000 optimistically. I also added a test in ReportWorkflowTest: partial approve with a held expense and no workspace chat in Onyx. It fails on current main (-15000) and passes with the fix.

What alternative solutions did you explore? (Optional)

Building a stub chat report so getReportFromHoldRequestsOnyxData can run. That would write an optimistic report preview and iouReportID into a chat the delegate doesn't have, leaving a partial report in their Onyx. Changing putOnHold or the split flow wouldn't help either, because the unheld values were already correct here.

mukhrr avatar Oct 29 '26 08:10 mukhrr

Proposal

What is the root cause of that problem?

  • After holding one split, unheldTotal is already the unheld amount. The footer does not use that field. It uses total / reimbursableTotal. Those are only updated when we copy unheldTotal onto total in getReportFromHoldRequestsOnyxData. https://github.com/Expensify/App/blob/be0b357acb8ff314c7dc38840efc618ed7e45f0a/src/libs/actions/IOU/Hold.ts#L971-L980
  • User C is a vacation delegate on the expense report and doens’t have access to workspace chat leads chatReport is undefined. https://github.com/Expensify/App/blob/be0b357acb8ff314c7dc38840efc618ed7e45f0a/src/libs/actions/IOU/ReportWorkflow.ts#L215
  • Then we never call getReportFromHoldRequestsOnyxData. https://github.com/Expensify/App/blob/be0b357acb8ff314c7dc38840efc618ed7e45f0a/src/libs/actions/IOU/ReportWorkflow.ts#L436-L449

What changes do you think we should make in order to solve the problem?

  • We don’t need to skip getReportFromHoldRequestsOnyxData just because chatReport is missing. That function only needs a few chat fields (reportID, policyID, whether it is a policy expense chat).
  1. Drop !!chatReport in approveMoneyRequest https://github.com/Expensify/App/blob/be0b357acb8ff314c7dc38840efc618ed7e45f0a/src/libs/actions/IOU/ReportWorkflow.ts#L436
  2. Allow chatReport to be undefined, fall back to iouReport for IDs / type, and only push chat Onyx updates when chatReport is defined. https://github.com/Expensify/App/blob/be0b357acb8ff314c7dc38840efc618ed7e45f0a/src/libs/actions/IOU/Hold.ts#L766-L767 chatReport: OnyxEntry<OnyxTypes.Report>; https://github.com/Expensify/App/blob/be0b357acb8ff314c7dc38840efc618ed7e45f0a/src/libs/actions/IOU/Hold.ts#L810
const isPolicyExpenseChat = isPolicyExpenseChatReportUtil(chatReport) || isExpenseReport(iouReport);
const chatReportID = chatReport?.reportID ?? iouReport?.chatReportID ?? '';
...
const optimisticExpenseReport = isPolicyExpenseChat
    ? buildOptimisticExpenseReport({
          chatReportID,
          policyID: chatReport?.policyID ?? iouReport?.policyID,
          ...
      })
    : buildOptimisticIOUReport(
          iouReport?.ownerAccountID ?? CONST.DEFAULT_NUMBER_ID,
          iouReport?.managerID ?? CONST.DEFAULT_NUMBER_ID,
          holdAmount,
          chatReportID,
...
      );
  • Skip buildOptimisticReportPreview when chatReport is missing. https://github.com/Expensify/App/blob/be0b357acb8ff314c7dc38840efc618ed7e45f0a/src/libs/actions/IOU/Hold.ts#L838-L847

What alternative solutions did you explore? (Optional)

N/A

https://github.com/user-attachments/assets/99128784-168c-4919-82b3-67f6ee8473dd

paulnjs avatar Oct 29 '26 08:10 paulnjs