[$175] AU - Track distance - Expense creation fails with unexpected error
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:
- Click on FAB > Track distance
- Ener waypoints
- 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
Applause Internal Information Exported by: Chandana Kiran Bug ID: 7307112
Upwork Automation - Do Not Edit
- Upwork Job URL: https://www.upwork.com/jobs/~022118785836380286085
- Upwork Job ID: 2118785836380286085
- Last Price Increase: 2026-11-06
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
Triggered auto assignment to Contributor-plus team member for initial proposal review - @eVoloshchak (External)
Job added to Upwork: https://www.upwork.com/jobs/~022118785836380286085
π€ 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.
| 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.![]() 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. |
β |
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:
-
customUnitRateIDis 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, defaultingcustomUnitRateIDtoCONST.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.tsxis 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:
!isPolicyExpenseChatand!selectedParticipants.some((participant) => participant.policyID === policy?.id). When creating an expense from FAB into a new report (Report: New report),isPolicyExpenseChatisfalse, andselectedParticipantsmay only holdreportID. As a result,DistanceRequestControllerreturns early without callingsetCustomUnitRateID. - On the confirmation page,
RateFielddisplays "Default Rate" because the UI presentation derives the default rate dynamically frompolicy, buttransaction.comment.customUnit.customUnitRateIDremains unset or'p2p'. - In
src/pages/iou/request/step/confirmation/submission/useDistanceSubmission.ts:customUnitRateID: getRateID(transaction) ?? '',getRateID(transaction)returnsCONST.CUSTOM_UNITS.FAKE_P2P_ID('p2p') fromfields.ts#L47. - Consequently,
createDistanceRequestsendscustomUnitRateID: 'p2p'for a workspace policy. Because'p2p'is not a valid custom unit rate on the workspace policy, the backend API commandCreateDistanceRequestrejects the request with an unexpected error.
- In
-
Onyx
failureDatasurfaces a misleading receipt error for map distance requests, and dismissing the error deletes the expense:- In
MoneyRequestBuilder.ts(lines 1076β1105), whenCreateDistanceRequestfails,failureDataattachesgetReceiptError(...)andgenericCreateFailureMessage. - In
src/components/ReportActionItem/MoneyRequestReceiptView.tsx:
Because the transaction was pending creation (if (transaction?.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD) { ... cleanUpMoneyRequest({...}); return; }pendingAction === 'add'), clicking theXbutton callscleanUpMoneyRequest, which deletes the optimistic transaction and report from local Onyx, causing the expense to disappear.
- In
What changes do you think we should make in order to solve the problem?
-
Ensure
customUnitRateIDresolves to the workspace policy's default rate upon submission: Insrc/pages/iou/request/step/confirmation/submission/useDistanceSubmission.ts: When creating an expense on a policy, ifcustomUnitRateIDis unset or isFAKE_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: resolvedCustomUnitRateIDtocreateDistanceRequestIOUActions. -
Loosen the auto-select rate guard in
DistanceRequestController.tsx: Insrc/components/MoneyRequestConfirmationList/DistanceRequestController.tsx: Allow auto-selection to run whenever a workspacepolicywith distance rates is present (even ifisPolicyExpenseChatis false because a new report or global create is selected), and check ifpolicy?.idmatches 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; } -
Prevent misleading receipt error display on map distance expenses in
MoneyRequestReceiptView.tsx: InMoneyRequestReceiptView.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 toDistanceRequestUtils.getDefaultMileageRate(policy)inuseDistanceSubmission.tsprovides a foolproof defense in depth that guarantees the API request payload is always valid.
Tests
- Create or use a workspace that has Distance rates enabled with custom rates.
- From the global FAB, click + > Track distance.
- Select the Map tab, enter a valid Start and Stop waypoint, and click Next.
- Select the workspace from step 1.
- On the Confirm details page, verify "Rate" displays the workspace's default rate.
- Toggle "Reimbursable" to OFF (or leave ON) without tapping into the "Rate" selector.
- Click Create expense.
- Verify that the expense is created successfully without any unexpected submission or receipt error.
- 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
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
β Contributor details stored successfully. Thank you for contributing to Expensify!
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:
-
Transaction initialization skips
customUnitsetup for global-create distance requests with workspace policies βsrc/libs/actions/IOU/MoneyRequest.tslines 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.customUnitis leftundefined, socustomUnitRateIDis never set on the transaction. -
The confirmation screen's auto-select rate effect returns early β
src/components/MoneyRequestConfirmationList/DistanceRequestController.tsxlines 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"),
isPolicyExpenseChatisfalse, so the effect returns at line 139 without ever callingsetCustomUnitRateIDto correct the missing/placeholder rate. (Note: the guard at line 142if (!isMovingTransactionFromTrackExpense && !isPolicyChanged) return;would also block it, but line 137 returns first.) -
At submission, the placeholder
'p2p'rate ID is sent βsrc/pages/iou/request/step/confirmation/submission/useDistanceSubmission.tsline 172:customUnitRateID: getRateID(transaction) ?? '',getRateID(src/libs/TransactionUtils/fields.tslines 46β47) returns:return transaction?.comment?.customUnit?.customUnitRateID ?? CONST.CUSTOM_UNITS.FAKE_P2P_ID;Since
customUnitwas never initialized (step 1) and never corrected (step 2), this returns'_FAKE_P2P_ID_'. -
createDistanceRequest(Split.ts) sendscustomUnitRateID: '_FAKE_P2P_ID_'for a workspace policy expense. The backendCreateDistanceRequestcommand rejects it because'_FAKE_P2P_ID_'is not a valid custom unit rate on the workspace policy β non-200 jsonCode. -
Why dismissing the error deletes the expense β
MoneyRequestBuilder.tsfailure handling appliesfailureData(including a misleading receipt error for map distance requests). ThenMoneyRequestReceiptView.tsxlines 518β555: because the transaction haspendingAction === 'add', clicking the X callscleanUpMoneyRequest, 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?
- 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).
- Same flow, selecting a workspace without distance rates β verify appropriate handling (not a crash).
- Same flow, selecting a P2P recipient β verify
FAKE_P2P_IDis still used correctly (no regression). - Verify
getRateIDreturns the workspace's default rate whencustomUnitis undefined and a policy is present at submission. - 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.tsxto run the auto-select whenisPolicyExpenseChatis 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.tsinitialization. This addresses the source but doesn't protect against the same class of bug if another code path leavescustomUnitRateIDunset. The submission-time resolution is the safety net.
PR
PR will be linked here once created.
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):
- When resolving the target
policyfor a distance request on the confirmation step, check whethertransaction?.comment?.customUnit?.customUnitRateIDis missing or equal toCONST.CUSTOM_UNITS.FAKE_P2P_IDwhile a valid workspacepolicywith distance rates is being used. - If so, resolve the default mileage rate from
DistanceRequestUtils.getDefaultMileageRate(policy)and update the draft transaction'scustomUnitRateID(viasetCustomUnitRateID) and pass that resolvedcustomUnitRateIDintotrackExpense/requestMoneysoCONST.CUSTOM_UNITS.FAKE_P2P_IDis 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! π£ 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:
- Make sure you've read and understood the contributing guidelines.
- 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.
- 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.
- Copy the format below and paste it in a comment on this issue. Replace the placeholder text with your actual details.
Format:
Contributor details
Your Expensify account email: <REPLACE EMAIL HERE>
Upwork Profile Link: <REPLACE LINK HERE>
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?
- Unset
customUnitRateIDduring 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 theif (!isFromGlobalCreate)branch (line 419) nor theelse if (hasOnlyPersonalPolicies)branch (line 433) executes. As a result,comment.customUnitis leftundefinedon the draft transaction. - Early return in
DistanceRequestController.tsxwhen 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 toCONST.CUSTOM_UNITS.FAKE_P2P_ID('_FAKE_P2P_ID_').- In the first
useEffect(lines 137-185), if!isPolicyExpenseChatis true (e.g. submitting to a newly created report on the workspace), line 137 returns early; even whenisPolicyExpenseChatis true, lines 173β182 only auto-select the best/default workspace rate whenisMovingTransactionFromTrackExpenseis true (if (isMovingTransactionFromTrackExpense)), so for a normal FAB creation flow (isMovingTransactionFromTrackExpense === false) withcustomUnitRateID === CONST.CUSTOM_UNITS.FAKE_P2P_ID, it falls straight through tosetFormError(errorKey)or leavescustomUnitRateIDas'_FAKE_P2P_ID_'! - In the fourth
useEffect(lines 245-269), if!lastSelectedRate(the workspace has no previously storedNVP_LAST_SELECTED_DISTANCE_RATESentry), line 251 (!lastSelectedRate) returns early without falling back todefaultMileageRateCustomUnitRateID!
- In the first
'_FAKE_P2P_ID_'is sent to the backend inuseDistanceSubmission.ts(src/pages/iou/request/step/confirmation/submission/useDistanceSubmission.ts:172):useDistanceSubmission.tspassescustomUnitRateID: getRateID(transaction) ?? '', which evaluates to'_FAKE_P2P_ID_'. Sending'_FAKE_P2P_ID_'for a workspace distance expense causesCreateDistanceRequest/RequestMoneyto fail on the backend.
What changes do you think we should make in order to solve the problem?
- In
src/components/MoneyRequestConfirmationList/DistanceRequestController.tsx:173-182 and 245-269:- In the rate-resolution effect (
lines 245-269), do not requirelastSelectedRateto be truthy whendefaultMileageRateCustomUnitRateIDis available; fall back toconst candidateRateID = lastSelectedRate ?? defaultMileageRateCustomUnitRateID, and also auto-resolve inlines 173-182wheneverDistanceRequestUtils.isUnsetDistanceCustomUnitRateID(customUnitRateID)is true (not only whenisMovingTransactionFromTrackExpenseis true):
- In the rate-resolution effect (
// 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;
}
}
- In
src/pages/iou/request/step/confirmation/submission/useDistanceSubmission.ts:172:- Add a submission-time safeguard so that if
policyis present andDistanceRequestUtils.isUnsetDistanceCustomUnitRateID(transactionRateID)is true,customUnitRateIDresolves toDistanceRequestUtils.getDefaultMileageRate(policy)?.customUnitRateID ?? transactionRateID:
- Add a submission-time safeguard so that if
// 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.
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.
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:
-
Draft initialization leaves
customUnit.customUnitRateIDunset when started from the global FAB (isFromGlobalCreate = true) by a user with a workspace (hasOnlyPersonalPolicies = false): Insrc/libs/actions/IOU/MoneyRequest.ts(lines 419-438),initMoneyRequestonly setscomment.customUnit.customUnitRateIDwhen!isFromGlobalCreate(line 421) orelse 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, leavingtransaction.comment.customUnitundefined. Consequently,getRateID(transaction)(src/libs/TransactionUtils/fields.ts:46-47) returnsCONST.CUSTOM_UNITS.FAKE_P2P_ID('_FAKE_P2P_ID_'). -
DistanceRequestControllerfails to replace'_FAKE_P2P_ID_'with the workspace's default mileage rate on the confirmation screen: Insrc/components/MoneyRequestConfirmationList/DistanceRequestController.tsx(lines 125-201), the firstuseEffectchecks whethercustomUnitRateID('_FAKE_P2P_ID_') exists in the selected workspace'smileageRates. BecausemileageRates['_FAKE_P2P_ID_']isundefined, execution reachesline 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), theif (isMovingTransactionFromTrackExpense)block is skipped! Meanwhile, the fourthuseEffect(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'spolicyIDdoes not match before submission,customUnitRateIDremains'_FAKE_P2P_ID_'. -
useDistanceSubmission.tssendscustomUnitRateID: '_FAKE_P2P_ID_'toCreateDistanceRequest: Insrc/pages/iou/request/step/confirmation/submission/useDistanceSubmission.ts(line 172),requestMoneyis called with:customUnitRateID: getRateID(transaction) ?? '',This passes
'_FAKE_P2P_ID_'directly to theCreateDistanceRequestAPI command for a workspace policy expense. The server rejects'_FAKE_P2P_ID_'on a workspace policy and returns the genericFailureDataerror ("Unexpected error creating this expense. Please try again later."). -
Why clicking
Xremoves the expense: BecauseCreateDistanceRequestfailed during initial creation (pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD), dismissing the error banner insrc/components/ReportActionItem/MoneyRequestReceiptView.tsx(lines 518-555) invokescleanUpMoneyRequest(transaction.transactionID, reportAction, report.reportID, true), which is the standard optimistic rollback for failedADDactions. OnceCreateDistanceRequestsends a valid workspacecustomUnitRateID, creation succeeds and this failure state is not reached.
What changes do you think we should make in order to solve the problem?
- 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-selectbestRate.customUnitRateID(matching currency rate or the workspace's default mileage rate) just likeisMovingTransactionFromTrackExpensedoes, instead of falling through tosetFormError('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;
}
}
- In
src/pages/iou/request/step/confirmation/submission/useDistanceSubmission.ts(line 172): As a defensive safeguard in case the user submits beforeDistanceRequestController's effect flushes to Onyx, resolvecustomUnitRateIDagainst the selected workspacepolicywhenisPolicyExpenseChatis true andgetRateID(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
initMoneyRequestwhenisFromGlobalCreate === true: At the momentinitMoneyRequestruns for the global FAB, the user has not chosen a recipient/workspace yet, so the targetpolicyis unknown until the confirmation step. Resolving the unsetFAKE_P2P_IDrate inDistanceRequestControlleronce the confirmation target policy is known (and guarding inuseDistanceSubmission) handles both initial global-create selection and workspace switching on the confirmation page.
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):
isFromGlobalCreateistrue.hasOnlyPersonalPoliciesisfalse(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?
- In
src/libs/actions/IOU/MoneyRequest.ts(lines 419β438), ensurecomment.customUnitis always initialized for distance requests created globally when the user has workspace policies:- If the user has multiple policies, initialize
comment.customUnitwith a fallback or resolve the default workspace'scustomUnitRateIDviaDistanceRequestUtils.getCustomUnitRateID(or dynamically assign it insetMoneyRequestParticipantswhen the destination policy/chat is selected).
- If the user has multiple policies, initialize
- Ensure that whenever
isFromGlobalCreateis true and a workspace participant is selected,DistanceRequestUtils.getCustomUnitRateIDis called to populatetransaction.comment.customUnitwith 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
β Contributor details stored successfully. Thank you for contributing to Expensify!
@eVoloshchak Whoops! This issue is 2 days overdue. Let's get this updated quick!
@eVoloshchak Eep! 4 days overdue now. Issues have feelings too...
Cannot reproduce this one
https://github.com/user-attachments/assets/c0147004-ae3f-4962-a693-0730e50e00d8
@MelvinBot, please add a retest label
@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!