Skip to content

[Due for payment 2025-08-29] [$250] Expense - Split distance expense shows unexpected error with rate not valid &duplicate violation #67213

Closed

Description

@jponikarchuk

If you haven’t already, check out our contributing guidelines for onboarding and email contributors@expensify.com to request to join our Slack channel!


Version Number: V9.1.86-3
Reproducible in staging?: Yes
Reproducible in production?: Yes
If this was caught during regression testing, add the test name, ID and link from TestRail: Exp https://test-management.browserstack.com/projects/2148171/test-runs/TR-215/folder/12015351/39318458/805630292
Email or phone of affected tester (no customers): slottwo1g@gmail.com
Issue reported by: Applause Internal Team
Device used: Redminote 10s android 13
App Component: Money Requests

Action Performed:

  1. Go to https://staging.new.expensify.com/home
  2. Open workpace chat
  3. Create 2 potential duplicate distance expense
  4. Enable distance rate
  5. Create new distance rate and delete old rate
  6. Go to workspace chat
  7. Open expense report
  8. Open the second expense - more- split
  9. Tap save

Expected Result:

Split distance expense must be created without error when there is rate not valid and duplicate violation.

Actual Result:

Split distance expense shows unexpected error when there is rate not valid and duplicate violation.

Workaround:

Unknown

Platforms:

  • Android: App
  • Android: mWeb Chrome
  • iOS: App
  • iOS: mWeb Safari
  • iOS: mWeb Chrome
  • Windows: Chrome
  • MacOS: Chrome / Safari
  • MacOS: Desktop

Screenshots/Videos

1.mp4

View all open jobs on GitHub

Upwork Automation - Do Not Edit
  • Upwork Job URL: https://www.upwork.com/jobs/~021952393342401200146
  • Upwork Job ID: 1952393342401200146
  • Last Price Increase: 2025-08-04
  • Automatic offers:
    • huult | Contributor | 108379578
Issue OwnerCurrent Issue Owner: @sonialiap

Activity

  1. added
    Daily
    Bug
    on Jul 27, 2025
  2. melvin-bot commented on Jul 27, 2025

    @melvin-bot

    Triggered auto assignment to @sonialiap (Bug), see https://stackoverflow.com/c/expensify/questions/14418 for more details. Please add this bug to a GH project, as outlined in the SO.

  3. melvin-bot commented on Aug 1, 2025

    @melvin-bot

    @sonialiap Huh... This is 4 days overdue. Who can take care of this?

  4. added
    External
    on Aug 4, 2025
  5. changed the title [-]Expense - Split distance expense shows unexpected error with rate not valid &duplicate violation[/-] [+][$250] Expense - Split distance expense shows unexpected error with rate not valid &duplicate violation[/+] on Aug 4, 2025
  6. melvin-bot commented on Aug 4, 2025

    @melvin-bot
  7. added
    Help Wanted
    on Aug 4, 2025
  8. melvin-bot commented on Aug 4, 2025

    @melvin-bot

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

  9. huult commented on Aug 5, 2025

    @huult
    Contributor

    Proposal

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

    Split distance expense shows unexpected error with rate not valid &duplicate violation

    What is the root cause of that problem?

    When we delete the old rate, the rate of the first/second expense will be out of policy because it was removed.

    Image

    Continuing to click ‘More’ and splitting the expense using a rate that has been removed or is out of policy will result in a backend validation error, preventing the split.

    Image

    Due to invalid data, the split expense incorrectly appears after the API call fails

    API.write(WRITE_COMMANDS.SPLIT_TRANSACTION, parameters, {optimisticData, successData, failureData});

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

    To fix this issue, we should validate the distance rate before proceeding with the split. If the rate doesn’t exist or is disabled, we should display an error and return early.

    add this

        const customUnitRateID = originalTransaction?.comment?.customUnit?.customUnitRateID;
        if (customUnitRateID && policy) {
            const customUnitRate = getDistanceRateCustomUnitRate(policy, customUnitRateID);
    
            // If the rate doesn't exist or is disabled, show an error and return early
            if (!customUnitRate || !customUnitRate.enabled) {
                const errorMessage = !customUnitRate ? 'iou.error.invalidRate' : 'iou.error.genericEditFailureMessage';
    
                console.log('****** errorMessage ******', errorMessage);
    
                // Show error to user
                Onyx.merge(`${ONYXKEYS.COLLECTION.SPLIT_TRANSACTION_DRAFT}${originalTransactionID}`, {
                    errors: getMicroSecondOnyxErrorWithTranslationKey(errorMessage),
                });
                return;
            }
        }

    and show this error in SplitExpensePage

    add

     useEffect(() => {
            if (!draftTransaction?.errors) {
                return;
            }
    
            const errorKeys = Object.keys(draftTransaction.errors);
            if (errorKeys.length === 0) {
                return;
            }
    
            const firstErrorKey = errorKeys.at(0);
            if (!firstErrorKey) {
                return;
            }
    
            const errorText = draftTransaction.errors[firstErrorKey];
            if (errorText) {
                // Error can be either a string or ReceiptError object
                const errorString = typeof errorText === 'string' ? errorText : errorText.source;
                setErrorMessage(errorString);
            }
        }, [draftTransaction?.errors]);

    addSplitExpenseField(transaction, draftTransaction);

    add:

    if (draftTransaction?.errors) {
        clearSplitTransactionDraftErrors(transactionID);
    }

    if (sumOfSplitExpenses > Math.abs(transactionDetailsAmount)) {

      if (draftTransaction?.errors) {
          clearSplitTransactionDraftErrors(transactionID);
      }
    Screen.Recording.2025-08-05.at.12.20.46.mp4

    Test branch

    What specific scenarios should we cover in automated tests to prevent reintroducing this issue in the future?

    none

    What alternative solutions did you explore? (Optional)

    Reminder: Please use plain English, be brief and avoid jargon. Feel free to use images, charts or pseudo-code if necessary. Do not post large multi-line diffs or write walls of text. Do not create PRs unless you have been hired for this job.

    Option 1:
    We will automatically select a valid rate when splitting an expense

    function getValidDistanceRate(policy: OnyxEntry<OnyxTypes.Policy>, originalRateID?: string): string | undefined {
        if (!policy?.customUnits) {
            return undefined;
        }
    
        const distanceUnit = getDistanceRateCustomUnit(policy);
        if (!distanceUnit?.rates) {
            return undefined;
        }
    
        // Check if the original rate is still valid and enabled
        if (originalRateID) {
            const originalRate = getDistanceRateCustomUnitRate(policy, originalRateID);
            if (originalRate?.enabled && originalRate.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE) {
                return originalRateID;
            }
        }
    
        // Get the default rate (first rate created) if it's enabled
        const defaultRate = DistanceRequestUtils.getDefaultMileageRate(policy);
        if (defaultRate?.customUnitRateID && defaultRate.enabled) {
            const rate = getDistanceRateCustomUnitRate(policy, defaultRate.customUnitRateID);
            if (rate?.enabled && rate.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE) {
                return defaultRate.customUnitRateID;
            }
        }
    
        // Find any enabled rate as fallback
        const enabledRates = Object.entries(distanceUnit.rates).filter(([, rate]) => rate.enabled && rate.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE);
    
        if (enabledRates.length > 0) {
            return enabledRates.at(0)?.[0]; // Return the first enabled rate ID
        }
    
        return undefined;
    }

    add:

        // If the original transaction is a distance request, ensure we use a valid rate
        if (originalTransaction && isDistanceRequestTransactionUtils(originalTransaction)) {
            const originalRateID = originalTransaction.comment?.customUnit?.customUnitRateID;
            const validRateID = getValidDistanceRate(policy, originalRateID);
    
            // If the original rate is invalid but we found a valid one, update the transaction params
            if (validRateID && validRateID !== originalRateID) {
                // Add customUnitRateID to transactionParams since it's a distance request
                (transactionParams as RequestMoneyTransactionParams).customUnitRateID = validRateID;
            }
        }

    Option 2:
    The BE needs to be updated to not return a 402 when we split an expense with an invalid rate

  10. 43 remaining items

  11. allroundexperts commented on Sep 1, 2025

    @allroundexperts
    Contributor

    @sonialiap The second PR is not deployed to prod yet I think. Let's wait for it before the payment summary 😄

  12. sonialiap commented on Sep 1, 2025

    @sonialiap
    Contributor

    Oh, whoops, I didn't realize there was a second

  13. melvin-bot commented on Sep 4, 2025

    @melvin-bot

    ⚠️ Looks like this issue was linked to a Deploy Blocker here

    If you are the assigned CME please investigate whether the linked PR caused a regression and leave a comment with the results.

    If a regression has occurred and you are the assigned CM follow the instructions here.

    If this regression could have been avoided please consider also proposing a recommendation to the PR checklist so that we can avoid it in the future.

  14. melvin-bot commented on Sep 4, 2025

    @melvin-bot

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

  15. sonialiap commented on Sep 5, 2025

    @sonialiap
    Contributor

    Regression caused by #68820, has been fixed.

    @allroundexperts looks like both PRs have been merged, is that correct? For payment, did we increase the scope of this issue or does the $250 sound reasonable for the work done?

  16. allroundexperts commented on Sep 8, 2025

    @allroundexperts
    Contributor

    I think it's reasonable.

  17. sonialiap commented on Sep 8, 2025

    @sonialiap
    Contributor

    Payment summary:
    50% reduction due to regression

  18. allroundexperts commented on Sep 8, 2025

    @allroundexperts
    Contributor

    BugZero Checklist:

    • [Contributor] Classify the bug:
    Bug classification

    Source of bug:

    • 1a. Result of the original design (eg. a case wasn't considered)
    • 1b. Mistake during implementation
    • 1c. Backend bug
    • 1z. Other:

    Where bug was reported:

    • 2a. Reported on production (eg. bug slipped through the normal regression and PR testing process on staging)
    • 2b. Reported on staging (eg. found during regression or PR testing)
    • 2d. Reported on a PR
    • 2z. Other:

    Who reported the bug:

    • 3a. Expensify user
    • 3b. Expensify employee
    • 3c. Contributor
    • 3d. QA
    • 3z. Other:
    • [Contributor] The offending PR has been commented on, pointing out the bug it caused and why, so the author and reviewers can learn from the mistake.

      Link to comment: I think this was a missed case and was not able to pinpoint a particular PR that caused this.

    • [Contributor] If the regression was CRITICAL (e.g. interrupts a core flow) A discussion in #expensify-open-source has been started about whether any other steps should be taken (e.g. updating the PR review checklist) in order to catch this type of bug sooner.

      Link to discussion: N/A

    • [Contributor] If it was decided to create a regression test for the bug, please propose the regression test steps using the template below to ensure the same bug will not reach production again.

    • [BugZero Assignee] Create a GH issue for creating/updating the regression test once above steps have been agreed upon.

      Link to issue:https://github.com/Expensify/Expensify/issues/545410

    Regression Test Proposal

    Precondition:

    • N/A

    Test:

    1. Open any workspace chat.
    2. Create the first distance expense.
    3. Create a second distance expense with the same details (to form a potential duplicate).
    4. Enable the distance rate feature in settings.
    5. Create a new distance rate.
    6. Delete the old/previous distance rate (so existing expenses may reference a now-invalid rate).
    7. Return to the Workspace Chat.
    8. Open the expense report that contains the two distance expenses.
    9. Open the second expense → tap More → choose Split.
    10. Tap Save (without selecting a valid rate).

    Verify the app shows an error telling the user to select a valid rate and prevents splitting until a valid rate is chosen.

    Do we agree 👍 or 👎

  19. trjExpensify commented on Jan 5, 2026

    @trjExpensify
    Contributor

    approved $125 for @allroundexperts.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

Awaiting PaymentBugDailyExternal

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions