К основному содержанию
скилл CX Codex

platform-role-hierarchy-apply — скилл для Claude Code

Скилл platform-role-hierarchy-apply для Claude Code перестраивает иерархию ролей Salesforce по оргсхеме. Он подключается для пакетного изменения ролей, а перед отправкой показывает сводку операций для подтверждения администратора.

Apache-2.0 178 установок ★ 1 183 обновлён 2026-10-23

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add forcedotcom/sf-skills --skill platform-role-hierarchy-apply -a claude-code
Открыть на GitHub

Что делает platform-role-hierarchy-apply

Скилл сравнивает оргсхему с текущей иерархией ролей Salesforce и готовит манифест изменений. Источником может быть PDF с выделяемым текстом, таблица .xlsx или .csv, текстовый список пар «роль — родитель» либо уже разобранный список. PDF без выделяемого текста обработать нельзя: нужен текстовый список.

В манифест могут войти создание, переименование и перенос ролей, удаление пустых ролей и переназначение пользователей. Перед сравнением с деревом агент уточняет охват и согласие на перенос пользователей; удаления ролей из оргсхемы сами по себе не происходят. Неоднозначные совпадения, пропущенные родители и циклы блокируют отправку. Для совпадения менее 20% ролей с текущим деревом требуется подтверждение замены структуры с нуля.

Перед отправкой агент показывает сводку и ждёт явного одобрения администратора. Изменения ролей, связанных с территориями или прогнозами, портальные роли и роли с более чем 500 пользователями требуют отдельного подтверждения. Скилл предназначен для массовой перестройки, а не для вопроса о существующих ролях или одиночного изменения.

Какие задачи решает

  • перестроить несколько ролей по оргсхеме из PDF или таблицы
  • сверить целевую структуру с текущей иерархией ролей
  • переназначить пользователей вместе с перемещением ролей
  • найти неоднозначные совпадения и циклы до отправки изменений

Примеры запросов агенту

  • Перестрой иерархию ролей Salesforce по этой таблице и покажи план изменений.
  • Обнови роли по оргсхеме из PDF; выясни, должны ли пользователи переходить вместе с ролями.
  • Массово измени родителей ролей по списку пар «роль — родитель» и подготовь сводку для подтверждения.

Как установить platform-role-hierarchy-apply

1Через Skills CLI (Vercel)

npx skills add forcedotcom/sf-skills --skill platform-role-hierarchy-apply -a claude-code

2Вручную: положить файлы

~/.claude/skills/platform-role-hierarchy-apply/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/platform-role-hierarchy-apply/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о platform-role-hierarchy-apply

Как установить platform-role-hierarchy-apply в Claude Code?

Выполни npx skills add forcedotcom/sf-skills --skill platform-role-hierarchy-apply -a claude-code. Файл скилла появится по пути ~/.claude/skills/platform-role-hierarchy-apply/SKILL.md.

Что делает platform-role-hierarchy-apply?

Скилл сравнивает оргсхему с иерархией Salesforce и подготавливает пакетное изменение ролей, а также, после отдельного согласия, переназначение пользователей. Перед отправкой администратор подтверждает сводку операций.

Какие файлы принимает platform-role-hierarchy-apply?

Подойдут PDF с выделяемым текстом, .xlsx или .csv с именами ролей и родителей, текстовый список пар или разобранный список объектов. PDF, из которого нельзя выделить текст, нужно заменить текстовым списком.

Исходный текст

SKILL.md · Apache-2.0
---
name: platform-role-hierarchy-apply
description: "Bulk-realign an existing Salesforce UserRole hierarchy from an external org-chart artifact (PDF, xlsx, or plain-text list of role-and-parent pairs) in one admin-approved manifest. Clarify scope and whether users move with roles, resolve identities that do not match verbatim, diff the artifact against the current tree, and submit create, rename, reparent, empty-role delete, and user-assignment mutations together. Triggers on \"reorganize the role hierarchy\", \"apply this org chart to roles\", \"bulk update role parents\", \"realign roles from PDF\", \"restructure the role hierarchy\", \"reparent roles from this spreadsheet\". Do not trigger for a single role create, rename, or reparent with no other changes, or for asking which roles exist or how they are nested — that is `managing-roles`. Do not trigger for territory, account, or forecast hierarchies, or for authoring sharing rules."
metadata:
  version: "1.0"
---

# Role Hierarchy Restructure

Apply many UserRole changes from an artifact in one admin-approved manifest.

If the admin only asks which roles exist or how they are nested, hand off to `managing-roles`. Do not query, do not ask the step 0 questions, and do not submit.

## Inputs

- PDF org chart (text-selectable), `.xlsx` / `.csv` with `role_name` and `parent_role_name` (empty parent = top-level), or plain text with one `Role: Parent` pair per line.
- Or a pre-parsed list of `{roleName, parentRoleName}` objects.
- Optional mapping hints when a chart name is not the org's `Name` or `DeveloperName`.

## Flow

### 0. Clarify before querying

Ask anything still unresolved. Do not guess.

- **Scope.** Default is selected branches: roles absent from the artifact stay. "Full hierarchy" still does not delete those roles unless the admin asked for each deletion.
- **User reassignment.** Default is no. Do not emit `AssignUser` or `MoveUser` without an explicit yes.
- **Ambiguous identities.** Resolve every role and user in one batch. See step 2.
- **Conflicts.** Two parents for one role, or a role parented to itself: stop until the admin picks.

If the artifact matches fewer than 20% of its roles to the current tree, stop and ask whether it is a greenfield replacement, the wrong file, or a mapping problem. Do not build a manifest until the admin confirms a greenfield replacement. Between 20% and 50%, show the fraction in the preview and continue.

### 1. Read the current hierarchy

```text
SELECT Id, DeveloperName, Name, ParentRoleId
FROM   UserRole
LIMIT  10000
```

Match artifact roles by `DeveloperName`, then case-insensitive `Name`.

### 2. Parse the artifact and resolve identities

Normalize to `{roleName, parentRoleName, users?}` and show that list to the admin before the diff. A PDF that is not text-selectable cannot be parsed. Ask for a plain-text `Role: Parent` list.

Roles: exact `DeveloperName`, then case-insensitive `Name`. No fuzzy match. When more than one role matches, list each candidate's `DeveloperName` and `Id` and wait. Do not pick one. Unresolved names go back to step 0.

Users, only after reassignment was confirmed:

1. 18-character id starting with `005` → `User.Id`
2. Email → `User.Email`
3. Username → `User.Username`
4. Display name → `User.Name`, and only when exactly one active user matches

`IsActive = false` is a non-match. A user listed under two roles is a conflict. Ask which role that user should land under, or whether to drop the reassignment. Do not submit until the admin answers.

Stop on a cycle in the target graph. Report the path, for example `A → B → C → A`, and ask for a corrected artifact. Do not submit.

### 3. Build the manifest

Each mutation has `operationId`, `operationType`, `dependsOnOperationIds`, and one nested payload. `dependsOnOperationIds` is the order that matters.

| operationType | Nested object | Use when |
|---|---|---|
| `CreateRole` | `createRole` | Role is in the artifact and not in the org. Set `roleReference`, `developerName`, `name`, and `parentRoleId` or `parentRoleReference`. Default the three account-owner access fields to the org defaults when the artifact omits them. |
| `ReparentRole` | `reparentRole` | Role exists and the parent differs. Set `targetRoleId` or `targetRoleReference`, `expectedParentRoleId`, and `desiredParentRoleId` or `desiredParentRoleReference`. |
| `RenameRole` | `renameRole` | Same role, different label or developer name. Set the expected and desired name fields. |
| `DeleteRole` | `deleteRole` | Admin asked to remove an empty role. Set `targetRoleId`, `expectedParentRoleId`, `expectedAssignedUserIds`, and `expectedDirectChildRoleIds`. |
| `AssignUser` or `MoveUser` | `userRoleAssignment` | Reassignment was confirmed. Set `userId`, `expectedCurrentRoleId`, and `desiredRoleId` or `desiredRoleReference`. |

`DeleteRole` applies only when the role has no direct children and no assigned users at the moment it runs. Reparent those children and move those users in earlier mutations, and put those `operationId`s in `dependsOnOperationIds`. The delete's expected user and child lists are then empty. If the admin declined reassignment, do not delete a role that still has users.

A mutation that names a role neither in the org nor created in this manifest is `missing-parent`. Name the roles that point at it. Ask whether to add a `CreateRole` for it in this manifest, skip those rows, or abort. Do not submit with that parent missing.

A cycle in `dependsOnOperationIds` blocks the submit. Give every new role a `roleReference` string and point parents and assignments at that string.

### 4. Validate, then preview

Block the submit when any of these remain: a cycle, a missing parent, a duplicate `developerName`, a dependency cycle, an `AssignUser` or `MoveUser` without the step 0 yes, a `DeleteRole` whose expected user or child lists are not empty, or overlap under 20% without a confirmed greenfield replacement.

On a duplicate `developerName`, show both rows and wait until the admin picks one or renames one.

Warn in the preview, and continue only after an explicit yes:

- A changed role is referenced by `Territory2.UserRoleId` or a forecast hierarchy override.
- A changed role has `PortalType != 'None'`.
- A changed role has more than 500 users (`SELECT COUNT() FROM User WHERE UserRoleId = :id`).

```text
Restructure preview
-------------------
  ReparentRole : 42
  CreateRole   :  3
  RenameRole   :  1
  DeleteRole   :  2
  MoveUser     :  2

  Territory / forecast references : 1
  Portal roles                    : 0
  Roles with more than 500 users  : 2

Approve this restructure? [yes / no]
```

`yes` submits. Anything else does not. Roles left in the org and absent from the artifact stay in place.

### 5. Submit

```text
POST /services/data/v{version}/sharing/role-hierarchy-restructure
{
  "operation": "Save",
  "mutations": [
    {
      "operationId": "reparent-sales-vp",
      "operationType": "ReparentRole",
      "dependsOnOperationIds": [],
      "reparentRole": {
        "targetRoleId": "00E000000000001",
        "expectedParentRoleId": "00E000000000002",
        "desiredParentRoleReference": "cro"
      }
    },
    {
      "operationId": "delete-legacy-region",
      "operationType": "DeleteRole",
      "dependsOnOperationIds": ["reparent-legacy-children"],
      "deleteRole": {
        "targetRoleId": "00E000000000003",
        "expectedParentRoleId": "00E000000000002",
        "expectedAssignedUserIds": [],
        "expectedDirectChildRoleIds": []
      }
    }
  ]
}
```

`CreateRole`, `RenameRole`, `AssignUser`, and `MoveUser` use the same envelope with their nested object from step 3.

Send the approved manifest once. Do not edit `UserRole` records one by one.

### 6. Read the response

- `Applied` — structural and sharing changes committed.
- `AppliedSharingPending` — hierarchy is live; sharing catches up on its own. Do not poll.
- `AsyncExecutionRequired` — the server queued the manifest. Do not poll.
- `RoleOperationInProgress` — another restructure is running. Stop. Do not queue the manifest. Ask the admin to retry once the other operation finishes.
- `NotApplied` — nothing committed. Show `reasonCodes` and stop.
- `404` on submit — API not enabled for this client tier. Halt, tell the admin, do not retry, do not fall back to per-record `/sobjects/UserRole` edits.

For each `operationResults[]` entry, `outcome` is `Applied`, `NotApplied`, or `DependencyNotApplied`. Show `reasonCode` for any entry that is not `Applied`. Do not retry and do not roll back.

## Out of scope

- A single role create, rename, or reparent with no other changes, and any request that only asks which roles exist or how they are nested (`managing-roles`).
- Territory, account, and forecast hierarchies.
- Authoring sharing rules.
- Image-only PDFs. Ask for text.
- Rollback. Report what the response says was committed.
---

<!-- skill-validate: ignore-start -->
<!-- codey:operations start -->
## Operations Reference

Operations this skill uses — routing and dependency reference.

| Operation | Purpose | Status | Call | Depends on |
|-----------|---------|--------|------|------------|
| `read-role-hierarchy` | read | — | `GET /services/data/v68.0/query` | — |
| `count-users-per-role` | read | — | `GET /services/data/v68.0/query` | `read-role-hierarchy` |
| `submit-role-hierarchy-restructure` | write | — | `POST /services/data/v68.0/sharing/role-hierarchy-restructure` | `read-role-hierarchy` |
| `verify-role-hierarchy-restructure` | verify | — | `GET /services/data/v68.0/query` | `submit-role-hierarchy-restructure` |
<!-- codey:operations end -->
<!-- skill-validate: ignore-end -->

© forcedotcom · Apache-2.0 · forcedotcom/sf-skills

Похожие скиллы

Все скиллы по теме «Бэкенд и API» →
Salesforce Cloud aaronsb MCP-сервер Salesforce Cloud подключает Salesforce к Claude Code, Cursor, Codex и другим агентам через SOQL-запросы и анализ сделок. Агент читает воронку, находит похожие выигранные сделки и генерирует бизнес-кейсы прямо в чате. CX Codex +1 ★ 6звёзд репо convert-documents-to-markdown firecrawl Скилл convert-documents-to-markdown для Claude Code конвертирует офисные документы, таблицы и PDF в GitHub-Flavored Markdown через утилиту anydoc. Извлекает данные из DOCX и XLSX без ручной вычитки. CX Codex +1 13 700установок PDF Converter claude-office-skills Скилл PDF Converter для Claude Code подсказывает, как переводить PDF в Word, Excel, изображения и другие форматы, а также создавать PDF из документов. Вызывается просьбами о конвертации файлов. CX Codex +1 5 300установок salesforce-flow-design официальный github Скилл salesforce-flow-design проверяет архитектуру Salesforce Flow: выбор типа, bulk-безопасность и обработку ошибок. Подходит для проектирования и ревью Flow перед активацией. CX Codex +1 839установок doc-extract официальный anthropics Скилл doc-extract для Claude Code конвертирует бинарные документы в чистый текст без сохранения файлов на диск. Агент запускает его при обработке договоров или медицинских вложений в формате PDF, DOCX, XLSX, PPTX, RTF и HTML. CX Codex +1 110установок crm-integration manojbajaj95 Скилл crm-integration для Claude Code содержит шаблоны интеграции Close CRM, HubSpot и Salesforce для синхронизации лидов, сделок и вебхуков. CX Codex +1 211установок

Из того же набора232

Весь набор →
experience-lwc-legacy-migrate Скилл experience-lwc-legacy-migrate проверяет полноту миграции компонентов Aura в LWC и переводит внешние страницы Lightning Out Beta на Lightning Out 2.0 с OAuth PKCE. CX Codex +1 245установок platform-agenticsetup-categories-get Скилл platform-agenticsetup-categories-get получает категории Agentic Setup из подключённой Salesforce org через Connect API. Можно запросить и вложенные промпты. CX Codex +1 235установок experience-cms-content-render Скилл experience-cms-content-render для Claude Code, Codex, Cursor и других агентов, который встраивает готовый контент Salesforce CMS в React- или Angular-приложение uiBundle. CX Codex +1 226установок experience-design-validate Скилл experience-design-validate проводит визуальный аудит интерфейса по скриншотам или URL и составляет отчёт по пяти критериям качества. Пригодится на дизайн-ревью перед релизом. CX Codex +1 220установок consumer-goods-promotion-bo-api-deploy Скилл consumer-goods-promotion-bo-api-deploy включает Promotion BO API в Salesforce Consumer Goods Cloud, создаёт и деплоит кастомный Workflow Step и проверяет весь путь через REST. CX Codex +1 160установок dx-org-snapshot-manage Скилл dx-org-snapshot-manage для Claude Code управляет снимками scratch-оргов Salesforce. Автоматизирует создание слепков данных и метаданных через командную строку sf. CX Codex +1 149установок agentforce-persona-generate Скилл agentforce-persona-generate для Claude Code и Codex проектирует образ ИИ-агента Salesforce Agentforce. Переводит брендбук в тон, границы поведения и готовый файл .agent. CX Codex +1 146установок education-cloud-student-recruitment-agent-configure Скилл education-cloud-student-recruitment-agent-configure для Claude Code настраивает Student Recruitment Agent в Salesforce Education Cloud для приёмной комиссии, записи на экскурсии и подачи заявок. CX Codex +1 141установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой