Skip to content

Skip non-existent categories when importing merchant rules from spreadsheet - #96522

Merged
NicolasBonet merged 5 commits into
mainfrom
nicolas-merchant-rules-import-category-validation
Jul 22, 2026
Merged

NicolasBonet merged 5 commits into
mainfrom
nicolas-merchant-rules-import-category-validation

Conversation

@NicolasBonet

@NicolasBonet NicolasBonet commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

Explanation of Change

Merchant rules can only reference categories that exist on the workspace — the manual flow's category picker enforces this by only offering existing enabled categories. The spreadsheet import flow, however, accepted the "Updated category" cell as free text, so a rule could be stored with a category that doesn't exist on the policy and would never be applied to a matching expense.

This PR makes the import flow enforce the same constraint as the manual flow:

  • Each imported "Updated category" cell is resolved against the policy's enabled (and not pending-deletion) categories, case-insensitively and against the decoded category name (policy category names are stored HTML-encoded, spreadsheet cells are plain text).
  • A matching cell stores the canonical policy category name, so casing and encoding differences (e.g. food & drink → Food & Drink) no longer produce dangling references.
  • A cell that doesn't match any workspace category is dropped from the rule, and the confirmation modal reports how many categories were skipped. If dropping the category leaves a row with no actions at all, the row is skipped entirely.

Fixed Issues

$ #96389
PROPOSAL: #96389 (comment)

Tests

Precondition: a workspace with Rules enabled and Categories enabled, including the default Travel category. Download the following CSV:
merchant-rules-test.csv

  1. Go to workspace settings > Rules.
  2. Click More > Import merchant rules.
  3. Upload the merchant-rules-test.csv file.
  4. Map the columns: Merchant → "Merchant is", Category → "Updated category", Description → "Updated description", then click Import.
  5. Verify the confirmation modal says "6 merchant rules have been added. 2 categories were skipped because they don't exist in this workspace."
  6. Open the imported rules and verify the Starbucks, Uber, and Delta rules all show the category as Travel (the workspace's casing, even though the CSV cells were Travel, TRAVEL, and travel), and the Shell and Walmart rules have a description but no category set (their categories Fuel Expenses and Nonexistent Category don't exist on the workspace).
  7. In the workspace chat, create an expense with the merchant Starbucks and verify the Travel category is applied to the expense.
  8. Import the same CSV again, but this time map Description → "Ignore" (keep Merchant → "Merchant is" and Category → "Updated category").
  9. Verify the modal says "3 merchant rules have been added. 2 categories were skipped because they don't exist in this workspace." — the Shell, Walmart, and Amazon rows are skipped entirely because dropping the unknown category leaves them with nothing to update.
  • Verify that no errors appear in the JS console

Offline tests

  1. Complete the Tests section above first (both imports).
  2. Go offline.
  3. Repeat the second import from Tests step 8 (same CSV, Description → "Ignore").
  4. Verify the modal "No merchant rules have been added, since they all already exist. 2 categories were skipped because they don't exist in this workspace." still appears while offline — every row is either a duplicate or fully skipped, so no API call is made.

QA Steps

Same as tests.

  • Verify that no errors appear in the JS console

PR Author Checklist

  • I linked the correct issue in the ### Fixed Issues section above
  • I wrote clear testing steps that cover the changes made in this PR
    • I added steps for local testing in the Tests section
    • I added steps for the expected offline behavior in the Offline steps section
    • I added steps for Staging and/or Production testing in the QA steps section
    • I added steps to cover failure scenarios (i.e. verify an input displays the correct error message if the entered data is not correct)
    • I turned off my network connection and tested it while offline to ensure it matches the expected behavior (i.e. verify the default avatar icon is displayed if app is offline)
    • I tested this PR with a High Traffic account against the staging or production API to ensure there are no regressions (e.g. long loading states that impact usability).
  • I included screenshots or videos for tests on all platforms
  • I ran the tests on all platforms & verified they passed on:
    • Android: Native
    • Android: mWeb Chrome
    • iOS: Native
    • iOS: mWeb Safari
    • MacOS: Chrome / Safari
  • I verified there are no console errors (if there's a console error not related to the PR, report it or open an issue for it to be fixed)
  • I followed proper code patterns (see Reviewing the code)
    • I verified that comments were added to code that is not self explanatory
    • I verified that any new or modified comments were clear, correct English, and explained "why" the code was doing something instead of only explaining "what" the code was doing.
    • I verified any copy / text that was added to the app is grammatically correct in English. It adheres to proper capitalization guidelines (note: only the first word of header/labels should be capitalized), and is either coming verbatim from figma or has been approved by marketing (in order to get marketing approval, ask the Bug Zero team member to add the Waiting for copy label to the issue)
  • If a new code pattern is added I verified it was agreed to be used by multiple Expensify engineers
  • I followed the guidelines as stated in the Review Guidelines
  • I tested other components that can be impacted by my changes (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar are working as expected)
  • If a new CSS style is added I verified that:
    • A similar style doesn't already exist
    • The style can't be created with an existing StyleUtils function (i.e. StyleUtils.getBackgroundAndBorderStyle(theme.componentBG))
  • If new assets were added or existing ones were modified, I verified that:
    • The assets are optimized and compressed (for SVG files, run npm run compress-svg)
    • The assets load correctly across all supported platforms.
  • If the PR modifies code that runs when editing or sending messages, I tested and verified there is no unexpected behavior for all supported markdown - URLs, single line code, code blocks, quotes, headings, bold, strikethrough, and italic.
  • If the PR modifies a generic component, I tested and verified that those changes do not break usages of that component in the rest of the App (i.e. if a shared library or component like Avatar is modified, I verified that Avatar is working as expected in all cases)
  • If the PR modifies a component related to any of the existing Storybook stories, I tested and verified all stories for that component are still working as expected.
  • If the PR modifies a component or page that can be accessed by a direct deeplink, I verified that the code functions as expected when the deeplink is used - from a logged in and logged out account.
  • If the PR modifies the UI (e.g. new buttons, new UI components, changing the padding/spacing/sizing, moving components, etc) or modifies the form input styles:
    • I verified that all the inputs inside a form are aligned with each other.
    • I added Design label and/or tagged @Expensify/design so the design team can review the changes.
  • I added unit tests for any new feature or bug fix in this PR to help automatically prevent regressions in this user flow.
  • If the main branch was merged into this PR after a review, I tested again and verified the outcome was still expected according to the Test steps.

Screenshots/Videos

Android: Native
Android: mWeb Chrome
iOS: Native
iOS: mWeb Safari
MacOS: Chrome / Safari pr96522-1-column-mapping pr96522-2-mixed-import-modal pr96522-3-rule-canonical-category pr96522-4-all-invalid-modal pr96522-5-expense-category-applied

Merchant rules can only reference categories that exist on the
workspace (the manual flow's picker enforces this), so the spreadsheet
import now resolves each "Updated category" cell against the policy's
enabled categories (case-insensitively, against the decoded name) and
stores the canonical name. Cells that don't match any category are
dropped and reported in the confirmation modal instead of being stored
as a category the rule could never apply.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@OSBotify

Copy link
Copy Markdown
Contributor

🦜 Polyglot Parrot! 🦜

Squawk! Looks like you added some shiny new English strings. Allow me to parrot them back to you in other tongues:

View the translation diff
diff --git a/src/languages/de.ts b/src/languages/de.ts
index ef0d300d9f9..fa21f11ca2c 100644
--- a/src/languages/de.ts
+++ b/src/languages/de.ts
@@ -1171,11 +1171,15 @@ const translations: TranslationDeepObject<typeof en> = {
         importTagsSuccessfulDescription: ({tags}: {tags: number}) => (tags > 1 ? `${tags} Tags wurden hinzugefügt.` : '1 Tag wurde hinzugefügt.'),
         importMultiLevelTagsSuccessfulDescription: 'Mehrstufige Tags wurden hinzugefügt.',
         importPerDiemRatesSuccessfulDescription: ({rates}: {rates: number}) => (rates > 1 ? `${rates} Tagessätze wurden hinzugefügt.` : '1 Tagegeldsatz wurde hinzugefügt.'),
-        importMerchantRulesSuccessfulDescription: ({rules}: {rules: number}) => {
+        importMerchantRulesSuccessfulDescription: ({rules, duplicates = 0, invalidCategories = 0}: {rules: number; duplicates?: number; invalidCategories?: number}) => {
+            const invalidCategoriesNote =
+                invalidCategories > 0
+                    ? `${invalidCategories === 1 ? '1 Kategorie wurde' : `${invalidCategories} Kategorien waren`} übersprungen, weil ${invalidCategories === 1 ? 'tut es nicht' : 'sie nicht'} in diesem Workspace vorhanden sind.`
+                    : '';
             if (rules === 0) {
-                return 'Es wurden keine Händlerregeln hinzugefügt, da sie alle bereits existieren.';
+                return `${duplicates > 0 ? 'Es wurden keine Händlerregeln hinzugefügt, da sie alle bereits existieren.' : 'Es wurden keine Händlerregeln hinzugefügt.'}${invalidCategoriesNote}`;
             }
-            return rules > 1 ? `${rules} Händlerregeln wurden hinzugefügt.` : '1 Händlerregel wurde hinzugefügt.';
+            return `${rules > 1 ? `${rules} Händlerrichtlinien wurden hinzugefügt.` : '1 Händlerregel wurde hinzugefügt.'}${invalidCategoriesNote}`;
         },
         importMerchantRulesRequiredColumns:
             'Ups! Du musst mindestens eine Spalte („Händler ist“ oder „Händler enthält“) zuordnen sowie mindestens ein zu aktualisierendes Feld. Bitte überprüfe es und versuche es erneut.',
diff --git a/src/languages/es.ts b/src/languages/es.ts
index 46958bee7e9..57e23fe0b40 100644
--- a/src/languages/es.ts
+++ b/src/languages/es.ts
@@ -1134,12 +1134,12 @@ const translations: TranslationDeepObject<typeof en> = {
         importMerchantRulesSuccessfulDescription: ({rules, duplicates = 0, invalidCategories = 0}: {rules: number; duplicates?: number; invalidCategories?: number}) => {
             const invalidCategoriesNote =
                 invalidCategories > 0
-                    ? ` ${invalidCategories === 1 ? 'Se omitió 1 categoría porque no existe' : `Se omitieron ${invalidCategories} categorías porque no existen`} en este espacio de trabajo.`
+                    ? `${invalidCategories === 1 ? '1 categoría fue' : `${invalidCategories} categorías eran`} omitido porque ${invalidCategories === 1 ? 'no lo hace' : 'no lo hacen'} existen en este espacio de trabajo.`
                     : '';
             if (rules === 0) {
-                return `${duplicates > 0 ? 'No se han añadido reglas de comerciante, ya que todas ya existen.' : 'No se han añadido reglas de comerciante.'}${invalidCategoriesNote}`;
+                return `${duplicates > 0 ? 'No se han añadido reglas de comercio, ya que todas ya existen.' : 'No se ha añadido ninguna regla de comerciante.'}${invalidCategoriesNote}`;
             }
-            return `${rules > 1 ? `Se han añadido ${rules} reglas de comerciante.` : 'Se ha añadido 1 regla de comerciante.'}${invalidCategoriesNote}`;
+            return `${rules > 1 ? `Se han añadido ${rules} reglas de comercio.` : 'Se ha añadido 1 regla de comerciante.'}${invalidCategoriesNote}`;
         },
         importMerchantRulesRequiredColumns:
             '¡Ups! Debes asignar al menos una columna "El comerciante es" o "El comerciante contiene", además de al menos un campo para actualizar. Por favor, revisa e inténtalo de nuevo.',
diff --git a/src/languages/fr.ts b/src/languages/fr.ts
index 3d3d2401ab0..dea44f0da9a 100644
--- a/src/languages/fr.ts
+++ b/src/languages/fr.ts
@@ -1175,11 +1175,15 @@ const translations: TranslationDeepObject<typeof en> = {
         importTagsSuccessfulDescription: ({tags}: {tags: number}) => (tags > 1 ? `${tags} tags ont été ajoutés.` : '1 tag a été ajouté.'),
         importMultiLevelTagsSuccessfulDescription: 'Des tags à plusieurs niveaux ont été ajoutés.',
         importPerDiemRatesSuccessfulDescription: ({rates}: {rates: number}) => (rates > 1 ? `${rates} indemnités journalières ont été ajoutées.` : '1 taux de per diem a été ajouté.'),
-        importMerchantRulesSuccessfulDescription: ({rules}: {rules: number}) => {
+        importMerchantRulesSuccessfulDescription: ({rules, duplicates = 0, invalidCategories = 0}: {rules: number; duplicates?: number; invalidCategories?: number}) => {
+            const invalidCategoriesNote =
+                invalidCategories > 0
+                    ? `${invalidCategories === 1 ? '1 catégorie a été' : `${invalidCategories} catégories ont été`} ignoré car ${invalidCategories === 1 ? 'ça ne marche pas' : 'ils ne le font pas'} existe dans cet espace de travail.`
+                    : '';
             if (rules === 0) {
-                return "Aucune règle de marchand n'a été ajoutée, car elles existent toutes déjà.";
+                return `${duplicates > 0 ? 'Aucune règle de commerçant n’a été ajoutée, car elles existent déjà toutes.' : 'Aucune règle de commerçant n’a été ajoutée.'}${invalidCategoriesNote}`;
             }
-            return rules > 1 ? `${rules} règles de marchand ont été ajoutées.` : '1 règle de marchand a été ajoutée.';
+            return `${rules > 1 ? `${rules} règles de marchand ont été ajoutées.` : '1 règle de commerçant a été ajoutée.'}${invalidCategoriesNote}`;
         },
         importMerchantRulesRequiredColumns:
             'Oups ! Vous devez associer au moins une colonne « Le marchand est » ou « Le marchand contient », ainsi qu’au moins un champ à mettre à jour. Veuillez examiner et réessayer.',
diff --git a/src/languages/it.ts b/src/languages/it.ts
index cbce8381f41..5760c57d10b 100644
--- a/src/languages/it.ts
+++ b/src/languages/it.ts
@@ -1172,11 +1172,15 @@ const translations: TranslationDeepObject<typeof en> = {
         importTagsSuccessfulDescription: ({tags}: {tags: number}) => (tags > 1 ? `Sono stati aggiunti ${tags} tag.` : 'È stato aggiunto 1 tag.'),
         importMultiLevelTagsSuccessfulDescription: 'Sono state aggiunte etichette multilivello.',
         importPerDiemRatesSuccessfulDescription: ({rates}: {rates: number}) => (rates > 1 ? `Sono state aggiunte le diarie giornaliere ${rates}.` : 'È stata aggiunta 1 diaria.'),
-        importMerchantRulesSuccessfulDescription: ({rules}: {rules: number}) => {
+        importMerchantRulesSuccessfulDescription: ({rules, duplicates = 0, invalidCategories = 0}: {rules: number; duplicates?: number; invalidCategories?: number}) => {
+            const invalidCategoriesNote =
+                invalidCategories > 0
+                    ? `${invalidCategories === 1 ? '1 categoria è stata' : `${invalidCategories} categorie erano`} saltato perché ${invalidCategories === 1 ? 'non lo fa' : 'non lo fanno'} esiste in questo workspace.`
+                    : '';
             if (rules === 0) {
-                return 'Nessuna regola esercente è stata aggiunta, poiché esistono già tutte.';
+                return `${duplicates > 0 ? 'Non è stata aggiunta alcuna regola per l’esercente, perché esistono già tutte.' : 'Non è stata aggiunta alcuna regola per l’esercente.'}${invalidCategoriesNote}`;
             }
-            return rules > 1 ? `Sono state aggiunte ${rules} regole esercente.` : 'È stata aggiunta 1 regola esercente.';
+            return `${rules > 1 ? `Sono state aggiunte ${rules} regole fornitore.` : 'È stata aggiunta 1 regola commerciante.'}${invalidCategoriesNote}`;
         },
         importMerchantRulesRequiredColumns: 'Ops! Devi mappare almeno una colonna “L’esercente è” o “L’esercente contiene”, oltre ad almeno un campo da aggiornare. Controlla e riprova.',
         importTransactionsSuccessfulDescription: ({transactions}: {transactions: number}) =>
diff --git a/src/languages/ja.ts b/src/languages/ja.ts
index 454f27960e3..b92a5aae06c 100644
--- a/src/languages/ja.ts
+++ b/src/languages/ja.ts
@@ -1154,11 +1154,15 @@ const translations: TranslationDeepObject<typeof en> = {
         importTagsSuccessfulDescription: ({tags}: {tags: number}) => (tags > 1 ? `${tags} 個のタグを追加しました。` : 'タグを1件追加しました。'),
         importMultiLevelTagsSuccessfulDescription: 'マルチレベルタグが追加されました。',
         importPerDiemRatesSuccessfulDescription: ({rates}: {rates: number}) => (rates > 1 ? `${rates}件の日当レートが追加されました。` : '1件の日当レートが追加されました。'),
-        importMerchantRulesSuccessfulDescription: ({rules}: {rules: number}) => {
+        importMerchantRulesSuccessfulDescription: ({rules, duplicates = 0, invalidCategories = 0}: {rules: number; duplicates?: number; invalidCategories?: number}) => {
+            const invalidCategoriesNote =
+                invalidCategories > 0
+                    ? `${invalidCategories === 1 ? 'そうではありません' : '彼らはしません'} がこのワークスペースに存在するため、${invalidCategories === 1 ? 'カテゴリ 1 件が' : `${invalidCategories} 個のカテゴリがありました`} をスキップしました。`
+                    : '';
             if (rules === 0) {
-                return 'すべての加盟店ルールが既に存在するため、追加されませんでした。';
+                return `${duplicates > 0 ? 'すでにすべてのルールが存在しているため、マーチャントルールは追加されませんでした。' : 'マーチャントルールはまだ追加されていません。'}${invalidCategoriesNote}`;
             }
-            return rules > 1 ? `${rules}件の加盟店ルールが追加されました。` : '1件の加盟店ルールが追加されました。';
+            return `${rules > 1 ? `${rules} 件のマーチャントルールが追加されました。` : 'マーチャントルールが 1 件追加されました。'}${invalidCategoriesNote}`;
         },
         importMerchantRulesRequiredColumns:
             'おっと!「加盟店が一致」または「加盟店を含む」の列を少なくとも1つ、さらに更新するフィールドを少なくとも1つマッピングしてください。確認してもう一度お試しください。',
diff --git a/src/languages/nl.ts b/src/languages/nl.ts
index 336718d2023..8421566b9b8 100644
--- a/src/languages/nl.ts
+++ b/src/languages/nl.ts
@@ -1170,11 +1170,15 @@ const translations: TranslationDeepObject<typeof en> = {
         importTagsSuccessfulDescription: ({tags}: {tags: number}) => (tags > 1 ? `${tags} tags zijn toegevoegd.` : '1 tag is toegevoegd.'),
         importMultiLevelTagsSuccessfulDescription: 'Tags met meerdere niveaus zijn toegevoegd.',
         importPerDiemRatesSuccessfulDescription: ({rates}: {rates: number}) => (rates > 1 ? `${rates} per diem-tarieven zijn toegevoegd.` : '1 dagvergoeding is toegevoegd.'),
-        importMerchantRulesSuccessfulDescription: ({rules}: {rules: number}) => {
+        importMerchantRulesSuccessfulDescription: ({rules, duplicates = 0, invalidCategories = 0}: {rules: number; duplicates?: number; invalidCategories?: number}) => {
+            const invalidCategoriesNote =
+                invalidCategories > 0
+                    ? `${invalidCategories === 1 ? '1 categorie is' : `${invalidCategories} categorieën waren`} overgeslagen omdat ${invalidCategories === 1 ? 'dat doet het niet' : 'zij niet'} in deze workspace bestaat.`
+                    : '';
             if (rules === 0) {
-                return 'Er zijn geen handelaarregels toegevoegd, omdat ze allemaal al bestaan.';
+                return `${duplicates > 0 ? 'Er zijn geen handelaarregels toegevoegd, omdat ze allemaal al bestaan.' : 'Er zijn geen handelsregels toegevoegd.'}${invalidCategoriesNote}`;
             }
-            return rules > 1 ? `${rules} handelaarregels zijn toegevoegd.` : '1 handelaarregel is toegevoegd.';
+            return `${rules > 1 ? `${rules} verkoopregelaars zijn toegevoegd.` : '1 merchantregel is toegevoegd.'}${invalidCategoriesNote}`;
         },
         importMerchantRulesRequiredColumns:
             'Oeps! Je moet ten minste één kolom "Handelaar is" of "Handelaar bevat" toewijzen, plus ten minste één veld om bij te werken. Controleer het en probeer het opnieuw.',
diff --git a/src/languages/pl.ts b/src/languages/pl.ts
index 7dacc8548a0..c4b13904b76 100644
--- a/src/languages/pl.ts
+++ b/src/languages/pl.ts
@@ -1167,11 +1167,15 @@ const translations: TranslationDeepObject<typeof en> = {
         importTagsSuccessfulDescription: ({tags}: {tags: number}) => (tags > 1 ? `Dodano ${tags} tagów.` : 'Dodano 1 znacznik.'),
         importMultiLevelTagsSuccessfulDescription: 'Dodano wielopoziomowe tagi.',
         importPerDiemRatesSuccessfulDescription: ({rates}: {rates: number}) => (rates > 1 ? `Dodano stawki diety: ${rates}.` : 'Dodano 1 stawkę diety.'),
-        importMerchantRulesSuccessfulDescription: ({rules}: {rules: number}) => {
+        importMerchantRulesSuccessfulDescription: ({rules, duplicates = 0, invalidCategories = 0}: {rules: number; duplicates?: number; invalidCategories?: number}) => {
+            const invalidCategoriesNote =
+                invalidCategories > 0
+                    ? `${invalidCategories === 1 ? '1 kategoria została' : `${invalidCategories} kategorie były`} pominięto, ponieważ ${invalidCategories === 1 ? 'nie działa' : 'oni nie'} istnieje w tym obszarze roboczym.`
+                    : '';
             if (rules === 0) {
-                return 'Nie dodano żadnych reguł sprzedawcy, ponieważ wszystkie już istnieją.';
+                return `${duplicates > 0 ? 'Nie dodano żadnych reguł sprzedawców, ponieważ wszystkie już istnieją.' : 'Nie dodano żadnych reguł dla sprzedawcy.'}${invalidCategoriesNote}`;
             }
-            return rules > 1 ? `Dodano reguły sprzedawcy: ${rules}.` : 'Dodano 1 regułę sprzedawcy.';
+            return `${rules > 1 ? `Dodano ${rules} reguł sprzedawców.` : 'Dodano 1 regułę sprzedawcy.'}${invalidCategoriesNote}`;
         },
         importMerchantRulesRequiredColumns:
             'Ups! Musisz zmapować co najmniej jedną kolumnę „Sprzedawca to” lub „Sprzedawca zawiera” oraz co najmniej jedno pole do aktualizacji. Sprawdź i spróbuj ponownie.',
diff --git a/src/languages/pt-BR.ts b/src/languages/pt-BR.ts
index 0059a89ff8f..50839b69ee4 100644
--- a/src/languages/pt-BR.ts
+++ b/src/languages/pt-BR.ts
@@ -1170,11 +1170,15 @@ const translations: TranslationDeepObject<typeof en> = {
         importTagsSuccessfulDescription: ({tags}: {tags: number}) => (tags > 1 ? `${tags} tags foram adicionadas.` : '1 tag foi adicionada.'),
         importMultiLevelTagsSuccessfulDescription: 'Tags de vários níveis foram adicionadas.',
         importPerDiemRatesSuccessfulDescription: ({rates}: {rates: number}) => (rates > 1 ? `Foram adicionadas ${rates} diárias.` : '1 diária foi adicionada.'),
-        importMerchantRulesSuccessfulDescription: ({rules}: {rules: number}) => {
+        importMerchantRulesSuccessfulDescription: ({rules, duplicates = 0, invalidCategories = 0}: {rules: number; duplicates?: number; invalidCategories?: number}) => {
+            const invalidCategoriesNote =
+                invalidCategories > 0
+                    ? `${invalidCategories === 1 ? '1 categoria foi' : `${invalidCategories} categorias foram`} ignorado porque ${invalidCategories === 1 ? 'não faz' : 'eles não'} existe neste workspace.`
+                    : '';
             if (rules === 0) {
-                return 'Nenhuma regra de comerciante foi adicionada, pois todas já existem.';
+                return `${duplicates > 0 ? 'Nenhuma regra de comerciante foi adicionada, pois todas elas já existem.' : 'Nenhuma regra de comerciante foi adicionada.'}${invalidCategoriesNote}`;
             }
-            return rules > 1 ? `Foram adicionadas ${rules} regras de comerciante.` : '1 regra de comerciante foi adicionada.';
+            return `${rules > 1 ? `${rules} regras de comerciante foram adicionadas.` : '1 regra de comerciante foi adicionada.'}${invalidCategoriesNote}`;
         },
         importMerchantRulesRequiredColumns:
             'Ops! Você precisa mapear pelo menos uma coluna "O comerciante é" ou "O comerciante contém", além de pelo menos um campo para atualizar. Revise e tente novamente.',
diff --git a/src/languages/zh-hans.ts b/src/languages/zh-hans.ts
index 7af5b5ed79f..9ed8dda8f16 100644
--- a/src/languages/zh-hans.ts
+++ b/src/languages/zh-hans.ts
@@ -1126,11 +1126,15 @@ const translations: TranslationDeepObject<typeof en> = {
         importTagsSuccessfulDescription: ({tags}: {tags: number}) => (tags > 1 ? `已添加 ${tags} 个标签。` : '已添加 1 个标签。'),
         importMultiLevelTagsSuccessfulDescription: '已添加多级标签。',
         importPerDiemRatesSuccessfulDescription: ({rates}: {rates: number}) => (rates > 1 ? `已添加 ${rates} 个每日补贴标准。` : '已添加 1 条日津贴费率。'),
-        importMerchantRulesSuccessfulDescription: ({rules}: {rules: number}) => {
+        importMerchantRulesSuccessfulDescription: ({rules, duplicates = 0, invalidCategories = 0}: {rules: number; duplicates?: number; invalidCategories?: number}) => {
+            const invalidCategoriesNote =
+                invalidCategories > 0
+                    ? `已跳过 ${invalidCategories === 1 ? '1 个类别被' : `有 ${invalidCategories} 个类别被`},因为此工作区中已存在 ${invalidCategories === 1 ? '它不会' : '他们不会'}。`
+                    : '';
             if (rules === 0) {
-                return '未添加任何商户规则,因为它们均已存在。';
+                return `${duplicates > 0 ? '未添加商家规则,因为它们已经全部存在。' : '尚未添加任何商户规则。'}${invalidCategoriesNote}`;
             }
-            return rules > 1 ? `已添加 ${rules} 条商户规则。` : '已添加 1 条商户规则。';
+            return `${rules > 1 ? `已添加 ${rules} 条商户规则。` : '已添加 1 条商家规则。'}${invalidCategoriesNote}`;
         },
         importMerchantRulesRequiredColumns: '哎呀!您必须至少映射一列“商户为”或“商户包含”,并且至少映射一个要更新的字段。请检查后重试。',
         importTransactionsSuccessfulDescription: ({transactions}: {transactions: number}) => (transactions > 1 ? `已导入 ${transactions} 笔交易。` : '已导入 1 笔交易。'),

Note

You can apply these changes to your branch by copying the patch to your clipboard, then running pbpaste | git apply 😉

View workflow run

@codecov

codecov Bot commented Jul 20, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ Changes either increased or maintained existing code coverage, great job!

Files with missing lines Coverage Δ
src/libs/actions/Policy/Rules.ts 29.92% <0.00%> (ø)
.../rules/MerchantRules/ImportedMerchantRulesPage.tsx 10.63% <36.84%> (+4.18%) ⬆️
... and 10 files with indirect coverage changes

@NicolasBonet
NicolasBonet marked this pull request as ready for review July 20, 2026 20:18
@NicolasBonet
NicolasBonet requested review from a team as code owners July 20, 2026 20:18
@melvin-bot
melvin-bot Bot requested review from Ollyws and removed request for a team July 20, 2026 20:18
@melvin-bot

melvin-bot Bot commented Jul 20, 2026

Copy link
Copy Markdown

@Ollyws Please copy/paste the Reviewer Checklist from here into a new comment on this PR and complete it. If you have the K2 extension, you can simply click: [this button]

@melvin-bot
melvin-bot Bot requested review from heyjennahay and removed request for a team July 20, 2026 20:18

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: eeb0e96716

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

The category lookup validates imported cells against the policy's
categories, so an unloaded collection (e.g. after a cache clear) would
wrongly treat every category cell as invalid. Fetch the categories on
focus and on reconnect, mirroring MerchantRulePageBase.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@Ollyws

Ollyws commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor

Reviewer Checklist

  • I have verified the author checklist is complete (all boxes are checked off).
  • I verified the correct issue is linked in the ### Fixed Issues section above
  • I verified testing steps are clear and they cover the changes made in this PR
    • I verified the steps for local testing are in the Tests section
    • I verified the steps for Staging and/or Production testing are in the QA steps section
    • I verified the steps cover any possible failure scenarios (i.e. verify an input displays the correct error message if the entered data is not correct)
    • I turned off my network connection and tested it while offline to ensure it matches the expected behavior (i.e. verify the default avatar icon is displayed if app is offline)
  • I checked that screenshots or videos are included for tests on all platforms
  • I included screenshots or videos for tests on all platforms
  • I verified that the composer does not automatically focus or open the keyboard on mobile unless explicitly intended. This includes checking that returning the app from the background does not unexpectedly open the keyboard.
  • I verified tests pass on all platforms & I tested again on:
    • Android: HybridApp
    • Android: mWeb Chrome
    • iOS: HybridApp
    • iOS: mWeb Safari
    • MacOS: Chrome / Safari
  • If there are any errors in the console that are unrelated to this PR, I either fixed them (preferred) or linked to where I reported them in Slack
  • I verified proper code patterns were followed (see Reviewing the code)
    • I verified that comments were added to code that is not self explanatory
    • I verified that any new or modified comments were clear, correct English, and explained "why" the code was doing something instead of only explaining "what" the code was doing.
    • I verified any copy / text that was added to the app is grammatically correct in English. It adheres to proper capitalization guidelines (note: only the first word of header/labels should be capitalized), and is either coming verbatim from figma or has been approved by marketing (in order to get marketing approval, ask the Bug Zero team member to add the Waiting for copy label to the issue)
  • If a new code pattern is added I verified it was agreed to be used by multiple Expensify engineers
  • I verified that this PR follows the guidelines as stated in the Review Guidelines
  • I verified other components that can be impacted by these changes have been tested, and I retested again (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar have been tested & I retested again)
  • If a new component is created I verified that:
    • A similar component doesn't exist in the codebase
    • All props are defined accurately
    • The component has a clear name that is non-ambiguous and the purpose of the component can be inferred from the name alone
    • The only data being stored in the state is data necessary for rendering and nothing else
    • The component has the minimum amount of code necessary for its purpose, and it is broken down into smaller components in order to separate concerns and functions
  • If a new CSS style is added I verified that:
    • A similar style doesn't already exist
    • The style can't be created with an existing StyleUtils function (i.e. StyleUtils.getBackgroundAndBorderStyle(theme.componentBG)
  • If the PR modifies code that runs when editing or sending messages, I tested and verified there is no unexpected behavior for all supported markdown - URLs, single line code, code blocks, quotes, headings, bold, strikethrough, and italic.
  • If the PR modifies a generic component, I tested and verified that those changes do not break usages of that component in the rest of the App (i.e. if a shared library or component like Avatar is modified, I verified that Avatar is working as expected in all cases)
  • If the PR modifies a component related to any of the existing Storybook stories, I tested and verified all stories for that component are still working as expected.
  • If the PR modifies a component or page that can be accessed by a direct deeplink, I verified that the code functions as expected when the deeplink is used - from a logged in and logged out account.
  • If the PR modifies the UI (e.g. new buttons, new UI components, changing the padding/spacing/sizing, moving components, etc) or modifies the form input styles:
    • I verified that all the inputs inside a form are aligned with each other.
    • I added Design label and/or tagged @Expensify/design so the design team can review the changes.
  • For any bug fix or new feature in this PR, I verified that sufficient unit tests are included to prevent regressions in this flow.
  • If the main branch was merged into this PR after a review, I tested again and verified the outcome was still expected according to the Test steps.
  • I have checked off every checkbox in the PR reviewer checklist, including those that don't apply to this PR.

Screenshots/Videos

Android: HybridApp Android_Native_01 Android_Native_02 Android_Native_03
Android: mWeb Chrome Android_Chrome_02 Android_Chrome_03 Android_Chrome
iOS: HybridApp iOS_Native_02 iOS_Native_03 iOS_Native
iOS: mWeb Safari iOS_Safari_01 iOS_Safari_02 iOS_Safari_03
MacOS: Chrome / Safari MacOS_Chrome_02 MacOS_Chrome_03 MacOS_Chrome

@Ollyws Ollyws left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM.

@melvin-bot
melvin-bot Bot requested a review from lakchote July 21, 2026 15:55
@melvin-bot

melvin-bot Bot commented Jul 21, 2026

Copy link
Copy Markdown

@lakchote Please copy/paste the Reviewer Checklist from here into a new comment on this PR and complete it. If you have the K2 extension, you can simply click: [this button]

@lakchote lakchote left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left some comments


const updatedMerchant = getCellValue(updatedMerchantColumn, rowIndex);
const category = getCellValue(categoryColumn, rowIndex);
// A rule may only reference a category that exists on the workspace, so unknown cells are dropped

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Put an empty line before the comment unless it’s on the first line of a block.

See https://github.com/Expensify/Style-Guides/blob/main/general.md#comments

Suggested change
// A rule may only reference a category that exists on the workspace, so unknown cells are dropped
// A rule may only reference a category that exists on the workspace, so unknown cells are dropped

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added!

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

NAB: next time if you accept the suggestion's content, please do so directly here by clicking Apply suggestion so we both get credit for it :)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Noted!

Comment on lines +98 to +104
/**
* Builds a lookup from decoded, lowercased category name to the canonical stored name for every category the
* manual "Add category" flow offers (enabled and not pending deletion). Imported "Updated category" cells are
* resolved through this map so a rule can only reference a category that exists on the workspace — mirroring the
* manual flow, where the category picker only offers existing categories — and so the rule stores the category
* exactly as the policy encodes it (policy category names are stored HTML-encoded, spreadsheet cells are plain text).
*/

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we slim down these AI comments? Explaining the why and not the what

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed.

@NicolasBonet
NicolasBonet requested a review from lakchote July 22, 2026 14:38

@lakchote lakchote left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@NicolasBonet

Copy link
Copy Markdown
Contributor Author

Product authorized here: #96389 (comment)

@NicolasBonet
NicolasBonet merged commit af1a310 into main Jul 22, 2026
41 checks passed
@NicolasBonet
NicolasBonet deleted the nicolas-merchant-rules-import-category-validation branch July 22, 2026 15:22
@OSBotify

Copy link
Copy Markdown
Contributor

✋ This PR was not deployed to staging yet because QA is ongoing. It will be automatically deployed to staging after the next production release.

@github-actions

Copy link
Copy Markdown
Contributor

🚧 NicolasBonet has triggered a test Expensify/App build. You can view the workflow run here.

@OSBotify OSBotify mentioned this pull request Jul 22, 2026
52 tasks done
@OSBotify

Copy link
Copy Markdown
Contributor

🚀 Deployed to staging by https://github.com/NicolasBonet in version: 9.4.43-0 🚀

platform result
🕸 web 🕸 success ✅
🤖 android 🤖 success ✅
🍎 iOS 🍎 success ✅

@MelvinBot

Copy link
Copy Markdown
Contributor

Help site review — no changes required

I reviewed this PR against the help site articles under docs/articles, and no documentation updates are needed.

Why: This PR is a correctness refinement to the spreadsheet import flow for merchant rules — imported "Updated category" cells are now resolved against the workspace's existing enabled categories (case-insensitive, HTML-decoded), unknown categories are dropped, and the confirmation modal reports how many were skipped.

The only merchant-rules help article, Workspace-Merchant-Rules.md, documents the manual creation flow (Rules → Add merchant rule) only. The spreadsheet import flow for merchant rules isn't documented anywhere in the help site today, so there's no existing content that this change makes inaccurate.

What I checked
  • Searched docs/articles for "merchant rule", "import merchant", "spreadsheet", and "CSV" — the merchant-rules import flow has no help-site coverage.
  • Confirmed Workspace-Merchant-Rules.md and Workspace-Rules.md don't mention importing rules from a spreadsheet.
  • The behavior this PR changes (dropping categories that don't exist on the workspace, and the "N categories were skipped…" modal copy) sits entirely inside that undocumented import flow — it's an edge-case validation fix, not a new user-facing capability.

Documenting the merchant-rules spreadsheet import flow end-to-end would be a net-new article covering a feature this PR didn't introduce — that's a separate, larger docs effort rather than something this PR requires. Happy to open that if you'd like it tracked.

@NicolasBonet, since no help site changes are required for this PR, I didn't open a docs PR. Let me know if you'd prefer the merchant-rules spreadsheet import flow documented as a separate effort and I'll create one.

@jponikarchuk

Copy link
Copy Markdown

This PR failing in offline test because of the issue #96842
This issue is reproducible in: All platforms

@OSBotify

Copy link
Copy Markdown
Contributor

🚀 Deployed to production by https://github.com/yuwenmemon in version: 9.4.43-1 🚀

platform result
🕸 web 🕸 success ✅
🤖 android 🤖 success ✅
🍎 iOS 🍎 success ✅

Bundle Size Analysis (Sentry):

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants