App icon indicating copy to clipboard operation
App copied to clipboard

[Due for payment 2026-11-19] [$250] Workspace chat - Export to NetSuite button still shows while an export is in progress

Open izarutskaya opened this issue 3 months ago • 99 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.4.50-3 Reproducible in staging?: Yes Reproducible in production?: Yes If this was caught during regression testing, add the test name, ID and link from BrowserStack: Email or phone of affected tester (no customers): Logs: https://stackoverflow.com/c/expensify/questions/4856 Expensify/Expensify Issue URL: Issue reported by: @roryabraham Slack conversation (hyperlinked to channel name): expensify_bugs

Action Performed:

  1. Create an account
  2. Create a workspace
  3. Set up a NetSuite connection
  4. After initial sync, go to Workspace -> Connections -> NetSuite -> Export -> Export out-of-pocket expenses as... and set:
  • Export as... to Journal entries
  • Reimbursable journal posting account to 2000 Accounts Payable (or whatever account you want I guess)
  1. Manually create an expense report. Do everything needed to finish the report in Expensify per your workspace settings (submit, approve, pay).
  2. (automatic export to NetSuite will begin, and you'll see started exporting this report to NetSuite... on the report)

Expected Result:

The big green Export to NetSuite button will show a loading spinner and become disabled, so you can't click it again to kick off another export while there's already one in progress.

Actual Result:

The big green Export to NetSuite button is still clickable, and clicking on it starts a duplicate export, which will correctly fail (as a duplicate journal entry should not be created).

Workaround:

Unknown

Platforms:

Select the officially supported platforms where the issue was reproduced:

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

Screenshots/Videos

Image

https://github.com/user-attachments/assets/2dba523e-43ea-4dc2-b8a0-baa244705929

View all open jobs on GitHub

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

izarutskaya avatar Aug 07 '26 09:08 izarutskaya

Proposal

What is the root cause of that problem?

The green Export to [integration] button never reflects an in-progress export. It's rendered by ExportWithDropdownMenu.tsx, which mounts ButtonWithDropdownMenu without passing isLoading or isDisabled. So even while an export is running, the button stays fully clickable and a second click fires a duplicate export.

The signal to detect an in-flight export already exists — it just isn't consumed. When an export starts, an EXPORTINTEGRATION report action (the "started exporting this report to NetSuite…" message) is written with originalMessage.inProgress === true and pendingAction: ADD (see buildOptimisticExportIntegrationAction). Neither canBeExported nor isExported encodes "in progress", so nothing currently disables the button.

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

In ExportWithDropdownMenu.tsx:

  1. Derive an isExportInProgress boolean from the reportActions already in scope — true when there is an EXPORTINTEGRATION action whose originalMessage.inProgress === true (equivalently pendingAction === ADD). This covers both the manual button press and the automatic post-payment export shown in the report.
  2. Pass both isLoading={isExportInProgress} and isDisabled={isExportInProgress} to ButtonWithDropdownMenu. isLoading shows the spinner and blocks the main button; because this is a split button, isDisabled is also needed so the dropdown-arrow half locks too.

SettlementButton is an existing caller that passes both props the same way — a good reference pattern.

Supporting evidence
  • Button has the props already — ButtonWithDropdownMenu accepts isLoading / isDisabled and forwards them to the underlying Button, which blocks onPress when isLoading || isDisabled and renders an ActivityIndicator spinner while loading.
  • Where the export fires — handleExport → exportToIntegration(reportID, connectionName) in Report/index.ts. Note it writes optimistic + failure data only (no successData), so the optimistic action's pendingAction: ADD persists until the backend echoes the canonical action — meaning either inProgress or pendingAction is a reliable "still running" signal to key off.
  • Alternative considered — keying off report.pendingFields.export (used by the manual markAsManuallyExported path). Rejected because the automatic exportToIntegration path does not set pendingFields.export, so it wouldn't cover the post-payment auto-export in the report. The EXPORTINTEGRATION action's inProgress flag covers both paths.

What alternative solutions did you explore? (Optional)

Adding pendingFields.export to the automatic exportToIntegration path (to mirror the manual path) is an option, but reading the existing inProgress report action requires no backend/action changes and already covers the auto-export case.


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

MelvinBot avatar Aug 07 '26 09:08 MelvinBot

VERDICT: POST ROOT_CAUSE_ONELINER: ExportWithDropdownMenu never reads the inProgress: true flag set on in-flight EXPORTED_TO_INTEGRATION report actions, so it never passes isLoading to ButtonWithDropdownMenu or disables the button while an export is running. PROPOSAL_TYPE: FIRST AUTOPOST_SAFE: YES

j3ffffff avatar Aug 07 '26 09:08 j3ffffff

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

melvin-bot[bot] avatar Aug 07 '26 09:08 melvin-bot[bot]

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

melvin-bot[bot] avatar Aug 07 '26 09:08 melvin-bot[bot]

RETRACTED / WITHDRAWN. Please do not consider this an active proposal or contributor claim. I am withdrawing it and will not pursue this bounty.

evanbrown3000 avatar Aug 08 '26 00:08 evanbrown3000

📣 @evanbrown3000! 📣 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 Aug 08 '26 00:08 melvin-bot[bot]

I'll take a look at this one today.

suneox avatar Aug 10 '26 04:08 suneox

I cannot be reproduced on the latest main or staging (v9.4.51-1). However, I ran into another issue: after clicking 'Export to NetSuite', the button remains hidden even when 'failed to export this report to NetSuite' message appears after started exporting this report to NetSuite... . Reloading the page brings the 'Export to NetSuite' button back.

Export to NetSuite hidden after reload page

https://github.com/user-attachments/assets/143114b3-2087-4807-bc20-9ac879eea384

https://github.com/user-attachments/assets/bfcced6a-c58b-47be-8943-b63977eeb8df

@MelvinBot review this latest behavior

suneox avatar Aug 10 '26 11:08 suneox

Thanks for re-testing, suneox. I looked into the new behavior and can pin it to a broken optimistic rollback.

What's happening

Export to NetSuite is hidden while an export is in progress and stays hidden after the export fails because the optimistic isExportedToIntegration: true flag is never rolled back on failure. A reload pulls fresh server data (where the flag is falsy), which is why the button comes back.

Root cause: In exportToIntegration the optimistic update sets isExportedToIntegration: true, and the failure update tries to restore it with isExportedToIntegration: previousExportedValue. For a report that was never exported, previousExportedValue is undefined — and Onyx MERGE skips undefined source values, so the rollback is a no-op and the flag stays true.

With the flag stuck at true, canExport returns false (if (isExported) return false), so getReportPreviewAction falls through to VIEW and the export button is no longer rendered until a reload.

Recommended fix

Coalesce the failure value to a boolean so the merge actually resets it:

- isExportedToIntegration: previousExportedValue,
+ isExportedToIntegration: previousExportedValue ?? false,

This keeps true for a genuine re-export (previous value was true) and resets to false for a first-time export, so the button reappears immediately on failure without a reload.

Supporting evidence
  • Onyx merge drops undefined: in react-native-onyx, mergeObject skips any source property that is undefined (if (sourceProperty === undefined ...) continue;), so merging {isExportedToIntegration: undefined} leaves the optimistic true in place. Only null/false would clear it.
  • The failure path does not set a report-level export error (report.hasExportError / errorFields.export are untouched — only the report action gets errors), so hasExportError stays false and can't re-surface the button either. The stuck isExportedToIntegration: true is the sole reason it stays hidden.
  • Same latent bug exists in markAsManuallyExported's failure data (identical previousExportedValue restore) — worth applying the same ?? false fix there for consistency.
  • I did not runtime-verify because reproducing needs a NetSuite connection whose export fails, but your videos already demonstrate it and the code path + Onyx merge semantics are conclusive.

This makes the original report moot in a good way: the optimistic isExportedToIntegration: true already hides the button during an in-progress export (so the "still clickable, duplicate export" symptom no longer reproduces) — the only remaining gap is this failed-export rollback.


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

MelvinBot avatar Aug 10 '26 11:08 MelvinBot

This issue is reproducible on the latest staging, so I'll take another look at it

https://github.com/user-attachments/assets/0d32f000-79c9-45ca-bb44-a1c8c6a02af3

suneox avatar Aug 11 '26 04:08 suneox

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

melvin-bot[bot] avatar Aug 14 '26 21:08 melvin-bot[bot]

I'll prioritize this issue later today

suneox avatar Aug 15 '26 05:08 suneox

@MelvinBot proposals are not accepted (verified against runtime data — failureData never runs, Report_Export api always return 200), so besides the expected in-flight behavior we also need to preserve the logic from #72292 and #87654

🆘 C+ Help Wanted

[!NOTE] Contributors providing a solution need to make sure you are able to reproduce this issue.

suneox avatar Aug 15 '26 15:08 suneox

Proposal

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

Workspace chat - Export to NetSuite button still shows while an export is in progress

What is the root cause of that problem?

We render the export button here with no loading/disabled state and we never check whether an export is already in progress https://github.com/Expensify/App/blob/6695479de5d7390b017f221c8dc61790dfd89cda/src/components/MoneyReportHeaderPrimaryAction/ExportPrimaryAction.tsx#L34-L47 so while a pending EXPORTED_TO_INTEGRATION action exists (the started exporting this report to NetSuite... message) the button stays clickable and pressing it fires a second exportToIntegration duplicate.

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

We should detect the in-progress export from the pending EXPORTED_TO_INTEGRATION report action and set the button to isLoading (which also disables it) https://github.com/Expensify/App/blob/6695479de5d7390b017f221c8dc61790dfd89cda/src/components/MoneyReportHeaderPrimaryAction/ExportPrimaryAction.tsx#L32

const isExportInProgress = reportActions.some((action) => isExportIntegrationAction(action) && action.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD);

and pass it to the button

<Button variant={CONST.BUTTON_VARIANT.SUCCESS} isLoading={isExportInProgress}

We can apply the same isLoading guard to the dropdown export button in ExportWithDropdownMenu if it shows the same issue.

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

N / A

What alternative solutions did you explore? (Optional)

yusufdeveloper2903 avatar Aug 15 '26 15:08 yusufdeveloper2903

🚨 Edited by proposal-police: This proposal was edited at 2026-08-15 16:22:52 UTC.

Proposal

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

After the report is paid the backend starts the NetSuite export and the report shows "started exporting this report to NetSuite…". For that whole window the green Export to NetSuite button in the report preview — and the header's Export button — stay pressable, so another press queues a duplicate export that NetSuite then rejects.

What is the root cause of that problem?

Neither control derives anything from the running export. ExportWithDropdownMenu mounts ButtonWithDropdownMenu with no isLoading/isDisabled, and ExportPrimaryAction computes only isExported before rendering the header Button.

The signal to read is already on the report. An export start is an EXPORTED_TO_INTEGRATION action carrying pendingAction: ADD, and that flag is the only gate that prints "started exporting this report to…" (ReportActionsUtils#L2760-L2775) — the copy is on screen in the repro, so the flag is there on the backend-driven path too.

What makes this more than a one-liner is how an export ends. Report_Export answers 200, so nothing on the client clears that start action; the outcome arrives later as a separate unreconciled INTEGRATIONSMESSAGE plus report.hasExportError (ReportUtils#L13193-L13202), while the pending start action stays where it was. A guard that only looks for a pending start therefore locks the button forever after a failure and kills the retry path from #72292 / #87654. Comparing timestamps is what fixes both directions: the button is busy while the newest export start is newer than the newest export result, and a retry started after that failure locks it again.

I ran this at a1f71ac: rendering the real ExportWithDropdownMenu with a pending export action and pressing it calls exportToIntegration once today — that is the duplicate — while with the helper below the press calls it zero times, a press after the failure message still fires the retry, and ExportActionButtonTest + ReportPreviewActionButtonTest stay green at 9/9.

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

// src/libs/ReportUtils.ts — beside isExported / hasExportError
+function isExportInProgress(reportActions: OnyxEntry<ReportActions> | ReportAction[]): boolean {
+    const list = Array.isArray(reportActions) ? reportActions : Object.values(reportActions ?? {});
+    const newestCreated = (actions: ReportAction[]) => actions.reduce((newest, action) => (action.created > newest ? action.created : newest), '');
+    const startedAt = newestCreated(list.filter((action) => isExportIntegrationAction(action) && action.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD));
+    // A rejected export never touches the start action — it lands as an unreconciled INTEGRATIONSMESSAGE — so the newest
+    // result is what releases the button, and an export started after that failure locks it again.
+    const resultAt = newestCreated(list.filter((action) => isIntegrationMessageAction(action) && !getOriginalMessage(action)?.result?.reconciled));
+    return !!startedAt && resultAt < startedAt;
+}
// src/components/ReportActionItem/ExportWithDropdownMenu.tsx
+    const isExportInProgress = isExportInProgressUtils(reportActions);
@@
             size={CONST.BUTTON_SIZE.MEDIUM}
+            isLoading={isExportInProgress}
+            isDisabled={isExportInProgress}
// src/components/MoneyReportHeaderPrimaryAction/ExportPrimaryAction.tsx
     const isExported = isExportedUtils(reportActions, moneyRequestReport);
+    const isExportInProgress = isExportInProgressUtils(reportActions);
@@
         <Button
             variant={CONST.BUTTON_VARIANT.SUCCESS}
+            isLoading={isExportInProgress}
+            isDisabled={isExportInProgress}

One helper and two call sites, and both props are needed at each: the primary half honours isLoading, while the split button's caret half is gated only on isDisabled, so without it the menu could still start a second export. Nothing in isExported, hasExportError, canExport or the Pay-vs-Export resolvers moves, which is what keeps #72292 / #87654 intact.

Precedent: the helper sits next to hasExportError and mirrors its OnyxEntry<ReportActions> | ReportAction[] signature, so both call sites pass what they already hold; SettlementButton is the existing split button that drives ButtonWithDropdownMenu with this same isLoading + isDisabled pair.

Layer: derived state and render, no action or API change. The manual path benefits for free — its optimistic start action has the same shape, so rapid double clicks are blocked until the backend's result lands.

What alternative solutions did you explore? (Optional)

Bailing out on hasExportError instead of comparing timestamps. It reads well until a report has failed once: the unreconciled INTEGRATIONSMESSAGE never goes away, so hasExportError stays true and the next export never locks the button at all — I checked that case with an old failure followed by a newer start.

Adding an "and not already exported" conjunct. In the window this issue is about, isExported returns true — its fallback counts the still-pending start action — so that guard never fires and the duplicate export stays possible, which is the exact behaviour reported here.

Abdulloh0109 avatar Aug 15 '26 15:08 Abdulloh0109

Proposal

What is the root cause of that problem?

The green Export to NetSuite button is ExportWithDropdownMenu, and it mounts ButtonWithDropdownMenu without ever passing isLoading or isDisabled. The component derives canBeExported and isExported (lines 62-64) but nothing that represents "an export is currently running." So while an export is in flight, the button stays fully pressable and a second press calls handleExport → exportToIntegration again → duplicate export.

The in-progress signal already exists — it's literally what the reporter is looking at. The started exporting this report to NetSuite... line renders only because the EXPORTED_TO_INTEGRATION action is still pending: getExportIntegrationActionFragments picks the "pending" text via isPending = pendingAction === ADD. That same action lives in the reportActions this component already receives — it just never reads it.

Why the automatic post-payment case fires a silent duplicate (no "export again" confirmation): isExported returns report.isExportedToIntegration, which the backend only sets to true once the export completes. Mid-export it's still falsy, so onPress skips the confirm modal and goes straight to handleExport.

Note the originalMessage.inProgress flag set in buildOptimisticExportIntegrationAction is a red herring — it's written but read nowhere in the client. pendingAction === ADD is the signal that's actually authoritative and drives the message on screen.

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

Layer: render/hook in ExportWithDropdownMenu.tsx. No backend or action change needed.

  1. Derive isExportInProgress from the reportActions already in scope — true when any action satisfies isExportIntegrationAction(action) && action.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD. Reuse the existing type guard isExportIntegrationAction. A completed prior export carries no pendingAction, so it won't false-trigger; only the in-flight one does. This covers both the manual button press and the automatic post-payment export, because both produce a pending EXPORTED_TO_INTEGRATION action.

  2. Pass both isLoading={isExportInProgress} and isDisabled={isExportInProgress} to ButtonWithDropdownMenu. Both are needed because this is a split button (shouldAlwaysShowDropdownMenu): the main half honors isLoading for the spinner + press-block, but the separate dropdown-caret half only honors isDisabled. Button blocks onPress when isDisabled || isLoading, so the spinner shows and neither half can start a second export.

The props already exist on ButtonWithDropdownMenu, and SettlementButton is an existing caller that passes both the same way — good reference pattern.

What alternative solutions did you explore? (Optional)

  • Key off report.pendingFields.export. Rejected: exportToIntegration writes only optimisticData/failureData touching the report action and isExportedToIntegration — it never sets pendingFields.export, and neither does the backend auto-export. So this wouldn't cover the reported (automatic) repro at all.

  • Key off report.isExportedToIntegration. Rejected: that's a completed-export flag (it's what gates the "export again" confirm modal), not an in-progress one, and it's falsy during the in-flight automatic export — exactly when we need the button locked.

  • Add a dedicated in-progress flag from the backend / start reading originalMessage.inProgress. Rejected as unnecessary: the pending EXPORTED_TO_INTEGRATION action is already the source of truth the message rendering trusts, so we can derive the state entirely client-side with no protocol change.

oqildev avatar Aug 15 '26 15:08 oqildev

🚨 Edited by proposal-police: This proposal was edited at 2026-08-19 12:02:06 UTC.

Proposal (updated)

Updated proposal — this corrects the root cause in my earlier proposal. My original answer keyed the fix off report.pendingFields.export; testing on a dev build showed that field is not the in-flight signal for the export in this issue. Details below.

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

While an export of a report to an accounting integration is already running — the report shows started exporting this report to NetSuite... — the big green Export to [integration] button stays fully enabled instead of showing a loading spinner and being disabled. Pressing it starts a second, duplicate export, which the integration then rejects. This affects both places the button renders: the workspace-chat report preview (ExportWithDropdownMenu) and the report header primary action (ExportPrimaryAction).

What is the root cause of that problem?

1. Neither button derives an "export is in flight" state.

ExportPrimaryAction computes only isExported. ExportWithDropdownMenu computes only canBeExported and isExported. Both mount their button without isLoading or isDisabled. isExported is a completed-export flag, so for the whole in-flight window it is falsy and nothing gates the press — onPress reaches exportToIntegration() on every click.

Both button primitives already support the state that is missing:

  • ButtonComposed/Button.tsx ignores the press when isDisabled || isLoading, hides its children and renders a spinner while isLoading.
  • ButtonWithDropdownMenu passes isLoading to the main half only, and isDisabled to both halves — so the split button needs both props, otherwise the dropdown caret can still start an export while the main half spins.

2. The in-flight signal already on the client is the export action's pendingAction, not a report field.

An in-flight export is represented by an EXPORTED_TO_INTEGRATION action carrying pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD. That is exactly the flag ReportActionsUtils.getExportIntegrationActionFragments gates the pending message on:

const isPending = reportAction?.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD;

and the pending message is the started exporting this report to <label>... line (report.actions.type.exportedToIntegration.pending in en.ts). The reproduction steps in this issue state that line is on screen during the automatic post-payment export, so the client does hold this flag while a backend-started export runs — it is simply never read outside the message formatting code.

3. Why report.pendingFields.export is the wrong field (correction to my earlier proposal).

  • exportToIntegration never writes it.
  • Only markAsManuallyExported and the Search bulk-export action write it, both as client-side optimistic data.
  • markAsManuallyExported clears it in failureData but not in successData, so once a manual "mark as exported" succeeds the field can stay add indefinitely. A button keyed off it would then be permanently disabled for that report if isExportedToIntegration is later reset server-side.
  • I could not find any path where the backend sets it for the automatic export, and the report keys the server returns express export state through first-class fields (isExportedToIntegration, hasExportError) rather than through pendingFields, which is the client's offline-feedback channel.

4. A naive "any pending export action" check would break retrying.

exportToIntegration has no successData, and its failureData only adds errors to the optimistic action — it never clears pendingAction. Measured on a dev build after a rejected export (details in the testing comment):

{"pendingAction":"add","inProgress":true,"errors":{"...":"Oops... something went wrong..."}}

…and no INTEGRATIONSMESSAGE action arrived. So a guard that only asks "is any export action pending" locks the button forever after the first failure and breaks the retry behaviour from #72292 / #87654. The released state has to exclude actions that already carry errors.

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

1. Add one predicate in src/libs/ReportUtils.ts, next to the existing isExported / hasExportError:

function isExportInProgress(reportActions: OnyxEntry<ReportActions> | ReportAction[]): boolean {
    if (!reportActions) {
        return false;
    }

    const reportActionList = Array.isArray(reportActions) ? reportActions : Object.values(reportActions);
    const getNewestCreated = (actions: ReportAction[]) => actions.reduce((newest, action) => (action.created > newest ? action.created : newest), '');

    const startedAt = getNewestCreated(
        reportActionList.filter((action) => isExportIntegrationAction(action) && action.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD && isEmptyObject(action.errors)),
    );
    if (!startedAt) {
        return false;
    }

    // Reconciled integration messages are informational (the export was already recorded in the integration), so they do not end an export.
    const finishedAt = getNewestCreated(reportActionList.filter((action) => isIntegrationMessageAction(action) && !getOriginalMessage(action)?.result?.reconciled));

    return finishedAt < startedAt;
}

An export can finish in two ways and both have to release this state, otherwise the button locks and can never be retried:

  • the request is rejected — failureData only adds errors to the export action and never clears pendingAction, so errored actions are excluded by isEmptyObject(action.errors).
  • the request is accepted and the export then fails inside the integration — that arrives as an unreconciled INTEGRATIONSMESSAGE rather than as an error on the export action, so a result newer than the pending action means the export we found has already finished. Comparing timestamps rather than just checking for a message matters, because a report that failed once and is exporting again has to go busy again. Credit to @emkhalid for this half of the release condition.

Exported alongside isExported / hasExportError.

2. src/components/MoneyReportHeaderPrimaryAction/ExportPrimaryAction.tsx — the report actions are already in scope via usePaginatedReportActions:

+const isExportInProgress = isExportInProgressUtils(reportActions);

 <Button
     variant={CONST.BUTTON_VARIANT.SUCCESS}
+    isLoading={isExportInProgress}
     onPress={() => {
-        if (!connectedIntegration || !moneyRequestReport) {
+        if (!connectedIntegration || !moneyRequestReport || isExportInProgress) {
             return;
         }

3. src/components/ReportActionItem/ExportWithDropdownMenu.tsx — reportActions is already a prop:

+const isExportInProgress = isExportInProgressUtils(reportActions);

 const handleExport = (exportType: ReportExportType) => {
-    if (!reportID) {
+    if (!reportID || isExportInProgress) {
         return;
     }

 <ButtonWithDropdownMenu<ReportExportType>
     variant={CONST.BUTTON_VARIANT.SUCCESS}
+    isLoading={isExportInProgress}
+    isDisabled={isExportInProgress}
     pressOnEnter

isDisabled is required in addition to isLoading here because this is a split button and the caret half is gated on isDisabled alone.

Nothing in isExported, hasExportError, canExport, canBeExported or the primary-action resolvers changes, so the existing retry paths are untouched. No backend or Onyx-write change is needed.

4. Tests — unit tests for isExportInProgress in tests/unit/ReportUtilsTest.ts: pending action with no errors is in progress; pending action with errors is not (retry stays possible); a completed action is not; a newer clean pending action after an older failed one is in progress; an unreconciled INTEGRATIONSMESSAGE newer than the pending action ends it; a pending action newer than the last message goes back to in progress; reconciled messages are ignored; pending actions of other types are ignored; no report actions is not.

What alternative solutions did you explore? (Optional)

  • report.pendingFields.export (my original proposal). Rejected for the reasons in root cause 3: not written by exportToIntegration, not observed from the backend for the automatic export, and not cleared on success by markAsManuallyExported.
  • originalMessage.inProgress. buildOptimisticExportIntegrationAction writes it, but nothing reads it and it lives on the same optimistic action as pendingAction, so it has the same lifetime — and without an errors guard it inherits the same lock-forever-after-failure problem.
  • Rolling back isExportedToIntegration on failure (previousExportedValue ?? false). That is a separate optimistic-rollback question and does not address the reported symptom.
  • Guarding inside exportToIntegration. Reasonable defence in depth, but the button would still look pressable and silently swallow presses, which is not the expected result asked for here.

abbasifaizan70 avatar Aug 15 '26 15:08 abbasifaizan70

Proposal

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

While an export to an accounting integration (e.g. NetSuite) is already running — the report shows started exporting this report to NetSuite... — the green Export to [integration] button stays visible and pressable, and clicking it fires a second, duplicate export. The confirmed expected behavior is that the button should not appear while an export is in progress. This must hold for both in-flight windows: the backend-started automatic export in the repro (the report is open and the user presses nothing), and a user-started export where Report_Export returns 200 and the real status arrives later. The failed-export retry behavior from #87654 / #72292 must be preserved: when an export fails, the Export button must come back.

What is the root cause of that problem?

1. Neither export surface derives an "in-flight" state. The header button is gated by isExportAction, the workspace-chat preview button by canExport. Both compute only canBeExported / isExported, and isExported is a completed-export flag (report.isExportedToIntegration). Nothing represents the in-flight window, so nothing gates the press.

2. The two in-flight windows have two different signals, and each alone covers only one.

  • The still-pending EXPORTED_TO_INTEGRATION action (pendingAction: ADD) is the exact signal that renders the started exporting... line. The backend pushes it for the automatic export too, so it is the only signal that reaches the reported repro. But it lives on the report's actions, which are not loaded in a preview or right after a refresh, so it is blind there.
  • For a user-started export read from a preview or after a refresh, there is no durable client signal at all.

3. isExportedToIntegration is misused as an in-flight signal. exportToIntegration sets it optimistically the instant a manual export fires. That field is server-owned: Report_Export returns 200 as soon as the request is accepted (so failureData never runs) and the real outcome arrives later over Pusher. So the optimistic write fails in every direction — it hides the in-flight window (the button flips straight to View), it never clears on failure (the button is stuck hidden), and it is wiped by any server refresh (the button returns mid-export and a second press queues a duplicate).

So the fix needs a real in-flight state assembled from both the pending action (automatic / open report) and a durable client marker (manual / preview / after refresh), both surfaces hidden while it is set, and it must stop expressing in-flight through isExportedToIntegration.

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

Pure front-end. No new server field.

1. Add isExportInProgress in ReportUtils, combining both signals (next to isExported / hasExportError):

function isExportInProgress(reportActions, report?, reportMetadata?): boolean {
    return isExportInProgressFromActions(reportActions) || isExportInProgressFromMetadata(report, reportMetadata);
}

isExportInProgressFromActions keys on the newest pending EXPORTED_TO_INTEGRATION start being newer than the newest INTEGRATIONS_MESSAGE result (mirrors how isExported already orders by created). This is temporal on purpose: a rejected export returns 200 and its failure lands later as a separate INTEGRATIONS_MESSAGE, so a plain !hasExportError gate would leave the button unlocked in the exact auto-sync repro (a new export starting while an older failure is still set), while a report whose newest event is the failure must stay enabled for retry (#87654 / #72292).

function isExportInProgressFromActions(reportActions): boolean {
    if (!reportActions) {
        return false;
    }
    const list = Array.isArray(reportActions) ? reportActions : Object.values(reportActions);
    let latestStarted = '';
    let latestResult = '';
    for (const action of list) {
        if (isExportIntegrationAction(action)) {
            const isStarted = action.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD;
            if (isStarted && isEmptyObject(action.errors) && action.created > latestStarted) {
                latestStarted = action.created;
            }
        }
        if (isIntegrationMessageAction(action) && action.created > latestResult) {
            latestResult = action.created;
        }
    }
    return !!latestStarted && latestStarted > latestResult;
}

isExportInProgressFromMetadata reads a client marker and resolves it at read time against the report's own outcome fields:

function isExportInProgressFromMetadata(report, reportMetadata): boolean {
    const pendingExport = reportMetadata?.pendingExport;
    if (!pendingExport) {
        return false;
    }
    // success: server marked it exported, and it wasn't already exported when this attempt started
    if ((report?.isExportedToIntegration ?? false) && !pendingExport.wasAlreadyExported) {
        return false;
    }
    // failure: a new errorFields.export entry appeared for this attempt
    const currentErrorCount = Object.keys(report?.errorFields?.export ?? {}).length;
    if (currentErrorCount > pendingExport.previousExportErrorCount) {
        return false;
    }
    return true;
}

2. Store the marker on report metadata, not the report. It is client-only optimistic state, and whitelistedReportKeys requires report keys to be returned by the server; client-only report state belongs on the metadata. It sits right next to the existing in-progress marker pendingExpenseAction:

pendingExport?: {
    previousExportErrorCount: number;
    wasAlreadyExported: boolean;
};

3. exportToIntegration: drop the optimistic isExportedToIntegration write and record the marker instead. Because Report_Export returns 200 and the outcome arrives over Pusher, the marker is resolved by comparison at read time (step 1), not cleared on a callback, so a stale marker can never strand the button.

// optimisticData: reportMetadata_<reportID>
pendingExport: {
    previousExportErrorCount: Object.keys(currentReport?.errorFields?.export ?? {}).length,
    wasAlreadyExported: currentReport?.isExportedToIntegration ?? false,
}
// failureData clears it: { pendingExport: null }

4. Hide both surfaces while in flight. In canExport and isExportAction, return false when isExportInProgress(...) is true, so the export action is not shown at all (the button does not appear, matching the confirmed behavior). Both callers already have reportActions and reportMetadata available; canExport gains the two params, threaded through getReportPreviewAction (the preview already reads reportMetadata via useReportPreviewActionDecision).

if (isExported) {
    return false;
}
if (isExportInProgress(reportActions, report, reportMetadata)) {
    return false;
}

The moment a rejection arrives (INTEGRATIONS_MESSAGE newer than the start, or a new errorFields.export entry), isExportInProgress flips to false and the Export button reappears for retry, so #87654 / #72292 stay intact.

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

Unit tests for isExportInProgress on both signals:

  • Action signal — reported repro: a pending started export that is newer than an older failure result → true (auto-sync with a prior failure, the reported case).
  • Action signal — retry guard: a started export with a newer failure result → false (button enabled for retry, #87654 / #72292).
  • Action signal — completed: a started export whose pendingAction was cleared → false.
  • Action signal — rejected start: a started action that itself carries errors → false.
  • Metadata marker — preview / cold load: marker set with empty report actions → true (the action signal is blind, the marker locks the button).
  • Metadata marker — success: marker set and the report now isExportedToIntegration (not already exported at start) → false.
  • Metadata marker — failure: marker set and a new errorFields.export entry appeared → false (retry enabled).
  • Empty / missing report actions and no marker → false.

Plus a render test per surface: while in progress the export button is not shown; on the reported repro pressing where it used to be does not call exportToIntegration.

What alternative solutions did you explore? (Optional)

  • Store the marker on the report (report.pendingExport). Rejected — it is client-only state; whitelistedReportKeys reserves report keys for server-returned data, so the marker belongs on the report metadata.
  • Derive it from the report actions only. Rejected — the report preview does not have the report's actions in Onyx, so the check reads empty and the button stays pressable exactly where the issue reports it; it only holds once the report has been opened. The metadata marker covers that window.
  • Keep writing isExportedToIntegration optimistically and add successData. Rejected — the 200 means the request was accepted, not finished, so clearing there brings the button back mid-export and the duplicate press is still possible.
  • Gate on !hasExportError, or key off originalMessage.inProgress / report.pendingFields.export. Rejected — !hasExportError fails the auto-sync repro (a new export while an older failure is still set), inProgress is optimistic-only and the backend does not clear it on completion, and pendingFields.export is written only by markAsManuallyExported, not by exportToIntegration or the backend auto-export.

Fix Video

Before — the green Export button is still shown and clickable while the export is in progress:

https://github.com/user-attachments/assets/c2dd920b-fceb-4a2e-87a8-dcbec78cb8b1

After — with this fix the button is hidden on the exact repro:

https://github.com/user-attachments/assets/3ef99ab3-a436-4758-823f-a94cb49ee84c

David-2002065 avatar Aug 15 '26 15:08 David-2002065

🚫 Duplicated proposal withdrawn by 🤖 ProposalPolice.

ahmdshrif avatar Aug 15 '26 15:08 ahmdshrif

🚨 Edited by proposal-police: This proposal was edited at 2026-08-15 15:27:15 UTC.

Proposal

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

After a report is paid, the automatic export to NetSuite runs on the backend and the report shows "started exporting this report to NetSuite…". During that window the green Export to NetSuite button is still clickable, and pressing it fires a second export — a duplicate.

What is the root cause of that problem?

Every listed proposal treats this as a button rendering bug. The deeper root cause is that the export action itself is not idempotent: exportToIntegration unconditionally builds optimistic data and calls API.write(WRITE_COMMANDS.REPORT_EXPORT, …) with no check for an export that is already in flight.

https://github.com/Expensify/App/blob/a1f71ac453d1df7962fc9c1fee0723dc108f5f9b/src/libs/actions/Report/index.ts#L6374-L6424

Both entry points funnel straight into it with no guard:

https://github.com/Expensify/App/blob/a1f71ac453d1df7962fc9c1fee0723dc108f5f9b/src/components/ReportActionItem/ExportWithDropdownMenu.tsx#L107-L116

https://github.com/Expensify/App/blob/a1f71ac453d1df7962fc9c1fee0723dc108f5f9b/src/components/MoneyReportHeaderPrimaryAction/ExportPrimaryAction.tsx#L37-L46

The in-flight signal already exists in Onyx: when an export starts, an EXPORTINTEGRATION report action is written with pendingAction: ADD — the same flag that renders the "started exporting…" line (isExportIntegrationAction):

https://github.com/Expensify/App/blob/a1f71ac453d1df7962fc9c1fee0723dc108f5f9b/src/libs/ReportActionsUtils.ts#L645-L648

https://github.com/Expensify/App/blob/a1f71ac453d1df7962fc9c1fee0723dc108f5f9b/src/libs/ReportUtils.ts#L9209

exportToIntegration simply never consults it. Because the fix targets the action rather than one button's props, it closes the duplicate for every caller (both buttons above, plus any future entry point) in one place.

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

Layer: action in Report/index.ts. No component or backend change.

Make exportToIntegration idempotent by early-returning when a pending EXPORTINTEGRATION action already exists for the report. The action file already keeps report actions in module scope, so no new Onyx read is needed:

https://github.com/Expensify/App/blob/a1f71ac453d1df7962fc9c1fee0723dc108f5f9b/src/libs/actions/Report/index.ts#L471

function exportToIntegration(reportID: string, connectionName: ConnectionName) {
    const reportActions = allReportActions?.[`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportID}`];
    const isExportInProgress = Object.values(reportActions ?? {}).some(
        (action) => isExportIntegrationAction(action) && action.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD,
    );
    if (isExportInProgress) {
        return;
    }
    // …existing optimistic/failure data + API.write…
}

isExportIntegrationAction is already exported from ReportActionsUtils, so this is a one-import, one-guard change. It reads the same authoritative signal the report renders, so it fires for both the manual press and the backend post-payment auto-export, and clears automatically when the backend resolves/fails the pending action. This directly eliminates the Actual Result ("clicking on it starts a duplicate export") at its source, independent of any button's visual state — which also makes it robust against split-button races the render-only approach can miss.

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

Unit test on exportToIntegration: seed a report-actions collection containing an EXPORTINTEGRATION action with pendingAction: ADD, call exportToIntegration, and assert API.write was not called; then with no pending action, assert it is called exactly once.

What alternative solutions did you explore? (Optional)

Driving the button's isLoading/isDisabled from the same pending EXPORTINTEGRATION action in ExportWithDropdownMenu/ExportPrimaryAction. Rejected as the primary fix: it patches each rendering site individually (and a split button needs both props to lock the dropdown half), so it must be repeated per entry point and doesn't make the underlying operation safe. It's a good visual complement — a spinner while the export runs — and can be layered on top of the action guard, but the guard is what actually prevents the duplicate.

lorretheboy avatar Aug 15 '26 15:08 lorretheboy