App icon indicating copy to clipboard operation
App copied to clipboard

[$250] Expense Coding Reverts to Default After Credit Card Transaction Import and Merge

Open m-natarajan opened this issue 7 months ago • 56 comments

If you haven’t already, check out our contributing guidelines for onboarding and email [email protected] to request to join our Slack channel!


Version Number: Reproducible in staging?: Needs Reproduction (Reproduction blocked) Reproducible in production?: Needs Reproduction If this was caught during regression testing, add the test name, ID and link from BrowserStack: Email or phone of affected tester (no customers): Logs: https://stackoverflow.com/c/expensify/questions/4856 Expensify/Expensify Issue URL: Issue reported by: @EmilioRojasBlanco Slack conversation (hyperlinked to channel name): #Expensify Bugs

Action Performed:

  1. Upload a receipt for a card transaction
  2. Observe Concierge auto-assigns coding (e.g., category/tag based on rules)
  3. Manually update the expense tag
  4. Wait for the credit card transaction to be imported
  5. Allow the system to auto-merge the transaction with the receipt
  6. Check the expense tag

Expected Result:

After merge: User-updated tag should be preserved System should not override manual changes

Actual Result:

Tag is reset/reverted based on: Personal expense rules Default system logic User’s manual updates are lost

Workaround:

Unknown

Platforms:

Select the officially supported platforms where the issue was reproduced:

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

Screenshots/Videos

The screenshot for the issue is in Slack thread

View all open jobs on GitHub

Upwork Automation - Do Not Edit
  • Upwork Job URL: https://www.upwork.com/jobs/~022041879648199782405
  • Upwork Job ID: 2041879648199782405
  • Last Price Increase: 2026-04-29
Issue OwnerCurrent Issue Owner: @eh2077

m-natarajan avatar Apr 08 '26 13:04 m-natarajan

Proposal

What is the root cause of that problem?

This is a backend issue. When a credit card transaction imports and auto-merges (SmartMatch) with an existing SmartScanned receipt, the backend re-applies personal expense rules and/or workspace coding rules, overwriting the user's manually-set tag/category.

The App frontend has no involvement in the auto-merge — it's entirely server-side. Critically, the Transaction type (Transaction.ts:518-598) tracks modifiedMerchant, modifiedAmount, modifiedCreated, modifiedCurrency, and modifiedMCCGroup — but there are no modifiedTag or modifiedCategory fields. This means the backend has no way to know whether a user manually changed the tag/category, and therefore cannot protect those values from being overwritten during auto-merge rule application.

The flow is:

  1. User scans a receipt → backend creates transaction with rter violation (pendingPattern=true)
  2. User manually updates the tag/category on the expense
  3. Card transaction imports → backend auto-merges, then re-applies personal expense rules (ExpenseRule) and/or workspace coding rules (CodingRule) based on merchant matching
  4. User's manual tag is overwritten because no modifiedTag flag exists to protect it

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

This requires a backend fix (Auth server), not an App change. The fix should:

  1. Add modifiedTag and modifiedCategory tracking to the transactions data model, similar to the existing modifiedMerchant/modifiedAmount fields
  2. Set these flags when a user manually updates tag or category
  3. Check these flags during auto-merge rule application — if a field has been manually modified, skip re-applying rules for that field

On the App side, the Transaction type in src/types/onyx/Transaction.ts would need to be updated to include the new modifiedTag and modifiedCategory fields once the backend supports them.

What alternative solutions did you explore? (Optional)

An alternative would be to skip rule re-application entirely during auto-merge (preserve all receipt field values unless the card transaction has a non-empty value). However, this would break the expected behavior for users who want rules applied to card-imported expenses. The modifiedTag/modifiedCategory flag approach is more surgical — it only protects fields the user explicitly changed.

Investigation details

Key code references:

Note: The Auth/Web-Expensify backend repos are not available in this workspace. The auto-merge logic is entirely server-side. The analysis above is based on the App frontend types and merge logic which mirror backend behavior, plus the documented SmartMatch criteria.


Next Steps for Contributor+ team: Reply with @MelvinBot implement this to create a draft PR, @MelvinBot <your feedback> to refine this analysis, or explain why you are rejecting Melvin's proposal.

MelvinBot avatar Apr 08 '26 14:04 MelvinBot

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

melvin-bot[bot] avatar Apr 08 '26 14:04 melvin-bot[bot]

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

melvin-bot[bot] avatar Apr 08 '26 14:04 melvin-bot[bot]

🚨 Edited by proposal-police: This proposal was edited at 2026-04-22 19:22:01 UTC.

Replaces my earlier proposal. The prior version pointed at buildMergedTransactionData in MergeTransactionUtils.ts (the client-side, user-initiated merge UI) and suggested adding new modifiedCategory / modifiedTag schema fields. After tracing the edit flow locally, the real root cause is in getUpdatedTransaction — the existing shouldStopSmartscan gate is simply not set for tag/category edits, so the receipt never transitions out of SmartScan-managed state. The fix is a small change in that function, not a schema addition.

Proposal

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

A user uploads a receipt for an upcoming card transaction, Concierge auto-applies coding via personal expense rules or workspace coding rules, and the user then manually updates the expense tag (or category). When the card transaction later imports and SmartMatch auto-merges it with the receipt, the user's manual tag/category is lost and the rule-based default is written back. Per docs/articles/new-expensify/reports-and-expenses/Why-Expenses-Duplicate.md, manually edited expenses are supposed to be excluded from auto-merge; that rule is not being enforced for tag/category edits.

What is the root cause of that problem?

Trigger — user saves a tag/category edit. The flow is updateMoneyRequestTag / updateMoneyRequestCategory → getUpdateMoneyRequestParams → getUpdatedTransaction in src/libs/TransactionUtils/index.ts.

Mechanism — getUpdatedTransaction has a shared shouldStopSmartscan gate that is set to true for every other user-authored edit (created, amount, currency, merchant, waypoints, customUnitRateID, distance). Later in the same function, that flag flips receipt.state to OPEN, which is the existing, API-persisted mechanism for removing a SmartScan-managed receipt from the auto-managed pipeline. The category and tag branches do not set this flag.

https://github.com/Expensify/App/blob/5f1063a7c03a3a9c4f4a2a05db4e44938f28cd27/src/libs/TransactionUtils/index.ts#L695-L721

https://github.com/Expensify/App/blob/5f1063a7c03a3a9c4f4a2a05db4e44938f28cd27/src/libs/TransactionUtils/index.ts#L831-L842

https://github.com/Expensify/App/blob/5f1063a7c03a3a9c4f4a2a05db4e44938f28cd27/src/libs/TransactionUtils/index.ts#L852-L861

Impact — after a manual tag/category edit, the receipt stays in SmartScan-managed state. When the card transaction imports, backend SmartMatch treats the receipt as auto-merge-eligible and re-applies personal / workspace coding rules on merge, overwriting the user's manual value.

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

Treat manual category and tag edits the same way every other user-authored expense edit is already treated:

  1. In getUpdatedTransaction (src/libs/TransactionUtils/index.ts), inside the existing category branch, set shouldStopSmartscan = true immediately after the updatedTransaction.category = transactionChanges.category assignment.
  2. In the same function, inside the existing tag branch, set shouldStopSmartscan = true immediately after the updatedTransaction.tag = transactionChanges.tag assignment.
  3. No other code needs to change. The existing block at L852–L861 already flips receipt.state to OPEN when shouldStopSmartscan is true, the receipt exists, and it is not already OPEN. The updated receipt.state is already persisted through the existing UPDATE_MONEY_REQUEST_TAG / UPDATE_MONEY_REQUEST_CATEGORY API calls in src/libs/actions/IOU/UpdateMoneyRequest.ts, so the backend also stops treating the transaction as SmartScan-managed and SmartMatch no longer auto-merges the card import into it.
  4. Add unit coverage around getUpdatedTransaction: (a) editing category on a SmartScan receipt flips receipt.state to OPEN, (b) same for tag, (c) editing either on a receipt already OPEN is idempotent, (d) editing either on a transaction without a receipt does not throw or create a receipt object.

Scope boundaries — the change is limited to the category and tag branches of getUpdatedTransaction in src/libs/TransactionUtils/index.ts. It applies to all platforms (web, iOS, Android, desktop, mWeb) via that shared util. No Transaction onyx schema change, no new fields, and no API contract change. The MergeTransactionUtils manual-merge UI, the compareDuplicateTransactionFields duplicate-review flow, and other non-edit callers of tag/category (violations, optimistic data builders, etc.) are explicitly not touched.

What alternative solutions did you explore? (Optional)

Add modifiedCategory / modifiedTag fields to the Transaction schema, symmetric with the existing modifiedAmount, modifiedCreated, modifiedCurrency, and modifiedMerchant fields. This is the direction the MelvinBot proposal took. It is correct that a modified-field marker would protect user edits in principle, but it is strictly broader than necessary — it requires Auth-server support to honor the flags during SmartMatch rule re-application, and it duplicates behavior that Expensify already models through the shared SmartScan-stop receipt-state flow. Reusing the existing mechanism is cleaner, app-only, and does not introduce new per-field merge metadata.

Special-case SmartMatch or the duplicate-review flow to always prefer the receipt-side category/tag (for example, changing the keep fallback in compareDuplicateTransactionFields when one side is a card import). This only helps once the transaction has already reached the duplicate-review UI, does not prevent the silent auto-merge path described in the issue, and pushes more field-specific logic into merge behavior instead of reusing the shared "manual edit stops automation" pattern.

KJ21-ENG avatar Apr 08 '26 14:04 KJ21-ENG

Proposal

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

When a user uploads a receipt for a future card transaction, lets Concierge auto-assign coding, and then manually changes the expense tag or category before the card transaction imports, the later SmartMatch auto-merge still runs and the imported card transaction’s coding wins. The user’s manual coding change is lost.


What is the root cause of that problem?

The bug is in the shared money-request update path, not in the merge UI itself.

Manual edits to an existing expense go through updateMoneyRequestTag() / updateMoneyRequestCategory() in src/libs/actions/IOU/UpdateMoneyRequest.ts, which call getUpdateMoneyRequestParams() in src/libs/actions/IOU/index.ts. That helper builds the optimistic updated transaction through getUpdatedTransaction() in src/libs/TransactionUtils/index.ts.

Inside getUpdatedTransaction(), Expensify already has a shouldStopSmartscan gate. For user edits like created, amount, currency, merchant, waypoints, and distance rate, that flag is set to true, and the common receipt-state block later flips receipt.state to OPEN. That is the existing mechanism that takes a SmartScanned receipt out of the auto-managed SmartScan flow.

However, category and tag edits do not set shouldStopSmartscan. So after a user manually changes coding, the transaction still remains in the SmartScan-managed state. That leaves it eligible for the later SmartMatch auto-merge, even though our own doc at docs/articles/new-expensify/reports-and-expenses/Why-Expenses-Duplicate.md says edited expenses should not auto-merge.

Once the card transaction imports, the merge path still prefers the card transaction as the merge target (selectTargetAndSourceTransactionsForMerge() in src/libs/MergeTransactionUtils.ts), so the user never reaches the manual conflict-resolution flow for tag / category. The imported card transaction’s coding becomes canonical and the user’s manual change disappears.


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

We should treat manual category and tag edits the same way we already treat other user-authored expense edits that stop SmartScan automation.

The smallest, most maintainable fix is to update getUpdatedTransaction() so that changing category or tag also sets shouldStopSmartscan = true. That makes the existing shared receipt-state logic mark the receipt as OPEN, which removes the transaction from the auto-managed SmartScan path before the card import arrives.

This is a better fit for the current architecture than introducing brand-new modifiedCategory / modifiedTag fields, because Expensify already has a shared “user edited this expense, stop SmartScan automation” mechanism. We should reuse that mechanism instead of adding another layer of per-field merge metadata.

Implementation

// File: src/libs/TransactionUtils/index.ts

@@
     if (Object.hasOwn(transactionChanges, 'category') && typeof transactionChanges.category === 'string') {
         updatedTransaction.category = transactionChanges.category;
+        shouldStopSmartscan = true;
         const {categoryTaxCode, categoryTaxAmount} = getCategoryTaxCodeAndAmount(transactionChanges.category, transaction, policy);
         if (categoryTaxCode && categoryTaxAmount !== undefined) {
             updatedTransaction.taxCode = categoryTaxCode;
             updatedTransaction.taxAmount = categoryTaxAmount;
         }
@@
     if (Object.hasOwn(transactionChanges, 'tag') && typeof transactionChanges.tag === 'string') {
         updatedTransaction.tag = transactionChanges.tag;
+        shouldStopSmartscan = true;
     }

This works because it reuses the existing receipt-state transition already handled later in the same function. It is safe because it only affects user-initiated edits in the persisted money-request update flow, and it is targeted to the two fields involved in the bug. It also avoids regressions in manual merge behavior, since if the user later merges intentionally, MergeTransactionUtils already treats differing category / tag values as conflicts instead of silently overwriting them.

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

None

What alternative solutions did you explore? (Optional)

Adding modifiedCategory / modifiedTag fields to the transaction model is possible, but it is a broader schema change and duplicates behavior that Expensify already models through the existing SmartScan-stop receipt-state flow.

Special-casing SmartMatch to always preserve receipt-side category/tag is also weaker, because it still allows an edited expense to remain in the auto-merge pipeline and pushes more field-specific logic into merge behavior instead of reusing the current shared “manual edit stops automation” pattern.

MassoudFSharifi avatar Apr 08 '26 14:04 MassoudFSharifi

⚠️ @MassoudFSharifi Your proposal is a duplicate of an already existing proposal and has been automatically withdrawn to prevent spam. Please review the existing proposals before submitting a new one.

github-actions[bot] avatar Apr 08 '26 14:04 github-actions[bot]

Proposal

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

When a user manually updates an expense tag on a receipt and then allows the system to merge it with an imported credit card transaction, the user's manual tag is silently discarded in favor of the tag that was auto-applied by personal expense rules.

What is the root cause of that problem?

The root cause is in compareDuplicateTransactionFields in src/libs/TransactionUtils/index.ts, specifically the tag field path (lines 2510–2529).

When the user enters the duplicate review flow (triggered by the DUPLICATED_TRANSACTION violation after a card import matches a receipt), this function decides which fields go to change (user must pick) vs keep (silently auto-selected). For tag, a conflict is only surfaced when there are two or more enabled policy tags among the differing values, or exactly one enabled policy tag plus an empty option:

https://github.com/Expensify/App/blob/c96612144e9666b79743fd92df466e6da7ad30af/src/libs/TransactionUtils/index.ts#L2524
if (!areAllFieldsEqualForKey && policy?.areTagsEnabled && (availableTags.length > 1 || (availableTags.length === 1 && differentValues.includes('')))) {
    change[fieldName] = [...availableTags, ...(differentValues.includes('') ? [''] : [])];
} else {
    keep[fieldName] = firstTransaction?.[keys[0]] ?? firstTransaction?.[keys[1]]; // L2527
}

When this condition is not met (e.g., the user manually set a tag that is no longer an enabled policy tag, or policy tags are disabled), the code falls to the keep path and blindly uses firstTransaction.tag. Since firstTransaction = transactions.at(0) = reviewingTransaction, and the reviewing transaction is typically the credit card transaction (which received a tag from personal expense rules at import), the receipt's manually-set user tag is silently lost.

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

In the keep fallback for the tag field at line 2527, when one transaction is a credit card import and the other is not, prefer the non-card transaction's tag. The card's tag comes from auto-applied personal expense rules; the receipt's tag is more likely to carry the user's manual override.

The same silent-override bug applies to category at line 2508, so the same fix should be applied there.

src/libs/TransactionUtils/index.ts — change the keep fallback for tag (and symmetrically for category):

// tag — line ~2527
} else {
    // When merging a credit card import with a receipt, prefer the non-card (receipt)
    // transaction's tag since it's more likely to carry a user's manual update.
    // Card transaction tags are typically auto-set by personal expense rules on import.
    const nonCardTransaction = transactions.find((t) => !isFromCreditCardImport(t));
    if (!areAllFieldsEqualForKey && nonCardTransaction && transactions.some((t) => isFromCreditCardImport(t))) {
        keep[fieldName] = nonCardTransaction?.[keys[0]];
    } else {
        keep[fieldName] = firstTransaction?.[keys[0]] ?? firstTransaction?.[keys[1]];
    }
}
// category — line ~2508 (same pattern)
} else {
    const nonCardTransaction = transactions.find((t) => !isFromCreditCardImport(t));
    if (!areAllFieldsEqualForKey && nonCardTransaction && transactions.some((t) => isFromCreditCardImport(t))) {
        keep[fieldName] = nonCardTransaction?.[keys[0]];
    } else {
        keep[fieldName] = firstTransaction?.[keys[0]] ?? firstTransaction?.[keys[1]];
    }
}

isFromCreditCardImport is already defined and exported in this same file at line 1352, so no new imports are needed. This is a minimal, targeted change: it only alters behavior when (a) tags are not equal, (b) one transaction is a card import and the other is not, and (c) a conflict was not already surfaced to the user.

Contributor Details
Field Value
Contributor email [email protected]
Upwork Profile https://www.upwork.com/freelancers/~01d016059c6701ebaa

Ltbltbltbltb avatar Apr 08 '26 14:04 Ltbltbltbltb

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

melvin-bot[bot] avatar Apr 13 '26 21:04 melvin-bot[bot]

📣 It's been a week! Do we have any satisfactory proposals yet? Do we need to adjust the bounty for this issue? 💸

melvin-bot[bot] avatar Apr 15 '26 16:04 melvin-bot[bot]

@situchan 6 days overdue. This is scarier than being forced to listen to Vogon poetry!

melvin-bot[bot] avatar Apr 15 '26 21:04 melvin-bot[bot]

@situchan 8 days overdue is a lot. Should this be a Weekly issue? If so, feel free to change it!

melvin-bot[bot] avatar Apr 17 '26 21:04 melvin-bot[bot]

@situchan 12 days overdue now... This issue's end is nigh!

melvin-bot[bot] avatar Apr 21 '26 21:04 melvin-bot[bot]

📣 It's been a week! Do we have any satisfactory proposals yet? Do we need to adjust the bounty for this issue? 💸

melvin-bot[bot] avatar Apr 22 '26 16:04 melvin-bot[bot]

reviewing proposals

situchan avatar Apr 22 '26 16:04 situchan

@situchan this issue was created 2 weeks ago. Are we close to approving a proposal? If not, what's blocking us from getting this issue assigned? Don't hesitate to create a thread in #expensify-open-source to align faster in real time. Thanks!

melvin-bot[bot] avatar Apr 22 '26 21:04 melvin-bot[bot]

@situchan Huh... This is 4 days overdue. Who can take care of this?

melvin-bot[bot] avatar Apr 27 '26 21:04 melvin-bot[bot]

📣 It's been a week! Do we have any satisfactory proposals yet? Do we need to adjust the bounty for this issue? 💸

melvin-bot[bot] avatar Apr 29 '26 16:04 melvin-bot[bot]

@MelvinBot implement this

situchan avatar Apr 29 '26 20:04 situchan

🤖 Draft PR created: https://github.com/Expensify/App/pull/89216 Please mark it as "Ready for review" when it is ready for review.

MelvinBot avatar Apr 29 '26 20:04 MelvinBot

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

melvin-bot[bot] avatar May 04 '26 21:05 melvin-bot[bot]