[$250] Expense- Unable to generate PDF to download a report
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:
- Navigate to staging.new.expensify.com
- Navigate to the expense conversation in WS
- Click "More"
- 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
Applause Internal Information Exported by: Svetlana Lazutkina Bug ID: 7307199
Upwork Automation - Do Not Edit
- Upwork Job URL: https://www.upwork.com/jobs/~022118819267753123572
- Upwork Job ID: 2118819267753123572
- Last Price Increase: 2026-11-26
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
Triggered auto assignment to Contributor-plus team member for initial proposal review - @abdulrahuman5196 (External)
Job added to Upwork: https://www.upwork.com/jobs/~022118819267753123572
🤖 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.
| 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.![]() |
❌ |
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. |
❌ |
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
✅ Contributor details stored successfully. Thank you for contributing to Expensify!
Proposal
Please re-state the problem that we are trying to solve in this issue.
When a user 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):
useExportActions.tslines 290–300 — theDOWNLOAD_PDFonSelectedhandler:onSelected: () => { if (isOffline) { showOfflineModal(); return; } if (!moneyRequestReport?.reportID) { return; } onPDFModalOpen?.(); // ← opens modal FIRST exportReportToPDF({reportID: moneyRequestReport.reportID}); // ← API + optimistic null fires AFTER },onPDFModalOpen→MoneyReportHeaderModals.tsxlines 84–89 →showReportPDFDownloadModal({reportID})— this rendersReportPDFDownloadModal, which subscribes toNVP_EXPENSIFY_REPORT_PDF_FILENAME{reportID}.exportReportToPDF(Report/index.tslines 7368–7388) setsoptimisticDatatoOnyx.METHOD.SET→null(clearing any prior state) andfailureDatatoMERGE→'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?
- 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. - Open Download PDF, dismiss while generating, reopen — verify no stale error shows.
- Open Download PDF for a report that genuinely fails — verify the error state shows once, and reopening shows generating (not stale error).
- Existing: modal updates in-place from generating → ready → download.
What alternative solutions did you explore?
- Adding a
useEffectinReportPDFDownloadModalto reset the key tonullon 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.
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?
- In
src/hooks/useExportActions.ts:290-300, theDOWNLOAD_PDFsecondary export action opens the modal before callingexportReportToPDF:onSelected: () => { if (!moneyRequestReport) { return; } onPDFModalOpen?.(); exportReportToPDF({reportID: moneyRequestReport.reportID}); }, - By contrast, in
src/hooks/useSearchBulkActions.ts:2956-2957,exportReportToPDFis called first so itsoptimisticData(Onyx.METHOD.SETsetting${ONYXKEYS.NVP_EXPENSIFY_REPORT_PDF_FILENAME}${reportID}tonullinsrc/libs/actions/Report/index.ts:5205-5215) clears any previous'error'or stale value beforesrc/components/ReportPDFDownloadModal.tsxrenders. - Furthermore, in
src/libs/actions/Report/index.ts:5201-5241,exportReportToPDF({reportID})sendsWRITE_COMMANDS.EXPORT_REPORT_TO_PDFthrough the sequential queue while optimistic expenses or report creation/update writes on the report may still be unsettled or whenreportPDFcontains a cached'error'value from an earlier attempt. And insrc/components/ReportPDFDownloadModal.tsx:36-62, ifreportPDF === CONST.REPORT.NH_PDF_ERROR('error') is still in Onyx whenisVisibleflips totrue, the modal immediately displaysreportPDFDownloadModal.errorMessageinstead of waiting for the newly triggeredexportReportToPDFcommand, 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?
- Call
exportReportToPDFbeforeonPDFModalOpen?.()insrc/hooks/useExportActions.ts:290-300(matchinguseSearchBulkActions.ts:2956-2957) so the optimisticOnyx.METHOD.SET(value: null) on${ONYXKEYS.NVP_EXPENSIFY_REPORT_PDF_FILENAME}${moneyRequestReport.reportID}is applied beforeReportPDFDownloadModalmounts:onSelected: () => { if (!moneyRequestReport) { return; } exportReportToPDF({reportID: moneyRequestReport.reportID}); onPDFModalOpen?.(); }, - Clear stale
${ONYXKEYS.NVP_EXPENSIFY_REPORT_PDF_FILENAME}${reportID}when closingReportPDFDownloadModalinsrc/components/ReportPDFDownloadModal.tsx(via a small helperclearReportPDFError(reportID)insrc/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.
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):
- When
More>Download reportis selected,Navigation.navigate(createDynamicRoute(DYNAMIC_ROUTES.REPORT_DOWNLOAD_PDF.path))opensReportDownloadPDFModalbeforeexportReportToPDFhas reset the report's PDF state in Onyx (${ONYXKEYS.COLLECTION.REPORT_METADATA}${reportID}/report.pdfFilename), orexportReportToPDFis called with a mismatched/missing parameter or staleCONST.REPORT.DOWNLOAD_PDF_TUX_ERROR('error') value in Onyx. - Specifically, in
useExportActions.ts,Navigation.navigate(...)runs first, so if a previous attempt left'error'in Onyx (or whenReportDownloadPDFModalmounts and inspects the Onyx state before theExportReportToPDFoptimistic 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?
- In
src/hooks/useExportActions.tsinside theDOWNLOAD_PDFonSelectedhandler, callexportReportToPDF({reportID: moneyRequestReport.reportID})(which synchronously queues theoptimisticDataclearing any stalepdfFilename/ error state and settingisGeneratingPDF: true) before callingNavigation.navigate(createDynamicRoute(DYNAMIC_ROUTES.REPORT_DOWNLOAD_PDF.path)). - In
src/libs/actions/Report/index.tsinsideexportReportToPDF, ensureoptimisticDataexplicitly 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! 📣 Hey, it seems we don’t have your contributor details yet! You'll only have to do this once, and this is how we'll hire you on Upwork. Please follow these steps:
- Make sure you've read and understood the contributing guidelines.
- Get the email address used to login to your Expensify account. If you don't already have an Expensify account, create one here. If you have multiple accounts (e.g. one for testing), please use your main account email.
- Get the link to your Upwork profile. It's necessary because we only pay via Upwork. You can access it by logging in, and then clicking on your name. It'll look like this. If you don't already have an account, sign up for one here.
- Copy the format below and paste it in a comment on this issue. Replace the placeholder text with your actual details.
Format:
Contributor details
Your Expensify account email: <REPLACE EMAIL HERE>
Upwork Profile Link: <REPLACE LINK HERE>
Proposal
Please re-state the problem that we are trying to solve in this issue.
When a user 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?
- In
src/hooks/useExportActions.ts:285-301, theCONST.REPORT.SECONDARY_ACTIONS.DOWNLOAD_PDFonSelectedhandler opens the PDF download modal before callingexportReportToPDF:onSelected: () => { if (isOffline) { showOfflineModal(); return; } if (!moneyRequestReport?.reportID) { return; } onPDFModalOpen?.(); exportReportToPDF({reportID: moneyRequestReport.reportID}); }, - In
src/libs/actions/Report/index.ts:7397-7418,exportReportToPDFclears${ONYXKEYS.COLLECTION.NVP_EXPENSIFY_REPORT_PDF_FILENAME}${reportID}tonullin itsoptimisticData(Onyx.METHOD.SET) and sets it to'error'in itsfailureData. - In
src/components/ReportPDFDownloadModal.tsx:27, 38-67,ReportPDFDownloadModalreadsreportPDFFilenamefrom${ONYXKEYS.COLLECTION.NVP_EXPENSIFY_REPORT_PDF_FILENAME}${reportID}and immediately setshasPDFDownloadFailed = reportPDFFilename === CONST.REPORT_DETAILS_MENU_ITEM.ERROR(status = CONST.FILE_DOWNLOAD_STATUS.FAILED,message = translate('reportDetailsPage.errorPDF')). - Because
onPDFModalOpen?.()mountsReportPDFDownloadModalbeforeexportReportToPDFis called (and closingReportPDFDownloadModaldoes 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 iffailureDataatReport/index.ts:7408usesOnyx.METHOD.MERGEon a primitive string value), the modal immediately renders the error state. By contrast, the bulk-action PDF download insrc/hooks/useSearchBulkActions.ts:2956-2957awaitsexportReportToPDFbefore openingshowReportPDFDownloadModal.
What changes do you think we should make in order to solve the problem?
- In
src/hooks/useExportActions.ts:290-300, callexportReportToPDF({reportID: moneyRequestReport.reportID})beforeonPDFModalOpen?.()(matchinguseSearchBulkActions.ts:2956-2957) so the optimisticOnyx.METHOD.SET(value: null) clears any prior state beforeReportPDFDownloadModalmounts:onSelected: () => { if (isOffline) { showOfflineModal(); return; } if (!moneyRequestReport?.reportID) { return; } exportReportToPDF({reportID: moneyRequestReport.reportID}); onPDFModalOpen?.(); }, - In
src/libs/actions/Report/index.ts:7406-7412, changeonyxMethod: Onyx.METHOD.MERGEtoonyxMethod: Onyx.METHOD.SETinfailureData(sinceNVP_EXPENSIFY_REPORT_PDF_FILENAMEstores a primitive string, not an object) and clear${ONYXKEYS.COLLECTION.NVP_EXPENSIFY_REPORT_PDF_FILENAME}${reportID}whenReportPDFDownloadModalcloses 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.
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:
useExportActionsreads the report using the passedreportID:
const [moneyRequestReport] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${getNonEmptyStringOnyxID(reportID)}`);
- When the user is viewing an expense thread or one-on-one conversation inside a workspace (
isChatReport(report)),reportIDis the ID of the chat conversation report, not the underlying expense/IOU report (report.iouReportID). - 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! 📣 Hey, it seems we don’t have your contributor details yet! You'll only have to do this once, and this is how we'll hire you on Upwork. Please follow these steps:
- Make sure you've read and understood the contributing guidelines.
- Get the email address used to login to your Expensify account. If you don't already have an Expensify account, create one here. If you have multiple accounts (e.g. one for testing), please use your main account email.
- Get the link to your Upwork profile. It's necessary because we only pay via Upwork. You can access it by logging in, and then clicking on your name. It'll look like this. If you don't already have an account, sign up for one here.
- Copy the format below and paste it in a comment on this issue. Replace the placeholder text with your actual details.
Format:
Contributor details
Your Expensify account email: <REPLACE EMAIL HERE>
Upwork Profile Link: <REPLACE LINK HERE>
Proposal
Please re-state the problem that we are trying to solve in this issue.
When a user 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:
-
useExportActions.tsopensReportPDFDownloadModalbefore callingexportReportToPDF: Insrc/hooks/useExportActions.ts(lines 285-301), theDOWNLOAD_PDFsecondary 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/triggersexportReportToPDFfirst and opens the modal second:await exportReportToPDF({reportID: reportIDForPDF}); showReportPDFDownloadModal(reportIDForPDF); -
ReportPDFDownloadModalnever clears a failed'error'NVP value on close, andexportReportToPDFusesOnyx.METHOD.MERGEfor a string primitive infailureData: Insrc/libs/actions/Report/index.ts(lines 7397-7418),exportReportToPDFconfigures: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?.()beforeexportReportToPDFmountsReportPDFDownloadModalwhilereportPDFFilenamestill holds the stale value ('error'or an old filename) before theOnyx.METHOD.SET(value: null) optimistic update fromexportReportToPDFis applied. - If
reportPDFFilenamewas a previous filename string,FileDownloadModal'suseEffect(src/components/Modal/FileDownloadModal.tsx:95-120) immediately firesattemptDownload()for the stale filename on the first render, setshasAttemptedDownloadRef.current = true(line 99), and then never downloads the newly generated PDF when the newExportReportToPDFresponse arrives (unless the filename string happens to differ, and if the server returns the same filename for the unchanged report,reportPDFFilenamedoes not change orhasAttemptedDownloadRefblocks re-entry). - Furthermore, in
exportReportToPDF(src/libs/actions/Report/index.ts:7409),failureDatausesOnyx.METHOD.MERGEinstead ofOnyx.METHOD.SETfor a string primitive NVP.
- Calling
What changes do you think we should make in order to solve the problem?
-
In
src/hooks/useExportActions.ts(lines 290-300): CallexportReportToPDFbeforeonPDFModalOpen?.()so that${ONYXKEYS.COLLECTION.NVP_EXPENSIFY_REPORT_PDF_FILENAME}${reportID}is synchronously reset tonullviaoptimisticDatabeforeReportPDFDownloadModalmounts (matchingsrc/hooks/useSearchBulkActions.ts:2956-2957):onSelected: () => { if (!moneyRequestReport) { return; } exportReportToPDF({ reportID: moneyRequestReport.reportID, }); onPDFModalOpen?.(); }, -
In
src/libs/actions/Report/index.ts(lines 7406-7413): ChangefailureDatainexportReportToPDFfromOnyx.METHOD.MERGEtoOnyx.METHOD.SET(consistent withoptimisticDataatline 7400sinceNVP_EXPENSIFY_REPORT_PDF_FILENAMEstores a string ornull, not an object), and add a helperclearReportPDFFilename(reportID: string)that resets${ONYXKEYS.COLLECTION.NVP_EXPENSIFY_REPORT_PDF_FILENAME}${reportID}tonull: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, }, ]; -
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
hasAttemptedDownloadRefinFileDownloadModal.tsx: WhileFileDownloadModalalready resetshasAttemptedDownloadRef.current = falsewhen!isVisible(line 90),ReportPDFDownloadModalinMoneyReportHeaderModals.tsxis conditionally mounted ({isPDFModalVisible && <ReportPDFDownloadModal ... />}atlines 84-89), soisVisibleis alreadytrueon initial mount. EnsuringexportReportToPDFruns beforeonPDFModalOpen?.()guaranteesreportPDFFilenameisnull(LOADING) whenReportPDFDownloadModalmounts.
Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~0179cdc82689f205c7
✅ Contributor details stored successfully. Thank you for contributing to Expensify!
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});
},
},
-
Missing
isEmptyReportcheck inDOWNLOAD_PDF(unlikebeginExportWithTemplateandDOWNLOAD_CSV):- In
useExportActions.ts, line 126 definesconst isEmptyReport = transactionIDs.length === 0 && (moneyRequestReport?.transactionCount ?? 0) === 0;. - Both
beginExportWithTemplate(lines 129-132) andDOWNLOAD_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 withshowEmptyReportDownloadErrorModal()before callingexportReportToPDF. - However,
DOWNLOAD_PDF(lines 290-300) omits theif (isEmptyReport)check and callsexportReportToPDF({reportID: moneyRequestReport.reportID})directly. WhenExportReportToPDFis called on a report with no exportable expenses (or an optimistic/unfinalized report), the backend fails the request and setsnvp_expensify_report_PDFFilename_${reportID}to'error', causingReportPDFDownloadModalto display"There was an error when trying to generate your PDF".
- In
-
Modal open ordering vs
exportReportToPDFoptimistic state reset andOnyx.METHOD.MERGEon a primitive string infailureData:- In
src/hooks/useSearchBulkActions.ts:2956-2957,exportReportToPDFis awaited before openingshowReportPDFDownloadModal({reportID: reportIDForPDF})so that${ONYXKEYS.COLLECTION.NVP_EXPENSIFY_REPORT_PDF_FILENAME}${reportID}is optimistically reset tonull(Onyx.METHOD.SET) beforeReportPDFDownloadModalmounts and subscribes to that key. - In
src/hooks/useExportActions.ts:298-299,onPDFModalOpen?.()is called beforeexportReportToPDF({reportID: moneyRequestReport.reportID}), so if${ONYXKEYS.COLLECTION.NVP_EXPENSIFY_REPORT_PDF_FILENAME}${reportID}still holds'error'or a previous filename from an earlier attempt,ReportPDFDownloadModalmounts and evaluateshasPDFDownloadFailed/hasFinishedPDFDownloadagainst the stale value on its initial render. - Additionally, in
src/libs/actions/Report/index.ts:7408(andsrc/libs/actions/IOU/ReportWorkflow.ts:1338),failureDatausesonyxMethod: Onyx.METHOD.MERGEinstead ofOnyx.METHOD.SETwhen writing the primitive string'error'(CONST.REPORT_DETAILS_MENU_ITEM.ERROR) toNVP_EXPENSIFY_REPORT_PDF_FILENAME.
- In
What changes do you think we should make in order to solve the problem?
- In
src/hooks/useExportActions.ts:290-300:- Guard
DOWNLOAD_PDFwithif (isEmptyReport) { showEmptyReportDownloadErrorModal(); return; }(consistent withDOWNLOAD_CSVatline 170andbeginExportWithTemplateatline 129). - Await
exportReportToPDF({reportID: moneyRequestReport.reportID})before callingonPDFModalOpen?.()(consistent withuseSearchBulkActions.ts:2956-2957).
- Guard
- In
src/libs/actions/Report/index.ts:7408:- Use
onyxMethod: Onyx.METHOD.SETinstead ofOnyx.METHOD.MERGEinexportReportToPDF'sfailureData.
- Use
What alternative solutions did you explore? (Optional)
- Resetting
NVP_EXPENSIFY_REPORT_PDF_FILENAMEinside auseEffecton mount ofReportPDFDownloadModal.tsxwas considered, but awaitingexportReportToPDFbefore openingReportPDFDownloadModalensures the optimisticnullvalue is already written before the modal renders its first frame and keepsuseExportActionsaligned withuseSearchBulkActions.
📣 @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:
- Make sure you've read and understood the contributing guidelines.
- Get the email address used to login to your Expensify account. If you don't already have an Expensify account, create one here. If you have multiple accounts (e.g. one for testing), please use your main account email.
- Get the link to your Upwork profile. It's necessary because we only pay via Upwork. You can access it by logging in, and then clicking on your name. It'll look like this. If you don't already have an account, sign up for one here.
- Copy the format below and paste it in a comment on this issue. Replace the placeholder text with your actual details.
Format:
Contributor details
Your Expensify account email: <REPLACE EMAIL HERE>
Upwork Profile Link: <REPLACE LINK HERE>
@abdulrahuman5196 Uh oh! This issue is overdue by 2 days. Don't forget to update your issues!
@abdulrahuman5196 Eep! 4 days overdue now. Issues have feelings too...