Skip to content

[Due for payment 2025-10-31] [$250] Expense - In confirm page, tax amount not updated accordingly to new waypoints selected #72380

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.2.29-1
Reproducible in staging?: Yes
Reproducible in production?: Yes
If this was caught during regression testing, add the test name, ID and link from BrowserStack: https://test-management.browserstack.com/projects/2219752/test-runs/TR-1238/folder/13176744/41237142/945417656
Email or phone of affected tester (no customers): Slottwo1 ployee@gmail.com
Issue reported by: Applause Internal Team
Device used: Redminote 10s android 13 phone
App Component: Money Requests

Action Performed:

  1. Launch app
  2. Go to workspace settings
  3. Enable distance rate
  4. Enable tax and set tax rate 1 as default in foreign and default currency
  5. Go to distance rate - settings - track tax
  6. Tap on default rate - tax rate - select tax rate 5%
  7. Set tax reclaimable amount as 0.01
  8. Go to workspace chat
  9. Tap distance expense
  10. Select waypoints and tap next
  11. Note tax amount
  12. Navigate back
  13. Change waypoints
  14. Tap next
  15. Note same tax amount is displayed
  16. Tap create expense
  17. Open the expense
  18. Scroll down to tax amount
  19. Wait few seconds
  20. Note tax amount is changed accordingly to new waypoints selected

Expected Result:

After changing waypoints, tax amount must be changed accordingly.

Actual Result:

In confirm page, tax amount not updated accordingly to new waypoints selected but after creating expense tax amount updated after few seconds.

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/~021977797907417201955
  • Upwork Job ID: 1977797907417201955
  • Last Price Increase: 2025-10-20
Issue OwnerCurrent Issue Owner: @garrettmknight

Activity

  1. added
    BugSomething is broken. Auto assigns a BugZero manager.
    on Oct 11, 2025
  2. melvin-bot commented on Oct 11, 2025

    @melvin-bot

    Triggered auto assignment to @garrettmknight (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. ShridharGoel commented on Oct 11, 2025

    @ShridharGoel
    Contributor

    Proposal

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

    When a workspace distance expense is edited to use a different set of waypoints, the confirmation page continues to display the tax amount that was calculated for the previous route. The amount only refreshes several seconds after the expense is created, so reviewers cannot validate the tax value before submitting the expense.

    What is the root cause of that problem?

    While we recompute the distance amount before leaving the waypoint step, we do not recompute the related tax amount. The calculation lives in setDistanceRequestData, which only calls setMoneyRequestAmount and leaves the cached taxAmount unchanged

    const setDistanceRequestData = useCallback(
    (participants: Participant[]) => {
    // Get policy report based on transaction participants
    const isPolicyExpenseChat = participants?.some((participant) => participant.isPolicyExpenseChat);
    const selectedReportID = participants?.length === 1 ? (participants.at(0)?.reportID ?? reportID) : reportID;
    const policyReport = participants.at(0) ? allReports?.[`${ONYXKEYS.COLLECTION.REPORT}${selectedReportID}`] : report;
    const IOUpolicyID = getIOURequestPolicyID(transaction, policyReport);
    // This will be fixed as part of https://github.com/Expensify/Expensify/issues/507850
    // eslint-disable-next-line deprecation/deprecation
    const IOUpolicy = getPolicy(report?.policyID ?? IOUpolicyID);
    const policyCurrency = policy?.outputCurrency ?? getPersonalPolicy()?.outputCurrency ?? CONST.CURRENCY.USD;
    const mileageRates = DistanceRequestUtils.getMileageRates(IOUpolicy);
    const defaultMileageRate = DistanceRequestUtils.getDefaultMileageRate(IOUpolicy);
    const mileageRate: MileageRate | undefined = isCustomUnitRateIDForP2P(transaction)
    ? DistanceRequestUtils.getRateForP2P(policyCurrency, transaction)
    : // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
    (customUnitRateID && mileageRates?.[customUnitRateID]) || defaultMileageRate;
    const {unit, rate} = mileageRate ?? {};
    const distance = getDistanceInMeters(transaction, unit);
    const currency = mileageRate?.currency ?? policyCurrency;
    const amount = DistanceRequestUtils.getDistanceRequestAmount(distance, unit ?? CONST.CUSTOM_UNITS.DISTANCE_UNIT_MILES, rate ?? 0);
    setMoneyRequestAmount(transactionID, amount, currency);
    const participantAccountIDs: number[] | undefined = participants?.map((participant) => Number(participant.accountID ?? CONST.DEFAULT_NUMBER_ID));
    if (isSplitRequest && amount && currency && !isPolicyExpenseChat) {
    setSplitShares(transaction, amount, currency ?? '', participantAccountIDs ?? []);
    }

    The confirmation UI then reads the stale value from transaction.taxAmount, so the user sees the old tax total until a later Onyx sync overwrites it.

    const taxRates = policy?.taxRates ?? null;
    // In Send Money and Split Bill with Scan flow, we don't allow the Merchant or Date to be edited. For distance requests, don't show the merchant as there's already another "Distance" menu item
    const shouldShowDate = (shouldShowSmartScanFields || isDistanceRequest) && !isTypeSend;
    // Determines whether the tax fields can be modified.
    // The tax fields can only be modified if the component is not in read-only mode
    // and it is not a distance request.
    const canModifyTaxFields = !isReadOnly && !isDistanceRequest && !isPerDiemRequest;
    // A flag for showing the billable field
    const shouldShowBillable = policy?.disabledFields?.defaultBillable === false;
    const shouldShowReimbursable = isPolicyExpenseChat && policy?.disabledFields?.reimbursable !== true && !isCardTransaction(transaction) && !isTypeInvoice;
    // Calculate the formatted tax amount based on the transaction's tax amount and the IOU currency code
    const taxAmount = getTaxAmount(transaction, false);
    const formattedTaxAmount = convertToDisplayString(taxAmount, iouCurrencyCode);
    // Get the tax rate title based on the policy and transaction
    const taxRateTitle = getTaxName(policy, transaction);
    // Determine if the merchant error should be displayed
    const shouldDisplayMerchantError = isMerchantRequired && (shouldDisplayFieldError || formError === 'iou.error.invalidMerchant') && isMerchantEmpty;
    const shouldDisplayDistanceRateError = formError === 'iou.error.invalidRate';
    const showReceiptEmptyState = shouldShowReceiptEmptyState(iouType, action, policy, isPerDiemRequest, isManualDistanceRequest);
    // The per diem custom unit
    const perDiemCustomUnit = getPerDiemCustomUnit(policy);

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

    1. Add a shared helper in DistanceRequestUtils that produces the updated tax amount (in backend units) for a distance transaction given the policy, the route distance, and the selected rate. The helper will guard on tax tracking being enabled and reuse the existing tax utilities so we keep rounding behaviour consistent.
    2. Call that helper whenever we recalculate the distance amount:
      • In setDistanceRequestData we will set both the amount and tax amount before we navigate to confirmation, ensuring optimistic data is complete for new expenses.
      • In updateMoneyRequestDistance we will include the recomputed taxAmount in the optimistic transactionChanges, so editing an existing expense updates the preview immediately.
      • MoneyRequestConfirmationList can reuse the helper to avoid duplicating the formula; this keeps the confirmation step consistent with the waypoint step.
    // src/libs/DistanceRequestUtils.ts
    export function calculateDistanceTaxAmount({
        policy,
        transaction,
        distanceInMeters,
        currency,
        customUnitRateID,
        isPolicyExpenseChat,
    }: {
        policy: OnyxEntry<Policy> | undefined;
        transaction: OnyxEntry<Transaction> | undefined;
        distanceInMeters: number;
        currency: string;
        customUnitRateID?: string;
        isPolicyExpenseChat: boolean;
    }): number | undefined {
        if (!policy || !transaction || distanceInMeters <= 0) {
            return undefined;
        }
        if (!isTaxTrackingEnabled(isPolicyExpenseChat, policy, true)) {
            return undefined;
        }
    
        const rateID = customUnitRateID ?? getRateID(transaction);
        const taxableAmount = getTaxableAmount(policy, rateID, distanceInMeters);
        if (!taxableAmount) {
            return undefined;
        }
    
        const taxCode = transaction.taxCode ?? getDefaultTaxCode(policy, transaction);
        const taxValue = taxCode ? getTaxValue(policy, transaction, taxCode) : undefined;
        if (!taxValue) {
            return undefined;
        }
    
        const taxAmount = calculateTaxAmount(taxValue, taxableAmount, currency);
        return convertToBackendAmount(Number(taxAmount));
    }
    // src/pages/iou/request/step/IOURequestStepDistance.tsx
    const amount = DistanceRequestUtils.getDistanceRequestAmount(distance, unit ?? CONST.CUSTOM_UNITS.DISTANCE_UNIT_MILES, rate ?? 0);
    setMoneyRequestAmount(transactionID, amount, currency);
    
    const updatedTaxAmount = DistanceRequestUtils.calculateDistanceTaxAmount({
        policy: IOUpolicy,
        transaction,
        distanceInMeters: distance,
        currency,
        customUnitRateID: mileageRate?.customUnitRateID ?? customUnitRateID,
        isPolicyExpenseChat,
    });
    if (typeof updatedTaxAmount === 'number') {
        setMoneyRequestTaxAmount(transactionID, updatedTaxAmount);
    }
    // src/libs/actions/IOU.ts
    const distanceForTax = distance ?? transaction?.routes?.route0?.distance ?? 0;
    const optimisticTaxAmount = DistanceRequestUtils.calculateDistanceTaxAmount({
        policy,
        transaction,
        distanceInMeters: distanceForTax,
        currency: transaction?.currency ?? policy?.outputCurrency ?? CONST.CURRENCY.USD,
        customUnitRateID: transactionChanges.customUnitRateID ?? getRateID(transaction),
        isPolicyExpenseChat: isPolicyExpenseChatReportUtil(transactionThreadReport) || isPolicyExpenseChatReportUtil(parentReport),
    });
    if (typeof optimisticTaxAmount === 'number') {
        transactionChanges.taxAmount = optimisticTaxAmount;
    }
  4. Burhan-Rashid commented on Oct 11, 2025

    @Burhan-Rashid
    Contributor

    Proposal

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

    Expense - In confirm page, tax amount not updated accordingly to new waypoints selected

    What is the root cause of that problem?

    The root cause of the issue is that when we go back from the confirmation step to select waypoints, the MoneyRequestConfirmationList component is unmounted and after that when we select new waypoints and again go the confirmation page, the component MoneyRequestConfirmationList is mounted again with updated transaction prop and our usePrevious hook only keeps track of previous value during rerenders and not at the time of component mounting. So our previous and current values of the transaction match in this condition and the early return happens without calculating the tax:

    useEffect(() => {
    if (
    !shouldShowTax ||
    !transaction ||
    (transaction.taxAmount !== undefined &&
    previousTransactionAmount === transaction.amount &&
    previousTransactionCurrency === transaction.currency &&
    previousCustomUnitRateID === customUnitRateID &&
    previousTaxCode === transaction.taxCode)
    ) {
    return;
    }

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

    Just like how we are doing it at other places, we need to keep a ref variable for checking the first render and calculate the tax amount whenever first render is true. we can make the following changes here:

        const firstRenderRef = useRef(true);

    and add the condition of firstRenderRef in this useEffect:

    useEffect(() => {
    if (
    !shouldShowTax ||
    !transaction ||
    (transaction.taxAmount !== undefined &&
    previousTransactionAmount === transaction.amount &&
    previousTransactionCurrency === transaction.currency &&
    previousCustomUnitRateID === customUnitRateID &&
    previousTaxCode === transaction.taxCode)
    ) {
    return;
    }

    useEffect(() => {
            if (
                !shouldShowTax ||
                !transaction ||
                (transaction.taxAmount !== undefined &&
                    previousTransactionAmount === transaction.amount &&
                    previousTransactionCurrency === transaction.currency &&
                    previousCustomUnitRateID === customUnitRateID &&
                    previousTaxCode === transaction.taxCode &&
                    !firstRenderRef.current)
            ) {
                firstRenderRef.current = false;
                return;
            }
            firstRenderRef.current = false;
    ...

    We are already having a check of previousTransactionAmount === transaction.amount , so adding previous and current distance check here is not required here. Optionally we can add that too during PR review after discussion.

    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.

  5. added
    ExternalAdded to denote the issue can be worked on by a contributor
    on Oct 13, 2025
  6. changed the title [-]Expense - In confirm page, tax amount not updated accordingly to new waypoints selected[/-] [+][$250] Expense - In confirm page, tax amount not updated accordingly to new waypoints selected[/+] on Oct 13, 2025
  7. melvin-bot commented on Oct 13, 2025

    @melvin-bot
  8. added
    Help WantedApply this label when an issue is open to proposals by contributors
    on Oct 13, 2025
  9. melvin-bot commented on Oct 13, 2025

    @melvin-bot

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

  10. 37 remaining items

  11. melvin-bot commented on Oct 31, 2025

    @melvin-bot

    Payment Summary

    Upwork Job

    BugZero Checklist (@garrettmknight)

    • (if NewFeature) I have created a PR for any necessary HelpDot updates, or I confirmed no updates are necessary.
    • I have verified the correct assignees and roles are listed above and updated the necessary manual offers
    • I have verified that there are no duplicate or incorrect contracts on Upwork for this job (https://www.upwork.com/ab/applicants/1977797907417201955/hired)
    • I have verified the PR was not reverted
    • I have applied any discounts due to bugs/regressions introduced by this PR
    • I have paid out the Upwork contracts or cancelled the ones that are incorrect
    • I have verified the payment summary above is correct
  12. Burhan-Rashid commented on Nov 3, 2025

    @Burhan-Rashid
    Contributor

    @garrettmknight Just curious to know if there will be any compensation for me, since my proposal was earlier reviewed and selected here, but later It was decided that internal engineer ( @roryabraham ) will handle all the changes.

  13. garrettmknight commented on Nov 4, 2025

    @garrettmknight
    Contributor

    Checking with @roryabraham on whether the solution materially differed.

  14. roryabraham commented on Nov 4, 2025

    @roryabraham
    Contributor

    Yeah, I think my solution was materially different from any of the other proposals here

  15. garrettmknight commented on Nov 4, 2025

    @garrettmknight
    Contributor

    Thanks, no payments in that case outside of the C+ review.

  16. Burhan-Rashid commented on Nov 4, 2025

    @Burhan-Rashid
    Contributor

    Thanks for the info. 👍

  17. garrettmknight commented on Nov 4, 2025

    @garrettmknight
    Contributor

    Payment summary is correct. @jjcoffee go ahead and request!

  18. trjExpensify commented on Nov 6, 2025

    @trjExpensify
    Contributor

    approved $250 for @jjcoffee.

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

Metadata

Metadata

Labels

Awaiting PaymentAuto-added when associated PR is deployed to productionBugSomething is broken. Auto assigns a BugZero manager.ExternalAdded to denote the issue can be worked on by a contributorReviewingHas a PR in reviewWeeklyKSv2

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions