App icon indicating copy to clipboard operation
App copied to clipboard

[$175] Previously assigned Brex cards appear again as unassigned under the newer “Name - last 4” format.

Open m-natarajan opened this issue 1 month ago • 33 comments

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


Version Number: 9.5.17-0 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: @Tmjarnesk1 Slack conversation (hyperlinked to channel name): #Expensify Bugs

Action Performed:

  1. Open the workspace.
  2. Navigate to Company cards > Brex cards.
  3. Locate the previously assigned card (shown under the older name-only format).
  4. Observe the same card also listed again under the newer "Name - last 4" format, as unassigned with an Assign button.

Expected Result:

Existing Brex card assignments are recognized across the naming-format change, without presenting the corresponding cards as unassigned.

Actual Result:

The name-only assignment remains visible, while the corresponding “Name - last 4” entry appears as unassigned. This allows overlapping assignments and may cause duplicate expense imports; duplicate expenses have not been confirmed.

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 screenshots for the issue are in Slack thread

View all open jobs on GitHub

Upwork Automation - Do Not Edit

m-natarajan avatar Oct 23 '26 11:10 m-natarajan

Issue Analysis

Root Cause: The Brex feed now sends each card's name as "Name - last 4". Cards assigned earlier still have the old name-only value. The App decides whether a direct-feed card is assigned by matching its exact name. So "Jane Doe - 1234" never matches the assigned "Jane Doe", and the App shows it as unassigned.

The naming change and the missing reconciliation for already-assigned cards are in the backend. This appears to be a backend/internal issue. A separate internal investigation is needed. The fix requires changes outside the App repo, so please escalate to an internal engineer.

Recommended Fix: No App code fix is recommended. Hiding the duplicate row in the App would not stop the backend from accepting a second assignment for the same physical card.

Investigation details

For direct/OAuth feeds such as Brex, the available cards come from the feed's accountList, and the card name is also its identifier. The App only skips an accountList entry when its normalized name or identifier exactly matches an assigned card:

Result: the old name-only assignment stays visible, and the renamed card appears as a new, assignable entry. Assigning it creates a second card for the same physical Brex card, which can import the same transactions twice.

An App-side change (for example, treating "X - dddd" as assigned when "X" is assigned) would only hide the row. It would also guess wrong when one cardholder has several Brex cards.

Possibly related: CSV imported cards display already-assigned cards as available for assignment shows a similar symptom on a different feed type.


Next Steps: Reply with @MelvinBot <your feedback> to refine this analysis.


view run

MelvinBot avatar Oct 23 '26 12:10 MelvinBot

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

melvin-bot[bot] avatar Oct 23 '26 12:10 melvin-bot[bot]

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

melvin-bot[bot] avatar Oct 23 '26 12:10 melvin-bot[bot]

Proposal

What is the root cause of that problem?

Brex changed its card-naming convention from a plain cardholder name (e.g. "John Smith") to a "Name - last 4" format (e.g. "John Smith - 1234").

The function getFilteredCardList in src/libs/CardUtils.ts (~line 1348) determines which cards are "unassigned" by building a set of already-assigned card names from card.cardName values, then filtering out any accountList entry whose exact string appears in that set. Because Brex is a direct (OAuth) feed, it takes the accountList path (line 1375-1381).

Since previously-assigned cards still have cardName = "John Smith" (stored at assignment time under the old format), while the fresh accountList from Brex now contains "John Smith - 1234", the exact-match check assignedCards.has("John Smith - 1234") returns false. The card therefore passes the filter and is incorrectly shown as unassigned with an Assign button, even though it is already assigned.

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

In getFilteredCardList, before inserting values into the assignedCards and allWorkspaceAssignedCards sets, normalize each card.cardName by stripping the " - XXXX" suffix (last 4 digits) using the regex / - \d{4}$/. Apply the same normalization to each accountList name before checking set membership. This way "John Smith" and "John Smith - 1234" both reduce to "John Smith" and match correctly.

A small private helper (similar to the already-existing normalizeCardName) can encapsulate this stripping, keeping the main filter logic clean. The existing maskCardNumber utility already uses the identical regex / - \d{4}$/g to strip the suffix for display purposes, confirming this is the right pattern.

What alternative solutions did you explore? (Optional)

  • Matching on encryptedCardNumber instead of cardName would be more robust long-term, but that value is only available for commercial (non-OAuth) feeds via cardList; direct Brex feeds don't carry a parallel encrypted identifier in accountList, so this is not viable for the direct-feed path.
  • Updating the stored card.cardName on the backend when the feed format changes is a server-side migration that would be more invasive and is outside the scope of this UI fix.

j3ffffff avatar Oct 23 '26 12:10 j3ffffff

Proposal

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

Una tarjeta Brex previamente asignada aparece también como disponible para asignar después de cambiar su denominación de Name a Name - last 4.

Debemos reconocer ambas representaciones como la misma tarjeta y conservar su asignación existente. La duplicación de gastos es una consecuencia posible, todavía no confirmada.

What is the root cause of that problem?

Causa primaria probable: pérdida de continuidad de identidad durante el cambio de formato. El registro asignado y la entrada actual del feed dejan de reconciliarse. El síntoma es compatible con usar una denominación mutable como identificador, pero el reporte por sí solo no demuestra dónde ocurre esa ruptura.

Esta distinción importa: los tipos públicos documentan que, para determinados feeds directos, el identificador enviado al backend coincide con cardName. Por tanto, el cambio podría afectar al contrato de asignación, además de la presentación. Tipos de tarjetas

Causa secundaria posible: conciliación incompleta en el cliente. En main, resolveCardListEntry() busca correspondencias mediante encryptedCardNumber, nombre normalizado y, finalmente, un sufijo basado en lastFourPAN. buildCompanyCardEntries() utiliza ese resultado para distinguir entradas asignadas y disponibles. Esa lógica ya contempla parcialmente diferencias de representación. useCompanyCards.ts

Además, normalizeCardName() conserva guiones y dígitos: normalizar Ana Pérez y Ana Pérez - 1234 no los convierte en valores iguales. CardUtils.ts

Límite de la evidencia: pude consultar main, pero no recuperar la versión 9.5.17-0 ni verificar los payloads y logs privados. No sería riguroso presentar una causa backend confirmada o atribuir el fallo a líneas concretas de esa versión.

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

Corregir la primera capa que pierde la identidad de la tarjeta, preservando el registro asignado. Diff mínimo significa el menor cambio que restaura ese contrato.

Primero contrastaría, para una tarjeta afectada y dentro de la misma conexión Brex:

  • El registro asignado: cardID, cardName, encryptedCardNumber y lastFourPAN.
  • Su entrada en cardList y accountList.
  • El identificador persistente del proveedor, si está disponible en el backend.

El resultado determina un cambio acotado:

Si el backend conserva correctamente la identidad y el cliente recibe una correspondencia inequívoca, modificar únicamente la conciliación existente en useCompanyCards.ts: reutilizar la asignación para la entrada actual y evitar añadir su representación como disponible. No añadir otro filtro en la tabla ni duplicar reglas en el botón Assign.

Si el cambio de nombre modifica también la identidad utilizada por el backend, corregir el adaptador Brex y la compatibilidad de asignaciones antiguas. El comportamiento requerido es:

misma conexión + misma identidad persistente del proveedor
    → conservar cardID y titular existentes
    → actualizar la denominación mostrada
    → excluir esa identidad de las tarjetas disponibles

La operación de asignación debe resolver esa misma identidad y respetar la asignación existente, incluso ante solicitudes concurrentes.

Si el registro antiguo solo conserva el nombre, no inferir automáticamente qué tarjeta nueva le corresponde. Se necesita recuperar una relación autoritativa desde el proveedor o los datos históricos.

No propongo números de línea ni un parche supuestamente aplicable sin verificar esos datos. Tampoco recomendaría implementar nuevamente la búsqueda por últimos cuatro dígitos: ya existe en el main consultado.

What alternative solutions did you explore? (Optional)

No se proporcionó una propuesta de MelvinBot; no hay una implementación concreta que desmontar. Sí descartaría estas alternativas:

  • Eliminar - \d{4}$ para comparar nombres: confunde tarjetas distintas del mismo titular.
  • Aceptar coincidencias por últimos cuatro dígitos: pueden colisionar. Tener un único candidato en la respuesta actual tampoco demuestra identidad.
  • Ocultar la fila o deshabilitar Assign: deja intacta una posible inconsistencia de asignación en el servidor.
  • Desasignar y volver a asignar: introduce cambios innecesarios sobre una asignación válida.

La objeción técnica central a cualquiera de esos enfoques es la misma: una coincidencia de presentación no prueba identidad.

What automated tests can you add to prevent this from re-occurring?

Añadir una regresión con un fixture anonimizado que reproduzca el payload afectado:

Assigned Brex card remains assigned after its display-name format changes

Preparación:

  • Una tarjeta asignada con denominación antigua.
  • La misma identidad persistente bajo Name - 1234 en el feed actualizado.
  • Otra tarjeta distinta, también del mismo titular.

Verificaciones:

  1. La primera tarjeta aparece una sola vez y como asignada.
  2. Conserva su cardID y titular.
  3. La segunda tarjeta continúa disponible.
  4. Repetir la actualización produce el mismo resultado.

Si el cambio corresponde al cliente, probar el hook mediante renderHook y datos Onyx. Si corresponde al backend, añadir también la regresión de compatibilidad y verificar que asignar mediante la nueva denominación no crea otra asignación.

Incluir casos negativos de nombres iguales, últimos cuatro coincidentes e identidad ausente. Son los casos que detectarían una deduplicación incorrecta.

Estos son tests propuestos; no se ejecutaron contra el repositorio.

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

camesenin avatar Oct 23 '26 12:10 camesenin

✅ Contributor details stored successfully. Thank you for contributing to Expensify!

melvin-bot[bot] avatar Oct 23 '26 12:10 melvin-bot[bot]

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

Proposal

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

When Brex updates its feed format from the legacy cardholder name-only convention (e.g., "John Doe") to the newer "Name - last 4" convention (e.g., "John Doe - 1234"), previously assigned Brex cards continue to be displayed as assigned under the old name, but also appear a second time as unassigned with an Assign button. This creates duplicate/overlapping entries in the Company Cards list and allows re-assigning the same card.

What is the root cause of that problem?

Brex is a direct OAuth feed, which means its available cards are delivered as an array of strings in selectedFeed.accountList rather than the Record<cardName, encryptedCardNumber> structure used by commercial feeds (cardList).

There are two distinct places where the frontend fails to recognize the identity continuity across this format change:

  1. useCompanyCards.ts (buildCompanyCardEntries):

    • In Phase 1 (lines 112–131), assigned cards from cardsList are processed as the source of truth. It calls resolveCardListEntry(card, cardListEntries). However, cardListEntries is built exclusively from cardList (Object.entries(cardList ?? {})), which is empty for direct feeds like Brex. As a result, resolveCardListEntry returns the card untouched with its old card.cardName (e.g. "John Doe"), adding only "john doe" to existingNames.
    • In Phase 2 (lines 146–156), it iterates over accountList. The incoming Brex entry is "John Doe - 1234". Calling normalizeCardName("John Doe - 1234") returns "john doe - 1234" (since normalizeCardName preserves alphanumeric characters and hyphens).
    • Because existingNames.has("john doe - 1234") evaluates to false and cardList?.[cardName] is undefined, it adds "John Doe - 1234" as a brand new unassigned card entry ({ cardName, encryptedCardNumber: cardName, isAssigned: false }).
  2. CardUtils.ts (getFilteredCardList lines 1354–1382):

    • When opening the assign card flow (CardSelectionStep.tsx), getFilteredCardList collects card.cardName strings from assignedCards into a Set<string>.
    • For direct feeds (accountList), it filters with:
      accountList.filter((cardName) => !assignedCards.has(cardName) && !allWorkspaceAssignedCards.has(cardName))
      
    • Because assignedCards contains the legacy "John Doe" while accountList contains "John Doe - 1234", the exact string check assignedCards.has("John Doe - 1234") returns false, causing the card to be returned as an available unassigned option to assign.

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

We should link direct feed accountList cards to previously assigned cards safely, taking into account lastFourPAN to avoid any false matches when the same cardholder has multiple cards.

Expensify already has helper utilities in src/libs/CardUtils.ts:

  • maskCardNumber(cardName): strips the / - \d{4}$/g suffix to return the base cardholder name.
  • lastFourNumbersFromCardName(cardName): extracts the last 4 digits via /(\d{4})$/.

1. In src/libs/CardUtils.ts:

Create a helper function to verify if an assigned card matches a direct feed account name:

/**
 * Checks if an assigned card matches an accountList card name across naming convention updates
 * (e.g., legacy "John Doe" vs updated "John Doe - 1234").
 */
function isMatchingDirectCard(assignedCard: Card, accountCardName: string): boolean {
    if (!assignedCard.cardName) {
        return false;
    }
    const normalizedAssigned = normalizeCardName(assignedCard.cardName);
    const normalizedAccount = normalizeCardName(accountCardName);

    if (normalizedAssigned === normalizedAccount) {
        return true;
    }

    const lastFour = lastFourNumbersFromCardName(accountCardName);
    const baseAccountName = normalizeCardName(maskCardNumber(accountCardName));

    if (normalizedAssigned === baseAccountName) {
        // If the assigned card has a lastFourPAN, ensure the suffix matches to prevent
        // collisions when a cardholder has multiple cards
        if (assignedCard.lastFourPAN && lastFour) {
            return assignedCard.lastFourPAN === lastFour;
        }
        return true;
    }

    return false;
}

In getFilteredCardList (src/libs/CardUtils.ts): Instead of only an exact assignedCards.has(cardName) check, check if the cardName matches any assigned card in the workspace:

    if (accountList) {
        const assignedCardList = Object.values(list ?? {}).filter((c): c is Card => typeof c === 'object' && !!c?.cardName);
        const allAssignedCardList = Object.values(workspaceCardFeeds ?? {}).flatMap((w) => Object.values(w ?? {})).filter((c): c is Card => typeof c === 'object' && !!c?.cardName);

        return filterAmexDirectParentCard(accountList, feedName)
            .filter((cardName) => {
                const isAssignedLocally = assignedCards.has(cardName) || assignedCardList.some((card) => isMatchingDirectCard(card, cardName));
                const isAssignedAcrossWorkspaces = allWorkspaceAssignedCards.has(cardName) || allAssignedCardList.some((card) => isMatchingDirectCard(card, cardName));
                return !isAssignedLocally && !isAssignedAcrossWorkspaces;
            })
            .map((cardName) => ({
                cardName,
                cardID: cardName,
            }));
    }

2. In src/hooks/useCompanyCards.ts:

In buildCompanyCardEntries: When processing accountList in Phase 1 and Phase 2:

  • In Phase 1: Reconcile assigned cards against accountList. If an assigned card matches an accountList entry via isMatchingDirectCard(card, accountCardName), enrich the assigned card with the updated name and add both the legacy normalizedName and the updated normalizeCardName(accountCardName) to existingNames.
  • In Phase 2:
    for (const cardName of filterAmexDirectParentCard(accountList ?? [], feedName)) {
        const normalizedName = normalizeCardName(cardName);
        const encryptedCardNumber = cardList?.[cardName] ?? cardName;
    
        if (existingNames.has(normalizedName) || existingEncryptedCardNumbers.has(encryptedCardNumber)) {
            continue;
        }
    
        entriesMap.set(normalizedName, {cardName, encryptedCardNumber, isAssigned: false});
        existingNames.add(normalizedName);
    }
    
    Since existingNames already contains the normalized updated name, Phase 2 skips it and does not render a duplicate unassigned entry.

What alternative solutions did you explore? (Optional)

  • Blindly stripping - \d{4}$ in string sets: As noted during exploration, stripping the last 4 suffix indiscriminately would cause collisions if a single cardholder holds multiple Brex cards (e.g. "John Doe - 1111" and "John Doe - 2222"). By validating card.lastFourPAN === lastFour when available, our solution avoids collisions and guarantees identity integrity.
  • Backend-only migration: While the backend could migrate legacy card names, frontends must remain resilient against feed provider format variations. A clean frontend reconciliation ensures immediate correctness without requiring an invasive database migration.

What automated tests can you add to prevent this from re-occurring?

Add unit tests in:

  1. tests/unit/CardUtilsTest.ts:
    • describe('isMatchingDirectCard'):
      • Verifies "John Doe" matches "John Doe - 1234" when lastFourPAN: "1234".
      • Verifies "John Doe" does NOT match "John Doe - 5678" when lastFourPAN: "1234".
      • Verifies exact matches match regardless of PAN.
    • describe('getFilteredCardList'):
      • Verifies that an assigned card with legacy name "John Doe" filters out "John Doe - 1234" from accountList.
  2. tests/unit/hooks/useCompanyCards.test.ts:
    • Tests that when an assigned card in assignedCards has legacy name "John Doe" and accountList contains ["John Doe - 1234"], companyCardEntries produces only 1 entry with isAssigned: true and 0 unassigned entries.

HamzaKhanBUIC avatar Oct 24 '26 08:10 HamzaKhanBUIC

✅ Contributor details stored successfully. Thank you for contributing to Expensify!

melvin-bot[bot] avatar Oct 24 '26 08:10 melvin-bot[bot]

Proposal

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

When a workspace uses a direct Brex OAuth feed that already has cards assigned under the legacy card-name format (<Cardholder Name>), opening Assign card after the backend update that appends the last 4 digits (<Cardholder Name> - <last 4>, from #95611) still lists those already-assigned Brex cards as unassigned.

What is the root cause of that problem?

There are two separate mismatches in how assigned cards are matched against feed cards in src/hooks/useCompanyCards.ts and src/libs/CardUtils.ts:

  1. resolveCardListEntry in src/hooks/useCompanyCards.ts:62-92 only inspects cardList, which is empty for direct OAuth feeds like Brex: In src/hooks/useCompanyCards.ts:108-127, cardListEntries is built exclusively from const {cardList, ...assignedCards} = workspaceCardFeeds?.[feedName] ?? {}:
    const cardListEntries = Object.entries(cardList ?? {});
    
    Encrypted cardList maps (Record<cardName, encryptedCardNumber>) only exist for commercial feeds. For direct OAuth feeds such as Brex (accountList on ONYXKEYS.COLLECTION.SHARED_NVP_PRIVATE_DOMAIN_MEMBER), cardList is undefined, so cardListEntries is [] and resolveCardListEntry immediately falls back to the legacy stored card.cardName ("John Smith"), which does not match "John Smith - 1234" in selectedFeed.accountList.
  2. resolveCardListEntry and getFilteredCardList (src/libs/CardUtils.ts:635-645) only handle suffix-matching (name.endsWith(panSuffix)), not prefix-to-<Name> - <last 4> migrations: resolveCardListEntry (added in PR #83737) was written for commercial feeds migrating from short PANs ("0487") to masked PANs ("553312XXXXXX0487"), where name.endsWith(panSuffix) holds. For Brex cards migrated by #95611, the legacy card.cardName is the prefix ("John Smith"), while the new accountList entry appends - <last 4> ("John Smith - 1234"). Note that unconditionally stripping / - \d{4}$/ from all card names would break cardholders who hold multiple Brex cards ("John Smith - 1234" and "John Smith - 5678"), because assigning or having one legacy card would hide both cards.

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

Extend the existing unambiguous resolution pattern in resolveCardListEntry (src/hooks/useCompanyCards.ts:62-92) and share it with getFilteredCardList (src/libs/CardUtils.ts:635-645):

  1. Build candidate entries from accountList when cardList is absent (src/hooks/useCompanyCards.ts:108):
    const accountListEntries: Array<[string, string]> = (selectedFeed?.accountList ?? []).map((name) => [name, cardList?.[name] ?? name]);
    const cardListEntries = accountListEntries.length > 0 ? accountListEntries : Object.entries(cardList ?? {});
    
  2. Support <Name> -> <Name> - <last 4> resolution in resolveCardListEntry (src/hooks/useCompanyCards.ts:62-92) without collapsing multi-card holders:
    • Define a helper to strip the trailing - <last 4> suffix (const BREX_LAST_FOUR_SUFFIX_REGEX = /\s-\s\d{4}$/;).
    • When card.cardName does not match an entry in cardListEntries directly:
      • If card.lastFourPAN is present on the assigned card, match the entry where normalizeCardName(name.replace(BREX_LAST_FOUR_SUFFIX_REGEX, '')) === normalizedCardName && name.endsWith(card.lastFourPAN).
      • If card.lastFourPAN is empty on the legacy assigned card, find candidate entries in cardListEntries where BREX_LAST_FOUR_SUFFIX_REGEX.test(name) and normalizeCardName(name.replace(BREX_LAST_FOUR_SUFFIX_REGEX, '')) === normalizedCardName. Following the exact ambiguity guard from PR #83737 (lines 83-88), resolve to that entry when it is the single unambiguous unassigned match among cardListEntries.
  3. Use the same resolution in getFilteredCardList (src/libs/CardUtils.ts:635-645):
    • Resolve assignedCards against the feed entries before building assignedCardNames, so getFilteredCardList and useCompanyCards stay consistent when filtering assignable cards during the assignment flow.

What alternative solutions did you explore? (Optional)

  • Unconditionally stripping - \d{4}$ when building assignedCards / filteredCardList: Rejected because a single Brex cardholder can hold multiple active cards ("Alice - 1234" and "Alice - 5678"). Stripping the suffix unconditionally would map both cards to "Alice" and hide all of a user's remaining unassigned Brex cards as soon as one card is assigned.

shilo1979jk avatar Oct 25 '26 00:10 shilo1979jk

Proposal

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

Previously assigned Brex cards store the legacy direct-feed card name, for example John Smith. Brex now returns the same cards in accountList using John Smith - 1234.

Because the App does not reconcile those two representations, the assigned card remains visible under its legacy name while the current accountList entry is also shown as unassigned, including in the Assign card flow.

What is the root cause of that problem?

There are two frontend reconciliation paths, and both rely on exact names for direct feeds.

In src/hooks/useCompanyCards.ts, buildCompanyCardEntries() creates the candidate entries used by resolveCardListEntry() exclusively from:

const cardListEntries = Object.entries(cardList ?? {});

That works for commercial feeds, but Brex is a direct OAuth feed. Its available cards are supplied through selectedFeed.accountList, while cardList is normally absent. Therefore the assigned legacy card is never reconciled against the current Name - last 4 entry.

Phase 1 consequently records the assigned card using its legacy name (John Smith). Phase 2 iterates over accountList and sees John Smith - 1234. normalizeCardName() only removes special characters; it preserves hyphens and digits. The two normalized names remain different, so Phase 2 creates a second unassigned entry.

The same mismatch exists in src/libs/CardUtils.ts. getFilteredCardList() collects the assigned card.cardName values and filters direct-feed accountList entries using exact set membership. Therefore John Smith - 1234 is also returned by the Assign card flow even though John Smith is already assigned.

The existing last-four fallback in resolveCardListEntry() does not handle this case because it never receives accountList entries. It also should not be reused unchanged for Brex: it only checks name.endsWith(lastFourPAN), without also checking the cardholder-name prefix.

Also, PR #95611 did not introduce the Name - last 4 format. That PR changed deduplication behavior for a separate commercial-feed case, so this issue should not rely on it as the source of the naming migration.

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

Add a shared helper in CardUtils.ts that reconciles an assigned direct-feed card with the current feed names.

The helper should:

  1. Preserve the existing exact normalized-name match.
  2. Restrict the legacy-name migration logic to the same Brex feed.
  3. Parse only a trailing - <last 4> suffix.
  4. Require the normalized legacy name to equal the normalized base name.
  5. When card.lastFourPAN exists, require it to equal the parsed suffix.
  6. Return a match only when exactly one accountList entry satisfies the conditions.
  7. When lastFourPAN is missing, use the name-only fallback only if exactly one current entry has that base name. If multiple cards have the same cardholder name, do not infer a match.

Use that helper in both reconciliation paths:

  • In buildCompanyCardEntries(), reconcile assigned cards against accountList before Phase 2. When a match is found, keep the original assigned Card as assignedCard, but cover both the legacy and current normalized names so the current entry is not added again as unassigned.
  • In getFilteredCardList(), exclude an accountList entry when an assigned card from the same Brex feed resolves to it through the same helper.
  • Reuse the same check in the confirmation step as a defensive guard against a stale Assign card screen. The backend should still remain authoritative for preventing concurrent or external duplicate assignments.

This keeps the company-card table and Assign card flow consistent and avoids duplicating identity rules in two places.

What alternative solutions did you explore? (Optional)

Strip - <last 4> from every name

Rejected because a cardholder can have multiple Brex cards, for example John Smith - 1111 and John Smith - 2222. Collapsing both names to John Smith would hide the second unassigned card after the first one is assigned.

Match only by lastFourPAN

Rejected because last-four values can collide across different cardholders. The match must require both the normalized base name and the PAN suffix.

Reuse resolveCardListEntry() unchanged with accountList

Rejected because its current suffix fallback does not verify the name prefix. It was designed for commercial-feed masked-number migrations and could associate an unrelated card that happens to share the same suffix.

Backend-only migration

A backend stable identifier would be the strongest long-term solution, especially because direct-feed assignment currently uses cardName as its identifier. However, the reported duplicate rows and Assign card option are directly produced by confirmed frontend comparison logic. The frontend must remain compatible with legacy assigned records even if the backend is later migrated.

An internal engineer should separately confirm that AssignCompanyCard rejects a second assignment of the same physical Brex card, because the issue has not confirmed duplicate expenses or the backend behavior.

What automated tests can you add to prevent this from re-occurring?

Add tests covering both buildCompanyCardEntries() and getFilteredCardList():

  1. Legacy assigned John Smith with lastFourPAN: "1234" matches John Smith - 1234 and produces only one assigned entry.
  2. The matched entry is absent from the Assign card list.
  3. Given John Smith - 1111 and John Smith - 2222, an assigned card with lastFourPAN: "1111" only hides/matches the first card.
  4. A different lastFourPAN does not match.
  5. A legacy card without lastFourPAN matches a single unambiguous candidate.
  6. A legacy card without lastFourPAN does not match when multiple current cards share the same base name.
  7. A card from a different feed does not match merely because its base name and last four digits are equal.
  8. Existing exact-name behavior remains unchanged.

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

switch-coders avatar Oct 25 '26 21:10 switch-coders

⚠️ Missing/invalid email or upwork profile link. Please make sure you add both your Expensify email and Upwork profile link in the format specified.

melvin-bot[bot] avatar Oct 25 '26 21:10 melvin-bot[bot]

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

switch-coders avatar Oct 25 '26 22:10 switch-coders

✅ Contributor details stored successfully. Thank you for contributing to Expensify!

melvin-bot[bot] avatar Oct 25 '26 22:10 melvin-bot[bot]

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

melvin-bot[bot] avatar Oct 26 '26 21:10 melvin-bot[bot]

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

melvin-bot[bot] avatar Oct 28 '26 21:10 melvin-bot[bot]

@linhvovan29546 Still overdue 6 days?! Let's take care of this!

melvin-bot[bot] avatar Oct 30 '26 21:10 melvin-bot[bot]

Proposal

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

During the Assign Card flow for commercial/company feeds (such as Brex), cards that were already assigned when the feed provided still appear as unassigned options after the provider updates the card name format to - <last 4 digits>.

What is the root cause of that problem?

In src/libs/CardUtils.ts (getFilteredCardList, lines 1351–1393), already-assigned cards are collected into ssignedCards = new Set(Object.values(workspaceCardFeeds ?? {}).flatMap(...).map((card) => card.cardName)) and filtered out of customFeedCardsToAssign using an exact string match: s !assignedCards.has(cardName) When a commercial card provider (like Brex) transitions a feed's card identifier from to - (or when lastFourPAN / encryptedCardNumber matches an existing assigned card whose cardName was stored without the - suffix), exact string equality ssignedCards.has(cardName) fails to match the previously assigned card.

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

In src/libs/CardUtils.ts (getFilteredCardList, lines 1351–1393):

  1. Normalize card names or check both exact match and - / stripped suffix match when filtering customFeedCardsToAssign against ssignedCards: s const isCardAlreadyAssigned = (cardName: string, assignedCards: Set<string>): boolean => { if (assignedCards.has(cardName)) { return true; } const baseName = cardName.replace(/\s*-\s*\d{4}$/, '').trim(); return baseName !== cardName && assignedCards.has(baseName); };
  2. Use !isCardAlreadyAssigned(cardName, assignedCards) in getFilteredCardList so cards that were assigned under are properly excluded when the feed reports - .

What alternative solutions did you explore? (Optional)

Performing the migration only on backend card sync was considered, but handling - normalization in getFilteredCardList immediately prevents duplicate card assignment in the client UI for existing feeds.

duongynhi000005-oss avatar Nov 01 '26 18:11 duongynhi000005-oss

@linhvovan29546 10 days overdue. I'm getting more depressed than Marvin.

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

@linhvovan29546 10 days overdue. Is anyone even seeing these? Hello?

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

Asking an internal engineer to confirm this here: https://expensify.slack.com/archives/C049HHMV9SM/p1793089911143509?thread_ts=1792696825.984409&cid=C049HHMV9SM

linhvovan29546 avatar Nov 04 '26 02:11 linhvovan29546