App icon indicating copy to clipboard operation
App copied to clipboard

[$175] AU - Track distance - Expense creation fails with unexpected error

Open applause-bot[bot] opened this issue 3 weeks ago β€’ 24 comments

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


Version Number: 9.5.33-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/folder/57599980/test-cases/41237166?q=3813 Email or phone of affected tester (no customers): - Issue reported by: Applause Internal Team Bug source: Regression TC Execution Device used: Win 11 / Chrome App Component: Money Requests

Action Performed:

  1. Click on FAB > Track distance
  2. Ener waypoints
  3. Click on Create expense

Expected Result:

Expense created without errors

Actual Result:

An error appears in expense. Click on X button to dismiss error closes expense without saving

Workaround:

Unknown

Platforms:

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

Screenshots/Videos

https://github.com/user-attachments/assets/3b4946ac-6ba3-46b1-b162-0394e2c41da5

View all open jobs on GitHub

Applause Internal Information Exported by: Chandana Kiran Bug ID: 7307112

Upwork Automation - Do Not Edit

applause-bot[bot] avatar Nov 06 '26 19:11 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/226caac1dac713b3143dada0e7af507cb64469db585156ef3286928cf8d92a1b

applause-bot[bot] avatar Nov 06 '26 19:11 applause-bot[bot]

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

melvin-bot[bot] avatar Nov 06 '26 19:11 melvin-bot[bot]

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

melvin-bot[bot] avatar Nov 06 '26 19:11 melvin-bot[bot]

πŸ€– Web test steps verification results: βœ… pass

Verified on dev NewDot web. The reported issue did not reproduce: the distance expense saved without an error and persisted after opening its details and returning to Expenses.

Saved /bin/bash.90 distance expense remains in Expenses
Step Status
FAB > Track distance opens waypoint flowThe Map flow displayed Start and Stop.
βœ…
Enter two valid waypointsSelected 350 5th Avenue, New York and Times Square. Confirmation displayed 1.19 miles at $0.76/mile.
βœ…
Click Create expenseβ€œExpense added” appeared with an Unreported $0.90 expense. No error or dismissal X appeared.
βœ…
Verify persistenceThe expense remained after opening its details and returning to Expenses. Error dismissal could not be tested because creation succeeded.
Saved /bin/bash.90 distance expense remains in Expenses

Preliminary analysis β€” low confidence
Creation failure: Root cause remains unconfirmed. The distance flow submits CreateDistanceRequest (request submission); its generic failure feedback does not identify the underlying cause (failure handling).
Why X removes it: Dismissing an error on a pending, optimistically created expense invokes local cleanup (dismissal handler). This explains disappearance without proving that a saved expense was deleted.
Alternative considered: Missing initialization is not established: the draft initializes waypoint placeholders (initialization). Account/rate-specific data or a server-side rejection remain possible.
Blocker: Production logs were unavailable. This development test does not establish behavior on reported version 9.5.33-0.
Next diagnostic: Capture the failing request and response, approximate timestamp/time zone, selected rate, and expense destination. No code fix is verified yet.
Potentially related: Unexpected error when reopening and changing a distance rate concerns editing, not creation; a shared cause is unconfirmed.
βœ…

view run

MelvinBot avatar Nov 06 '26 19:11 MelvinBot

Proposal

What is the root cause of that problem?

There are two root causes that combine to trigger this creation failure and subsequent data loss:

  1. customUnitRateID is not updated from the P2P placeholder when a workspace is selected during FAB-initiated distance creation:

    • In src/libs/actions/IOU/MoneyRequest.ts, when initiating a distance request from the FAB (TrackDistanceMenuItem.tsx / startDistanceRequest), the transaction draft is initialized without a policy, defaulting customUnitRateID to CONST.CUSTOM_UNITS.FAKE_P2P_ID ('p2p').
    • When the user selects a workspace report/participant and lands on the confirmation page (Confirm details), src/components/MoneyRequestConfirmationList/DistanceRequestController.tsx is responsible for auto-selecting the workspace's default/eligible mileage rate:
      if (
          !DistanceRequestUtils.isUnsetDistanceCustomUnitRateID(customUnitRateID) ||
          !isDistanceRequest ||
          !isPolicyExpenseChat ||
          !transactionID ||
          !lastSelectedRate ||
          (isMovingTransactionFromTrackExpense && customUnitRateID === CONST.CUSTOM_UNITS.FAKE_P2P_ID) ||
          !selectedParticipants.some((participant) => participant.policyID === policy?.id)
      ) {
          return;
      }
      
    • Notice the guards: !isPolicyExpenseChat and !selectedParticipants.some((participant) => participant.policyID === policy?.id). When creating an expense from FAB into a new report (Report: New report), isPolicyExpenseChat is false, and selectedParticipants may only hold reportID. As a result, DistanceRequestController returns early without calling setCustomUnitRateID.
    • On the confirmation page, RateField displays "Default Rate" because the UI presentation derives the default rate dynamically from policy, but transaction.comment.customUnit.customUnitRateID remains unset or 'p2p'.
    • In src/pages/iou/request/step/confirmation/submission/useDistanceSubmission.ts:
      customUnitRateID: getRateID(transaction) ?? '',
      
      getRateID(transaction) returns CONST.CUSTOM_UNITS.FAKE_P2P_ID ('p2p') from fields.ts#L47.
    • Consequently, createDistanceRequest sends customUnitRateID: 'p2p' for a workspace policy. Because 'p2p' is not a valid custom unit rate on the workspace policy, the backend API command CreateDistanceRequest rejects the request with an unexpected error.
  2. Onyx failureData surfaces a misleading receipt error for map distance requests, and dismissing the error deletes the expense:

    • In MoneyRequestBuilder.ts (lines 1076–1105), when CreateDistanceRequest fails, failureData attaches getReceiptError(...) and genericCreateFailureMessage.
    • In src/components/ReportActionItem/MoneyRequestReceiptView.tsx:
      if (transaction?.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD) {
          ...
          cleanUpMoneyRequest({...});
          return;
      }
      
      Because the transaction was pending creation (pendingAction === 'add'), clicking the X button calls cleanUpMoneyRequest, which deletes the optimistic transaction and report from local Onyx, causing the expense to disappear.

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

  1. Ensure customUnitRateID resolves to the workspace policy's default rate upon submission: In src/pages/iou/request/step/confirmation/submission/useDistanceSubmission.ts: When creating an expense on a policy, if customUnitRateID is unset or is FAKE_P2P_ID, fall back to the policy's default/eligible mileage rate:

    const transactionRateID = getRateID(transaction);
    const resolvedCustomUnitRateID =
        policy && DistanceRequestUtils.isUnsetDistanceCustomUnitRateID(transactionRateID)
            ? (DistanceRequestUtils.getDefaultMileageRate(policy)?.customUnitRateID ?? transactionRateID)
            : transactionRateID;
    

    Pass customUnitRateID: resolvedCustomUnitRateID to createDistanceRequestIOUActions.

  2. Loosen the auto-select rate guard in DistanceRequestController.tsx: In src/components/MoneyRequestConfirmationList/DistanceRequestController.tsx: Allow auto-selection to run whenever a workspace policy with distance rates is present (even if isPolicyExpenseChat is false because a new report or global create is selected), and check if policy?.id matches the workspace:

    const isPolicyMatch = !!policy?.id && (isPolicyExpenseChat || selectedParticipants.some((participant) => participant.policyID === policy?.id || participant.reportID));
    if (
        !DistanceRequestUtils.isUnsetDistanceCustomUnitRateID(customUnitRateID) ||
        !isDistanceRequest ||
        !isPolicyMatch ||
        !transactionID ||
        !lastSelectedRate ||
        (isMovingTransactionFromTrackExpense && customUnitRateID === CONST.CUSTOM_UNITS.FAKE_P2P_ID)
    ) {
        return;
    }
    
  3. Prevent misleading receipt error display on map distance expenses in MoneyRequestReceiptView.tsx: In MoneyRequestReceiptView.tsx, ensure that map-based distance requests (which use generated map e-receipts and have no uploaded file) only display the transaction's creation failure message (genericCreateFailureMessage) rather than the receipt upload failure message.


What alternative solutions did you explore? (Optional)

  • Only modifying DistanceRequestController: While auto-selecting the rate on the confirmation page is helpful for the UI state, relying exclusively on an effect hook is fragile (e.g. if the user clicks "Create expense" immediately before the effect commits or if navigating quickly). Falling back to DistanceRequestUtils.getDefaultMileageRate(policy) in useDistanceSubmission.ts provides a foolproof defense in depth that guarantees the API request payload is always valid.

Tests

  1. Create or use a workspace that has Distance rates enabled with custom rates.
  2. From the global FAB, click + > Track distance.
  3. Select the Map tab, enter a valid Start and Stop waypoint, and click Next.
  4. Select the workspace from step 1.
  5. On the Confirm details page, verify "Rate" displays the workspace's default rate.
  6. Toggle "Reimbursable" to OFF (or leave ON) without tapping into the "Rate" selector.
  7. Click Create expense.
  8. Verify that the expense is created successfully without any unexpected submission or receipt error.
  9. Verify that clicking on the expense card in the report correctly displays the route, distance, and calculated amount.

Contributor details

Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~0131dae36abcf59374

kevinjosh10 avatar Nov 06 '26 21:11 kevinjosh10

Proposal

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

Distance expense creation reportedly fails on Windows/Chrome in 9.5.33-0; dismissing the error removes the expense. Verdict: insufficient evidence for a verified fix. No faulty function, file, or line has been established.

What is the root cause of that problem?

Unconfirmed. The issue’s latest verification reports successful creation in development, explicitly excludes validation of 9.5.33-0, and identifies missing production logs. Its explanation of optimistic cleanup is preliminary analysis, not independently verified evidence.

There is no failing request/response, stack trace, reproducible fixture, or demonstrated frontend defect. Assigning exact fault locations would fabricate precision.

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

Do not submit a speculative TypeScript diff. First capture the failing CreateDistanceRequest payload and response, build SHA, account/workspace configuration, selected rate, destination, and timestamp. Reproduce with those conditions and identify the violated contract before selecting the correction.

Compare branch: https://github.com/Expensify/App/compare/main...camesenin:App:fix-issue-106242?expand=1

The comparison could not be retrieved; branch existence, contents, and validation remain unverified. Source retrieval also failed. No code or tests were executed.

What alternative solutions did you explore? (Optional)

There is no MelvinBot fix to dismantle. Its successful development run cannot disprove the reported regression. Suppressing the error, preserving a rejected optimistic expense, or changing waypoint initialization without evidence could conceal failure or introduce regressions.

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

After reproducing the defect, add a regression case to the existing test suite for the responsible action/component, using sanitized failing inputs. Assert the corrected behavior and legitimate rejection handling; no passing test is claimed.

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

camesenin avatar Nov 07 '26 00:11 camesenin

βœ… Contributor details stored successfully. Thank you for contributing to Expensify!

melvin-bot[bot] avatar Nov 07 '26 00:11 melvin-bot[bot]

Proposal

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

When a user creates a track distance expense via FAB β†’ Track distance β†’ enters waypoints β†’ Create expense, the expense creation fails with an unexpected error. Clicking the X to dismiss the error closes the expense without saving.

What is the root cause of that problem?

The root cause is that when a distance request is initiated from the global FAB (isFromGlobalCreate = true) and the user has workspace policies (not only personal policies), the transaction's customUnit is never initialized, so customUnitRateID defaults to CONST.CUSTOM_UNITS.FAKE_P2P_ID ('_FAKE_P2P_ID_') and is submitted to the backend for a workspace expense β€” which the backend rejects.

The chain:

  1. Transaction initialization skips customUnit setup for global-create distance requests with workspace policies β€” src/libs/actions/IOU/MoneyRequest.ts lines 411–438:

    if (/* distance request types */) {
        if (!isFromGlobalCreate) {                                    // line 419 β€” SKIPPED for FAB
            const customUnitRateID = DistanceRequestUtils.getCustomUnitRateID({...});
            comment.customUnit = { customUnitRateID, name: ... };
        } else if (hasOnlyPersonalPolicies) {                        // line 433 β€” only if NO workspace policies
            comment.customUnit = { customUnitRateID: CONST.CUSTOM_UNITS.FAKE_P2P_ID, ... };
        }
        // If isFromGlobalCreate && !hasOnlyPersonalPolicies β†’ comment.customUnit is UNDEFINED
    }
    

    When the FAB initiates the request (isFromGlobalCreate = true) and the user belongs to a workspace (hasOnlyPersonalPolicies = false), neither branch runs. comment.customUnit is left undefined, so customUnitRateID is never set on the transaction.

  2. The confirmation screen's auto-select rate effect returns early β€” src/components/MoneyRequestConfirmationList/DistanceRequestController.tsx lines 131–140:

    useEffect(() => {
        // ...
        if (!transactionID || !isDistanceRequest) { return; }
        if (!isPolicyExpenseChat) {                                   // line 137
            clearFormErrors([errorKey]);
            return;                                                   // ← returns entirely for non-policy-expense-chat
        }
        // ... auto-select logic never reached ...
    }, [...])
    

    When the user selects a workspace report/destination from the FAB flow (e.g. "Report: New report"), isPolicyExpenseChat is false, so the effect returns at line 139 without ever calling setCustomUnitRateID to correct the missing/placeholder rate. (Note: the guard at line 142 if (!isMovingTransactionFromTrackExpense && !isPolicyChanged) return; would also block it, but line 137 returns first.)

  3. At submission, the placeholder 'p2p' rate ID is sent β€” src/pages/iou/request/step/confirmation/submission/useDistanceSubmission.ts line 172:

    customUnitRateID: getRateID(transaction) ?? '',
    

    getRateID (src/libs/TransactionUtils/fields.ts lines 46–47) returns:

    return transaction?.comment?.customUnit?.customUnitRateID ?? CONST.CUSTOM_UNITS.FAKE_P2P_ID;
    

    Since customUnit was never initialized (step 1) and never corrected (step 2), this returns '_FAKE_P2P_ID_'.

  4. createDistanceRequest (Split.ts) sends customUnitRateID: '_FAKE_P2P_ID_' for a workspace policy expense. The backend CreateDistanceRequest command rejects it because '_FAKE_P2P_ID_' is not a valid custom unit rate on the workspace policy β†’ non-200 jsonCode.

  5. Why dismissing the error deletes the expense β€” MoneyRequestBuilder.ts failure handling applies failureData (including a misleading receipt error for map distance requests). Then MoneyRequestReceiptView.tsx lines 518–555: because the transaction has pendingAction === 'add', clicking the X calls cleanUpMoneyRequest, which deletes the optimistic transaction/report from Onyx.

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

Primary fix β€” resolve the rate ID at submission time (src/pages/iou/request/step/confirmation/submission/useDistanceSubmission.ts line 172): When submitting to a workspace policy, if the transaction's customUnitRateID is unset or is FAKE_P2P_ID, fall back to the policy's default/eligible mileage rate:

import {isUnsetDistanceCustomUnitRateID, getDefaultMileageRate} from '@libs/DistanceRequestUtils';
// ...
const transactionRateID = getRateID(transaction);
const resolvedCustomUnitRateID =
    policy && isUnsetDistanceCustomUnitRateID(transactionRateID)
        ? (getDefaultMileageRate(policy)?.customUnitRateID ?? transactionRateID)
        : transactionRateID;
// pass: customUnitRateID: resolvedCustomUnitRateID,

This is a foolproof defense that guarantees the API payload is always valid, regardless of how the transaction was initialized or whether the effect ran.

Secondary fix β€” initialize customUnit for global-create distance requests (src/libs/actions/IOU/MoneyRequest.ts lines 419–438): Currently, when isFromGlobalCreate is true and the user has workspace policies, comment.customUnit is left undefined. The else if (hasOnlyPersonalPolicies) branch should be broadened so that when isFromGlobalCreate is true, customUnit is always initialized (with FAKE_P2P_ID as a placeholder to be resolved later, or resolved immediately if a default policy is available). This ensures the transaction always has a customUnit object for downstream logic.

Tertiary fix (UX) β€” prevent misleading receipt error: In MoneyRequestReceiptView.tsx, ensure map-based distance requests (which use generated e-receipts, no uploaded file) only display the transaction creation failure message, not the receipt upload failure message.

What specific scenarios should be covered by automated tests?

  1. FAB β†’ Track distance β†’ enter waypoints β†’ select a workspace with distance rates β†’ Create expense (without manually tapping Rate) β†’ verify the expense is created successfully (no error).
  2. Same flow, selecting a workspace without distance rates β†’ verify appropriate handling (not a crash).
  3. Same flow, selecting a P2P recipient β†’ verify FAKE_P2P_ID is still used correctly (no regression).
  4. Verify getRateID returns the workspace's default rate when customUnit is undefined and a policy is present at submission.
  5. Verify the Rate field on the confirmation page displays the workspace default rate (not "Default Rate" placeholder) when the transaction was FAB-initiated.

What alternative solutions did you explore?

  • Only fixing DistanceRequestController.tsx to run the auto-select when isPolicyExpenseChat is false but a policy is present. This helps the UI state but is fragile β€” an effect hook can be skipped if the user taps "Create expense" before it commits, or if navigating quickly. Resolving the rate at submission (useDistanceSubmission.ts) is the guaranteed fix. Both together provide defense in depth.
  • Only fixing MoneyRequest.ts initialization. This addresses the source but doesn't protect against the same class of bug if another code path leaves customUnitRateID unset. The submission-time resolution is the safety net.

PR

PR will be linked here once created.

vanshshah11 avatar Nov 07 '26 00:11 vanshshah11

Proposal

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

When a user who belongs to a workspace policy initiates a distance expense from the global FAB (+ > Track distance), enters start and finish waypoints, and clicks Create expense on the confirmation screen, expense creation fails with "Unexpected error submitting this expense. Please try again later." and dismissing the error deletes the optimistic expense.

What is the root cause of that problem?

When a distance expense is started from the global FAB via Track distance (iouType === CONST.IOU.TYPE.TRACK and isFromGlobalCreate === true), the initial draft transaction is created before a target workspace policy is selected, so transaction.comment.customUnit.customUnitRateID is initialized to CONST.CUSTOM_UNITS.FAKE_P2P_ID ('_FAKE_P2P_ID_').

When the user advances to the confirmation step (src/pages/iou/request/step/IOURequestStepConfirmation.tsx / src/components/MoneyRequestConfirmationList), if the expense is routed to an active workspace policy (or submitted with policyID set to a group workspace rather than the personal policy), the transaction's customUnitRateID is still CONST.CUSTOM_UNITS.FAKE_P2P_ID ('_FAKE_P2P_ID_') instead of the target policy's valid default distance rate ID (DistanceRequestUtils.getDefaultMileageRate(policy)?.customUnitRateID). Submitting '_FAKE_P2P_ID_' against a workspace policy causes the backend API command (TrackExpense / RequestMoney) to fail with a generic error.

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

In src/pages/iou/request/step/IOURequestStepConfirmation.tsx (and src/libs/DistanceRequestUtils.ts / src/pages/iou/request/step/IOURequestStepDistance.tsx):

  1. When resolving the target policy for a distance request on the confirmation step, check whether transaction?.comment?.customUnit?.customUnitRateID is missing or equal to CONST.CUSTOM_UNITS.FAKE_P2P_ID while a valid workspace policy with distance rates is being used.
  2. If so, resolve the default mileage rate from DistanceRequestUtils.getDefaultMileageRate(policy) and update the draft transaction's customUnitRateID (via setCustomUnitRateID) and pass that resolved customUnitRateID into trackExpense / requestMoney so CONST.CUSTOM_UNITS.FAKE_P2P_ID is never sent for a workspace policy distance expense.

What alternative solutions did you explore? (Optional)

We also considered forcing Track distance from the global FAB to always stay on the personal policy (personalPolicyID), but when the confirmation screen binds the expense to a workspace policy (or when a user switches the receiver/workspace), resolving the workspace policy's default customUnitRateID ensures both personal and workspace distance expenses succeed.

jeffrey-graham avatar Nov 07 '26 01:11 jeffrey-graham

πŸ“£ @jeffrey-graham! πŸ“£ Hey, it seems we don’t have your contributor details yet! You'll only have to do this once, and this is how we'll hire you on Upwork. Please follow these steps:

  1. Make sure you've read and understood the contributing guidelines.
  2. Get the email address used to login to your Expensify account. If you don't already have an Expensify account, create one here. If you have multiple accounts (e.g. one for testing), please use your main account email.
  3. Get the link to your Upwork profile. It's necessary because we only pay via Upwork. You can access it by logging in, and then clicking on your name. It'll look like this. If you don't already have an account, sign up for one here.
  4. Copy the format below and paste it in a comment on this issue. Replace the placeholder text with your actual details. Screen Shot 2022-11-16 at 4 42 54 PM Format:
Contributor details
Your Expensify account email: <REPLACE EMAIL HERE>
Upwork Profile Link: <REPLACE LINK HERE>

melvin-bot[bot] avatar Nov 07 '26 01:11 melvin-bot[bot]

Proposal

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

When a user who belongs to a workspace policy initiates a distance expense from the global FAB (FAB > Track distance), enters waypoints, selects a workspace on the confirmation screen, and clicks Create expense, expense creation fails with "Unexpected error submitting this expense" and "There was a problem uploading the receipt", and dismissing the error deletes the expense.

What is the root cause of that problem?

  1. Unset customUnitRateID during FAB-initiated distance creation (src/libs/actions/IOU/MoneyRequest.ts:419-438): When starting a distance request from the global FAB (isFromGlobalCreate === true) for a user who belongs to at least one workspace policy (hasOnlyPersonalPolicies === false), neither the if (!isFromGlobalCreate) branch (line 419) nor the else if (hasOnlyPersonalPolicies) branch (line 433) executes. As a result, comment.customUnit is left undefined on the draft transaction.
  2. Early return in DistanceRequestController.tsx when destination is a workspace report (src/components/MoneyRequestConfirmationList/DistanceRequestController.tsx:137-144, 246-256): When the user selects a workspace or workspace report on the confirmation step, getRateID(transaction) (src/libs/TransactionUtils/fields.ts:46-47) falls back to CONST.CUSTOM_UNITS.FAKE_P2P_ID ('_FAKE_P2P_ID_').
    • In the first useEffect (lines 137-185), if !isPolicyExpenseChat is true (e.g. submitting to a newly created report on the workspace), line 137 returns early; even when isPolicyExpenseChat is true, lines 173–182 only auto-select the best/default workspace rate when isMovingTransactionFromTrackExpense is true (if (isMovingTransactionFromTrackExpense)), so for a normal FAB creation flow (isMovingTransactionFromTrackExpense === false) with customUnitRateID === CONST.CUSTOM_UNITS.FAKE_P2P_ID, it falls straight through to setFormError(errorKey) or leaves customUnitRateID as '_FAKE_P2P_ID_'!
    • In the fourth useEffect (lines 245-269), if !lastSelectedRate (the workspace has no previously stored NVP_LAST_SELECTED_DISTANCE_RATES entry), line 251 (!lastSelectedRate) returns early without falling back to defaultMileageRateCustomUnitRateID!
  3. '_FAKE_P2P_ID_' is sent to the backend in useDistanceSubmission.ts (src/pages/iou/request/step/confirmation/submission/useDistanceSubmission.ts:172): useDistanceSubmission.ts passes customUnitRateID: getRateID(transaction) ?? '', which evaluates to '_FAKE_P2P_ID_'. Sending '_FAKE_P2P_ID_' for a workspace distance expense causes CreateDistanceRequest / RequestMoney to fail on the backend.

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

  1. In src/components/MoneyRequestConfirmationList/DistanceRequestController.tsx:173-182 and 245-269:
    • In the rate-resolution effect (lines 245-269), do not require lastSelectedRate to be truthy when defaultMileageRateCustomUnitRateID is available; fall back to const candidateRateID = lastSelectedRate ?? defaultMileageRateCustomUnitRateID, and also auto-resolve in lines 173-182 whenever DistanceRequestUtils.isUnsetDistanceCustomUnitRateID(customUnitRateID) is true (not only when isMovingTransactionFromTrackExpense is true):
// src/components/MoneyRequestConfirmationList/DistanceRequestController.tsx (lines 173-182)
if (isMovingTransactionFromTrackExpense || DistanceRequestUtils.isUnsetDistanceCustomUnitRateID(customUnitRateID)) {
    const expenseDate = getCreated(transaction);
    const bestRate = expenseDate ? DistanceRequestUtils.getBestEligibleRate(policyRates, expenseDate) : undefined;
    const fallbackRateID = bestRate?.customUnitRateID ?? defaultMileageRateCustomUnitRateID;
    if (fallbackRateID) {
        setCustomUnitRateID(transactionID, fallbackRateID, transaction, policy, false, personalPolicy?.outputCurrency);
        clearFormErrors([errorKey]);
        return;
    }
}
  1. In src/pages/iou/request/step/confirmation/submission/useDistanceSubmission.ts:172:
    • Add a submission-time safeguard so that if policy is present and DistanceRequestUtils.isUnsetDistanceCustomUnitRateID(transactionRateID) is true, customUnitRateID resolves to DistanceRequestUtils.getDefaultMileageRate(policy)?.customUnitRateID ?? transactionRateID:
// src/pages/iou/request/step/confirmation/submission/useDistanceSubmission.ts
const transactionRateID = getRateID(transaction);
const resolvedCustomUnitRateID =
    policy && DistanceRequestUtils.isUnsetDistanceCustomUnitRateID(transactionRateID)
        ? (DistanceRequestUtils.getDefaultMileageRate(policy)?.customUnitRateID ?? transactionRateID)
        : (transactionRateID ?? '');

What alternative solutions did you explore? (Optional)

Notice why fixing only useDistanceSubmission.ts or only lastSelectedRate in DistanceRequestController.tsx is incomplete: in DistanceRequestController.tsx:173, when a workspace has no lastSelectedRate in Onyx yet (!lastSelectedRate at line 251), the first useEffect at lines 125–186 runs on policy selection and hits setFormError('iou.error.invalidRate') at line 185 because line 173 only checked if (isMovingTransactionFromTrackExpense). Checking isMovingTransactionFromTrackExpense || DistanceRequestUtils.isUnsetDistanceCustomUnitRateID(customUnitRateID) at line 173 alongside the useDistanceSubmission.ts fallback fixes both the UI rate state and the API payload.

tungnguyen84 avatar Nov 07 '26 06:11 tungnguyen84

Proposal

What is the root cause of that problem?

A distance draft started from the FAB (isFromGlobalCreate) by a user who has workspaces never gets a customUnit: in src/libs/actions/IOU/MoneyRequest.ts:419-438 the !isFromGlobalCreate branch is skipped and the else if (hasOnlyPersonalPolicies) branch is skipped, so comment.customUnit stays undefined. getRateID (src/libs/TransactionUtils/fields.ts:46-47) then falls back to CONST.CUSTOM_UNITS.FAKE_P2P_ID, and useDistanceSubmission.ts:172 (customUnitRateID: getRateID(transaction) ?? '') sends that placeholder with a workspace policy to CreateDistanceRequest. The failure data then leaves a pending add transaction with an error, and the X in MoneyRequestReceiptView.tsx cleans it up, which is why the expense vanishes. Note this is read from code only: MelvinBot's dev run did not reproduce it, so it likely depends on the account having a workspace and no stored last-selected rate.

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

One guard at the single place the payload is built, useDistanceSubmission.ts:172:

const rateID = getRateID(transaction);
customUnitRateID: policy && DistanceRequestUtils.isUnsetDistanceCustomUnitRateID(rateID)
    ? (DistanceRequestUtils.getDefaultMileageRate(policy)?.customUnitRateID ?? rateID)
    : rateID,

Both helpers exist (DistanceRequestUtils.ts:93 and :536). P2P submissions have no policy, so they keep FAKE_P2P_ID.

Test: a hook/unit test for useDistanceSubmission (or createDistanceRequest params) with a workspace policy and a draft without customUnit asserts the API param customUnitRateID equals the policy default rate id; a second case with no policy asserts FAKE_P2P_ID is still sent.

What alternative solutions did you explore? (Optional)

kevinjosh10, vanshshah11 and tungnguyen84 also add this submission fallback, but pair it with edits to DistanceRequestController.tsx effect guards, MoneyRequest.ts initialization and the receipt error view. Those touch more files and the effect-based paths can be skipped if the user submits quickly. Mine is only the submission guard, which is enough to make the payload valid, plus a named test. jeffrey-graham's setCustomUnitRateID in the confirmation step has the same race. camesenin's proposal names no cause.

Stephen3453 avatar Nov 07 '26 16:11 Stephen3453

Proposal

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

When an Australian user (who belongs to at least one workspace) creates a Map or Manual distance expense from the global + (Create expense) button and submits it to a workspace on the confirmation screen, expense creation fails with "Unexpected error creating this expense. Please try again later." Afterward, opening the failed expense and clicking the X button on the RHP deletes the expense entirely.

What is the root cause of that problem?

The bug is caused by customUnitRateID remaining set to CONST.CUSTOM_UNITS.FAKE_P2P_ID ('_FAKE_P2P_ID_') through confirmation and being sent to CreateDistanceRequest for a workspace policy expense:

  1. Draft initialization leaves customUnit.customUnitRateID unset when started from the global FAB (isFromGlobalCreate = true) by a user with a workspace (hasOnlyPersonalPolicies = false): In src/libs/actions/IOU/MoneyRequest.ts (lines 419-438), initMoneyRequest only sets comment.customUnit.customUnitRateID when !isFromGlobalCreate (line 421) or else if (hasOnlyPersonalPolicies) (line 430). When the user has at least one workspace policy and starts from the global + button (isFromGlobalCreate === true, hasOnlyPersonalPolicies === false), neither branch runs, leaving transaction.comment.customUnit undefined. Consequently, getRateID(transaction) (src/libs/TransactionUtils/fields.ts:46-47) returns CONST.CUSTOM_UNITS.FAKE_P2P_ID ('_FAKE_P2P_ID_').

  2. DistanceRequestController fails to replace '_FAKE_P2P_ID_' with the workspace's default mileage rate on the confirmation screen: In src/components/MoneyRequestConfirmationList/DistanceRequestController.tsx (lines 125-201), the first useEffect checks whether customUnitRateID ('_FAKE_P2P_ID_') exists in the selected workspace's mileageRates. Because mileageRates['_FAKE_P2P_ID_'] is undefined, execution reaches line 173:

    if (isMovingTransactionFromTrackExpense) {
        const bestRate =
            rateForCurrency?.customUnitRateID && mileageRates[rateForCurrency.customUnitRateID]
                ? mileageRates[rateForCurrency.customUnitRateID]
                : mileageRates[defaultMileageRateCustomUnitRateID ?? ''];
        if (bestRate?.customUnitRateID) {
            setCustomUnitRateID(transactionID, bestRate.customUnitRateID, transaction, isTransactionDraft);
            return;
        }
    }
    
    setFormError('iou.error.invalidRate');
    

    Because this is a normal global-FAB creation flow (isMovingTransactionFromTrackExpense === false), the if (isMovingTransactionFromTrackExpense) block is skipped! Meanwhile, the fourth useEffect (lines 245-281) checks:

    if (!defaultMileageRateCustomUnitRateID || !selectedParticipants.some((participant) => participant.policyID === policy?.id)) {
        return;
    }
    

    When lastSelectedDistanceRates?.[policy.id] is unset or when the participant entry's policyID does not match before submission, customUnitRateID remains '_FAKE_P2P_ID_'.

  3. useDistanceSubmission.ts sends customUnitRateID: '_FAKE_P2P_ID_' to CreateDistanceRequest: In src/pages/iou/request/step/confirmation/submission/useDistanceSubmission.ts (line 172), requestMoney is called with:

    customUnitRateID: getRateID(transaction) ?? '',
    

    This passes '_FAKE_P2P_ID_' directly to the CreateDistanceRequest API command for a workspace policy expense. The server rejects '_FAKE_P2P_ID_' on a workspace policy and returns the generic FailureData error ("Unexpected error creating this expense. Please try again later.").

  4. Why clicking X removes the expense: Because CreateDistanceRequest failed during initial creation (pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD), dismissing the error banner in src/components/ReportActionItem/MoneyRequestReceiptView.tsx (lines 518-555) invokes cleanUpMoneyRequest(transaction.transactionID, reportAction, report.reportID, true), which is the standard optimistic rollback for failed ADD actions. Once CreateDistanceRequest sends a valid workspace customUnitRateID, creation succeeds and this failure state is not reached.

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

  1. In src/components/MoneyRequestConfirmationList/DistanceRequestController.tsx (line 173): When a distance request on a workspace policy chat (isPolicyExpenseChat === true) currently has an unset/fake P2P rate (DistanceRequestUtils.isUnsetDistanceCustomUnitRateID(customUnitRateID)), auto-select bestRate.customUnitRateID (matching currency rate or the workspace's default mileage rate) just like isMovingTransactionFromTrackExpense does, instead of falling through to setFormError('iou.error.invalidRate'):
// src/components/MoneyRequestConfirmationList/DistanceRequestController.tsx
if (isMovingTransactionFromTrackExpense || DistanceRequestUtils.isUnsetDistanceCustomUnitRateID(customUnitRateID)) {
    const bestRate =
        rateForCurrency?.customUnitRateID && mileageRates[rateForCurrency.customUnitRateID]
            ? mileageRates[rateForCurrency.customUnitRateID]
            : mileageRates[defaultMileageRateCustomUnitRateID ?? ''];
    if (bestRate?.customUnitRateID) {
        setCustomUnitRateID(transactionID, bestRate.customUnitRateID, transaction, isTransactionDraft);
        return;
    }
}
  1. In src/pages/iou/request/step/confirmation/submission/useDistanceSubmission.ts (line 172): As a defensive safeguard in case the user submits before DistanceRequestController's effect flushes to Onyx, resolve customUnitRateID against the selected workspace policy when isPolicyExpenseChat is true and getRateID(transaction) is still unset/FAKE_P2P_ID:
// src/pages/iou/request/step/confirmation/submission/useDistanceSubmission.ts
const transactionRateID = getRateID(transaction);
const resolvedCustomUnitRateID =
    isPolicyExpenseChat && DistanceRequestUtils.isUnsetDistanceCustomUnitRateID(transactionRateID)
        ? (DistanceRequestUtils.getDefaultMileageRate(policy)?.customUnitRateID ?? transactionRateID ?? '')
        : (transactionRateID ?? '');

And pass customUnitRateID: resolvedCustomUnitRateID to requestMoney (line 172).

What alternative solutions did you explore? (Optional)

  • Setting a workspace rate inside initMoneyRequest when isFromGlobalCreate === true: At the moment initMoneyRequest runs for the global FAB, the user has not chosen a recipient/workspace yet, so the target policy is unknown until the confirmation step. Resolving the unset FAKE_P2P_ID rate in DistanceRequestController once the confirmation target policy is known (and guarding in useDistanceSubmission) handles both initial global-create selection and workspace switching on the confirmation page.

e5ash avatar Nov 07 '26 18:11 e5ash

Proposal

What is the root cause of that problem?

In src/libs/actions/IOU/MoneyRequest.ts (lines 419–438 inside initMoneyRequest / setupDistanceExpenseState):

if (!isFromGlobalCreate) {
    const isPolicyExpenseChat = isPolicyExpenseChatReportUtil(report) || isPolicyExpenseChatReportUtil(parentReport);
    const customUnitRateID = DistanceRequestUtils.getCustomUnitRateID({
        reportID,
        isPolicyExpenseChat,
        isTrackDistanceExpense,
        policy,
        lastSelectedDistanceRates,
        expenseDate: created,
    });
    comment.customUnit = {
        customUnitRateID,
        name: CONST.CUSTOM_UNITS.NAME_DISTANCE,
    };
} else if (hasOnlyPersonalPolicies) {
    comment.customUnit = {
        customUnitRateID: CONST.CUSTOM_UNITS.FAKE_P2P_ID,
        name: CONST.CUSTOM_UNITS.NAME_DISTANCE,
    };
}

When a user with active workspace policies starts a distance expense from the global FAB (+ > Track distance):

  1. isFromGlobalCreate is true.
  2. hasOnlyPersonalPolicies is false (because the user belongs to workspace policies).

Under these conditions, neither branch executes, leaving comment.customUnit completely undefined. When the user proceeds through the flow, enters waypoints, and submits, the backend/Onyx transaction builder fails due to missing customUnitRateID on comment.customUnit, throwing an unexpected error modal.

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

  1. In src/libs/actions/IOU/MoneyRequest.ts (lines 419–438), ensure comment.customUnit is always initialized for distance requests created globally when the user has workspace policies:
    • If the user has multiple policies, initialize comment.customUnit with a fallback or resolve the default workspace's customUnitRateID via DistanceRequestUtils.getCustomUnitRateID (or dynamically assign it in setMoneyRequestParticipants when the destination policy/chat is selected).
  2. Ensure that whenever isFromGlobalCreate is true and a workspace participant is selected, DistanceRequestUtils.getCustomUnitRateID is called to populate transaction.comment.customUnit with the target policy's distance rate before submission.

What alternative solutions did you explore? (Optional)

Initializing with CONST.CUSTOM_UNITS.FAKE_P2P_ID universally for all global creates, but updating to the workspace's actual customUnitRateID during policy assignment is cleaner and prevents rate miscalculations.

Contributor Details

Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~0179cdc82689f205c7

TassioSales avatar Nov 07 '26 23:11 TassioSales

βœ… Contributor details stored successfully. Thank you for contributing to Expensify!

melvin-bot[bot] avatar Nov 07 '26 23:11 melvin-bot[bot]

@eVoloshchak Whoops! This issue is 2 days overdue. Let's get this updated quick!

melvin-bot[bot] avatar Nov 09 '26 22:11 melvin-bot[bot]

@eVoloshchak Eep! 4 days overdue now. Issues have feelings too...

melvin-bot[bot] avatar Nov 11 '26 21:11 melvin-bot[bot]

Cannot reproduce this one

https://github.com/user-attachments/assets/c0147004-ae3f-4962-a693-0730e50e00d8

@MelvinBot, please add a retest label

eVoloshchak avatar Nov 17 '26 10:11 eVoloshchak

Added the retest-weekly label.


view run

MelvinBot avatar Nov 17 '26 10:11 MelvinBot

@eVoloshchak this issue was created 2 weeks ago. Are we close to approving a proposal? If not, what's blocking us from getting this issue assigned? Don't hesitate to create a thread in #expensify-open-source to align faster in real time. Thanks!