App icon indicating copy to clipboard operation
App copied to clipboard

[$250] [Sentry: APP-PPW] TrackExpense submits empty draft expense and returns 666 (Missing currency)

Open mountiny opened this issue 2 days ago β€’ 73 comments

Problem

APP-PPW reports Expense API Error: TrackExpense returned 666.

  • Impact: 1 user, 24 events.
  • Platform: web, Chrome on Windows.
  • Release: [email protected].
  • Route: /search (Search_Root).
  • First seen: 2026-11-28 02:07 UTC.

Production logs show an empty expense submitted alongside a populated expense. The empty request omits currency and amount and has blank merchant/date/comment with no receipt. Auth returns 402 Missing currency, which PHP wraps as 666. This does not establish loss of the populated expense.

First-party frames

  • src/libs/actions/OnyxUpdates.ts:160 β€” trackExpenseApiError
  • src/libs/telemetry/trackExpenseCreationError.ts:145 β€” Sentry.captureMessage

Likely cause

useOptimisticDraftTransactions includes every truthy draft when multiple drafts exist. useTrackExpenseSubmission submits each without validating currency or draft completeness.

A leftover partial draft is the suspected trigger; its origin has not been reproduced.

Suggested fix

Skip or clean up unintended partial drafts before submission, while preserving legitimate receipt-only scan drafts. Add regression coverage for a valid expense submitted while a partial draft exists.

Investigation thread

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

mountiny avatar Nov 30 '26 01:11 mountiny

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

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

Proposal

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

On web, when more than one draft transaction exists in Onyx, tracking an expense can also submit a leftover empty draft (no amount, currency, merchant, date or receipt) as its own TrackExpense request. Auth rejects that request with 402 Missing currency, which is wrapped as 666 and reported as an expense API error.

What is the root cause of that problem?

The submit path does not check whether a draft is complete. In current main:

  1. src/hooks/useOptimisticDraftTransactions.ts switches to every TRANSACTION_DRAFT value as soon as there is more than one, and the only filter it applies is truthiness:
    const allTransactions = optimisticTransactions && optimisticTransactions.length > 1 ? optimisticTransactions : [transaction];
    const transactions = allTransactions.filter((value): value is Transaction => !!value);
    
    A stale or partial draft object therefore counts as a real item. useConfirmationTransactionPager shows it, and it is passed down as transactions.
  2. In useTrackExpenseSubmission.ts, trackExpense() loops over transactions.entries() and calls trackExpenseIOUActions for each item. Its upfront checks cover only the participant and, for CATEGORIZE/SHARE/SUBMIT, the linked tracked expense. Nothing checks currency or completeness, so the empty draft goes out with currency: undefined.

What I could not confirm: where the partial draft comes from in the first place. Like the issue says, I have not reproduced its creation and won't claim a specific origin. One detail that may be relevant: 24 events from a single user suggests the stub survives the cleanup that runs after a submit. That cleanup removes draftTransactionIDs, which validTransactionDraftIDsSelector builds from each draft's transactionID field, not from its Onyx key. So a stub written under a transactionsDraft_<id> key without its own transactionID (for example, a late Onyx.merge into a draft that was already removed) would never be cleaned up. That is a hypothesis to verify, not a proven cause.

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

  1. Add one shared helper, for example isUsableDraftTransaction(draft) in TransactionUtils. It returns false only for real empty shells, which means all of the following are missing: a currency, a non-zero amount, a receipt (receipt?.source, or a receipt file in progress), and a transactionID. This criterion is deliberately narrow, so receipt-only SmartScan drafts (amount 0, filled in later) and distance/per-diem drafts are kept.
  2. Filter in useOptimisticDraftTransactions with that helper before the length > 1 check. Then one valid draft plus one empty shell falls back to the single-transaction path, and the empty shell no longer shows as an extra page on the confirmation pager. I'd check the other callers (the scan components, useParticipantSubmission, useReportPickerActions) so their behavior only changes for empty shells.
  3. Guard at submit time. In useTrackExpenseSubmission.trackExpense(), and in the matching loop in useRequestMoneySubmission that reads the same transactions, skip any item that fails the helper and Log.warn its key/transactionID. This is defense in depth, and the log will show where these drafts come from.
  4. Make cleanup remove the shell. Pass the skipped drafts' Onyx keys (or derive draftTransactionIDs from the collection keys rather than draft.transactionID) so cleanupAfterExpenseCreate / removeDraftTransactionsByIDs actually removes them and they don't come back on the next confirmation.
  5. Tests
    • useOptimisticDraftTransactions: (a) one valid draft plus one empty draft returns only the valid one, (b) one valid draft plus one receipt-only scan draft returns both, (c) two valid drafts return both.
    • In the existing tests/unit/hooks/useTrackExpenseSubmission.test.ts, assert that trackExpense is called exactly once when a valid expense is submitted while an empty draft exists. This is the regression case the issue asks for.

What alternative solutions did you explore? (Optional)

  • Validating only inside trackExpenseIOUActions. This stops the API error, but the empty draft still shows up as an extra row/page on the confirmation screen and is never cleaned up, so the hook-level filter is the better fix.
  • Defaulting a missing currency (for example, to the user's local currency). I rejected this because it would quietly create a junk $0 expense instead of dropping the stub.

AI disclosure: I used AI-assisted tooling to investigate the code and draft this proposal, and I reviewed it myself against current main. I'll write and test the implementation myself if I'm assigned.

mathewtimeus-collab avatar Nov 30 '26 02:11 mathewtimeus-collab

πŸ“£ @mathewtimeus-collab! πŸ“£ 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 30 '26 02:11 melvin-bot[bot]

Proposal

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

On web (seen on /search), submitting a TrackExpense flow when multiple entries exist in ONYXKEYS.COLLECTION.TRANSACTION_DRAFT can submit a leftover empty partial draft alongside the real expense (missing currency and amount, blank merchant/date/comment, no receipt). Auth rejects the empty request with 402 Missing currency, which PHP wraps as 666 (APP-PPW), and a single user hit this repeatedly across submissions.

What is the root cause of that problem?

Three linked gaps allow partial/placeholder drafts in COLLECTION.TRANSACTION_DRAFT to survive cleanup and enter TrackExpense:

  1. Unintended drafts live in COLLECTION.TRANSACTION_DRAFT and can evade removeDraftTransactionsByIDs cleanup:
    • /search bulk edit (initBulkEditDraftTransaction in src/libs/actions/IOU/BulkEdit.ts) writes {transactionID: CONST.IOU.OPTIMISTIC_BULK_EDIT_TRANSACTION_ID, selectedTransactionIDs} into COLLECTION.TRANSACTION_DRAFT with no currency/amount/receipt.
    • Delayed Onyx.merge updates (such as receipt failure resets or flag setters after a draft removal) can also leave entries without draft.transactionID.
    • In src/selectors/TransactionDraft.ts, validTransactionDraftIDsSelector reads draft.transactionID instead of falling back to the Onyx key suffix (transactionsDraft_<id>). When a partial draft lacks draft.transactionID, the selector returns undefined, so removeDraftTransactionsByIDs never removes transactionsDraft_<id> and the stub persists across subsequent expense creations.
  2. useOptimisticDraftTransactions checks length > 1 before validating drafts (src/hooks/useOptimisticDraftTransactions.ts):
    • As soon as one valid draft and one partial or bulk-edit draft coexist, optimisticTransactions.length > 1 becomes true and only filters truthiness (Boolean), passing the partial draft to the confirmation list and submission hook.
  3. useTrackExpenseSubmission iterates and submits unvalidated drafts (src/pages/iou/request/step/confirmation/submission/useTrackExpenseSubmission.ts):
    • trackExpense() loops through transactions.entries() without skipping partial drafts lacking both currency and a valid receipt, forwarding them straight into trackExpenseIOUActions.

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

  1. Centralize draft validity and fix ID selection in src/selectors/TransactionDraft.ts:
    • Export isValidTransactionDraft(draft, receipt?): returns false if !draft?.transactionID or draft.transactionID === CONST.IOU.OPTIMISTIC_BULK_EDIT_TRANSACTION_ID; otherwise returns true when the draft has a non-empty currency OR a valid attached receipt (checking both receiptFiles[id], draft.receipt non-empty properties, hasReceiptSource, and hasReceipt, while rejecting cleared empty receipt objects like {source: '', filename: '', type: ''}). This keeps legitimate receipt-only SmartScan drafts (amount: 0, filled later or scanned server-side) intact.
    • Update validTransactionDraftIDsSelector to read Object.entries(drafts ?? {}) and fall back to the ONYXKEYS.COLLECTION.TRANSACTION_DRAFT key suffix when draft.transactionID is missing so cleanup removes orphaned stubs.
    • Update validTransactionDraftsSelector to skip entries without draft.transactionID or CONST.IOU.OPTIMISTIC_BULK_EDIT_TRANSACTION_ID.
  2. Filter before the multi-draft check in src/hooks/useOptimisticDraftTransactions.ts:
    • Filter optimisticTransactions via isValidTransactionDraft before testing validOptimisticTransactions.length > 1, so one valid draft plus one leftover partial/bulk-edit draft cleanly falls back to [transaction].
  3. Guard and clean up skipped drafts in src/pages/iou/request/step/confirmation/submission/useTrackExpenseSubmission.ts:
    • Partition transactions using isValidTransactionDraft(item, receiptFiles[item.transactionID]) into submittableTransactions and skippedDraftTransactionIDs. Return early if submittableTransactions.length === 0.
    • Use submittableTransactions for the linked-tracked check, shouldDeferAutoSubmitForBatchItem, the trackExpenseIOUActions loop, and performPostBatchCleanup({transactions: submittableTransactions, ...}).
    • Merge skippedDraftTransactionIDs into cleanupDraftTransactionIDs passed to trackExpenseIOUActions and performPostBatchCleanup so skipped stubs are cleaned up on completion, and ensure legitimate receipt-only scan drafts missing currency/amount safely default to amount: item.amount ?? 0 and currentUserLocalCurrency.
  4. Tests:
    • Add tests/unit/selectors/TransactionDraftTest.ts and tests/unit/hooks/useOptimisticDraftTransactions.test.ts.
    • Extend tests/unit/hooks/useTrackExpenseSubmission.test.ts with regression cases covering: a populated expense alongside an empty partial draft (asserts 1 call and cleanup of both IDs), a bulk-edit placeholder draft, receipt-only scan drafts without currency, and an all-partial batch no-op.

What alternative solutions did you explore? (Optional)

  • Defaulting missing currency unconditionally in trackExpense() would still turn empty partial stubs into unintended $0 expenses.
  • Filtering only inside useTrackExpenseSubmission would still expose empty stubs as extra confirmation pager entries if multiple drafts are loaded; sharing isValidTransactionDraft across the hook and submission path addresses both layers cleanly.

ryancooper312 avatar Nov 30 '26 02:11 ryancooper312

πŸ“£ @ryancooper312! πŸ“£ 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 30 '26 02:11 melvin-bot[bot]

Proposal

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

When submitting a tracked expense via TrackExpense on the confirmation step, an unintended empty/partial draft transaction (missing currency and amount, with blank merchant/created/comment and no receipt) can be submitted alongside a populated expense. Auth rejects the empty request with 402 Missing currency, wrapped by PHP as a 666 error (Sentry: APP-PPW).

What is the root cause of that problem?

  1. In useOptimisticDraftTransactions.ts, whenever more than one entry exists in ONYXKEYS.COLLECTION.TRANSACTION_DRAFT, every truthy object (!!value) is returned without checking whether the draft is actually populated or valid:
    const allTransactions = optimisticTransactions && optimisticTransactions.length > 1 ? optimisticTransactions : [transaction];
    const transactions = allTransactions.filter((value): value is Transaction => !!value);
    
    A stale/partial leftover draft in Onyx therefore enters the transactions array passed into the confirmation step (useConfirmationTransactionPager.ts).
  2. In useTrackExpenseSubmission.ts, trackExpense iterates directly over every item in transactions (L182) and passes item.currency, item.amount, item.merchant, item.created, and receiptFiles[item.transactionID] directly to trackExpenseIOUActions (L212-L292) without filtering out incomplete/empty drafts that lack a valid currency or expense payload.

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

  1. Add a pure, reusable draft-validation helper (e.g., isValidTrackExpenseDraft in src/pages/iou/request/step/confirmation/submission/utils/) that distinguishes submittable tracked expense drafts from empty/partial leftover drafts while explicitly preserving legitimate receipt-only SmartScan drafts:

    • A draft is invalid/empty and should be skipped if:
      • !item.currency (since TrackExpense strictly requires currency and returns 402 Missing currency without it), OR
      • It has no receipt (!receiptFiles[item.transactionID] && !hasReceipt(item)) and no populated core expense fields (item.amount === undefined && !item.merchant && !item.created && !item.comment?.comment?.trim()).
    • A legitimate receipt-only scan draft (which has receiptFiles[item.transactionID] or hasReceipt(item) and a valid currency, even when amount === 0 and merchant/comment are empty) passes validation and is preserved.
    function isValidTrackExpenseDraft(item: Transaction, receiptFiles: Record<string, Receipt>): boolean {
        if (!item.currency) {
            return false;
        }
    
        const hasAttachedReceipt = !!receiptFiles[item.transactionID] || hasReceipt(item);
        if (hasAttachedReceipt) {
            return true;
        }
    
        const hasExpenseDetails =
            item.amount !== undefined ||
            !!item.merchant?.trim() ||
            !!item.created ||
            !!item.comment?.comment?.trim();
    
        return hasExpenseDetails;
    }
    
  2. Filter out and clean up unintended partial drafts upfront in useTrackExpenseSubmission.ts:

    • Partition transactions at the start of trackExpense into validTransactions and invalidTransactions using isValidTrackExpenseDraft(item, receiptFiles).
    • If validTransactions.length === 0, remove any leftover invalidTransactions from Onyx draft storage (removeDraftTransaction / removeDraftTransactions) and return early without issuing any TrackExpense API call.
    • Run requiresLinkedTracked, the submission for (const [index, item] of validTransactions.entries()) loop, and shouldDeferAutoSubmitForBatchItem (index < validTransactions.length - 1) exclusively against validTransactions β€” this also prevents a trailing empty draft from falsely setting hasNextItem: true and deferring auto-submit on the last valid expense.
    • Ensure invalidTransactions are also cleaned up in Onyx alongside validTransactions (via performPostBatchCleanup receiving the full transactions list or explicitly clearing skipped draft IDs) so the stale partial draft does not persist into subsequent submissions.

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

Add unit / regression tests (e.g., in tests/unit/useTrackExpenseSubmissionTest.ts or alongside existing confirmation submission tests) covering:

  1. Valid expense + empty partial draft in transactions: Only the valid expense invokes trackExpenseIOUActions, the empty draft (missing currency/amount/receipt) is skipped and cleaned up from draft storage, and shouldDeferAutoSubmitForBatchItem treats the valid expense as the last item (hasNextItem: false).
  2. Legitimate receipt-only SmartScan draft: A draft with currency + attached receipt (receiptFiles[transactionID] or item.receipt.source) and amount: 0, blank merchant/comment IS submitted normally.
  3. Only empty/partial draft(s) present: trackExpenseIOUActions is not called at all, and the stray partial draft is cleaned up.
  4. Multiple valid expenses (mixed manual + receipt-only scan) + leftover partial draft: Both valid expenses submit cleanly while the partial draft is skipped and purged.

What alternative solutions did you explore? (Optional)

  • Filtering inside useOptimisticDraftTransactions directly: Considered filtering incomplete drafts inside useOptimisticDraftTransactions, which is shared across intermediate IOU creation steps. However, drafts may legitimately be partially populated during earlier wizard steps before reaching confirmation, so filtering globally there risks breaking intermediate flows. Filtering and purging stale partial drafts at submission time in useTrackExpenseSubmission (with a reusable helper that can also be shared by useRequestMoneySubmission if needed) is tightly scoped, safe, and directly cleans up stale Onyx drafts.

StoneFancyX avatar Nov 30 '26 03:11 StoneFancyX

πŸ“£ @StoneFancyX! πŸ“£ 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 30 '26 03:11 melvin-bot[bot]

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

StoneFancyX avatar Nov 30 '26 04:11 StoneFancyX

βœ… Contributor details stored successfully. Thank you for contributing to Expensify!

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

Proposal

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

When submitting a tracked expense via TrackExpense on the confirmation step, an unintended empty/partial draft transaction (missing currency and amount, with blank merchant/created/comment and no receipt) can be submitted alongside a populated expense. Auth rejects the empty request with 402 Missing currency, wrapped by PHP as a 666 error (Sentry: APP-PPW).

What is the root cause of that problem?

  1. In useOptimisticDraftTransactions.ts, whenever more than one entry exists in ONYXKEYS.COLLECTION.TRANSACTION_DRAFT, every truthy object (!!value) is returned without checking whether the draft is actually populated or valid:
    const allTransactions = optimisticTransactions && optimisticTransactions.length > 1 ? optimisticTransactions : [transaction];
    const transactions = allTransactions.filter((value): value is Transaction => !!value);
    
    A stale/partial leftover draft in Onyx therefore enters the transactions array passed into the confirmation step (useConfirmationTransactionPager.ts).
  2. In useTrackExpenseSubmission.ts, trackExpense iterates directly over every item in transactions (L182) and passes item.currency, item.amount, item.merchant, item.created, and receiptFiles[item.transactionID] directly to trackExpenseIOUActions (L212-L292) without filtering out incomplete/empty drafts that lack a valid currency or expense payload.

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

  1. Add a pure, reusable draft-validation helper (e.g., isValidTrackExpenseDraft in src/pages/iou/request/step/confirmation/submission/utils/) that distinguishes submittable tracked expense drafts from empty/partial leftover drafts while explicitly preserving legitimate receipt-only SmartScan drafts:

    • A draft is invalid/empty and should be skipped if:
      • !item.currency (since TrackExpense strictly requires currency and returns 402 Missing currency without it), OR
      • It has no receipt (!receiptFiles[item.transactionID] && !hasReceipt(item)) and no populated core expense fields (item.amount === undefined && !item.merchant && !item.created && !item.comment?.comment?.trim()).
    • A legitimate receipt-only scan draft (which has receiptFiles[item.transactionID] or hasReceipt(item) and a valid currency, even when amount === 0 and merchant/comment are empty) passes validation and is preserved.
    function isValidTrackExpenseDraft(item: Transaction, receiptFiles: Record<string, Receipt>): boolean {
        if (!item.currency) {
            return false;
        }
    
        const hasAttachedReceipt = !!receiptFiles[item.transactionID] || hasReceipt(item);
        if (hasAttachedReceipt) {
            return true;
        }
    
        const hasExpenseDetails =
            item.amount !== undefined ||
            !!item.merchant?.trim() ||
            !!item.created ||
            !!item.comment?.comment?.trim();
    
        return hasExpenseDetails;
    }
    
  2. Filter out and clean up unintended partial drafts upfront in useTrackExpenseSubmission.ts:

    • Partition transactions at the start of trackExpense into validTransactions and invalidTransactions using isValidTrackExpenseDraft(item, receiptFiles).
    • If validTransactions.length === 0, remove any leftover invalidTransactions from Onyx draft storage (removeDraftTransaction / removeDraftTransactions) and return early without issuing any TrackExpense API call.
    • Run requiresLinkedTracked, the submission for (const [index, item] of validTransactions.entries()) loop, and shouldDeferAutoSubmitForBatchItem (index < validTransactions.length - 1) exclusively against validTransactions β€” this also prevents a trailing empty draft from falsely setting hasNextItem: true and deferring auto-submit on the last valid expense.
    • Ensure invalidTransactions are also cleaned up in Onyx alongside validTransactions (via performPostBatchCleanup receiving the full transactions list or explicitly clearing skipped draft IDs) so the stale partial draft does not persist into subsequent submissions.

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

Add unit / regression tests (e.g., in tests/unit/useTrackExpenseSubmissionTest.ts or alongside existing confirmation submission tests) covering:

  1. Valid expense + empty partial draft in transactions: Only the valid expense invokes trackExpenseIOUActions, the empty draft (missing currency/amount/receipt) is skipped and cleaned up from draft storage, and shouldDeferAutoSubmitForBatchItem treats the valid expense as the last item (hasNextItem: false).
  2. Legitimate receipt-only SmartScan draft: A draft with currency + attached receipt (receiptFiles[transactionID] or item.receipt.source) and amount: 0, blank merchant/comment IS submitted normally.
  3. Only empty/partial draft(s) present: trackExpenseIOUActions is not called at all, and the stray partial draft is cleaned up.
  4. Multiple valid expenses (mixed manual + receipt-only scan) + leftover partial draft: Both valid expenses submit cleanly while the partial draft is skipped and purged.

What alternative solutions did you explore? (Optional)

  • Filtering inside useOptimisticDraftTransactions directly: Considered filtering incomplete drafts inside useOptimisticDraftTransactions, which is shared across intermediate IOU creation steps. However, drafts may legitimately be partially populated during earlier wizard steps before reaching confirmation, so filtering globally there risks breaking intermediate flows. Filtering and purging stale partial drafts at submission time in useTrackExpenseSubmission (with a reusable helper that can also be shared by useRequestMoneySubmission if needed) is tightly scoped, safe, and directly cleans up stale Onyx drafts.

StoneFancyX avatar Nov 30 '26 04:11 StoneFancyX

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

ryancooper312 avatar Nov 30 '26 04:11 ryancooper312

βœ… Contributor details stored successfully. Thank you for contributing to Expensify!

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

Withdrawing my proposal here as I won't be able to take this on β€” please feel free to proceed with other contributors. Thanks!

ryancooper312 avatar Nov 30 '26 04:11 ryancooper312

@MelvinBot post proposal for this issue

Eskalifer1 avatar Nov 30 '26 20:11 Eskalifer1

Proposal

What is the root cause of that problem?

The confirmation flow treats the entire draft collection as one expense batch whenever multiple drafts exist, filtering only falsy values. An empty draft therefore joins the populated expense.

Track submission then submits every batch item without validating currency. The empty item’s missing fields reach TrackExpense, consistent with the Missing currency response documented in this issue.

The empty draft’s origin remains unverified. This proposal addresses its admission into submission, not a confirmed draft-creation race.

Code evidence

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

  1. Partition drafts at confirmation, not throughout the wizard. Exclude only additional drafts matching the reported empty shape: absent amount/currency, blank merchant/date/comment, and no receipt or other expense payload. Preserve the initial/current draft, zero amounts, receipt-bearing drafts, distance/per-diem data, and unfamiliar fields rather than assuming they are disposable.
  2. Validate before submission or dismissal. If a retained draft lacks required currency, stop before any writes, preserve the drafts, and surface a recoverable validation error. Do not silently discard meaningful expenses or invent currency.
  3. Use the retained batch consistently for the pager, submission loop, final-item auto-submit handling, and post-submit metadata.
  4. Clean up by actual storage keys. After successful submission, remove submitted drafts and excluded empty extras using captured collection-key IDsβ€”not potentially missing embedded IDs. Do not delete drafts during rendering or failed validation.
Implementation locations and regression tests

Use the confirmation-specific useConfirmationTransactionPager.ts:25–36, leaving intermediate wizard consumers unchanged.

Validation must also precede the dismissal path in SubmitExpenseOrchestrator.tsx:478–484.

The existing cleanup selector trusts embedded IDs: TransactionDraft.ts:13–19.

Regression coverage:

  • Valid expense plus empty extra, in either order: exactly one submission.
  • Empty extra with/without embedded ID: correct storage-key cleanup.
  • Receipt-only scans, zero/negative amounts, distance and per-diem drafts remain intact.
  • Meaningful missing-currency draft: no writes, dismissal, or cleanup.
  • Two valid expenses plus empty extra: correct final-item auto-submit behavior.

What alternative solutions did you explore? (Optional)

  • Global completeness filtering: risks hiding legitimately incomplete wizard drafts.
  • Defaulting missing currency: masks malformed input and can create unintended expenses.
  • Submission-loop-only filtering: leaves the pager, batch bookkeeping, and cleanup inconsistent.

Confidence: Medium; code-supported mechanism, without a reproduced origin for the production draft.


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


view run

MelvinBot avatar Nov 30 '26 20:11 MelvinBot

@MelvinBot Do you have likely steps to repro this one? Try to find them

Eskalifer1 avatar Dec 01 '26 16:12 Eskalifer1

πŸ€– Web test steps verification results: ❌ fail

Both candidate scenarios require same-account two-tab orchestration, which the available browser-testing tool does not support. Neither was executed; these are code-supported candidate steps, not confirmed reproductions.

Step Status
Candidate 1: introduce bulk edit after preparing an expense1. Open two browser tabs signed into the same account.
2. In tab A, prepare a valid manual personal expense and leave confirmation open.
3. In tab B, select two editable expenses in Search and choose Edit multiple.
4. Leave that panel open without changing anything.
5. Return to A and submit. Check for an extra pager item and a second TrackExpense request missing amount/currency.
Why plausible: opening bulk edit writes an amount/currency-free placeholder into the shared draft collection; its cleanup runs on panel unmount. See BulkEdit.ts:944–968.
Not verified: cross-tab propagation, submission, or error.
❌
Candidate 2: recreate an ID-less draft from a still-open bulk editor β€” strongest match for repeated failures1. In tab B, open Edit multiple for two expenses.
2. In tab A, start a new personal expense and reach confirmation. Starting this flow should clear B’s original draft.
3. Return to B without reopening its panel. Type a character into Merchant, then erase it completely. Do not save or dismiss.
4. Return to A and submit.
5. Create another expense to check whether the empty extra persists.
Why plausible: the merchant handler merges into the bulk-edit key without restoring transactionID, potentially recreating it as an empty-merchant shell. Cleanup reads embedded IDs rather than storage keys, so that shell could survive. See SearchEditMultiplePage.tsx:319–325 and TransactionDraft.ts:13–19.
Not verified: whether the cleared editor remains interactive or produces the reported request.
❌

view run

MelvinBot avatar Dec 01 '26 16:12 MelvinBot

I was not able to repro this one. I think this is happening in one tab and we already have 60 events in a couple of days. I'm gonna open it for external contributors, maybe someone will find reliable steps to reproduce this one.

Note for contributors: In order for your proposal to be selected you should be able to repro the bug and add steps to reproduce

Eskalifer1 avatar Dec 01 '26 17:12 Eskalifer1

🚨 Edited by proposal-police: This proposal was edited at 2026-12-01 19:20:09 UTC.

Proposal

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

When an expense is created, a second, empty "expense" can be sent with it: TrackExpense with no amount, currency, merchant, date, comment or receipt. The server rejects it with 402 Missing currency (666). We need the confirmation step to send only the expenses the user is actually creating, keep real receipt-only scan drafts working, and stop leftover drafts from building up in the first place.

What is the root cause of that problem?

The confirmation step decides what to send from the whole draft collection. If more than one draft exists, it takes every truthy one:

https://github.com/Expensify/App/blob/11696bb3c5afb092f27d7e0c6053c4f30874be63/src/hooks/useOptimisticDraftTransactions.ts#L15-L24

https://github.com/Expensify/App/blob/11696bb3c5afb092f27d7e0c6053c4f30874be63/src/pages/iou/request/step/confirmation/submission/useTrackExpenseSubmission.ts#L182

So any draft that isn't part of this expense becomes a second request. There are two ways such a draft ends up in the collection.

1. Bulk edit keeps its own draft in the same collection. Search > select > Edit multiple stores {transactionID: 'optimisticBulkEditTransactionID', selectedTransactionIDs} as a transaction draft. That is exactly the empty request in the logs: no amount, currency, merchant, date, comment or receipt.

https://github.com/Expensify/App/blob/11696bb3c5afb092f27d7e0c6053c4f30874be63/src/libs/actions/IOU/BulkEdit.ts#L950-L962

It's only removed in the bulk edit page's unmount cleanup:

https://github.com/Expensify/App/blob/11696bb3c5afb092f27d7e0c6053c4f30874be63/src/pages/Search/SearchEditMultiple/SearchEditMultiplePage.tsx#L224-L228

Its value has a matching transactionID, so clearMoneyRequest also removes it the next time an expense is started. That means a copy left by a closed tab can't reach a submit. It reaches one when it's created while an expense flow is already open: Onyx keeps tabs in sync on web, so opening Edit multiple in a second tab while the confirmation page is open in the first adds it to the first tab's list. The issue's route is /search, which is where bulk edit lives.

2. Leftover drafts can't be cleaned up when their value has no transactionID. Starting a new expense clears the old drafts using IDs from this selector:

https://github.com/Expensify/App/blob/11696bb3c5afb092f27d7e0c6053c4f30874be63/src/selectors/TransactionDraft.ts#L13-L19

It reads draft.transactionID from the value, not the Onyx key. Actions write into drafts with Onyx.merge (there are 32 such calls under src/libs/actions). A merge that lands after a draft was removed recreates the key with only the merged fields and no transactionID. For that draft the selector returns undefined, so clearMoneyRequest removes transactionsDraft_undefined, and the real key survives every future cleanup:

https://github.com/Expensify/App/blob/11696bb3c5afb092f27d7e0c6053c4f30874be63/src/libs/actions/TransactionEdit.ts#L117-L132

From then on, every expense flow sees "more than one draft" and sends that leftover too. That fits 24 events from one user: the leftover is still there on every submit.

useOptimisticDraftTransactions is shared by the confirmation pager, participant selection, the report picker and the submission, so the same leftover also shows up and gets sent in the Submit and Split paths, not only Track.

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

Fix it on both sides: never treat a non-expense draft as part of the expense, and make sure every leftover can actually be cleaned up.

  1. One definition of "a draft of this expense flow", in src/selectors/TransactionDraft.ts, built from the Onyx key:
/** A draft belongs to an expense flow when it's stored under its own transactionID. Bulk edit's draft and fragments recreated by a late merge don't. */
function isExpenseFlowDraft(key: string, draft: OnyxEntry<Transaction>): draft is Transaction {
    const transactionID = key.replace(ONYXKEYS.COLLECTION.TRANSACTION_DRAFT, '');
    return !!draft && draft.transactionID === transactionID && transactionID !== CONST.IOU.OPTIMISTIC_BULK_EDIT_TRANSACTION_ID;
}
  1. useTransactionDraftValues returns only isExpenseFlowDraft entries. So useOptimisticDraftTransactions falls back to the current transaction when the only "other" draft is bulk edit's or a fragment, and all seven callers (confirmation pager, participant selection, participant submission, report picker and the three scan components) see the same correct list.

  2. Cleanup by key, so nothing can get stuck. validTransactionDraftIDsSelector returns the key suffix of every draft, instead of draft.transactionID:

const validTransactionDraftIDsSelector = (drafts: OnyxCollection<Transaction>): string[] =>
    Object.entries(drafts ?? {}).reduce<string[]>((acc, [key, draft]) => {
        const transactionID = key.replace(ONYXKEYS.COLLECTION.TRANSACTION_DRAFT, '');
        if (draft) {
            acc.push(transactionID);
        }
        return acc;
    }, []);

startMoneyRequest / initMoneyRequest and the post-submit cleanup already remove every ID this returns, so a fragment is now deleted the next time any expense is started or created. validTransactionDraftsSelector gets the same key-based change.

Bulk edit's draft stays in the cleanup list, as it is today, so a copy left by a closed tab is still removed the next time an expense is started. It's only kept out of the list of expenses to show and send.

  1. Last guard before the request. Before the submission loop, drop a transaction with no currency and log it, instead of sending a request the server will reject. It's filtered before the loop, not skipped inside it, so nextTransaction / hasNextItem for auto-submit deferral are computed on the list that is really sent:
const submittableTransactions = transactions.filter((item) => {
    if (item.currency) {
        return true;
    }
    Log.warn('[useTrackExpenseSubmission] Skipped a draft without currency', {transactionID: item.transactionID});
    return false;
});
for (const [index, item] of submittableTransactions.entries()) {
    const shouldDeferAutoSubmit = shouldDeferAutoSubmitForBatchItem({
        nextTransaction: submittableTransactions.at(index + 1),
        hasNextItem: index < submittableTransactions.length - 1,

Every real draft gets a currency from initMoneyRequest (overrideCurrency ?? policy outputCurrency ?? personal outputCurrency ?? USD), including receipt-only scan drafts, so this never skips a real expense. It only stops a malformed one if a third source ever appears. useRequestMoneySubmission is the only other submission hook that loops over this transactions list, so it gets the same guard.

Other places and why they are not broken

  • Multi-receipt scan drafts are created by buildOptimisticTransactionAndCreateDraft under their own transactionID with a currency, so they still count as "more than one draft" and are all submitted.
  • Receipt-only scan drafts have a currency from initMoneyRequest, so the guard in step 4 leaves them alone.
  • Bulk edit itself reads and writes its draft by its fixed key, which none of these changes touch. Its cleanup works the same as today.
  • The default draft 1 is stored under its own ID, so it passes isExpenseFlowDraft. initMoneyRequest still keeps it through shouldExcludeInitialTransaction.
  • startMoneyRequest sets {isFromFloatingActionButton} on draft 1 before initMoneyRequest fills it. Until then that value has no transactionID, so it isn't counted as a second expense, which is correct. The key-based cleanup still removes it.

Tests

  • TransactionDraft selectors: a draft whose value has no transactionID is returned by key, so it can be cleaned up; normal drafts are unchanged; isExpenseFlowDraft is false for bulk edit's draft and for a fragment.
  • useOptimisticDraftTransactions: draft 1 + bulk edit draft gives [transaction]; draft 1 + a fragment without transactionID gives [transaction]; two real scan drafts give both.
  • useTrackExpenseSubmission (extending its existing test): a populated expense + bulk edit draft makes one trackExpense call; a populated expense + a currency-less transaction makes one call and logs; two receipt-only scan drafts make two calls.
  • Cleanup: after startMoneyRequest, a fragment key without transactionID is gone.

Manual check on web:

  1. In tab A, start a tracked expense and stop on the confirmation page.
  2. In tab B, select expenses in Search > Edit multiple.
  3. Back in tab A, submit. Only one TrackExpense should be sent, with no 666.
  4. Repeat with two receipts dropped onto Search. Two expenses should be sent.

What alternative solutions did you explore? (Optional)

  • Only filter drafts without currency at submit. It hides the symptom, but the leftover stays in storage forever, keeps showing up in the confirmation pager and report picker, and grows with every new fragment.
  • Skip drafts without transactionID in the selectors. That filters them out, but it also means they can never be cleaned up, because cleanup works from the same IDs.
  • Move bulk edit's draft to its own Onyx key. It's cleaner long term, but it touches every bulk edit page and action. Excluding its fixed ID gives the same safety with a much smaller change.

dostonbunyodov0006 avatar Dec 01 '26 17:12 dostonbunyodov0006