App icon indicating copy to clipboard operation
App copied to clipboard

[Due for payment 2026-11-18] [$175] [Sentry: APP-NVN] Billing receipt crashes reading undefined billingType

Open melvin-bot[bot] opened this issue 3 weeks ago • 24 comments

Sentry: https://expensify.sentry.io/issues/APP-NVN

Impact: 1 user, 1 event; first seen November 4, 2026 at 17:46 UTC. Unhandled fatal error blocks the billing receipt view.

Platform: Web, Chrome, standalone
Release: 9.5.30
Route: /settings/subscription/payment-history/:purchaseID/receipt

Error: TypeError: Cannot read properties of undefined (reading 'billingType')

Top first-party frames:

PaymentHistoryUtils.ts:174 — isClear
PaymentHistoryUtils.ts:351 — getReceiptPurchase
PaymentHistoryUtils.ts:373 — getReceiptSource
BillingReceiptModalContent.tsx:42 — BillingReceiptModalContent

Root cause: getReceiptPurchase() checks that the purchase exists but assumes its message exists. openPaymentDetailsPage() can create an incomplete purchase containing only {isLoaded: true} through unconditional finallyData when no purchase data was returned. The receipt modal calls getReceiptSource() before its loading guard, leading to the unsafe dereference.

This code path matches the exception, although the specific response that produced this event’s incomplete entry has not been established.

Suggested fix:

  • Only mark a purchase loaded after successfully receiving valid purchase data.
  • Handle missing purchase/message data safely in receipt resolution and display an appropriate loading, error, or not-found state.
  • Add regression coverage for an uncached receipt route whose details lookup returns no purchase.

Investigation: https://expensify.slack.com/archives/C027V2LD9D1/p1793891524758489

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

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

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

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

@MelvinBot can you investigate the RCA and propose a fix?

mountiny avatar Nov 05 '26 21:11 mountiny

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

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

Proposal

Updated November 6, 2026: Revised based on feedback from nkdengineer.

What is the root cause of that problem?

Receipt resolution accepts an existing purchase without message, then reads message.billingType. The modal resolves the source before checking loading. A completed lookup can leave an incomplete {isLoaded: true} entry, so loading completion alone does not establish that a purchase exists.

The frontend failure mechanism matches the reported stack; the exact response/cache state behind the production event remains unconfirmed.

Code evidence

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

  1. In getReceiptPurchase, return null when the purchase is absent, lacks purchaseID, or lacks message. Apply these checks to linked purchases too, before returning a receipt or inspecting billing fields. Preserve cycle detection.
  2. In the receipt modal, check loading first. Once loaded, if purchaseID is missing, render null and dismiss the modal. Only calculate the source, filename and invoice status after both guards.
  3. Perform dismissal in an unconditional effect gated on purchase?.isLoaded && !purchase.purchaseID, not during render. Keep all hooks—including the download hook—above the conditional returns.
  4. Add regressions for pending lookup → loaded ID-less placeholder → dismissal, invalid root/linked purchases, and unchanged valid receipt/invoice previews and downloads. A loaded purchase with an ID but no resolvable receipt retains the existing not-found behavior.
Scope and validation

This retains the completion marker so an empty lookup can leave loading. It changes the ID-less placeholder outcome from not-found to dismissal, as requested. Retaining the message checks also protects malformed entries that do contain an ID.

The existing attachment container uses Navigation.dismissModal(); DomainNotFoundPageWrapper.tsx:39–52 demonstrates dismissal from an effect after loading.

This refinement was checked against source only. No implementation, tests, or browser verification were performed.


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

MelvinBot avatar Nov 05 '26 21:11 MelvinBot

@nkdengineer can you review please

mountiny avatar Nov 06 '26 01:11 mountiny

@MelvinBot We should do two things

  1. getReceiptPurchase, also return null if !purchase.purchaseID

  2. In this page, we should only get the source after !purchase?.isLoaded block, and after this block also add another check !purchase.purchaseID to dismiss the modal and render nothing in this case

https://github.com/Expensify/App/blob/63acb1ed08949b77fb80f02e8b2d1d6360d0d90b/src/pages/media/AttachmentModalScreen/routes/BillingReceiptModalContent.tsx#L42-L60

nkdengineer avatar Nov 06 '26 03:11 nkdengineer

Agreed—I've updated the proposal with both changes:

  1. Reject missing purchaseID in getReceiptPurchase, retaining the missing-message checks for the root and linked purchases.
  2. In BillingReceiptModalContent, check loading, then return null for a loaded purchase without purchaseID; resolve the source only afterward.

Dismissal should run in an effect, not during render. All hooks, including the download hook, must remain above the early returns. Regression coverage should verify that the loaded ID-less placeholder dismisses without crashing and valid receipts remain unchanged.

Proposal only; no code changes or tests performed.


view run

MelvinBot avatar Nov 06 '26 03:11 MelvinBot

Melvin's proposal looks good to me

🎀 👀 🎀 C+ reviewed

nkdengineer avatar Nov 06 '26 04:11 nkdengineer

Current assignee @mountiny is eligible for the choreEngineerContributorManagement assigner, not assigning anyone new.

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

@nkdengineer please go ahead.

mountiny avatar Nov 06 '26 23:11 mountiny

Proposal

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

On Web when opening /settings/subscription/payment-history/:purchaseID/receipt, the billing receipt modal crashes with TypeError: Cannot read properties of undefined (reading 'billingType') inside PaymentHistoryUtils.ts (isClear -> getReceiptPurchase -> getReceiptSource) called from BillingReceiptModalContent.tsx.

What is the root cause of that problem?

There are two bugs working together:

  1. In src/libs/actions/PaymentMethods.ts inside openPaymentDetailsPage, the finallyData for OPEN_PAYMENT_DETAILS_PAGE unconditionally merges {isLoaded: true} into ${ONYXKEYS.COLLECTION.PURCHASE}${purchaseID} even when the backend returns no purchase data or the request fails, creating a stub purchase object in Onyx with isLoaded: true and message: undefined.
  2. In src/pages/settings/Subscription/PaymentHistory/BillingReceiptModalContent.tsx (line 42), getReceiptSource(purchase, ...) (src/libs/PaymentHistoryUtils.ts line 373) calls getReceiptPurchase(purchase) (src/libs/PaymentHistoryUtils.ts line 351), which only checks if (!purchase) before calling isClear(purchase) (src/libs/PaymentHistoryUtils.ts line 174). Inside isClear(purchase), purchase.message.billingType is dereferenced directly without guarding purchase?.message, throwing TypeError: Cannot read properties of undefined (reading 'billingType') before the loading/not-found guard in BillingReceiptModalContent.tsx runs.

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

  1. In src/libs/PaymentHistoryUtils.ts:
    • In isClear (line 174) and the other purchase.message helpers (isFailed, isRefunded, isBillingReceiptAvailable, getReceiptPurchase), use optional chaining purchase?.message?.billingType and guard if (!purchase?.message) { return undefined; } in getReceiptPurchase.
  2. In src/pages/settings/Subscription/PaymentHistory/BillingReceiptModalContent.tsx:
    • Guard against a missing purchase?.message when purchase?.isLoaded is true so FullPageNotFoundView (or the appropriate error/not-found state) is rendered instead of crashing.
  3. In src/libs/actions/PaymentMethods.ts (openPaymentDetailsPage), only mark the purchase loaded or handle missing purchase payloads cleanly in successData / failureData, and add a unit test in tests/unit/PaymentHistoryUtilsTest.ts covering a purchase object with {isLoaded: true} and message: undefined.

What alternative solutions did you explore? (Optional)

We considered only adding optional chaining in isClear, but fixing both getReceiptPurchase / isClear in PaymentHistoryUtils.ts and the not-found check in BillingReceiptModalContent.tsx ensures the UI displays a clean not-found state rather than a blank modal when a receipt URL points to a non-existent or failed purchase lookup.

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 opening a billing receipt route (/settings/subscription/payment-details/:purchaseID) for a purchaseID that does not exist in the backend response (or resolves without a message payload), the app crashes with:

TypeError: Cannot read properties of undefined (reading 'billingType')

in isClear (src/libs/PaymentHistoryUtils.ts:174) called from getReceiptPurchase (src/libs/PaymentHistoryUtils.ts:351).

What is the root cause of that problem?

  1. When BillingReceiptModalContent mounts and !purchase?.isLoaded is true, it calls openPaymentDetailsPage(numericPurchaseID) (src/libs/actions/Subscription.ts:87-101). In openPaymentDetailsPage, finallyData unconditionally merges { [purchaseID]: { isLoaded: true } } into ONYXKEYS.PURCHASES. If the backend returns no purchase record for purchaseID, purchases[purchaseID] becomes { isLoaded: true } (where purchaseID and message are undefined).
  2. In src/pages/media/AttachmentModalScreen/routes/BillingReceiptModalContent.tsx:42, getReceiptSource(purchases, numericPurchaseID) is invoked before the if (!purchase?.isLoaded) guard at line 45, and there is no guard for !purchase.purchaseID when isLoaded becomes true with empty purchase data.
  3. Inside getReceiptPurchase (src/libs/PaymentHistoryUtils.ts:339-370), const purchase = purchases?.[purchaseID]; if (!purchase) { return null; } passes because purchase is { isLoaded: true }. Execution proceeds to line 351 (if (isClear(purchase))), which evaluates purchase.message.billingType === CONST.BILLING.TYPE_CLEAR (src/libs/PaymentHistoryUtils.ts:174) and throws TypeError: Cannot read properties of undefined (reading 'billingType'). The same unsafe assumption exists in the while loop at lines 359–367 when traversing purchases[String(currentId)].

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

  1. In src/libs/PaymentHistoryUtils.ts (getReceiptPurchase, lines 339–370):

    • Guard against incomplete/stub purchase entries at the start of getReceiptPurchase:
      const purchase = purchases?.[purchaseID];
      if (!purchase?.purchaseID || !purchase.message) {
          return null;
      }
      
    • Add the same guard inside the failedPurchaseID traversal loop (lines 359–367) before reading current.receipt?.source or current.message.failedPurchaseID:
      const current = purchases[String(currentId)];
      if (!current?.purchaseID || !current.message) {
          return null;
      }
      
  2. In src/pages/media/AttachmentModalScreen/routes/BillingReceiptModalContent.tsx (lines 35–51):

    • Add a useEffect that dismisses the modal if the purchase finished loading without valid purchase data (purchase?.isLoaded && !purchase.purchaseID):
      useEffect(() => {
          if (!purchase?.isLoaded || purchase.purchaseID) {
              return;
          }
          Navigation.dismissModal();
      }, [purchase?.isLoaded, purchase?.purchaseID]);
      
    • Move getReceiptSource, originalFileName, and isInvoice below the loading and missing-purchase early returns so they only run once purchase?.isLoaded && purchase.purchaseID is confirmed (while keeping useDownloadAttachment above the early returns to preserve unconditional hook ordering):
      if (!purchase?.isLoaded) {
          return <FullScreenLoadingIndicator shouldUseGoBackButton />;
      }
      
      if (!purchase.purchaseID) {
          return null;
      }
      
      const source = getReceiptSource(purchases, numericPurchaseID) ?? '';
      const isInvoice = isInvoicePurchase(purchase);
      const originalFileName = `${isInvoice ? 'invoice' : 'receipt'}_${numericPurchaseID}.html`;
      

What alternative solutions did you explore? (Optional)

  • Showing NotFoundPage instead of dismissing the modal when purchase?.isLoaded && !purchase.purchaseID, but since BillingReceiptModalContent is rendered inside an attachment modal route, dismissing the modal via Navigation.dismissModal() and returning null is cleaner and avoids leaving a broken modal header state.

zaidrain06 avatar Nov 07 '26 07:11 zaidrain06

📣 @ronanchnlps-bit! 📣 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 10:11 melvin-bot[bot]

Proposal

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

When navigating to the billing receipt route (/settings/subscription/payment-history/:purchaseID/receipt), the app crashes with TypeError: Cannot read properties of undefined (reading 'billingType') if the purchase has not loaded complete message data or if the purchase lookup returns an incomplete record.

What is the root cause of that problem?

  1. In PaymentHistoryUtils.ts within isClear(), purchase.message.billingType is accessed directly without optional chaining or verification that purchase.message is defined.
  2. getReceiptPurchase(purchaseID) returns a purchase record as valid if an entry exists, but during an initial or failed fetch, openPaymentDetailsPage() can populate the purchase in Onyx with {isLoaded: true} in finallyData without populating message.
  3. In BillingReceiptModalContent.tsx, getReceiptSource() and downstream helper checks (such as isClear(purchase)) are called during render before checking whether purchase or purchase.message is actually defined, which causes an unhandled runtime error.

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

  1. In PaymentHistoryUtils.ts:
    • In isClear(purchase) and other helper functions accessing message attributes, use safe optional chaining (e.g., purchase?.message?.billingType) and return false if purchase?.message is absent.
    • In getReceiptPurchase(), ensure it validates that purchase?.message exists or that isLoaded is paired with valid purchase metadata; otherwise treat it as not found / not loaded.
  2. In BillingReceiptModalContent.tsx:
    • Add a guard check to verify that purchase and purchase.message exist before computing receipt properties. If the purchase data is still loading, display the FullScreenLoadingIndicator. If loaded but the purchase does not exist or has no message, render NotFoundPage.
  3. In openPaymentDetailsPage:
    • Ensure isLoaded: true is only set in finallyData if valid response data was obtained, or handle empty states gracefully without corrupting the store.

What alternative solutions did you explore? (Optional)

Only adding optional chaining (purchase?.message?.billingType) in isClear, but this would leave the user viewing a blank or broken receipt page instead of properly displaying a NotFoundPage or loading state when receipt data is missing.

TassioSales avatar Nov 08 '26 00:11 TassioSales

@nkdengineer any eta for the pr?

mountiny avatar Nov 08 '26 02:11 mountiny

@MelvinBot Implement this https://github.com/Expensify/App/issues/106147#issuecomment-6670211371

nkdengineer avatar Nov 08 '26 02:11 nkdengineer

🤖 Web test steps verification results: ❌ fail

Browser verification was blocked by a blank app page. Neither receipt scenario could be tested; this does not establish a regression in the fix.

Blank app page in the handed-off session
Step Status
Invalid uncached receipt dismisses after lookupBlocked: the page remained blank and receipt navigation was unavailable.
Blank app page in the handed-off session
❌
Valid receipt preview, title, and download remain usableBlocked by the blank page; receipt availability could not be checked.
❌

Implemented in draft PR Prevent billing receipt crashes on incomplete purchase data, assigned to nkdengineer, with PullerBear review requested.

The fix adds purchase/message guards and dismisses loaded ID-less purchases before resolving modal content.

Passed: 50 targeted tests, lint, typecheck, spelling, Storybook smoke, and explicit-file React Compiler check. Code review found no violations. Full Jest exceeded 15 minutes without finishing; formatting and changed-file compiler checks had tooling limitations documented in the PR.


view run

MelvinBot avatar Nov 08 '26 03:11 MelvinBot

@nkdengineer

The solution for this issue has been :rocket: deployed to production :rocket: in version 9.5.35-3 and is now subject to a 7-day regression period :calendar:. Here is the list of pull requests that resolve this issue:

  • https://github.com/Expensify/App/pull/106315

If no regressions arise, payment will be issued on 2026-11-18. :confetti_ball:

The following checklist (instructions) will need to be completed before the issue can be closed. Please copy/paste the Contributor+ Checklist from here into a new comment on this GH and complete it. If you have the K2 extension, you can simply click: [this button]. If no checklist is needed for this issue, you can click: [no checklist button]

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

Contributor+ Checklist:

  • [x] [Contributor] The offending PR and associated issue have been commented on, pointing out the bug it caused and why, so the author and reviewers can learn from the mistake.

    Link to the comment on the PR: https://github.com/Expensify/App/pull/104020/changes#r4534364516

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

    Link to discussion: N/A

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

Regression Test Proposal

Test:

  1. Go to the deeplink https://staging.new.expensify.com/settings/subscription/payment-history/1/receipt
  2. Verify that we went to the home page, as the purchase is not found.
  3. Do the same for step 1, but replace purchaseID param with the valid one of your account with receipt.
  4. Verify that the App doesn't crash and the receipt is displayed.

Do we agree 👍 or 👎

nkdengineer avatar Nov 11 '26 05:11 nkdengineer