Skip to content

[No QA] [Bulk workspace edits] Add CopyPolicySettings action file and tests#89963

Draft
fedirjh wants to merge 17 commits intoExpensify:mainfrom
fedirjh:copy-policy-settings-actions
Draft

[No QA] [Bulk workspace edits] Add CopyPolicySettings action file and tests#89963
fedirjh wants to merge 17 commits intoExpensify:mainfrom
fedirjh:copy-policy-settings-actions

Conversation

@fedirjh
Copy link
Copy Markdown
Contributor

@fedirjh fedirjh commented May 7, 2026

Explanation of Change

Adds the action layer for the new "Copy configuration" RHP flow that's part of the Bulk workspace edits project. This is task 2 of the project — task 1 is the declarative plumbing in #89959 and this PR is stacked on top of it. Please review #89959 first.

What this PR adds

  1. src/libs/actions/Policy/CopyPolicySettings.ts — owns all logic that talks to Onyx and the API for the copy flow. Exports:

    • setCopyPolicySettingsData(data)Onyx.merge helper for COPY_POLICY_SETTINGS.
    • clearCopyPolicySettings() — clears the key when the flow exits.
    • requestCopyPolicySettingsNotification() — fires CopyPolicySettings_Notify.
    • PARTS_TO_POLICY_FIELDS — map of part key → list of Policy field names. Drives pendingFields expansion so existing OfflineWithFeedback wrappers grey out per settings tab during the copy.
    • buildCopyPolicySettingsData(sourcePolicy, targetPolicies, parts, allPolicyCategories, allPolicyTags) — produces {optimisticData, successData, failureData} following the four-step algorithm in the design doc:
      • Step 1: build the field patch from parts using the mapping table
      • Step 2: per-target merge with snapshot rollback; pendingFields keyed by Policy field names (not part names)
      • Step 3: SET-level overwrite of POLICY_CATEGORIES / POLICY_TAGS collection keys; failure data restores the target's snapshot
      • Step 4: drive currentStep on COPY_POLICY_SETTINGS itself ('loading' optimistically, cleared on failure, untouched on success — backend transitions to 'complete' via NVP)
    • copyPolicySettings(...) — entry point that calls API.write(WRITE_COMMANDS.COPY_POLICY_SETTINGS, ...).
  2. tests/actions/CopyPolicySettingsTest.ts — 20 unit tests for buildCopyPolicySettingsData covering each part key in isolation, collection key overwrites, failure rollback, and customUnits ID preservation.

  3. Translation key workspace.copyPolicySettings.error added to all 10 language files. The failureData updates surface this RBR via ErrorUtils.getMicroSecondOnyxErrorWithTranslationKey, which requires the key to exist in TranslationPaths.

Notes on customUnits preservation

Unlike Duplicate (which generates new unit IDs for the new policy), Copy Settings preserves each target's existing distance/per-diem unit ID — the source unit data is written under the target's existing ID. A new 13-character hex ID is generated only when the target has no unit of that type yet.

Fixed Issues

$ #88668
PROPOSAL: N/A

Tests

This PR has no UI surface yet (the pages it powers land in later issues). To verify the action layer:

  1. Pull the branch and run npm install.
  2. Run npm run typecheck — should pass with no errors.
  3. Run npx jest tests/actions/CopyPolicySettingsTest.ts — all 20 tests should pass.
  4. Run npm run lint on the changed files — should pass with no errors.
  5. Verify that no errors appear in the JS console.
  • Verify that no errors appear in the JS console

Offline tests

N/A — no runtime UI is wired up yet. The optimistic / failure data structure that this PR produces is what enables the offline pattern "B - Optimistic WITH Feedback" once the pages are wired up in follow-up issues.

QA Steps

This PR contains no user-facing changes and ships behind no UI entry point.

  • 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 any callback methods that were added or modified are named for what the method does and never what callback they handle (i.e. toggleReport and not onIconClick)
    • 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 shown in the product is localized by adding it to src/languages/* files and using the translation method
      • If any non-english text was added/modified, I used JaimeGPT to get English > Spanish translation. I then posted it in #expensify-open-source and it was approved by an internal Expensify engineer. Link to Slack message:
    • I verified all numbers, amounts, dates and phone numbers shown in the product are using the localization methods
    • 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)
    • I verified proper file naming conventions were followed for any new files or renamed files. All non-platform specific files are named after what they export and are not named "index.js". All platform-specific files are named for the platform the code supports as outlined in the README.
    • I verified the JSDocs style guidelines (in STYLE.md) were followed
  • 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)
  • I verified all code is DRY (the PR doesn't include any logic written more than once, with the exception of tests)
  • I verified any variables that can be defined as constants (ie. in CONST.ts or at the top of the file that uses the constant) are defined as such
  • I verified that if a function's arguments changed that all usages have also been updated correctly
  • If any new file was added I verified that:
    • The file has a description of what it does and/or why is needed at the top of the file if the code is not self explanatory
  • 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.
  • If a new page is added, I verified it's using the ScrollView component to make it scrollable when more elements are added to the page.
  • 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

N/A — no UI changes in this PR.

Android: Native

N/A

Android: mWeb Chrome

N/A

iOS: Native

N/A

iOS: mWeb Safari

N/A

MacOS: Chrome / Safari

N/A

fedirjh added 3 commits May 7, 2026 20:32
Adds the failure RBR message used when a bulk Copy Policy Settings
request fails. Defined across all ten language files so the
TranslationPaths type accepts it.
Implements the Onyx + API logic for the bulk Copy Policy Settings
flow. Exports:

- setCopyPolicySettingsData / clearCopyPolicySettings — Onyx helpers
- requestCopyPolicySettingsNotification — fires CopyPolicySettings_Notify
- PARTS_TO_POLICY_FIELDS — part key → list of Policy field names; drives
  pendingFields expansion so OfflineWithFeedback wrappers grey out
  per-tab during the copy
- buildCopyPolicySettingsData — produces optimistic/success/failure
  Onyx updates following the four-step algorithm in the design doc:
  field patch from source, per-target merge with snapshot rollback,
  SET-level overwrite of POLICY_CATEGORIES / POLICY_TAGS collection
  keys, and currentStep lifecycle on COPY_POLICY_SETTINGS
- copyPolicySettings — entry point that calls API.write

customUnits handling preserves each target's existing distance /
per-diem unit ID and only generates a new hex ID when the target has
no unit of that type yet.
Covers the four behaviors required by the design doc:
- each part key in isolation patches the right Policy fields and
  marks each one pending
- SET-level overwrite of POLICY_CATEGORIES and POLICY_TAGS collection
  keys, with failure data restoring the target's snapshot
- failure data restores the target's pre-copy field values
- customUnits preservation: target's existing distance / per-diem
  unit ID is reused; a new ID is generated only when absent
@melvin-bot
Copy link
Copy Markdown

melvin-bot Bot commented May 7, 2026

Hey, I noticed you changed src/languages/en.ts in a PR from a fork. For security reasons, translations are not generated automatically for PRs from forks.

If you want to automatically generate translations for other locales, an Expensify employee will have to:

  1. Look at the code and make sure there are no malicious changes.
  2. Run the Generate static translations GitHub workflow. If you have write access and the K2 extension, you can simply click: [this button]

Alternatively, if you are an external contributor, you can run the translation script locally with your own OpenAI API key. To learn more, try running:

npx ts-node ./scripts/generateTranslations.ts --help

Typically, you'd want to translate only what you changed by running npx ts-node ./scripts/generateTranslations.ts --compare-ref main

@fedirjh fedirjh changed the title Add CopyPolicySettings action file and tests [No QA] [Bulk workspace edits] Add CopyPolicySettings action file and tests May 7, 2026
@codecov
Copy link
Copy Markdown

codecov Bot commented May 7, 2026

Codecov Report

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

Files with missing lines Coverage Δ
src/libs/actions/Policy/CopyPolicySettings.ts 86.59% <86.59%> (ø)
... and 9 files with indirect coverage changes

fedirjh added 2 commits May 7, 2026 21:13
Switches from `import type * as OnyxCommon` to `import type {Errors}`
to satisfy the no-restricted-syntax rule that disallows namespace
imports from sibling modules.
@fedirjh fedirjh changed the title [No QA] [Bulk workspace edits] Add CopyPolicySettings action file and tests [Hold #App/89959][No QA] [Bulk workspace edits] Add CopyPolicySettings action file and tests May 7, 2026
fedirjh added 3 commits May 7, 2026 21:43
Replaces `import * as` namespace imports for `@libs/API`,
`@libs/ErrorUtils`, and `@libs/NumberUtils` with named imports
(`write`, `getMicroSecondOnyxErrorWithTranslationKey`,
`generateHexadecimalValue`) to satisfy the no-restricted-syntax rule
that disallows namespace imports from `@libs`. Also picks up a
prettier formatting fix in the test import.
Renames the placeholder custom unit IDs (`SOURCEDISTID`,
`SOURCEPERDIEM`, `TARGETDISTID`, `TARGETPERDIEMID`) to digit-only
13-character strings so cspell stops flagging them as unknown words.
The strings remain valid `[0-9A-F]{13}` hex IDs and tests still pass.
@fedirjh fedirjh requested a review from francoisl May 7, 2026 21:25
Includes a JSDoc comment to clarify the purpose of the sourcePolicyID field, indicating that it represents the ID of the source policy from which settings are copied.
@fedirjh fedirjh changed the title [Hold #App/89959][No QA] [Bulk workspace edits] Add CopyPolicySettings action file and tests [No QA] [Bulk workspace edits] Add CopyPolicySettings action file and tests May 8, 2026
@fedirjh
Copy link
Copy Markdown
Contributor Author

fedirjh commented May 8, 2026

@francoisl Can you please trigger translation action #89963 (comment)

@francoisl
Copy link
Copy Markdown
Contributor

francoisl commented May 8, 2026

Looks like they're already included? Started it for good measure though.

https://github.com/Expensify/App/actions/runs/25572505841

@OSBotify
Copy link
Copy Markdown
Contributor

OSBotify commented May 8, 2026

🦜 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 d9b5c0c8..53b996df 100644
--- a/src/languages/de.ts
+++ b/src/languages/de.ts
@@ -5964,9 +5964,7 @@ _Für ausführlichere Anweisungen [besuchen Sie unsere Hilfeseite](${CONST.NETSU
                 `Sie sind dabei, ${newWorkspaceName ?? ''} mit ${totalMembers ?? 0} Mitgliedern aus dem ursprünglichen Workspace zu erstellen und zu teilen.`,
             error: 'Beim Duplizieren deines neuen Workspace ist ein Fehler aufgetreten. Bitte versuche es erneut.',
         },
-        copyPolicySettings: {
-            error: 'Beim Kopieren der Arbeitsbereich-Einstellungen ist ein Fehler aufgetreten. Bitte versuche es erneut.',
-        },
+        copyPolicySettings: {error: 'Beim Kopieren der Arbeitsbereichseinstellungen ist ein Fehler aufgetreten. Bitte versuche es erneut.'},
         emptyWorkspace: {
             title: 'Du hast keine Arbeitsbereiche',
             subtitle: 'Belege erfassen, Auslagen erstatten, Reisen verwalten, Rechnungen versenden und mehr.',
diff --git a/src/languages/fr.ts b/src/languages/fr.ts
index a7b12004..84d4f848 100644
--- a/src/languages/fr.ts
+++ b/src/languages/fr.ts
@@ -5984,9 +5984,7 @@ _Pour des instructions plus détaillées, [visitez notre site d’aide](${CONST.
                 `Vous êtes sur le point de créer et de partager ${newWorkspaceName ?? ''} avec ${totalMembers ?? 0} membres de l’espace de travail d’origine.`,
             error: 'Une erreur s’est produite lors de la duplication de votre nouvel espace de travail. Veuillez réessayer.',
         },
-        copyPolicySettings: {
-            error: 'Une erreur s’est produite lors de la copie des paramètres de l’espace de travail. Veuillez réessayer.',
-        },
+        copyPolicySettings: {error: 'Une erreur s’est produite lors de la copie des paramètres de l’espace de travail. Veuillez réessayer.'},
         emptyWorkspace: {
             title: 'Vous n’avez aucun espace de travail',
             subtitle: 'Suivez les reçus, remboursez les dépenses, gérez les voyages, envoyez des factures, et plus encore.',
diff --git a/src/languages/it.ts b/src/languages/it.ts
index 0de05c84..098859a5 100644
--- a/src/languages/it.ts
+++ b/src/languages/it.ts
@@ -5954,9 +5954,7 @@ _Per istruzioni più dettagliate, [visita il nostro sito di assistenza](${CONST.
                 `Stai per creare e condividere ${newWorkspaceName ?? ''} con ${totalMembers ?? 0} membri dello spazio di lavoro originale.`,
             error: 'Si è verificato un errore durante la duplicazione del tuo nuovo workspace. Riprova.',
         },
-        copyPolicySettings: {
-            error: 'Si è verificato un errore durante la copia delle impostazioni del workspace. Riprova.',
-        },
+        copyPolicySettings: {error: 'Si è verificato un errore durante la copia delle impostazioni dello spazio di lavoro. Riprova.'},
         emptyWorkspace: {
             title: 'Non hai nessuna area di lavoro',
             subtitle: 'Tieni traccia delle ricevute, rimborsa le spese, gestisci i viaggi, invia le fatture e altro ancora.',
diff --git a/src/languages/ja.ts b/src/languages/ja.ts
index 1bb9bda1..f9d589e4 100644
--- a/src/languages/ja.ts
+++ b/src/languages/ja.ts
@@ -5887,9 +5887,7 @@ _詳しい手順については、[ヘルプサイトをご覧ください](${CO
                 `元のワークスペースから ${totalMembers ?? 0} 人のメンバーと一緒に、${newWorkspaceName ?? ''} を作成して共有しようとしています。`,
             error: '新しいワークスペースの複製中にエラーが発生しました。もう一度お試しください。',
         },
-        copyPolicySettings: {
-            error: 'ワークスペース設定のコピー中にエラーが発生しました。もう一度お試しください。',
-        },
+        copyPolicySettings: {error: 'ワークスペース設定のコピー中にエラーが発生しました。もう一度お試しください。'},
         emptyWorkspace: {
             title: 'ワークスペースがありません',
             subtitle: '領収書を管理し、経費を精算し、出張を管理し、請求書を送信するなど、さまざまなことができます。',
diff --git a/src/languages/nl.ts b/src/languages/nl.ts
index d09a9548..4c12551f 100644
--- a/src/languages/nl.ts
+++ b/src/languages/nl.ts
@@ -5934,9 +5934,7 @@ _Voor meer gedetailleerde instructies, [bezoek onze help-site](${CONST.NETSUITE_
                 `Je staat op het punt ${newWorkspaceName ?? ''} te maken en te delen met ${totalMembers ?? 0} leden van de oorspronkelijke werkruimte.`,
             error: 'Er is een fout opgetreden bij het dupliceren van je nieuwe werkruimte. Probeer het opnieuw.',
         },
-        copyPolicySettings: {
-            error: 'Er is een fout opgetreden bij het kopiëren van de werkruimte-instellingen. Probeer het opnieuw.',
-        },
+        copyPolicySettings: {error: 'Er is een fout opgetreden bij het kopiëren van de werkruimtainstellingen. Probeer het opnieuw.'},
         emptyWorkspace: {
             title: 'Je hebt geen werkruimtes',
             subtitle: 'Volg bonnen, vergoed uitgaven, beheer reizen, verstuur facturen en meer.',
diff --git a/src/languages/pl.ts b/src/languages/pl.ts
index a4d23675..6bf18a28 100644
--- a/src/languages/pl.ts
+++ b/src/languages/pl.ts
@@ -5928,9 +5928,7 @@ _Aby uzyskać bardziej szczegółowe instrukcje, [odwiedź naszą stronę pomocy
                 `Za chwilę utworzysz i udostępnisz ${newWorkspaceName ?? ''} ${totalMembers ?? 0} członkom oryginalnego obszaru roboczego.`,
             error: 'Wystąpił błąd podczas duplikowania Twojego nowego obszaru roboczego. Spróbuj ponownie.',
         },
-        copyPolicySettings: {
-            error: 'Wystąpił błąd podczas kopiowania ustawień przestrzeni roboczej. Spróbuj ponownie.',
-        },
+        copyPolicySettings: {error: 'Wystąpił błąd podczas kopiowania ustawień przestrzeni roboczej. Spróbuj ponownie.'},
         emptyWorkspace: {
             title: 'Nie masz żadnych przestrzeni roboczych',
             subtitle: 'Śledź paragony, rozliczaj wydatki, zarządzaj podróżami, wysyłaj faktury i wiele więcej.',
diff --git a/src/languages/pt-BR.ts b/src/languages/pt-BR.ts
index c1ba130b..a9027d77 100644
--- a/src/languages/pt-BR.ts
+++ b/src/languages/pt-BR.ts
@@ -5934,9 +5934,7 @@ _Para instruções mais detalhadas, [visite nossa central de ajuda](${CONST.NETS
                 `Você está prestes to criar e compartilhar ${newWorkspaceName ?? ''} com ${totalMembers ?? 0} membros do workspace original.`,
             error: 'Ocorreu um erro ao duplicar seu novo espaço de trabalho. Tente novamente.',
         },
-        copyPolicySettings: {
-            error: 'Ocorreu um erro ao copiar as configurações do espaço de trabalho. Tente novamente.',
-        },
+        copyPolicySettings: {error: 'Ocorreu um erro ao copiar as configurações do workspace. Tente novamente.'},
         emptyWorkspace: {
             title: 'Você não tem nenhum workspace',
             subtitle: 'Controle recibos, reembolse despesas, gerencie viagens, envie faturas e muito mais.',
diff --git a/src/languages/zh-hans.ts b/src/languages/zh-hans.ts
index 3b2bbf5c..ede27d7c 100644
--- a/src/languages/zh-hans.ts
+++ b/src/languages/zh-hans.ts
@@ -5789,9 +5789,7 @@ _如需更详细的说明,请[访问我们的帮助网站](${CONST.NETSUITE_IM
                 `您即将创建并共享 ${newWorkspaceName ?? ''},其中包含来自原始工作区的 ${totalMembers ?? 0} 位成员。`,
             error: '复制您的新工作区时发生错误。请重试。',
         },
-        copyPolicySettings: {
-            error: '复制工作区设置时发生错误。请重试。',
-        },
+        copyPolicySettings: {error: '复制工作区设置时发生错误。请重试。'},
         emptyWorkspace: {
             title: '你还没有工作区',
             subtitle: '跟踪收据、报销费用、管理差旅、发送发票等。',

Note

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

View workflow run

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.

3 participants