Skip to content

[Due for payment 2026-07-21] [$250] CSV upload in New Expensify blocks repeat card assignment for a second batch #95010

Closed

Description

@m-natarajan

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


Version Number: 9.4.17-3
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: @scerrato88
Slack conversation (hyperlinked to channel name): #Expensify Bugs

Action Performed:

  1. Upload a CSV batch for a card transactions in New Expensify.
  2. Confirm the card is assigned and expenses are processed.
  3. Upload a second CSV batch for the same card number.
  4. Observe that New Expensify does not allow the user to map or assign the expenses to the existing card again.

Expected Result:

Users should be able to upload multiple CSV batches for the same card number and manually assign them to that card each time, consistent with Expensify Classic.

Actual Result:

The upload is blocked with an error indicating that the card is already assigned.

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
  • Windows: Chrome
  • 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
Issue OwnerCurrent Issue Owner: @mallenexpensify

Activity

  1. added
    BugSomething is broken. Auto assigns a BugZero manager.
    on Jun 30, 2026
  2. exfy-zapier commented on Jun 30, 2026

    @exfy-zapier

    This has been labelled "Needs Reproduction". Follow the steps here: https://stackoverflowteams.com/c/expensify/questions/16989

  3. MelvinBot commented on Jun 30, 2026

    @MelvinBot
    Contributor

    Issue Analysis

    Root Cause: The CSV upload itself is not blocked — the block happens at the assign step. When a user tries to assign a card number that is already assigned in the same workspace/feed (which is the case after batch #1), a client-side guard in App short-circuits the assignment and shows a misleading "already assigned to a user in another workspace" error. There are two layers:

    1. The hard block + error — ConfirmationStep.tsx:116-122 calls isCardAlreadyAssigned() and, if true, sets cardAlreadyAssignedError and returns without calling the assign API.
    2. The decision — isCardAlreadyAssigned in CardUtils.ts:1574-1617 returns true whenever the card number already exists in WORKSPACE_CARDS_LIST for the same domain/workspace + feed. Its own comment (L1599-L1605) states that genuine cross-account duplicates are "rejected server-side by ASSIGN_COMPANY_CARD — the same path Expensify Classic uses, which is why the identical assignment succeeds there."

    The user-facing string is misleading: en.ts:5706 — cardAlreadyAssignedError: 'This card is already assigned to a user in another workspace.' — but the guard fires for same-workspace/same-feed re-assignment too, which is exactly the repeat-batch case here.

    ⚠️ This issue is Needs Reproduction (Reproduction blocked). The code path above is verified, but it's unconfirmed which of two NewDot behaviors the reporter actually hit (see below), so treat the recommended fix as a starting direction pending repro.

    The product question that decides the real fix: In NewDot the model is assign the card once, and subsequent transaction batches flow into the already-assigned card automatically — you are not expected to re-assign per batch the way Classic works. So either:

    • (A) The second batch's transactions do import into the already-assigned card — then the user simply shouldn't be in the assign flow again, and this is a copy/UX problem (the misleading error + the card reappearing as assignable). This part is fixable in App.
    • (B) The second batch's transactions don't attach to the existing card (a duplicate unassigned card is created server-side, forcing re-assignment) — then the real bug is in the backend IMPORT_CSV_COMPANY_CARDS / card-import logic (Web-Expensify/Auth), which is outside the App repo. Per our policy I can't propose code there — this would need an internal engineer with backend access.
    Investigation details

    Upload is allowed: importCSVCompanyCards always fires IMPORT_CSV_COMPANY_CARDS (CompanyCards.ts:1128+). No "already assigned" copy exists in the upload/column-mapping step — only csvErrors.requiredColumns / csvErrors.duplicateColumns.

    Secondary, quieter block: getFilteredCardList (CardUtils.ts:994-1034, consumed at CardSelectionStep.tsx:57) removes already-assigned cardNames from the selectable list. If everything is filtered out, the user sees the noActiveCards empty state instead of the explicit error. So the reporter may see either the "already assigned" error or the card silently missing — useful to nail down during repro.

    Data flow: upload batch #1 → assign card (card lands in WORKSPACE_CARDS_LIST) → upload batch #2 (succeeds) → re-assign attempt → isCardAlreadyAssigned returns true → error, no API call.

    Alternative explanations considered: duplicateFeedModal (en.ts:5644) is about adding the same feed twice, not the same card — not this issue.

    If fix lands in App (scenario A): candidates are (1) correct the misleading copy, and/or (2) scope isCardAlreadyAssigned so a custom/CSV (ccupload) feed re-upload of an already-assigned card in the current feed isn't treated as a blocking duplicate — and let the server (ASSIGN_COMPANY_CARD) be the arbiter, matching Classic. This needs a product call on whether re-assigning the same card is ever valid for CSV feeds.

    Verified against App at SHA c49419e.

    Related issues: no open duplicates found. Closed Expensify/App#86814 ("Imported card feed only appears after importing for the second time") is in the same CSV-import area and worth a glance, though not the same symptom.


    Next Steps for Contributor+ team:
    To accept: @MelvinBot implement [this](https://github.com/Expensify/App/issues/95010) to create a draft PR (App-side copy/guard scoping — scenario A only).
    To refine: @MelvinBot <your feedback> — especially repro confirming whether batch-2 transactions auto-import (A) or a duplicate card is created (B, backend).
    To reject: Explain why you are rejecting Melvin's proposal.

  4. added
    ExternalAdded to denote the issue can be worked on by a contributor
    on Jun 30, 2026
  5. kitvasyl commented on Jun 30, 2026

    @kitvasyl

    Proposal

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

    Users cannot assign a second batch of imported CSV transactions to a card that was assigned during an earlier import.

    What is the root cause of that problem?

    In src/pages/workspace/companyCards/assignCard/ConfirmationStep.tsx, submit() calls isCardAlreadyAssigned() and returns a cardAlreadyAssignedError when the imported card already exists in workspaceCardFeeds. This validation treats CSV imports like ordinary card-feed assignments, although reusing an existing card is valid for subsequent CSV batches, so assignWorkspaceCompanyCard() is never called.

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

    Update submit() in ConfirmationStep.tsx to skip the client-side already-assigned rejection for CSV/upload feeds while retaining it for regular company-card feeds. Then allow assignWorkspaceCompanyCard() to run so the newly imported transactions can be associated with the existing card. Add a focused test covering a previously assigned CSV card and confirming that another batch can be submitted without the local error.

    What alternative solutions did you explore? (Optional)

    Changing isCardAlreadyAssigned() globally would affect duplicate protection for other assignment flows, so scoping the exception to CSV imports at the confirmation call site is safer.

  6. added
    Help WantedApply this label when an issue is open to proposals by contributors
    on Jun 30, 2026
  7. yusufdeveloper2903 commented on Jun 30, 2026

    @yusufdeveloper2903
    Contributor

    Proposal

    What is the root cause of that problem?

    The card selection step for assignment builds its list with getFilteredCardList, which decides which unassigned commercial-feed cards are still selectable by filtering out anything whose cardName (the masked PAN display string) matches an already-assigned card:

    The problem is that cardName is not unique for commercial feeds — it is the masked PAN, where every digit except the last four is replaced by X/•. maskCardNumber confirms this: it turns X into • and only the last four digits survive (CardUtils.ts#L364-L389), and lastFourNumbersFromCardName keys entirely off the trailing four digits (CardUtils.ts#L398-L406). So two distinct physical cards that share the same trailing four digits collapse to the same cardName string, and to the reporter they read as “the same card number.”

    The actual unique identifier is encryptedCardNumber — it is the value half of every commercial cardList entry and is what the selection step ultimately stores as the card ID and what the assign request sends to the backend (CardUtils.ts#L1029-L1034, CompanyCards.ts#L428-L437), and the assigned Card object carries it as a first-class field (Card.ts#L88-L89).

    So: once one card ending in e.g. …7012 is assigned, its masked cardName lands in the assigned set → the second batch’s still-unassigned card (different encryptedCardNumber, same masked …7012) is filtered out by matching cardName → it never appears in CardSelectionStep → the user cannot assign it. The direct-feed branch is unaffected because there cardName === cardID and is unique (CardUtils.ts#L1019-L1026).

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

    In getFilteredCardList, filter the commercial-feed branch by the unique encryptedCardNumber instead of the non-unique cardName. The encrypted number is already the value of each cardList entry and already exists on the assigned Card objects, so no new data is needed — we only change which field we key the exclusion set on.

    Build an encrypted-number set alongside the existing cardName set:

      const assignedCards = new Set(Object.values(cards).map((card) => card.cardName));
    + const assignedEncryptedCardNumbers = new Set(Object.values(cards).map((card) => card.encryptedCardNumber).filter(Boolean));

    Then key the commercial-feed exclusion off the encrypted number (the entry value), keeping the existing key/value mapping intact:

    - .filter(([cardName]) => !assignedCards.has(cardName) && !allWorkspaceAssignedCards.has(cardName))
    + .filter(([, encryptedCardNumber]) => !assignedEncryptedCardNumbers.has(encryptedCardNumber) && !allWorkspaceAssignedEncryptedCardNumbers.has(encryptedCardNumber))

    The same one-line change applies to the cross-workspace loop at CardUtils.ts#L1004-L1016: collect card.encryptedCardNumber into an allWorkspaceAssignedEncryptedCardNumbers set in the same pass it already collects cardName. The direct-feed branch (CardUtils.ts#L1019-L1026) keeps using cardName, since there it equals the unique card identifier — so this fix is scoped to the commercial feed path with zero regression to direct/OAuth feeds. Minor changes/improvements can be discussed in the PR phase.

    What alternative solutions did you explore? (Optional)

    Normalize/de-collide the masked cardName (e.g. append the encrypted suffix) before building the exclusion set. This is strictly worse — it re-derives a synthetic unique key when a real unique key (encryptedCardNumber) is already present on both the unassigned entries and the assigned cards, adds string-munging that the display layer would have to undo, and risks new collisions. Keying directly off encryptedCardNumber is the smaller, exact fix.

  8. lorretheboy commented on Jun 30, 2026

    @lorretheboy
    Contributor

    🚫 Duplicated proposal withdrawn by 🤖 ProposalPolice.

  9. oqildev commented on Jun 30, 2026

    @oqildev
    Contributor

    🚨 Edited by proposal-police: This proposal was edited at 2026-06-30 20:30:54 UTC.

    Proposal

    What is the root cause of that problem?

    NewDot treats a company card as something that is assigned exactly once. That holds for bank/commercial/direct feeds — a physical card belongs to one cardholder — but it's wrong for CSV-upload feeds, where re-uploading a later batch for an already-assigned card number is a normal, repeatable operation (new rows just append transactions to the existing card, exactly as Classic handles it).

    That single-assignment assumption is enforced at two independent client-side gates, and neither special-cases CSV feeds.

    Gate 1 — the card never appears in the selection list.
    CardSelectionStep builds its picker via getFilteredCardList:

    const filteredCardList = getFilteredCardList(list, cardFeeds?.[feed]?.accountList, workspaceCardFeeds, feed);

    Inside getFilteredCardList, the commercial-feed branch strips any entry whose cardName already exists in assignedCards (current workspace) or allWorkspaceAssignedCards (all workspaces):

    App/src/libs/CardUtils.ts

    Lines 1000 to 1034 in c49419e

    const {cardList: customFeedCardsToAssign, ...cards} = list ?? {};
    const assignedCards = new Set(Object.values(cards).map((card) => card.cardName));
    // Get cards assigned across all workspaces
    const allWorkspaceAssignedCards = new Set<string>();
    for (const workspaceCards of Object.values(workspaceCardFeeds ?? {})) {
    if (!workspaceCards) {
    continue;
    }
    const {cardList, ...workspaceCardItems} = workspaceCards;
    for (const card of Object.values(workspaceCardItems)) {
    if (!card?.cardName) {
    continue;
    }
    allWorkspaceAssignedCards.add(card.cardName);
    }
    }
    // For direct feeds (Plaid/OAuth): displayName === cardIdentifier
    if (accountList) {
    return filterAmexDirectParentCard(accountList, feedName)
    .filter((cardName) => !assignedCards.has(cardName) && !allWorkspaceAssignedCards.has(cardName))
    .map((cardName) => ({
    cardName,
    cardID: cardName,
    }));
    }
    // For commercial feeds: displayName is the key, cardIdentifier is the encrypted value
    return Object.entries(customFeedCardsToAssign ?? {})
    .filter(([cardName]) => !assignedCards.has(cardName) && !allWorkspaceAssignedCards.has(cardName))
    .map(([cardName, encryptedCardNumber]) => ({
    cardName,
    cardID: encryptedCardNumber,
    }));

    After batch #1 the card number lands in assignedCards. When batch #2 is uploaded, getFilteredCardList drops it, cardListOptions is empty, and the user hits the "no active cards" empty state.

    Gate 2 — even if the card is reached, the confirm step hard-blocks it.
    ConfirmationStep.submit() calls isCardAlreadyAssigned before ever calling assignWorkspaceCompanyCard. If it returns true, the function sets cardAlreadyAssignedError and returns without making any API call:

    // Check both encryptedCardNumber and cardName since isCardAlreadyAssigned matches on either
    // This handles cases where workspace card entries only have cardName (masked display name) stored
    const cardIdentifier = cardToAssign?.encryptedCardNumber ?? cardToAssign?.cardName;
    if (cardIdentifier && isCardAlreadyAssigned(cardIdentifier, workspaceCardFeeds, domainOrWorkspaceAccountID, bankName)) {
    setCardError(getMicroSecondOnyxErrorWithTranslationKey('workspace.companyCards.cardAlreadyAssignedError'));
    return;
    }

    isCardAlreadyAssigned returns true for any same-workspace/same-feed match:

    App/src/libs/CardUtils.ts

    Lines 1574 to 1617 in c49419e

    function isCardAlreadyAssigned(cardNumberToCheck: string, workspaceCardFeeds: OnyxCollection<WorkspaceCardsList>, domainOrWorkspaceAccountID: number, feedName?: string): boolean {
    if (!cardNumberToCheck || !workspaceCardFeeds) {
    return false;
    }
    return Object.entries(workspaceCardFeeds).some(([key, workspaceCards]) => {
    if (!workspaceCards) {
    return false;
    }
    // Strip the collection prefix and split on the first underscore only,
    // so feed names containing underscores (e.g., "plaid.ins_123456") are preserved.
    const feedKey = key.replace(ONYXKEYS.COLLECTION.WORKSPACE_CARDS_LIST, '');
    const separatorIndex = feedKey.indexOf('_');
    if (separatorIndex === -1) {
    return false;
    }
    const feedDomainID = Number(feedKey.substring(0, separatorIndex));
    const feedBankName = feedKey.substring(separatorIndex + 1);
    if (Number.isNaN(feedDomainID) || !feedBankName) {
    return false;
    }
    // Only flag a card already assigned within the CURRENT workspace/domain (and feed).
    // Direct feeds (Plaid/OAuth) must NOT be matched across other workspaces: the only
    // identifier the client has for them is the masked display name (getFilteredCardList
    // sets cardID = cardName, which CardSelectionStep stores into encryptedCardNumber),
    // e.g. "CREDIT CARD...6607", which is not unique across accounts. Genuine cross-account
    // duplicates are rejected server-side by ASSIGN_COMPANY_CARD — the same path Expensify
    // Classic uses, which is why the identical assignment succeeds there.
    if (feedDomainID !== domainOrWorkspaceAccountID) {
    return false;
    }
    if (feedName && feedBankName !== feedName) {
    return false;
    }
    const {cardList, ...assignedCards} = workspaceCards;
    return Object.values(assignedCards).some(
    (card) => card && card.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE && isMatchingCard(card, cardNumberToCheck, cardNumberToCheck),
    );
    });

    So even if Gate 1 were fixed alone, Gate 2 would still block the assignment.

    The codebase already recognizes that CSV feeds behave differently elsewhere — maskCardNumber special-cases FEED_BANK_NAME.UPLOAD and returns the card name as-is without masking:

    App/src/libs/CardUtils.ts

    Lines 369 to 372 in c49419e

    // CSV imported cards use user-provided display names, not card numbers - return as-is
    if (feed === CONST.COMPANY_CARD.FEED_BANK_NAME.UPLOAD) {
    return cardName;
    }

    This means for CSV feeds cardName is the full, unmasked card number — already unique per entry. A masked-PAN collision between two different physical cards sharing the same last four digits cannot occur here. The block is not a uniqueness problem; it is purely that the same valid card number is rejected as "already assigned" on a second batch. getFilteredCardList has no such UPLOAD exemption, which is the gap.

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

    Fix at both gates, scoped to CSV feeds only, using the isCSVUploadFeed helper already exported from CardUtils:

    App/src/libs/CardUtils.ts

    Lines 612 to 618 in c49419e

    function isCSVUploadFeed(feed: string | undefined): boolean {
    if (!feed) {
    return false;
    }
    const lowerFeed = feed.toLowerCase();
    return lowerFeed.startsWith(CONST.COMPANY_CARD.FEED_BANK_NAME.CSV) || lowerFeed.startsWith(CONST.COMPANY_CARD.FEED_BANK_NAME.CSV_CLASSIC);
    }

    In getFilteredCardList — keep already-assigned card numbers in the list for CSV feeds so the second batch's number stays selectable:

    const isCSVFeed = isCSVUploadFeed(feedName);
    
    return Object.entries(customFeedCardsToAssign ?? {})
      .filter(
        ([cardName]) =>
          isCSVFeed ||
          (!assignedCards.has(cardName) &&
            !allWorkspaceAssignedCards.has(cardName)),
      )
      .map(([cardName, encryptedCardNumber]) => ({
        cardName,
        cardID: encryptedCardNumber,
      }));

    In ConfirmationStep.submit() — skip the client-side isCardAlreadyAssigned block for CSV feeds so the request actually reaches the server:

    if (
      !isCSVUploadFeed(bankName) &&
      cardIdentifier &&
      isCardAlreadyAssigned(
        cardIdentifier,
        workspaceCardFeeds,
        domainOrWorkspaceAccountID,
        bankName,
      )
    ) {
      setCardError(
        getMicroSecondOnyxErrorWithTranslationKey(
          "workspace.companyCards.cardAlreadyAssignedError",
        ),
      );
      return;
    }

    Because the batch-1 card is still present in cardList with its original encryptedCardNumber, re-selecting it in the picker carries that same encryptedCardNumber as cardID. So assignWorkspaceCompanyCard re-maps to the existing card (append) rather than creating a second assignment. ASSIGN_COMPANY_CARD remains the server-side arbiter for genuine cross-account duplicates — the same path Classic uses.

    What specific scenarios should we cover in automated tests to prevent this bug from happening again?

    • getFilteredCardList: a CSV (ccupload) feed whose cardList entry has the same cardName as an already-assigned card still returns that entry as selectable; the same fixture on a commercial/direct feed still filters it out (no regression to single-assignment).
    • isCardAlreadyAssigned / confirm-step guard: still blocks for non-CSV feeds, does not block a repeat CSV assignment, so assignWorkspaceCompanyCard is invoked.

    What alternative solutions did you explore? (Optional)

    • Fix only Gate 1 (selection filter). Rejected — isCardAlreadyAssigned in ConfirmationStep would still block the request even after the card becomes selectable. Both gates must be fixed together.

    • Handle it in the import action (importCSVCompanyCards) by detecting an already-assigned card number and routing transactions straight to the existing card, skipping the assign step. Rejected as the primary fix: the user-facing block is the assign flow rendering an empty list or an error, so even with smart import routing the UI still confuses admins who expect to confirm the mapping. Worth considering as a complementary improvement, but it doesn't unblock the visible flow on its own.

    • Key the exclusion on encryptedCardNumber instead of cardName. Does not apply here — for CSV feeds maskCardNumber returns the name as-is (never masked), so cardName is already the full unique card number. The block is a repeated-batch policy issue, not a masked-PAN collision.

  10. melvin-bot commented on Jun 30, 2026

    @melvin-bot

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

  11. melvin-bot commented on Jun 30, 2026

    @melvin-bot
  12. 33 remaining items

  13. melvin-bot commented on Jul 14, 2026

    @melvin-bot

    @thesahindia The PR fixing this issue has been merged! The following checklist (instructions) will need to be completed before the issue can be closed. Please copy/paste the BugZero 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]

  14. melvin-bot commented on Jul 17, 2026

    @melvin-bot

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

  15. thesahindia commented on Jul 20, 2026

    @thesahindia
    Member

    No checklist is needed. Steps for test case are below -

    1. Go to Company Cards > Add Cards > Import from File
    2. Upload a file where not all columns get mapped by default, like this one: fakeyfakes.csv
    3. Manually map the missing attributes, complete the process and wait until the cards appear
    4. For that same feed, go to settings > Import from Spreadsheet to add more transactions
    5. Upload the same file again
    6. Verify that the columns are now premapped
  16. added
    Awaiting PaymentAuto-added when associated PR is deployed to production
    and removed on Jul 20, 2026
  17. melvin-bot commented on Jul 20, 2026

    @melvin-bot

    Triggered auto assignment to @mallenexpensify (Awaiting Payment)

  18. melvin-bot commented on Jul 20, 2026

    @melvin-bot

    Payment Summary

    Upwork Job

    BugZero Checklist (@mallenexpensify)

    • I have verified the correct assignees and roles are listed above and updated the necessary manual offers
    • I have verified that there are no duplicate or incorrect contracts on Upwork for this job (https://www.upwork.com/ab/applicants/2072048852936523261/hired)
    • I have verified the PR was not reverted
    • I have applied any discounts due to bugs/regressions introduced by this PR
    • I have paid out the Upwork contracts or cancelled the ones that are incorrect
    • I have verified the payment summary above is correct
  19. mallenexpensify commented on Jul 23, 2026

    @mallenexpensify
    Contributor

    Payment Summary

    Contributor+: @thesahindia due $250 via NewDot

    ^ Test case created. Thx

  20. garrettmknight commented on Aug 7, 2026

    @garrettmknight
    Contributor

    $250 approved for @thesahindia

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

Awaiting PaymentAuto-added when associated PR is deployed to productionBugSomething is broken. Auto assigns a BugZero manager.DailyKSv2InternalRequires API changes or must be handled by Expensify staff

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions