App icon indicating copy to clipboard operation
App copied to clipboard

[$250] Expense- Unable to generate PDF to download a report

Open applause-bot[bot] opened this issue 3 weeks ago • 58 comments

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


Version Number: v9.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/57600464/test-cases/41237193 Email or phone of affected tester (no customers): [email protected] Issue reported by: Applause Internal Team Bug source: Regression TC Execution Device used: Windows 10 / Chrome, Samsung s10/ Chrome, IPhone 15 pro/ IOS 27.2 App Component: Money Requests

Action Performed:

  1. Navigate to staging.new.expensify.com
  2. Navigate to the expense conversation in WS
  3. Click "More"
  4. Click on Download report

Expected Result:

It should display download option and download correctly

Actual Result:

"There was an error when trying to generate your PDF" error shown

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/d2ee2a26-8685-49cd-a6f1-15ced5587684

View all open jobs on GitHub

Applause Internal Information Exported by: Svetlana Lazutkina Bug ID: 7307199

Upwork Automation - Do Not Edit

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

While Applause doesn't embed attachments for this bug, here are the links for quick view: https://platform.applause.com/services/links/v1/external/7e7f8538314ba828564ff822196add1db9f116f22865ed22ea6142238ef96859

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

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

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

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

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

🤖 Web test steps verification results: ⚠️ partial

Verified app access and workspace expense conversation navigation on dev NewDot web. PDF export could not be tested: the fresh conversation had no More/Download report control, and creating a report was blocked by an overlay.

Workspace expense conversation with actions menu
Step Status
1. Open the appThe existing signed-in session displayed Home.
✅
2. Navigate to a workspace expense conversationReached the workspace expense conversation after creating a workspace for the fresh account.
✅
3. Click MoreBlocked: the conversation had no More button. Its composer menu offered Create expense and Create report instead.
Workspace expense conversation with actions menu
❌
4. Click Download report and verify the resultNot reached; an overlay blocked report creation. No export request was triggered.

⚠️ Preliminary analysis — low confidence in the underlying cause.

Confirmed mechanism: The reported message appears when the report’s PDF-filename state equals the literal “error” (ReportPDFDownloadModal.tsx:26–85). The export action explicitly writes that state on request failure (Report/index.ts:7393–7414); response handling applies this failure data for non-200 application jsonCodes, except 460 (OnyxUpdates.ts:65–105). Server-provided state can also supply the error.

Hypothesis: The export request was rejected or PDF generation failed. The message alone cannot distinguish these causes. A downstream file-download failure is insufficient to explain this exact message: downloading starts only after generation reaches READY (FileDownloadModal.tsx:84–97).

Missing evidence: Capture the affected reportID, attempt timestamp, ExportReportToPDF response jsonCode/message, and filename-state updates. Production logs were unavailable, and the inspected checkout was not verified against v9.5.33-0. No specific code fix is established yet.

Related work: Migrate the report PDF download modal to the global modal stack concerns the same flow, but is not a confirmed duplicate or cause.
❌

view run

MelvinBot avatar Nov 06 '26 21:11 MelvinBot

Proposal

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

Descargar un reporte muestra un error de generación de PDF. Dictamen: propuesta no sustentada para selección técnica; se aporta un síntoma, pero ninguna causa raíz ni corrección verificable.

What is the root cause of that problem?

No determinada. No se proporcionan código, commit de v9.5.33-0, petición/respuesta de red ni logs. Atribuir ahora una función, archivo y línea sería inventar evidencia.

El mensaje no distingue entre parámetros incorrectos, permisos, generación en backend o descarga. Tampoco está demostrada una vulnerabilidad ni corresponde asignar CVSS.

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

No es defendible entregar un diff de 3–10 líneas sin localizar el fallo. Primero se necesita:

  • Reproducción con rol, estado del reporte y datos mínimos definidos.
  • Petición fallida y respuesta sanitizadas, con identificador de correlación.
  • Traza hasta la condición defectuosa en el commit afectado.
  • Test que falle antes del parche y pase después.

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

No pude recuperar esa comparación; sus cambios quedan sin verificar, lo que no demuestra que la rama no exista.

What alternative solutions did you explore? (Optional)

MelvinBot: no hay propuesta disponible que refutar. Existe un reporte similar con delegados y gastos rechazados; exige contrastar precondiciones, pero compartir mensaje de error no demuestra duplicidad.

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

Tras confirmar la causa, añadir un test de regresión en el archivo existente correspondiente que reproduzca la entrada defectuosa y compruebe el resultado correcto. No se ejecutaron tests; todavía no puede identificarse honestamente ese archivo.

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

camesenin avatar Nov 06 '26 23:11 camesenin

✅ Contributor details stored successfully. Thank you for contributing to Expensify!

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

Proposal

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

When a user opens an expense report conversation, taps "More" → "Download report", the app shows "There was an error when trying to generate your PDF" instead of downloading the report. This is reproducible in both staging and production across platforms (Windows Chrome, Samsung Chrome, iPhone).

What is the root cause of that problem?

The root cause is a ordering bug in the report-header PDF download flow: the download modal is opened before exportReportToPDF fires, so the modal reads a stale 'error' value left in Onyx from a previous failed attempt instead of the freshly-cleared null.

The flow in the report header (More → Download report):

  1. useExportActions.ts lines 290–300 — the DOWNLOAD_PDF onSelected handler:
    onSelected: () => {
        if (isOffline) { showOfflineModal(); return; }
        if (!moneyRequestReport?.reportID) { return; }
        onPDFModalOpen?.();                                    // ← opens modal FIRST
        exportReportToPDF({reportID: moneyRequestReport.reportID}); // ← API + optimistic null fires AFTER
    },
    
  2. onPDFModalOpen → MoneyReportHeaderModals.tsx lines 84–89 → showReportPDFDownloadModal({reportID}) — this renders ReportPDFDownloadModal, which subscribes to NVP_EXPENSIFY_REPORT_PDF_FILENAME{reportID}.
  3. exportReportToPDF (Report/index.ts lines 7368–7388) sets optimisticData to Onyx.METHOD.SET → null (clearing any prior state) and failureData to MERGE → 'error' on non-200.

The problem: If a prior PDF download for the same reportID failed, the Onyx key NVP_EXPENSIFY_REPORT_PDF_FILENAME{reportID} still holds 'error' (it is never reset on modal close — FileDownloadModalWrapper only hides the modal, it does not clear the Onyx key). When the modal mounts (step 2), ReportPDFDownloadModal.tsx line 38 reads this stale value:

const hasPDFDownloadFailed = reportPDFFilename === CONST.REPORT_DETAILS_MENU_ITEM.ERROR;

and immediately renders the FAILED status with reportDetailsPage.errorPDF — before the new request's optimistic null (step 3) has a chance to clear it. Depending on Onyx write batching/timing, the user sees the error flash or it sticks.

Contrast with the Search flow (useSearchBulkActions.ts lines 2956–2957), which does NOT have this bug because it fires the API first:

await exportReportToPDF({reportID: reportIDForPDF});   // optimistic null clears stale 'error' FIRST
showReportPDFDownloadModal({reportID: reportIDForPDF}); // modal opens on a clean state

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

Fix the ordering in useExportActions.ts so the API request (which carries the optimisticData that clears the stale state) fires before the modal opens — mirroring the proven Search flow:

[CONST.REPORT.SECONDARY_ACTIONS.DOWNLOAD_PDF]: {
    // ...
    onSelected: async () => {
        if (isOffline) { showOfflineModal(); return; }
        if (!moneyRequestReport?.reportID) { return; }
        await exportReportToPDF({reportID: moneyRequestReport.reportID}); // optimistic clears stale state first
        onPDFModalOpen?.();                                              // modal opens on a clean null
    },
},

Additionally (defense in depth): clear the stale Onyx key when the modal is dismissed in FileDownloadModalWrapper.tsx handleClose (or in ReportPDFDownloadModal's unmount), so a failed attempt doesn't leak its 'error' value into the next open. This prevents the same class of bug for any other caller.

What specific scenarios should be covered by automated tests?

  1. Open Download PDF for a report whose previous download failed (Onyx key = 'error'), verify the modal shows the generating/spinner state (not the error) and resolves to ready when the backend pushes a filename.
  2. Open Download PDF, dismiss while generating, reopen — verify no stale error shows.
  3. Open Download PDF for a report that genuinely fails — verify the error state shows once, and reopening shows generating (not stale error).
  4. Existing: modal updates in-place from generating → ready → download.

What alternative solutions did you explore?

  • Adding a useEffect in ReportPDFDownloadModal to reset the key to null on mount. This works but duplicates the optimistic clear and races with the API write; fixing the call ordering is the root-cause fix.
  • Only clearing the key on modal dismiss. This addresses the symptom (stale leak) but not the cause (wrong ordering); the ordering fix is necessary regardless.

PR

PR will be linked here once created.

vanshshah11 avatar Nov 07 '26 00:11 vanshshah11

Proposal

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

When a user opens a multi-expense report and selects More > Download PDF, the PDF download modal fails with "Unable to generate a PDF at this time. Please try again later." instead of generating and downloading the report PDF.

What is the root cause of that problem?

  1. In src/hooks/useExportActions.ts:290-300, the DOWNLOAD_PDF secondary export action opens the modal before calling exportReportToPDF:
    onSelected: () => {
        if (!moneyRequestReport) {
            return;
        }
        onPDFModalOpen?.();
        exportReportToPDF({reportID: moneyRequestReport.reportID});
    },
    
  2. By contrast, in src/hooks/useSearchBulkActions.ts:2956-2957, exportReportToPDF is called first so its optimisticData (Onyx.METHOD.SET setting ${ONYXKEYS.NVP_EXPENSIFY_REPORT_PDF_FILENAME}${reportID} to null in src/libs/actions/Report/index.ts:5205-5215) clears any previous 'error' or stale value before src/components/ReportPDFDownloadModal.tsx renders.
  3. Furthermore, in src/libs/actions/Report/index.ts:5201-5241, exportReportToPDF({reportID}) sends WRITE_COMMANDS.EXPORT_REPORT_TO_PDF through the sequential queue while optimistic expenses or report creation/update writes on the report may still be unsettled or when reportPDF contains a cached 'error' value from an earlier attempt. And in src/components/ReportPDFDownloadModal.tsx:36-62, if reportPDF === CONST.REPORT.NH_PDF_ERROR ('error') is still in Onyx when isVisible flips to true, the modal immediately displays reportPDFDownloadModal.errorMessage instead of waiting for the newly triggered exportReportToPDF command, and closing the modal does not clear the 'error' NVP key.

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

  1. Call exportReportToPDF before onPDFModalOpen?.() in src/hooks/useExportActions.ts:290-300 (matching useSearchBulkActions.ts:2956-2957) so the optimistic Onyx.METHOD.SET (value: null) on ${ONYXKEYS.NVP_EXPENSIFY_REPORT_PDF_FILENAME}${moneyRequestReport.reportID} is applied before ReportPDFDownloadModal mounts:
    onSelected: () => {
        if (!moneyRequestReport) {
            return;
        }
        exportReportToPDF({reportID: moneyRequestReport.reportID});
        onPDFModalOpen?.();
    },
    
  2. Clear stale ${ONYXKEYS.NVP_EXPENSIFY_REPORT_PDF_FILENAME}${reportID} when closing ReportPDFDownloadModal in src/components/ReportPDFDownloadModal.tsx (via a small helper clearReportPDFError(reportID) in src/libs/actions/Report/index.ts) so a transient backend failure never leaves 'error' stuck in Onyx across retries.

What alternative solutions did you explore? (Optional)

We also considered tracking an isExportingPDF loading state inside ReportPDFDownloadModal until the EXPORT_REPORT_TO_PDF command finishes, which complements the optimisticData reset in exportReportToPDF.

zaidrain06 avatar Nov 07 '26 01:11 zaidrain06

Proposal

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

When a user opens an expense report in a workspace chat and clicks More > Download report, the PDF download modal displays "There was an error when trying to generate your PDF" instead of generating and downloading the report PDF.

What is the root cause of that problem?

In src/hooks/useExportActions.ts (around lines 290–300, inside the DOWNLOAD_PDF action's onSelected callback) and src/libs/actions/Report/index.ts (exportReportToPDF):

  1. When More > Download report is selected, Navigation.navigate(createDynamicRoute(DYNAMIC_ROUTES.REPORT_DOWNLOAD_PDF.path)) opens ReportDownloadPDFModal before exportReportToPDF has reset the report's PDF state in Onyx (${ONYXKEYS.COLLECTION.REPORT_METADATA}${reportID} / report.pdfFilename), or exportReportToPDF is called with a mismatched/missing parameter or stale CONST.REPORT.DOWNLOAD_PDF_TUX_ERROR ('error') value in Onyx.
  2. Specifically, in useExportActions.ts, Navigation.navigate(...) runs first, so if a previous attempt left 'error' in Onyx (or when ReportDownloadPDFModal mounts and inspects the Onyx state before the ExportReportToPDF optimistic update commits), the modal immediately renders the error state "There was an error when trying to generate your PDF".

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

  1. In src/hooks/useExportActions.ts inside the DOWNLOAD_PDF onSelected handler, call exportReportToPDF({reportID: moneyRequestReport.reportID}) (which synchronously queues the optimisticData clearing any stale pdfFilename / error state and setting isGeneratingPDF: true) before calling Navigation.navigate(createDynamicRoute(DYNAMIC_ROUTES.REPORT_DOWNLOAD_PDF.path)).
  2. In src/libs/actions/Report/index.ts inside exportReportToPDF, ensure optimisticData explicitly clears any prior PDF error state on ${ONYXKEYS.COLLECTION.REPORT_METADATA}${reportID} / ${ONYXKEYS.COLLECTION.REPORT}${reportID} when starting a new PDF generation request.

What alternative solutions did you explore? (Optional)

We also considered clearing the PDF error state only inside ReportDownloadPDFModal's unmount cleanup, but triggering exportReportToPDF (and its optimisticData reset) prior to navigating to REPORT_DOWNLOAD_PDF guarantees the modal always observes a clean generating state on mount.

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

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

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

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

Proposal

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

When a user opens an expense report in a workspace conversation and clicks More > Download report, the PDF download modal displays "There was an error when trying to generate your PDF" instead of generating and downloading the PDF.

What is the root cause of that problem?

  1. In src/hooks/useExportActions.ts:285-301, the CONST.REPORT.SECONDARY_ACTIONS.DOWNLOAD_PDF onSelected handler opens the PDF download modal before calling exportReportToPDF:
    onSelected: () => {
        if (isOffline) {
            showOfflineModal();
            return;
        }
        if (!moneyRequestReport?.reportID) {
            return;
        }
        onPDFModalOpen?.();
        exportReportToPDF({reportID: moneyRequestReport.reportID});
    },
    
  2. In src/libs/actions/Report/index.ts:7397-7418, exportReportToPDF clears ${ONYXKEYS.COLLECTION.NVP_EXPENSIFY_REPORT_PDF_FILENAME}${reportID} to null in its optimisticData (Onyx.METHOD.SET) and sets it to 'error' in its failureData.
  3. In src/components/ReportPDFDownloadModal.tsx:27, 38-67, ReportPDFDownloadModal reads reportPDFFilename from ${ONYXKEYS.COLLECTION.NVP_EXPENSIFY_REPORT_PDF_FILENAME}${reportID} and immediately sets hasPDFDownloadFailed = reportPDFFilename === CONST.REPORT_DETAILS_MENU_ITEM.ERROR (status = CONST.FILE_DOWNLOAD_STATUS.FAILED, message = translate('reportDetailsPage.errorPDF')).
  4. Because onPDFModalOpen?.() mounts ReportPDFDownloadModal before exportReportToPDF is called (and closing ReportPDFDownloadModal does not clear a stale 'error' value from Onyx), if ${ONYXKEYS.COLLECTION.NVP_EXPENSIFY_REPORT_PDF_FILENAME}${reportID} holds a stale 'error' from a prior attempt (or if failureData at Report/index.ts:7408 uses Onyx.METHOD.MERGE on a primitive string value), the modal immediately renders the error state. By contrast, the bulk-action PDF download in src/hooks/useSearchBulkActions.ts:2956-2957 awaits exportReportToPDF before opening showReportPDFDownloadModal.

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

  1. In src/hooks/useExportActions.ts:290-300, call exportReportToPDF({reportID: moneyRequestReport.reportID}) before onPDFModalOpen?.() (matching useSearchBulkActions.ts:2956-2957) so the optimistic Onyx.METHOD.SET (value: null) clears any prior state before ReportPDFDownloadModal mounts:
    onSelected: () => {
        if (isOffline) {
            showOfflineModal();
            return;
        }
        if (!moneyRequestReport?.reportID) {
            return;
        }
        exportReportToPDF({reportID: moneyRequestReport.reportID});
        onPDFModalOpen?.();
    },
    
  2. In src/libs/actions/Report/index.ts:7406-7412, change onyxMethod: Onyx.METHOD.MERGE to onyxMethod: Onyx.METHOD.SET in failureData (since NVP_EXPENSIFY_REPORT_PDF_FILENAME stores a primitive string, not an object) and clear ${ONYXKEYS.COLLECTION.NVP_EXPENSIFY_REPORT_PDF_FILENAME}${reportID} when ReportPDFDownloadModal closes so a failed attempt never leaks into subsequent opens.

What alternative solutions did you explore? (Optional)

Resetting NVP_EXPENSIFY_REPORT_PDF_FILENAME inside a useEffect on mount of ReportPDFDownloadModal was considered, but calling exportReportToPDF before onPDFModalOpen ensures the optimistic null update is already applied before the modal renders its first frame and keeps useExportActions consistent with useSearchBulkActions.

tungnguyen84 avatar Nov 07 '26 06:11 tungnguyen84

Proposal

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

When navigating to an expense conversation in a workspace chat and clicking More > Download report, the PDF generation modal immediately shows "There was an error when trying to generate your PDF" instead of downloading the report.

What is the root cause of that problem?

In src/hooks/useExportActions.ts:

  1. useExportActions reads the report using the passed reportID:
const [moneyRequestReport] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${getNonEmptyStringOnyxID(reportID)}`);
  1. When the user is viewing an expense thread or one-on-one conversation inside a workspace (isChatReport(report)), reportID is the ID of the chat conversation report, not the underlying expense/IOU report (report.iouReportID).
  2. In exportActionEntries[CONST.REPORT.SECONDARY_ACTIONS.DOWNLOAD_PDF], it passes:
exportReportToPDF({reportID: moneyRequestReport.reportID});

Because the chat report ID is passed rather than the expense report ID (iouReportID), the backend API command Export_ReportToPDF rejects the request since chat reports cannot be exported as expense report PDFs. 4. The failure callback sets ${ONYXKEYS.COLLECTION.NVP_EXPENSIFY_REPORT_PDF_FILENAME}${reportID} to 'error', which triggers the error banner in the PDF modal.

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

In src/hooks/useExportActions.ts: Resolve the correct target expense report ID by checking if moneyRequestReport is a chat report with an iouReportID, falling back to moneyRequestReport.reportID when already on an expense/IOU report:

const expenseReportID = moneyRequestReport?.iouReportID ?? (isMoneyRequestReport(moneyRequestReport) ? moneyRequestReport?.reportID : undefined);

And in DOWNLOAD_PDF.onSelected:

const targetReportID = isMoneyRequestReport(moneyRequestReport) ? moneyRequestReport.reportID : moneyRequestReport?.iouReportID;
if (!targetReportID) {
    return;
}
onPDFModalOpen?.();
exportReportToPDF({reportID: targetReportID});

This ensures exportReportToPDF always receives a valid expense report ID regardless of whether the action was triggered from the expense conversation view or directly from the expense report header.

What alternative solutions did you explore?

Handling the ID mapping in Report.ts inside exportReportToPDF, but useExportActions also controls transactionIDs and export templates for CSV/ZIP where resolving the expense report ID consistently at the hook level ensures all secondary export actions operate on the same report context.

TassioSales avatar Nov 07 '26 16:11 TassioSales

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

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

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

Proposal

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

When a user opens an expense report and selects More -> Download as PDF from the header menu, the PDF download modal displays "There was an error when trying to generate your PDF" instead of generating and downloading the report PDF.

What is the root cause of that problem?

There is an ordering and Onyx state management bug across src/hooks/useExportActions.ts, src/components/ReportPDFDownloadModal.tsx, and src/libs/actions/Report/index.ts:

  1. useExportActions.ts opens ReportPDFDownloadModal before calling exportReportToPDF: In src/hooks/useExportActions.ts (lines 285-301), the DOWNLOAD_PDF secondary action handler does:

    [CONST.REPORT.SECONDARY_ACTIONS.DOWNLOAD_PDF]: {
        text: translate('common.downloadAsPDF'),
        icon: expensifyIcons.File,
        value: CONST.REPORT.SECONDARY_ACTIONS.DOWNLOAD_PDF,
        onSelected: () => {
            if (!moneyRequestReport) {
                return;
            }
            onPDFModalOpen?.();
            exportReportToPDF({
                reportID: moneyRequestReport.reportID,
            });
        },
    },
    

    Contrast this with bulk search PDF download in src/hooks/useSearchBulkActions.ts (lines 2956-2957), which resets/triggers exportReportToPDF first and opens the modal second:

    await exportReportToPDF({reportID: reportIDForPDF});
    showReportPDFDownloadModal(reportIDForPDF);
    
  2. ReportPDFDownloadModal never clears a failed 'error' NVP value on close, and exportReportToPDF uses Onyx.METHOD.MERGE for a string primitive in failureData: In src/libs/actions/Report/index.ts (lines 7397-7418), exportReportToPDF configures:

    const optimisticData: Array<OnyxUpdate<typeof ONYXKEYS.COLLECTION.NVP_EXPENSIFY_REPORT_PDF_FILENAME>> = [
        {
            onyxMethod: Onyx.METHOD.SET,
            key: `${ONYXKEYS.COLLECTION.NVP_EXPENSIFY_REPORT_PDF_FILENAME}${reportID}`,
            value: null,
        },
    ];
    
    const failureData: Array<OnyxUpdate<typeof ONYXKEYS.COLLECTION.NVP_EXPENSIFY_REPORT_PDF_FILENAME>> = [
        {
            onyxMethod: Onyx.METHOD.MERGE,
            key: `${ONYXKEYS.COLLECTION.NVP_EXPENSIFY_REPORT_PDF_FILENAME}${reportID}`,
            value: CONST.REPORT_DETAILS_MENU_ITEM.ERROR,
        },
    ];
    

    And in src/components/ReportPDFDownloadModal.tsx (lines 27-46):

    const [reportPDFFilename] = useOnyx(`${ONYXKEYS.COLLECTION.NVP_EXPENSIFY_REPORT_PDF_FILENAME}${reportID}`);
    const hasPDFDownloadFailed = reportPDFFilename === CONST.REPORT_DETAILS_MENU_ITEM.ERROR;
    
    const status = useMemo(() => {
        if (hasPDFDownloadFailed) {
            return CONST.FILE_DOWNLOAD_STATUS.FAILED;
        }
        if (reportPDFFilename) {
            return CONST.FILE_DOWNLOAD_STATUS.SUCCESS;
        }
        return CONST.FILE_DOWNLOAD_STATUS.LOADING;
    }, [hasPDFDownloadFailed, reportPDFFilename]);
    

    When ${ONYXKEYS.COLLECTION.NVP_EXPENSIFY_REPORT_PDF_FILENAME}${reportID} holds 'error' (from a prior failed attempt, offline state, or stale Onyx cache) or a previous filename:

    • Calling onPDFModalOpen?.() before exportReportToPDF mounts ReportPDFDownloadModal while reportPDFFilename still holds the stale value ('error' or an old filename) before the Onyx.METHOD.SET (value: null) optimistic update from exportReportToPDF is applied.
    • If reportPDFFilename was a previous filename string, FileDownloadModal's useEffect (src/components/Modal/FileDownloadModal.tsx:95-120) immediately fires attemptDownload() for the stale filename on the first render, sets hasAttemptedDownloadRef.current = true (line 99), and then never downloads the newly generated PDF when the new ExportReportToPDF response arrives (unless the filename string happens to differ, and if the server returns the same filename for the unchanged report, reportPDFFilename does not change or hasAttemptedDownloadRef blocks re-entry).
    • Furthermore, in exportReportToPDF (src/libs/actions/Report/index.ts:7409), failureData uses Onyx.METHOD.MERGE instead of Onyx.METHOD.SET for a string primitive NVP.

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

  1. In src/hooks/useExportActions.ts (lines 290-300): Call exportReportToPDF before onPDFModalOpen?.() so that ${ONYXKEYS.COLLECTION.NVP_EXPENSIFY_REPORT_PDF_FILENAME}${reportID} is synchronously reset to null via optimisticData before ReportPDFDownloadModal mounts (matching src/hooks/useSearchBulkActions.ts:2956-2957):

    onSelected: () => {
        if (!moneyRequestReport) {
            return;
        }
        exportReportToPDF({
            reportID: moneyRequestReport.reportID,
        });
        onPDFModalOpen?.();
    },
    
  2. In src/libs/actions/Report/index.ts (lines 7406-7413): Change failureData in exportReportToPDF from Onyx.METHOD.MERGE to Onyx.METHOD.SET (consistent with optimisticData at line 7400 since NVP_EXPENSIFY_REPORT_PDF_FILENAME stores a string or null, not an object), and add a helper clearReportPDFFilename(reportID: string) that resets ${ONYXKEYS.COLLECTION.NVP_EXPENSIFY_REPORT_PDF_FILENAME}${reportID} to null:

    const failureData: Array<OnyxUpdate<typeof ONYXKEYS.COLLECTION.NVP_EXPENSIFY_REPORT_PDF_FILENAME>> = [
        {
            onyxMethod: Onyx.METHOD.SET,
            key: `${ONYXKEYS.COLLECTION.NVP_EXPENSIFY_REPORT_PDF_FILENAME}${reportID}`,
            value: CONST.REPORT_DETAILS_MENU_ITEM.ERROR,
        },
    ];
    
  3. In src/components/ReportPDFDownloadModal.tsx (lines 50-56): Clear ${ONYXKEYS.COLLECTION.NVP_EXPENSIFY_REPORT_PDF_FILENAME}${reportID} when the modal closes after an error or download so stale 'error' or old filename values never persist across modal openings.

What alternative solutions did you explore? (Optional)

  • Only resetting hasAttemptedDownloadRef in FileDownloadModal.tsx: While FileDownloadModal already resets hasAttemptedDownloadRef.current = false when !isVisible (line 90), ReportPDFDownloadModal in MoneyReportHeaderModals.tsx is conditionally mounted ({isPDFModalVisible && <ReportPDFDownloadModal ... />} at lines 84-89), so isVisible is already true on initial mount. Ensuring exportReportToPDF runs before onPDFModalOpen?.() guarantees reportPDFFilename is null (LOADING) when ReportPDFDownloadModal mounts.

e5ash avatar Nov 07 '26 18:11 e5ash

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

TassioSales avatar Nov 07 '26 19:11 TassioSales

✅ Contributor details stored successfully. Thank you for contributing to Expensify!

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

Proposal

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

When a user navigates to an expense conversation in a workspace, clicks More, and clicks Download report, the PDF download modal displays "There was an error when trying to generate your PDF" instead of generating and downloading the PDF.

What is the root cause of that problem?

In src/hooks/useExportActions.ts:285-301 and src/libs/actions/Report/index.ts:7397-7418:

// src/hooks/useExportActions.ts:285-301
[CONST.REPORT.SECONDARY_ACTIONS.DOWNLOAD_PDF]: {
    value: CONST.REPORT.SECONDARY_ACTIONS.DOWNLOAD_PDF,
    text: translate('common.downloadReport', {count: 1}),
    icon: expensifyIcons.Download,
    sentryLabel: CONST.SENTRY_LABEL.MORE_MENU.DOWNLOAD_PDF,
    onSelected: () => {
        if (isOffline) {
            showOfflineModal();
            return;
        }
        if (!moneyRequestReport?.reportID) {
            return;
        }
        onPDFModalOpen?.();
        exportReportToPDF({reportID: moneyRequestReport.reportID});
    },
},
  1. Missing isEmptyReport check in DOWNLOAD_PDF (unlike beginExportWithTemplate and DOWNLOAD_CSV):

    • In useExportActions.ts, line 126 defines const isEmptyReport = transactionIDs.length === 0 && (moneyRequestReport?.transactionCount ?? 0) === 0;.
    • Both beginExportWithTemplate (lines 129-132) and DOWNLOAD_CSV (lines 170-173) guard against empty reports with:
      if (isEmptyReport) {
          showEmptyReportDownloadErrorModal();
          return;
      }
      
    • And in bulk search (src/hooks/useSearchBulkActions.ts), empty reports are likewise blocked with showEmptyReportDownloadErrorModal() before calling exportReportToPDF.
    • However, DOWNLOAD_PDF (lines 290-300) omits the if (isEmptyReport) check and calls exportReportToPDF({reportID: moneyRequestReport.reportID}) directly. When ExportReportToPDF is called on a report with no exportable expenses (or an optimistic/unfinalized report), the backend fails the request and sets nvp_expensify_report_PDFFilename_${reportID} to 'error', causing ReportPDFDownloadModal to display "There was an error when trying to generate your PDF".
  2. Modal open ordering vs exportReportToPDF optimistic state reset and Onyx.METHOD.MERGE on a primitive string in failureData:

    • In src/hooks/useSearchBulkActions.ts:2956-2957, exportReportToPDF is awaited before opening showReportPDFDownloadModal({reportID: reportIDForPDF}) so that ${ONYXKEYS.COLLECTION.NVP_EXPENSIFY_REPORT_PDF_FILENAME}${reportID} is optimistically reset to null (Onyx.METHOD.SET) before ReportPDFDownloadModal mounts and subscribes to that key.
    • In src/hooks/useExportActions.ts:298-299, onPDFModalOpen?.() is called before exportReportToPDF({reportID: moneyRequestReport.reportID}), so if ${ONYXKEYS.COLLECTION.NVP_EXPENSIFY_REPORT_PDF_FILENAME}${reportID} still holds 'error' or a previous filename from an earlier attempt, ReportPDFDownloadModal mounts and evaluates hasPDFDownloadFailed / hasFinishedPDFDownload against the stale value on its initial render.
    • Additionally, in src/libs/actions/Report/index.ts:7408 (and src/libs/actions/IOU/ReportWorkflow.ts:1338), failureData uses onyxMethod: Onyx.METHOD.MERGE instead of Onyx.METHOD.SET when writing the primitive string 'error' (CONST.REPORT_DETAILS_MENU_ITEM.ERROR) to NVP_EXPENSIFY_REPORT_PDF_FILENAME.

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

  1. In src/hooks/useExportActions.ts:290-300:
    • Guard DOWNLOAD_PDF with if (isEmptyReport) { showEmptyReportDownloadErrorModal(); return; } (consistent with DOWNLOAD_CSV at line 170 and beginExportWithTemplate at line 129).
    • Await exportReportToPDF({reportID: moneyRequestReport.reportID}) before calling onPDFModalOpen?.() (consistent with useSearchBulkActions.ts:2956-2957).
  2. In src/libs/actions/Report/index.ts:7408:
    • Use onyxMethod: Onyx.METHOD.SET instead of Onyx.METHOD.MERGE in exportReportToPDF's failureData.

What alternative solutions did you explore? (Optional)

  • Resetting NVP_EXPENSIFY_REPORT_PDF_FILENAME inside a useEffect on mount of ReportPDFDownloadModal.tsx was considered, but awaiting exportReportToPDF before opening ReportPDFDownloadModal ensures the optimistic null value is already written before the modal renders its first frame and keeps useExportActions aligned with useSearchBulkActions.

cocvn157 avatar Nov 08 '26 04:11 cocvn157

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

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

melvin-bot[bot] avatar Nov 08 '26 04:11 melvin-bot[bot]

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

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

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

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