A plugin marketplace for GitHub Copilot and other AI agents that provides Power Platform development plugins, including reusable skills, agents, and commands for building and deploying solutions.
JavaScript claude-code-pluginclaude-code-skillscode-appsgithub-copilot-pluginpower-appspower-pagespower-platform
Add meta shared instructions pattern (#4)
Priyanshu Agrawal99fed3384fd9
diff --git a/AGENTS.md b/AGENTS.mdindex 93a089b5a..62c046116 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -1,6 +1,6 @@# Power Platform Claude Plugins - Development Guidelines-This file provides instructions for Claude Code when working on this plugin marketplace.+This file provides generic instructions for Claude Code when working on this plugin marketplace. For plugin-specific guidelines, see the `AGENTS.md` file in each plugin's folder.## Official Documentation@@ -14,25 +14,26 @@ This file provides instructions for Claude Code when working on this plugin markThis repository is a **plugin marketplace** containing multiple plugins:```-power-platform-claude-plugin/+power-platform-claude-plugins/├── .claude-plugin/│ └── marketplace.json # Marketplace manifest (lists all available plugins)├── plugins/ # Directory containing individual plugins-│ └── power-pages/ # Power Pages plugin+│ └── <plugin-name>/ # Individual plugin (e.g., power-pages)│ ├── .claude-plugin/│ │ └── plugin.json # Plugin manifest-│ ├── .mcp.json # MCP server configuration+│ ├── AGENTS.md # Plugin-specific development guidelines│ ├── agents/ # Agent persona files│ ├── commands/ # Command entry points│ ├── shared/ # Shared resources and documentation│ └── skills/ # Skill workflows (SKILL.md in subdirectories)-├── AGENTS.md # Development guidelines+├── AGENTS.md # Generic development guidelines (this file)└── README.md # Repository overview```**Important**:- The root `.claude-plugin/marketplace.json` defines the marketplace and lists available plugins- Each plugin in `plugins/` has its own `.claude-plugin/plugin.json` manifest+- Each plugin has its own `AGENTS.md` with plugin-specific guidelines- Plugin components (agents, commands, skills, shared) must be at the plugin root, not inside `.claude-plugin/`## When Modifying Skills@@ -45,7 +46,7 @@ name: skill-name # Optional: defaults to directory namedescription: What this skill does # Recommended: Claude uses for auto-loadinguser-invocable: true # Optional: default truedisable-model-invocation: false # Optional: default false-allowed-tools: Read, Bash(pac:*) # Optional: tool restrictions+allowed-tools: ["Read", "Write", "Grep", "Glob", "Bash", "TodoWrite", "AskUserQuestion", "Skill", "Task"] # Optional: tool restrictionsargument-hint: [project-path] # Optional: autocomplete hintcontext: fork # Optional: run in subagentagent: Explore # Optional: subagent type@@ -90,17 +91,19 @@ Use these in skills, hooks, and scripts:3. **Reference shared files** using `${CLAUDE_PLUGIN_ROOT}/shared/<filename>` instead of duplicating content4. **Never copy-paste** the same instructions into multiple skill files-### Example+### When to Create a Shared File-Instead of duplicating cleanup instructions in each skill:+Create a new file in `shared/` **BEFORE** adding content to skill files when:-```markdown-## Cleanup Helper Files--**📖 See: [cleanup-reference.md](${CLAUDE_PLUGIN_ROOT}/shared/cleanup-reference.md)**+- The same instructions apply to 2+ skills+- The content is a cross-cutting concern (applies during multiple workflows)+- The logic, script, or documentation would otherwise be duplicated+- The content describes a reusable pattern-Remove any temporary helper files created during this skill's execution.-```+**Decision process:**+1. Identify where the content is needed+2. If needed in multiple places → create shared file first+3. Then add references to the shared file in each skill### Shared Resources Location@@ -108,21 +111,39 @@ Common resources should be placed in:- `plugins/<plugin-name>/shared/` - Plugin-specific shared files- Reference using `${CLAUDE_PLUGIN_ROOT}/shared/<filename>`-## Memory Bank System+## Meta Shared Instructions Pattern-Plugins use a memory bank (`memory-bank.md`) to persist state across sessions.+Each plugin should have a **meta shared instructions file** (`shared/shared-instructions.md`) that aggregates all cross-cutting concerns:-- Each plugin has its own memory bank at `plugins/<plugin-name>/shared/memory-bank.md`-- Skills should read memory bank at start-- Skills should update memory bank after major steps+```+plugins/<plugin-name>/shared/+├── shared-instructions.md # Meta file - referenced by ALL skills+├── planning-policy.md # Sub-instruction (example)+├── memory-bank.md # Sub-instruction (example)+└── ...other shared files+```-## Tool Restrictions+**How it works:**+1. Each SKILL.md references ONLY `shared-instructions.md` at the top+2. `shared-instructions.md` references all cross-cutting sub-instructions+3. When adding new shared concerns, update only `shared-instructions.md`+4. No changes needed to individual SKILL.md files-Skills in this plugin use restricted tools for security:+**Example SKILL.md header:**+```markdown+---+description: What this skill does+---++**📋 Shared Instructions: [shared-instructions.md](${CLAUDE_PLUGIN_ROOT}/shared/shared-instructions.md)** - Cross-cutting concerns.++# Skill Title+```-- `Bash(pac:*)` - PAC CLI commands only-- `Bash(az:*)` - Azure CLI commands only-- `Bash(dotnet:*)` - .NET CLI commands only+**Adding new shared instructions:**+1. Create the new file in `shared/` (e.g., `new-policy.md`)+2. Add a section to `shared-instructions.md` referencing it+3. Done - all skills automatically pick up the new instruction## Testing Changes@@ -138,6 +159,8 @@ To add a new plugin to this marketplace:1. Create a new directory under `plugins/` (e.g., `plugins/power-apps`)2. Add `.claude-plugin/plugin.json` with required manifest fields-3. Add components: `agents/`, `commands/`, `skills/`, `shared/`-4. Update `marketplace.json` at root to include the new plugin-5. Update `README.md` to document the new plugin+3. Add `AGENTS.md` with plugin-specific development guidelines+4. Add components: `agents/`, `commands/`, `skills/`, `shared/`+5. Create `shared/shared-instructions.md` for cross-cutting concerns+6. Update `marketplace.json` at root to include the new plugin+7. Update `README.md` to document the new plugindiff --git a/README.md b/README.mdindex 396e12686..23ab8a65c 100644--- a/README.md+++ b/README.md@@ -1,6 +1,16 @@# Power Platform Claude Plugins-Official Claude Code extensions for Power Platform development by Microsoft.+Official Copilot CLI extensions for Power Platform development by Microsoft.++[](https://github.com/microsoft/power-platform-claude-plugins#quick-start)++## Quick Start++Run this command in your terminal to clone and launch Copilot CLI with the Power Pages plugin:++```bash+git clone https://github.com/microsoft/power-platform-claude-plugins.git && copilot --plugin-dir power-platform-claude-plugins/plugins/power-pages+```## Overview@@ -42,13 +52,13 @@ To use a plugin from this marketplace:1. Add the marketplace to your Claude Code instance```bash- /plugin marketplace add microsoft/power-platform-claude-plugin+ /plugin marketplace add microsoft/power-platform-claude-plugins```2. Install the desired plugin```bash- /plugin install power-pages@power-platform-claude-plugin+ /plugin install power-pages@power-platform-claude-plugins```### Add from local path@@ -57,13 +67,13 @@ To use a plugin from this marketplace:1. Add the marketplace to your Claude Code instance```bash- /plugin marketplace add /path/to/power-platform-claude-plugin+ /plugin marketplace add /path/to/power-platform-claude-plugins```1. Install the desired plugin (installs to user scope by default)```bash- /plugin install power-pages@power-platform-claude-plugin+ /plugin install power-pages@power-platform-claude-plugins```## Local Developmentdiff --git a/plugins/power-pages/.claude-plugin/plugin.json b/plugins/power-pages/.claude-plugin/plugin.jsonindex a515a8f26..711a1c378 100644--- a/plugins/power-pages/.claude-plugin/plugin.json+++ b/plugins/power-pages/.claude-plugin/plugin.json@@ -6,8 +6,8 @@"name": "Microsoft","url": "https://www.microsoft.com"},- "homepage": "https://learn.microsoft.com/power-pages/configure/create-code-sites",- "repository": "https://github.com/microsoft/power-pages-claude-plugin",+ "homepage": "https://github.com/microsoft/power-platform-claude-plugins/",+ "repository": "https://github.com/microsoft/power-platform-claude-plugins/","license": "MIT","keywords": ["power-pages",diff --git a/plugins/power-pages/AGENTS.md b/plugins/power-pages/AGENTS.mdnew file mode 100644index 000000000..24243dd1e--- /dev/null+++ b/plugins/power-pages/AGENTS.md@@ -0,0 +1,184 @@+# Power Pages Plugin - Development Guidelines++This file provides instructions for Claude Code when working on the Power Pages plugin specifically.++## Overview++The Power Pages plugin helps users create and deploy Power Pages sites using modern frontend frameworks. It provides skills for:++- Creating code sites (SPAs) with React, Angular, Vue, or Astro+- Setting up Dataverse tables and schema+- Configuring Web API access and permissions+- Implementing authentication and authorization++## Memory Bank System++This plugin uses a memory bank (`memory-bank.md`) to persist state across sessions.++**Location**: `<PROJECT_ROOT>/memory-bank.md` (in the user's project, not the plugin)++**Instructions**: See `shared/memory-bank.md` for detailed memory bank usage.++**Key Points**:+- Skills read memory bank at start to resume progress+- Skills update memory bank after major steps+- Tracks completed steps, user preferences, and created resources++## Shared Resources++This plugin's shared resources are in `shared/`:++| File | Purpose |+|------|---------|+| `shared-instructions.md` | Meta file aggregating all cross-cutting concerns |+| `planning-policy.md` | Planning requirements before major changes |+| `memory-bank.md` | Memory bank usage instructions |+| `cleanup-reference.md` | Cleanup instructions for helper files |+| `authoring-tool-reference.md` | Authoring tool site setting configuration |++### Adding New Shared Instructions++1. Create the new file in `shared/` (e.g., `new-policy.md`)+2. Add a section to `shared/shared-instructions.md` referencing it+3. Done - all skills automatically pick up the new instruction++## Skills++### Core Skills++| Skill | Description |+|-------|-------------|+| `/create-site` | Create a Power Pages code site with modern frameworks |+| `/setup-dataverse` | Set up Dataverse tables and schema |+| `/setup-webapi` | Configure Web API permissions and site settings |+| `/integrate-webapi` | Connect frontend code to Web API (replace mock data) |+| `/setup-auth` | Implement authentication and authorization |++### Optional Enhancement Skills++| Skill | Description | After |+|-------|-------------|-------|+| `/add-seo` | Add SEO assets (meta tags, robots.txt, sitemap) | `/create-site` |+| `/add-tests` | Add unit tests (Vitest) and E2E tests (Playwright) | `/create-site` |+| `/add-sample-data` | Insert sample data with foreign key relationships | `/setup-dataverse` |++### Workflow Sequence++```+/create-site → /add-seo (optional) → /add-tests (optional)+ ↓+/setup-dataverse → /add-sample-data (optional)+ ↓+/setup-webapi → /integrate-webapi+ ↓+/setup-auth+```++### Skill Structure++Each skill follows this structure:++```+skills/<skill-name>/+├── SKILL.md # Main skill workflow+└── references/ # Detailed reference files+ ├── <topic>-reference.md+ └── troubleshooting.md+```++### Skill Header Pattern++All skills reference the shared instructions at the top:++```markdown+---+name: doing-something # Required, gerund form (verb-ing)+description: Does X for Y # Third person, specific, <160 chars+user-invocable: true+allowed-tools: ["Read", "Write", "Grep", "Glob", "Bash", "TodoWrite", "AskUserQuestion", "Skill", "Task"]+model: opus+---++**📋 Shared Instructions: [shared-instructions.md](${CLAUDE_PLUGIN_ROOT}/shared/shared-instructions.md)**++# Skill Title+```++### Writing Clean Skills (Anti-Bloat Guidelines)++Follow these rules to keep skills concise and effective:++**DO:**+- Keep SKILL.md under 500 lines total+- Use `name` field with gerund form (e.g., `creating-power-pages-site`)+- Write descriptions in third person ("Creates X" not "This skill guides you through creating X")+- Use numbered lists for workflows instead of ASCII diagrams+- Trust Claude's intelligence - omit explanations of well-known concepts+- Use progressive disclosure: SKILL.md for workflow, reference files for details+- Link to reference files inline: `See [reference.md](./reference.md)`++**DON'T:**+- Start with "This skill/document guides/covers/describes..." (AI slop)+- Include ASCII workflow diagrams (waste 50+ lines)+- Duplicate content between "Quick Summary" and "Actions" sections+- Explain obvious concepts Claude already knows+- Add verbose tables for simple lists (use inline format instead)+- Repeat the same information in multiple places++**Example - BAD (bloated):**+```markdown+This document describes how to configure site settings for Power Pages.++## Overview+Site settings control the behavior of your Power Pages site...+[50 lines of explanation]+```++**Example - GOOD (concise):**+```markdown+## Site Settings+Create YAML files in `.powerpages-site/site-settings/`. See [site-settings-reference.md](./references/site-settings-reference.md) for format details.+```++## Agents++| Agent | Purpose |+|-------|---------|+| `code-site-architect` | Specialized for Power Pages code site architecture decisions |++## Power Pages Concepts++### Code Sites vs Traditional Sites++- **Code Sites**: Static SPAs (React, Angular, Vue, Astro) deployed to Azure CDN+- **Traditional Sites**: Liquid template-based sites with server-side rendering++This plugin focuses on **Code Sites** only.++### Supported Frameworks++| Framework | Build Tool | Notes |+|-----------|------------|-------|+| React | Vite | Recommended |+| Angular | Angular CLI | |+| Vue | Vite | |+| Astro | Astro | Static output only |++**NOT Supported**: Next.js, Nuxt.js, Remix, SvelteKit (require server-side rendering)++### Key APIs++| API | Endpoint | Purpose |+|-----|----------|---------|+| Web API | `/_api/<table>` | CRUD operations on Dataverse tables |+| Auth Token | `/_layout/tokenhtml` | CSRF token for write operations |+| Portal Object | `window.Microsoft.Dynamic365.Portal` | User info, roles, settings |++## Testing Changes++After modifying this plugin:++1. Run `claude --debug` to see plugin loading details+2. Test skill invocation with `/create-site`, `/setup-dataverse`, etc.+3. Verify tool restrictions work (should only allow pac, az, dotnet commands)+4. Test memory bank read/write in a sample projectdiff --git a/plugins/power-pages/CLAUDE.md b/plugins/power-pages/CLAUDE.mdnew file mode 120000index 000000000..47dc3e3d8--- /dev/null+++ b/plugins/power-pages/CLAUDE.md@@ -0,0 +1 @@+AGENTS.md\ No newline at end of filediff --git a/plugins/power-pages/commands/add-sample-data.md b/plugins/power-pages/commands/add-sample-data.mdnew file mode 100644index 000000000..fb816505f--- /dev/null+++ b/plugins/power-pages/commands/add-sample-data.md@@ -0,0 +1,10 @@+# Add Sample Data++Read and follow the instructions in `${CLAUDE_PLUGIN_ROOT}/skills/add-sample-data/SKILL.md`.++**Important**:++- Do not announce steps - just execute them+- Check memory-bank.md for table mapping and publisher prefix+- Insert data in dependency order (parent tables before children)+- Verify data was created successfullydiff --git a/plugins/power-pages/commands/add-seo.md b/plugins/power-pages/commands/add-seo.mdnew file mode 100644index 000000000..1fec66d12--- /dev/null+++ b/plugins/power-pages/commands/add-seo.md@@ -0,0 +1,10 @@+# Add SEO Assets++Read and follow the instructions in `${CLAUDE_PLUGIN_ROOT}/skills/add-seo/SKILL.md`.++**Important**:++- Do not announce steps - just execute them+- Check memory-bank.md for project context first+- Create all SEO assets (meta tags, robots.txt, sitemap.xml, favicon)+- Build and upload after completiondiff --git a/plugins/power-pages/commands/add-tests.md b/plugins/power-pages/commands/add-tests.mdnew file mode 100644index 000000000..3ea387941--- /dev/null+++ b/plugins/power-pages/commands/add-tests.md@@ -0,0 +1,10 @@+# Add Tests++Read and follow the instructions in `${CLAUDE_PLUGIN_ROOT}/skills/add-tests/SKILL.md`.++**Important**:++- Do not announce steps - just execute them+- Check memory-bank.md for project context first+- Set up both unit tests (Vitest) and E2E tests (Playwright)+- Run tests to verify they pass before completingdiff --git a/plugins/power-pages/commands/create-site.md b/plugins/power-pages/commands/create-site.mdindex ad865d69d..a04aedd55 100644--- a/plugins/power-pages/commands/create-site.md+++ b/plugins/power-pages/commands/create-site.md@@ -1,12 +1,13 @@# Create Power Pages Code Site-Read and follow the instructions in `${CLAUDE_PLUGIN_ROOT}/skills/create-site/SKILL.md` to guide the user through creating a Power Pages code site.+Read and follow the instructions in `${CLAUDE_PLUGIN_ROOT}/skills/create-site/SKILL.md`.**Important**:-- Do not summarize the skill - execute it step by step-- Start by gathering requirements in STEP 1 (ask what they want to build)-- Check prerequisites (PAC CLI and Azure CLI) in STEP 3 before uploading-- Use the AskUserQuestion tool for gathering requirements+- Do not announce steps - just execute them+- Start by gathering requirements (ask what they want to build)+- Check prerequisites (PAC CLI and Azure CLI) before uploading- Use the frontend-design skill when creating the site+- Create complete `powerpages.config.json` with siteName, defaultLandingPage, and compiledPath- Execute all PAC CLI and API commands as specified+- Clean up any temporary helper scripts after completiondiff --git a/plugins/power-pages/commands/integrate-webapi.md b/plugins/power-pages/commands/integrate-webapi.mdnew file mode 100644index 000000000..6d5b00097--- /dev/null+++ b/plugins/power-pages/commands/integrate-webapi.md@@ -0,0 +1,12 @@+# Integrate Web API++Read and follow the instructions in `${CLAUDE_PLUGIN_ROOT}/skills/integrate-webapi/SKILL.md`.++**Important**:++- Do not announce steps - just execute them+- Check memory-bank.md for table mapping and publisher prefix+- Create Web API service with CSRF token handling+- Find and replace ALL mock/static data with API calls+- Delete unused mock data files after replacement+- Build and upload after completiondiff --git a/plugins/power-pages/commands/setup-auth.md b/plugins/power-pages/commands/setup-auth.mdindex be8ce205b..76802d44d 100644--- a/plugins/power-pages/commands/setup-auth.md+++ b/plugins/power-pages/commands/setup-auth.md@@ -1,5 +1,12 @@-# Setup Authentication & Authorization+# Setup Authentication-Read and follow the instructions in `${CLAUDE_PLUGIN_ROOT}/skills/setup-auth/SKILL.md` to guide the user through implementing authentication (login/logout) and role-based authorization for their Power Pages site.+Read and follow the instructions in `${CLAUDE_PLUGIN_ROOT}/skills/setup-auth/SKILL.md`.-DO NOT summarize the skill instructions. Follow them step by step, using the tools available to you as directed.+**Important**:++- Do not announce steps - just execute them+- Check memory-bank.md for project context first+- Verify /setup-webapi was completed (site must be uploaded)+- Create auth service, authorization utils, and UI components+- Build and upload after completion+- Clean up any temporary helper scripts after completiondiff --git a/plugins/power-pages/commands/setup-dataverse.md b/plugins/power-pages/commands/setup-dataverse.mdindex 1d38284cf..d92d70001 100644--- a/plugins/power-pages/commands/setup-dataverse.md+++ b/plugins/power-pages/commands/setup-dataverse.md@@ -1,5 +1,11 @@# Setup Dataverse Tables-Read and follow the instructions in `${CLAUDE_PLUGIN_ROOT}/skills/setup-dataverse/SKILL.md` to guide the user through setting up Dataverse tables and schema for their Power Pages site.+Read and follow the instructions in `${CLAUDE_PLUGIN_ROOT}/skills/setup-dataverse/SKILL.md`.-DO NOT summarize the skill instructions. Follow them step by step, using the tools available to you as directed.+**Important**:++- Do not announce steps - just execute them+- Check memory-bank.md for project context first+- Create tables in dependency order (parent tables before children)+- Execute all REST API commands as specified+- Clean up any temporary helper scripts after completiondiff --git a/plugins/power-pages/commands/setup-webapi.md b/plugins/power-pages/commands/setup-webapi.mdindex bc19808f8..763ac3418 100644--- a/plugins/power-pages/commands/setup-webapi.md+++ b/plugins/power-pages/commands/setup-webapi.md@@ -1,5 +1,11 @@-# Setup Web API+# Setup Web API Access-Read and follow the instructions in `${CLAUDE_PLUGIN_ROOT}/skills/setup-webapi/SKILL.md` to guide the user through configuring Web API access for their Power Pages site.+Read and follow the instructions in `${CLAUDE_PLUGIN_ROOT}/skills/setup-webapi/SKILL.md`.-DO NOT summarize the skill instructions. Follow them step by step, using the tools available to you as directed.+**Important**:++- Do not announce steps - just execute them+- Check memory-bank.md for table mapping first+- Create site settings, web roles, and table permissions+- Build and upload after completion+- Clean up any temporary helper scripts after completiondiff --git a/plugins/power-pages/shared/authoring-tool-reference.md b/plugins/power-pages/shared/authoring-tool-reference.mdnew file mode 100644index 000000000..17ad60cf6--- /dev/null+++ b/plugins/power-pages/shared/authoring-tool-reference.md@@ -0,0 +1,252 @@+# AI Site Settings Reference++This document describes how to create site settings to track AI tooling usage in Power Pages sites.++## Overview++When a site is created or modified using Claude Code skills, site settings are added to track:+1. **Authoring tool** - Which tool created the site+2. **Skills used** - Which skills have been executed on the site++## Site Setting Details++### Authoring Tool Setting++| Property | Value |+|----------|-------|+| Setting Name | `Site/AI/AuthoringTool` |+| File Name | `Site-AI-AuthoringTool.sitesetting.yml` |+| Location | `.powerpages-site/site-settings/` |++| Value | Description |+|-------|-------------|+| `ClaudeCodeCLI` | Site created using Claude Code command-line interface |+| `ClaudeCodeVSCode` | Site created using Claude Code VS Code extension |++### Skill Tracking Settings++Each time a skill is used, create or update a site setting to track usage count:++| Property | Value |+|----------|-------|+| Setting Name | `Site/AI/<SkillName>` |+| File Name | `Site-AI-<SkillName>.sitesetting.yml` |+| Value | Integer count (increments each time skill is used) |++| Skill | Setting Name |+|-------|--------------|+| `/create-site` | `Site/AI/CreateSite` |+| `/add-seo` | `Site/AI/AddSeo` |+| `/add-tests` | `Site/AI/AddTests` |+| `/setup-dataverse` | `Site/AI/SetupDataverse` |+| `/add-sample-data` | `Site/AI/AddSampleData` |+| `/setup-webapi` | `Site/AI/SetupWebApi` |+| `/integrate-webapi` | `Site/AI/IntegrateWebApi` |+| `/setup-auth` | `Site/AI/SetupAuth` |++## YAML Format++### Authoring Tool++**File**: `.powerpages-site/site-settings/Site-AI-AuthoringTool.sitesetting.yml`++```yaml+description: Identifies the tool used to create this Power Pages site+id: <GENERATE_UUID>+name: Site/AI/AuthoringTool+value: ClaudeCodeCLI+```++### Skill Tracking++**File**: `.powerpages-site/site-settings/Site-AI-CreateSite.sitesetting.yml`++```yaml+description: Tracks usage count of /create-site skill on this site+id: <GENERATE_UUID>+name: Site/AI/CreateSite+value: 1+```++**Note**: The `value` is an integer that increments each time the skill is used (1, 2, 3, etc.).++## Detection Logic++The authoring tool value is determined by checking environment variables:++```powershell+$authoringTool = if ($env:TERM_PROGRAM -eq "vscode" -or $env:VSCODE_GIT_ASKPASS_NODE) {+ "ClaudeCodeVSCode"+} else {+ "ClaudeCodeCLI"+}+```++## PowerShell Helper Functions++### Create Authoring Tool Setting++```powershell+function New-AuthoringToolSetting {+ param(+ [Parameter(Mandatory=$true)]+ [string]$ProjectRoot+ )++ $siteSettingsPath = Join-Path $ProjectRoot ".powerpages-site\site-settings"++ if (-not (Test-Path $siteSettingsPath)) {+ New-Item -ItemType Directory -Path $siteSettingsPath -Force | Out-Null+ }++ $authoringTool = if ($env:TERM_PROGRAM -eq "vscode" -or $env:VSCODE_GIT_ASKPASS_NODE) {+ "ClaudeCodeVSCode"+ } else {+ "ClaudeCodeCLI"+ }++ $uuid = [guid]::NewGuid().ToString()++ $content = @"+description: Identifies the tool used to create this Power Pages site+id: $uuid+name: Site/AI/AuthoringTool+value: $authoringTool+"@++ $fileName = "Site-AI-AuthoringTool.sitesetting.yml"+ $filePath = Join-Path $siteSettingsPath $fileName+ Set-Content -Path $filePath -Value $content -Encoding UTF8+ Write-Host "Created: $filePath (Value: $authoringTool)"+}+```++### Create/Update Skill Tracking Setting++```powershell+function New-SkillTrackingSetting {+ param(+ [Parameter(Mandatory=$true)]+ [string]$ProjectRoot,+ [Parameter(Mandatory=$true)]+ [string]$SkillName # e.g., "CreateSite", "AddSeo", "AddTests", "SetupDataverse", "AddSampleData", "SetupWebApi", "IntegrateWebApi", "SetupAuth"+ )++ $siteSettingsPath = Join-Path $ProjectRoot ".powerpages-site\site-settings"++ if (-not (Test-Path $siteSettingsPath)) {+ New-Item -ItemType Directory -Path $siteSettingsPath -Force | Out-Null+ }++ $fileName = "Site-AI-$SkillName.sitesetting.yml"+ $filePath = Join-Path $siteSettingsPath $fileName++ # Check if setting already exists and get current count+ $currentCount = 0+ $existingId = $null+ if (Test-Path $filePath) {+ $existingContent = Get-Content $filePath -Raw+ if ($existingContent -match 'value:\s*(\d+)') {+ $currentCount = [int]$Matches[1]+ }+ if ($existingContent -match 'id:\s*([a-f0-9-]+)') {+ $existingId = $Matches[1]+ }+ }++ $newCount = $currentCount + 1+ $uuid = if ($existingId) { $existingId } else { [guid]::NewGuid().ToString() }+ $skillSlug = $SkillName.ToLower() -replace '([a-z])([A-Z])', '$1-$2'++ $content = @"+description: Tracks usage count of /$skillSlug skill on this site+id: $uuid+name: Site/AI/$SkillName+value: $newCount+"@++ Set-Content -Path $filePath -Value $content -Encoding UTF8+ Write-Host "Updated: $filePath (count: $newCount)"+}+```++## When to Create These Settings++### Authoring Tool Setting+- **After first upload** during `/create-site` (after `.powerpages-site` folder is created)+- If it already exists, do NOT overwrite (preserve original authoring tool)++### Skill Tracking Settings+- **Every skill** should update its tracking setting before final upload+- If setting exists, increment the count; if not, create with count = 1++| Skill | When to Update | Setting Name |+|-------|----------------|--------------|+| `/create-site` | After first upload, before second upload | `Site/AI/CreateSite` |+| `/add-seo` | Before final upload | `Site/AI/AddSeo` |+| `/add-tests` | Before final upload | `Site/AI/AddTests` |+| `/setup-dataverse` | Before final upload | `Site/AI/SetupDataverse` |+| `/add-sample-data` | Before final upload | `Site/AI/AddSampleData` |+| `/setup-webapi` | Before final upload | `Site/AI/SetupWebApi` |+| `/integrate-webapi` | Before final upload | `Site/AI/IntegrateWebApi` |+| `/setup-auth` | Before final upload | `Site/AI/SetupAuth` |++## Usage Examples++### In /create-site skill++```powershell+# After first upload creates .powerpages-site folder+New-AuthoringToolSetting -ProjectRoot $projectRoot+New-SkillTrackingSetting -ProjectRoot $projectRoot -SkillName "CreateSite"+# Then upload again to push the settings+```++### In /add-seo skill++```powershell+New-SkillTrackingSetting -ProjectRoot $projectRoot -SkillName "AddSeo"+# Then upload+```++### In /add-tests skill++```powershell+New-SkillTrackingSetting -ProjectRoot $projectRoot -SkillName "AddTests"+# Then upload (if deploying tests to site)+```++### In /setup-dataverse skill++```powershell+New-SkillTrackingSetting -ProjectRoot $projectRoot -SkillName "SetupDataverse"+# Then upload+```++### In /add-sample-data skill++```powershell+New-SkillTrackingSetting -ProjectRoot $projectRoot -SkillName "AddSampleData"+# Then upload+```++### In /setup-webapi skill++```powershell+New-SkillTrackingSetting -ProjectRoot $projectRoot -SkillName "SetupWebApi"+# Then upload+```++### In /integrate-webapi skill++```powershell+New-SkillTrackingSetting -ProjectRoot $projectRoot -SkillName "IntegrateWebApi"+# Then upload+```++### In /setup-auth skill++```powershell+New-SkillTrackingSetting -ProjectRoot $projectRoot -SkillName "SetupAuth"+# Then upload+```diff --git a/plugins/power-pages/shared/memory-bank.md b/plugins/power-pages/shared/memory-bank.mdindex cb58d3721..97d9bc4ff 100644--- a/plugins/power-pages/shared/memory-bank.md+++ b/plugins/power-pages/shared/memory-bank.md@@ -145,19 +145,24 @@ Update after:## Created Resources+### Publisher Prefix++The publisher prefix is fetched dynamically from the Default solution's publisher via `Initialize-DataverseApi`:+- **Prefix**: `{prefix}` (e.g., `cr`, `contoso`, `new`)+### Dataverse Tables| Table Name | Display Name | Columns | Sample Data ||------------|--------------|---------|-------------|-| cr_contactsubmission | Contact Submission | name, email, message, status | 3 records |-| cr_product | Product | name, description, price, category | 5 records |+| {prefix}_contactsubmission | Contact Submission | name, email, message, status | 3 records |+| {prefix}_product | Product | name, description, price, category | 5 records |### Site Settings| Setting | Value ||---------|-------|-| Webapi/cr_product/enabled | true |-| Webapi/cr_product/fields | cr_name,cr_description,cr_price,cr_category |+| Webapi/{prefix}_product/enabled | true |+| Webapi/{prefix}_product/fields | {prefix}_name,{prefix}_description,{prefix}_price,{prefix}_category |## Current Statusdiff --git a/plugins/power-pages/shared/planning-policy.md b/plugins/power-pages/shared/planning-policy.mdnew file mode 100644index 000000000..de4f27ef7--- /dev/null+++ b/plugins/power-pages/shared/planning-policy.md@@ -0,0 +1,40 @@+# Planning Policy++**Before implementing major changes, Claude MUST enter plan mode first.**++## When Planning is Required++- Adding new features or components+- Modifying existing workflows or logic+- Changes affecting multiple files+- Schema, API, or configuration changes+- Adding new pages, forms, or UI components+- Modifying Dataverse table structures+- Changes to authentication or authorization++## How to Plan++1. **Enter Plan Mode**: Use the `EnterPlanMode` tool before writing any code+2. **Explore**: Read relevant files and understand the current implementation+3. **Design**: Create a clear implementation approach+4. **Present**: Show the plan to the user for approval+5. **Wait**: Do not proceed until the user approves+6. **Exit**: Use `ExitPlanMode` when ready to implement++## When Planning is NOT Required++- Single-line fixes (typos, minor corrections)+- Documentation-only updates+- Memory bank updates+- Adding comments or improving readability+- Running diagnostic commands++## Planning Checklist++Before exiting plan mode, ensure your plan covers:++- [ ] What files will be created or modified+- [ ] What the changes will do+- [ ] Any dependencies or prerequisites+- [ ] Potential risks or rollback steps+- [ ] Testing approachdiff --git a/plugins/power-pages/shared/shared-instructions.md b/plugins/power-pages/shared/shared-instructions.mdnew file mode 100644index 000000000..550c8bf73--- /dev/null+++ b/plugins/power-pages/shared/shared-instructions.md@@ -0,0 +1,65 @@+# Shared Instructions++**This file aggregates all cross-cutting instructions that apply to every skill in the Power Pages plugin.**++All skills reference this single file. When new shared instructions are added, update this file only - no changes needed to individual skills.++---++## Planning Policy++**📋 [planning-policy.md](./planning-policy.md)**++Before implementing major changes, Claude MUST enter plan mode first. This ensures user approval before significant work begins.++**Key Points:**+- Use `EnterPlanMode` tool before writing code for new features or multi-file changes+- Present plan for user approval+- Exit plan mode with `ExitPlanMode` when approved++---++## Memory Bank++**📋 [memory-bank.md](./memory-bank.md)**++The memory bank persists context across sessions. Every skill reads it at start and updates it after major steps.++**Key Points:**+- Check for `<PROJECT_ROOT>/memory-bank.md` before starting+- Skip completed steps, resume from where the user left off+- Update after each major step to save progress++---++## Cleanup++**📋 [cleanup-reference.md](./cleanup-reference.md)**++Remove temporary helper files after skill completion.++**Key Points:**+- Only clean up after confirming success+- Never remove `memory-bank.md`, `.powerpages-site/`, or source files++---++## Authoring Tool++**📋 [authoring-tool-reference.md](./authoring-tool-reference.md)**++Configure the authoring tool site setting for Power Pages sites.++**Key Points:**+- Required for `.powerpages-site/` folder structure to work+- Create the site setting file when setting up site settings++---++## Adding New Shared Instructions++When adding a new cross-cutting concern:++1. Create the new file in `shared/` (e.g., `new-policy.md`)+2. Add a section to THIS file referencing the new file+3. No changes needed to individual SKILL.md filesdiff --git a/plugins/power-pages/skills/add-sample-data/SKILL.md b/plugins/power-pages/skills/add-sample-data/SKILL.mdnew file mode 100644index 000000000..0b252cd07--- /dev/null+++ b/plugins/power-pages/skills/add-sample-data/SKILL.md@@ -0,0 +1,94 @@+---+name: adding-sample-data+description: Inserts sample data into Dataverse tables with proper foreign key relationships. Use when populating tables with test data, adding demo content, or seeding databases.+user-invocable: true+allowed-tools: ["Read", "Write", "Grep", "Glob", "Bash", "AskUserQuestion"]+model: opus+---++**📋 [Shared Instructions](${CLAUDE_PLUGIN_ROOT}/shared/shared-instructions.md)** - Read before starting.++# Add Sample Data++**References:** [sample-data](./references/sample-data-reference.md)++Inserts sample data into Dataverse tables created by `/setup-dataverse`.++## Prerequisites++- Tables created with `/setup-dataverse`+- `$tableMap` available in memory bank with actual table names+- API authentication set up++## Workflow++1. **Check Context** → Read memory bank, get table mapping+2. **Check Existing Data** → Query tables to avoid duplicates+3. **Confirm with User** → Show what will be inserted+4. **Insert Tier 0** → Reference tables (categories, statuses)+5. **Insert Tier 1** → Primary entities with lookups+6. **Insert Tier 2** → Dependent records+7. **Verify Data** → Query with $expand to check relationships++---++## Step 1: Check Context++Read `memory-bank.md` for:+- Table name mapping (`$tableMap`)+- Publisher prefix+- Environment URL++If `/setup-dataverse` not completed, tell user to run it first.++---++## Step 2: Check Existing Data++```powershell+$api = Initialize-DataverseApi -EnvironmentUrl "https://<org>.crm.dynamics.com"++# Check record counts for each table+foreach ($purpose in $tableMap.Keys) {+ $entitySet = $tableMap[$purpose].EntitySetName+ $count = Get-ExistingRecordCount -EntitySetName $entitySet+ Write-Host "$purpose ($entitySet): $count records"+}+```++---++## Step 3: Confirm with User++Use `AskUserQuestion` to show:+- Tables that already have data (will skip or append)+- Tables that are empty (will populate)+- Sample records to be created++Options:+- **Proceed** - Insert sample data+- **Skip existing** - Only populate empty tables+- **Cancel** - Don't insert any data++---++## Step 4-6: Insert Data by Tier++See [sample-data-reference.md](./references/sample-data-reference.md#complete-sample-data-script).++**Tier 0** (reference tables): Categories, Statuses, Departments+**Tier 1** (primary entities): Products, Team Members+**Tier 2** (dependent): Testimonials, Contact Submissions++Use `New-DataverseRecordIfNotExists` to skip existing records.++---++## Step 7: Verify Data++```powershell+# Verify relationships with $expand+$products = Invoke-RestMethod -Uri "$baseUrl/$productEntitySet`?`$expand=${prefix}_categoryid" -Headers $headers+```++Update memory-bank.md with sample data status.diff --git a/plugins/power-pages/skills/add-sample-data/references/sample-data-reference.md b/plugins/power-pages/skills/add-sample-data/references/sample-data-reference.mdnew file mode 100644index 000000000..594d31be6--- /dev/null+++ b/plugins/power-pages/skills/add-sample-data/references/sample-data-reference.md@@ -0,0 +1,462 @@+# Sample Data Reference++## Insertion Order++Insert data by dependency tier:+1. **Tier 0** (reference tables) - Categories, Statuses, Departments (skip existing)+2. **Tier 1** (primary entities) - Products, Team Members (with lookups to Tier 0)+3. **Tier 2** (dependent tables) - Testimonials, Contact Submissions (with lookups to Tier 1)++**Important**: Check for existing data first. Never insert records with invalid lookup values.+```++## Check Existing Data++```powershell+function Get-ExistingRecordCount {+ param([string]$EntitySetName)++ $result = Invoke-RestMethod -Uri "$baseUrl/$EntitySetName/`$count" -Headers $headers+ return [int]$result+}++function Get-ExistingRecordByName {+ param(+ [string]$EntitySetName,+ [string]$NameColumn, # Usually "${publisherPrefix}_name" or the primary name attribute+ [string]$NameValue+ )++ $filter = "$NameColumn eq '$NameValue'"+ $result = Invoke-RestMethod -Uri "$baseUrl/$EntitySetName`?`$filter=$filter&`$top=1" -Headers $headers++ if ($result.value.Count -gt 0) {+ return $result.value[0]+ }+ return $null+}++# Check existing data counts+# NOTE: Use $tableMap from Build-TableNameMapping for actual entity set names+Write-Host "`nChecking existing data in tables..." -ForegroundColor Cyan++# Build counts using table mapping (handles both reused and new tables)+$existingDataCounts = @{}+foreach ($purpose in @("category", "status", "department", "product", "teammember", "testimonial", "contactsubmission")) {+ if ($tableMap.ContainsKey($purpose)) {+ $entitySet = $tableMap[$purpose].EntitySetName+ $existingDataCounts[$entitySet] = Get-ExistingRecordCount -EntitySetName $entitySet+ }+}++Write-Host "`nExisting record counts:" -ForegroundColor Yellow+$existingDataCounts.GetEnumerator() | ForEach-Object {+ $status = if ($_.Value -gt 0) { "[!]" } else { "[OK]" }+ Write-Host " $status $($_.Key): $($_.Value) records"+}+```++## Create Record Helper Function++```powershell+function New-DataverseRecord {+ param(+ [string]$EntitySetName,+ [hashtable]$Data+ )++ $body = $Data | ConvertTo-Json -Depth 5+ $response = Invoke-RestMethod -Uri "$baseUrl/$EntitySetName" -Method Post -Headers $headers -Body $body+ return $response+}+```++## Safe Record Creation (Skip If Exists)++```powershell+function New-DataverseRecordIfNotExists {+ param(+ [string]$EntitySetName,+ [hashtable]$Data,+ [string]$NameColumn = "${publisherPrefix}_name"+ )++ $nameValue = $Data[$NameColumn]+ $existing = Get-ExistingRecordByName -EntitySetName $EntitySetName -NameColumn $NameColumn -NameValue $nameValue++ if ($existing) {+ Write-Host " [SKIP] Record '$nameValue' already exists - using existing" -ForegroundColor Yellow+ return @{+ Skipped = $true+ Record = $existing+ }+ }++ Write-Host " [CREATE] Creating record '$nameValue'..." -ForegroundColor Cyan+ $body = $Data | ConvertTo-Json -Depth 5+ $response = Invoke-RestMethod -Uri "$baseUrl/$EntitySetName" -Method Post -Headers $headers -Body $body+ Write-Host " [OK] Record '$nameValue' created" -ForegroundColor Green++ return @{+ Skipped = $false+ Record = $response+ }+}+```++## Foreign Key Syntax++When inserting records with lookup values, use the `@odata.bind` syntax:++```powershell+# Format: "[email protected]" = "/entitysetname(guid)"+# NOTE: Use $publisherPrefix from Initialize-DataverseApi++$product = @{+ "${publisherPrefix}_name" = "Professional Consultation"+ "${publisherPrefix}_description" = "One-on-one consultation with our expert team."+ "${publisherPrefix}_price" = 299.99+ # Reference category by its ID+ "${publisherPrefix}[email protected]" = "/${publisherPrefix}_categories($categoryId)"+}+```++## Complete Sample Data Script++**IMPORTANT**: Use the `$tableMap` from `Build-TableNameMapping` to get the correct table names and entity set names. This ensures:+- **Reused tables**: Use their actual logical names and column names from Dataverse+- **New tables**: Use the publisher prefix pattern++```powershell+$api = Initialize-DataverseApi -EnvironmentUrl "https://orgname.crm.dynamics.com"+$publisherPrefix = $api.PublisherPrefix++# $tableMap should be built in STEP 5 using Build-TableNameMapping+# It maps table purposes to actual logical names and entity set names+```++### Helper Functions for Table Mapping++```powershell+# Get entity set name from table mapping+function Get-EntitySet { param([string]$Purpose) return $tableMap[$Purpose].EntitySetName }++# Get table logical name from mapping+function Get-TableName { param([string]$Purpose) return $tableMap[$Purpose].LogicalName }++# Get the primary key column name for a table+# For reused tables, this may differ from the standard pattern+function Get-PrimaryKeyColumn {+ param([string]$Purpose)+ $tableName = Get-TableName $Purpose+ # Primary key is typically {tablename}id+ return "${tableName}id"+}+```++```powershell+# ============================================+# TIER 0: Insert Reference/Lookup Data FIRST+# ============================================++Write-Host "`n=== TIER 0: Processing Reference/Lookup Data ===" -ForegroundColor Magenta++# --- Categories ---+$categoryIds = @{}+$categoryEntitySet = Get-EntitySet "category"+$categoryPK = Get-PrimaryKeyColumn "category"++# NOTE: For reused tables, column names may use the existing table's prefix+# For new tables, use $publisherPrefix for column names+$categories = @(+ @{ "${publisherPrefix}_name" = "Services"; "${publisherPrefix}_description" = "Professional services"; "${publisherPrefix}_displayorder" = 1; "${publisherPrefix}_isactive" = $true },+ @{ "${publisherPrefix}_name" = "Packages"; "${publisherPrefix}_description" = "Bundled offerings"; "${publisherPrefix}_displayorder" = 2; "${publisherPrefix}_isactive" = $true },+ @{ "${publisherPrefix}_name" = "Products"; "${publisherPrefix}_description" = "Physical and digital products"; "${publisherPrefix}_displayorder" = 3; "${publisherPrefix}_isactive" = $true }+)++Write-Host "Processing categories (using $categoryEntitySet)..." -ForegroundColor Cyan+foreach ($cat in $categories) {+ $result = New-DataverseRecordIfNotExists -EntitySetName $categoryEntitySet -Data $cat -NameColumn "${publisherPrefix}_name"+ $categoryIds[$cat["${publisherPrefix}_name"]] = $result.Record.$categoryPK+}++# --- Statuses ---+$statusIds = @{}+$statusEntitySet = Get-EntitySet "status"+$statusPK = Get-PrimaryKeyColumn "status"++$statuses = @(+ @{ "${publisherPrefix}_name" = "New"; "${publisherPrefix}_displayorder" = 1 },+ @{ "${publisherPrefix}_name" = "Reviewed"; "${publisherPrefix}_displayorder" = 2 },+ @{ "${publisherPrefix}_name" = "Responded"; "${publisherPrefix}_displayorder" = 3 },+ @{ "${publisherPrefix}_name" = "Closed"; "${publisherPrefix}_displayorder" = 4 }+)++Write-Host "`nProcessing statuses (using $statusEntitySet)..." -ForegroundColor Cyan+foreach ($status in $statuses) {+ $result = New-DataverseRecordIfNotExists -EntitySetName $statusEntitySet -Data $status -NameColumn "${publisherPrefix}_name"+ $statusIds[$status["${publisherPrefix}_name"]] = $result.Record.$statusPK+}++# --- Departments ---+$departmentIds = @{}+$departmentEntitySet = Get-EntitySet "department"+$departmentPK = Get-PrimaryKeyColumn "department"++$departments = @(+ @{ "${publisherPrefix}_name" = "Executive"; "${publisherPrefix}_code" = "EXEC" },+ @{ "${publisherPrefix}_name" = "Engineering"; "${publisherPrefix}_code" = "ENG" },+ @{ "${publisherPrefix}_name" = "Customer Success"; "${publisherPrefix}_code" = "CS" },+ @{ "${publisherPrefix}_name" = "Sales"; "${publisherPrefix}_code" = "SALES" }+)++Write-Host "`nProcessing departments (using $departmentEntitySet)..." -ForegroundColor Cyan+foreach ($dept in $departments) {+ $result = New-DataverseRecordIfNotExists -EntitySetName $departmentEntitySet -Data $dept -NameColumn "${publisherPrefix}_name"+ $departmentIds[$dept["${publisherPrefix}_name"]] = $result.Record.$departmentPK+}++# ============================================+# TIER 1: Insert Primary Entity Data+# ============================================++Write-Host "`n=== TIER 1: Processing Primary Entity Data ===" -ForegroundColor Magenta++# --- Products (with Category lookup) ---+$productIds = @{}+$productEntitySet = Get-EntitySet "product"+$productPK = Get-PrimaryKeyColumn "product"++# NOTE: For lookup bindings, use the actual entity set name from the table mapping+$products = @(+ @{+ "${publisherPrefix}_name" = "Professional Consultation"+ "${publisherPrefix}_description" = "One-on-one consultation with our expert team."+ "${publisherPrefix}_price" = 299.99+ "${publisherPrefix}_imageurl" = "https://images.unsplash.com/photo-1553877522-43269d4ea984?w=400"+ "${publisherPrefix}_isactive" = $true+ "${publisherPrefix}[email protected]" = "/$categoryEntitySet($($categoryIds['Services']))"+ },+ @{+ "${publisherPrefix}_name" = "Enterprise Solution Package"+ "${publisherPrefix}_description" = "Complete enterprise solution with 12 months support."+ "${publisherPrefix}_price" = 4999.99+ "${publisherPrefix}_imageurl" = "https://images.unsplash.com/photo-1460925895917-afdab827c52f?w=400"+ "${publisherPrefix}_isactive" = $true+ "${publisherPrefix}[email protected]" = "/$categoryEntitySet($($categoryIds['Packages']))"+ },+ @{+ "${publisherPrefix}_name" = "Starter Kit"+ "${publisherPrefix}_description" = "Perfect for small businesses getting started."+ "${publisherPrefix}_price" = 99.99+ "${publisherPrefix}_imageurl" = "https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=400"+ "${publisherPrefix}_isactive" = $true+ "${publisherPrefix}[email protected]" = "/$categoryEntitySet($($categoryIds['Packages']))"+ }+)++Write-Host "Processing products (using $productEntitySet)..." -ForegroundColor Cyan+foreach ($product in $products) {+ $result = New-DataverseRecordIfNotExists -EntitySetName $productEntitySet -Data $product -NameColumn "${publisherPrefix}_name"+ $productIds[$product["${publisherPrefix}_name"]] = $result.Record.$productPK+}++# --- Team Members (with Department lookup) ---+$teamMemberIds = @{}+$teammemberEntitySet = Get-EntitySet "teammember"+$teammemberPK = Get-PrimaryKeyColumn "teammember"++$team = @(+ @{+ "${publisherPrefix}_name" = "Emily Rodriguez"+ "${publisherPrefix}_title" = "Chief Executive Officer"+ "${publisherPrefix}_email" = "[email protected]"+ "${publisherPrefix}_bio" = "Emily has over 15 years of experience in technology leadership."+ "${publisherPrefix}_photourl" = "https://images.unsplash.com/photo-1573496359142-b8d87734a5a2?w=300"+ "${publisherPrefix}_linkedin" = "https://linkedin.com/in/emilyrodriguez"+ "${publisherPrefix}_displayorder" = 1+ "${publisherPrefix}[email protected]" = "/$departmentEntitySet($($departmentIds['Executive']))"+ },+ @{+ "${publisherPrefix}_name" = "David Kim"+ "${publisherPrefix}_title" = "Chief Technology Officer"+ "${publisherPrefix}_email" = "[email protected]"+ "${publisherPrefix}_bio" = "David brings deep technical expertise from his decade at leading tech companies."+ "${publisherPrefix}_photourl" = "https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=300"+ "${publisherPrefix}_linkedin" = "https://linkedin.com/in/davidkim"+ "${publisherPrefix}_displayorder" = 2+ "${publisherPrefix}[email protected]" = "/$departmentEntitySet($($departmentIds['Engineering']))"+ },+ @{+ "${publisherPrefix}_name" = "Lisa Thompson"+ "${publisherPrefix}_title" = "Head of Customer Success"+ "${publisherPrefix}_email" = "[email protected]"+ "${publisherPrefix}_bio" = "Lisa ensures our customers achieve their goals."+ "${publisherPrefix}_photourl" = "https://images.unsplash.com/photo-1580489944761-15a19d654956?w=300"+ "${publisherPrefix}_linkedin" = "https://linkedin.com/in/lisathompson"+ "${publisherPrefix}_displayorder" = 3+ "${publisherPrefix}[email protected]" = "/$departmentEntitySet($($departmentIds['Customer Success']))"+ }+)++Write-Host "`nProcessing team members (using $teammemberEntitySet)..." -ForegroundColor Cyan+foreach ($member in $team) {+ $result = New-DataverseRecordIfNotExists -EntitySetName $teammemberEntitySet -Data $member -NameColumn "${publisherPrefix}_name"+ $teamMemberIds[$member["${publisherPrefix}_name"]] = $result.Record.$teammemberPK+}++# ============================================+# TIER 2: Insert Dependent Data+# ============================================++Write-Host "`n=== TIER 2: Processing Dependent Data ===" -ForegroundColor Magenta++# --- Contact Submissions (with Status lookup) ---+$contactsubmissionEntitySet = Get-EntitySet "contactsubmission"++$contacts = @(+ @{+ "${publisherPrefix}_name" = "John Smith"+ "${publisherPrefix}_email" = "[email protected]"+ "${publisherPrefix}_message" = "I'm interested in learning more about your services."+ "${publisherPrefix}_submissiondate" = (Get-Date).ToString("yyyy-MM-ddTHH:mm:ssZ")+ "${publisherPrefix}[email protected]" = "/$statusEntitySet($($statusIds['New']))"+ },+ @{+ "${publisherPrefix}_name" = "Sarah Johnson"+ "${publisherPrefix}_email" = "[email protected]"+ "${publisherPrefix}_message" = "Looking for a partner for our upcoming project."+ "${publisherPrefix}_submissiondate" = (Get-Date).AddDays(-2).ToString("yyyy-MM-ddTHH:mm:ssZ")+ "${publisherPrefix}[email protected]" = "/$statusEntitySet($($statusIds['Reviewed']))"+ },+ @{+ "${publisherPrefix}_name" = "Michael Chen"+ "${publisherPrefix}_email" = "[email protected]"+ "${publisherPrefix}_message" = "Questions about pricing and availability."+ "${publisherPrefix}_submissiondate" = (Get-Date).AddDays(-5).ToString("yyyy-MM-ddTHH:mm:ssZ")+ "${publisherPrefix}[email protected]" = "/$statusEntitySet($($statusIds['Responded']))"+ }+)++Write-Host "Processing contact submissions (using $contactsubmissionEntitySet)..." -ForegroundColor Cyan+foreach ($contact in $contacts) {+ New-DataverseRecordIfNotExists -EntitySetName $contactsubmissionEntitySet -Data $contact -NameColumn "${publisherPrefix}_name"+}++# --- Testimonials (with optional Product lookup) ---+$testimonialEntitySet = Get-EntitySet "testimonial"++$testimonials = @(+ @{+ "${publisherPrefix}_name" = "Amanda Foster"+ "${publisherPrefix}_quote" = "Their solution increased our efficiency by 40%."+ "${publisherPrefix}_company" = "TechStart Inc."+ "${publisherPrefix}_role" = "Operations Director"+ "${publisherPrefix}_rating" = 5+ "${publisherPrefix}_photourl" = "https://images.unsplash.com/photo-1494790108377-be9c29b29330?w=200"+ "${publisherPrefix}_isactive" = $true+ "${publisherPrefix}[email protected]" = "/$productEntitySet($($productIds['Enterprise Solution Package']))"+ },+ @{+ "${publisherPrefix}_name" = "Robert Martinez"+ "${publisherPrefix}_quote" = "The best investment we've made this year."+ "${publisherPrefix}_company" = "Global Solutions Ltd"+ "${publisherPrefix}_role" = "CEO"+ "${publisherPrefix}_rating" = 5+ "${publisherPrefix}_photourl" = "https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=200"+ "${publisherPrefix}_isactive" = $true+ "${publisherPrefix}[email protected]" = "/$productEntitySet($($productIds['Professional Consultation']))"+ },+ @{+ "${publisherPrefix}_name" = "Jennifer Wu"+ "${publisherPrefix}_quote" = "Delivered beyond expectations. Highly recommend."+ "${publisherPrefix}_company" = "Innovate Partners"+ "${publisherPrefix}_role" = "Managing Partner"+ "${publisherPrefix}_rating" = 5+ "${publisherPrefix}_photourl" = "https://images.unsplash.com/photo-1438761681033-6461ffad8d80?w=200"+ "${publisherPrefix}_isactive" = $true+ # General testimonial - no specific product linked+ }+)++Write-Host "`nProcessing testimonials (using $testimonialEntitySet)..." -ForegroundColor Cyan+foreach ($testimonial in $testimonials) {+ New-DataverseRecordIfNotExists -EntitySetName $testimonialEntitySet -Data $testimonial -NameColumn "${publisherPrefix}_name"+}++Write-Host "`n=== Sample data processing complete ===" -ForegroundColor Green+```++## Verify Data and Relationships++**NOTE**: Use the `$tableMap` entity set names to query the correct tables (handles both reused and new tables).++```powershell+# Verify products with their categories (expanded relationship)+$productEntitySet = Get-EntitySet "product"+Write-Host "Products with Categories (from $productEntitySet):" -ForegroundColor Cyan+$products = Invoke-RestMethod -Uri "$baseUrl/$productEntitySet`?`$select=${publisherPrefix}_name,${publisherPrefix}_price&`$expand=${publisherPrefix}_categoryid(`$select=${publisherPrefix}_name)" -Headers $headers+$products.value | ForEach-Object {+ Write-Host " $($_."${publisherPrefix}_name") - `$$($_."${publisherPrefix}_price") - Category: $($_."${publisherPrefix}_categoryid"."${publisherPrefix}_name")"+}++# Verify team members with their departments+$teammemberEntitySet = Get-EntitySet "teammember"+Write-Host "`nTeam Members with Departments (from $teammemberEntitySet):" -ForegroundColor Cyan+$members = Invoke-RestMethod -Uri "$baseUrl/$teammemberEntitySet`?`$select=${publisherPrefix}_name,${publisherPrefix}_title&`$expand=${publisherPrefix}_departmentid(`$select=${publisherPrefix}_name)" -Headers $headers+$members.value | ForEach-Object {+ Write-Host " $($_."${publisherPrefix}_name") ($($_."${publisherPrefix}_title")) - Dept: $($_."${publisherPrefix}_departmentid"."${publisherPrefix}_name")"+}++# Verify contact submissions with their statuses+$contactsubmissionEntitySet = Get-EntitySet "contactsubmission"+Write-Host "`nContact Submissions with Statuses (from $contactsubmissionEntitySet):" -ForegroundColor Cyan+$submissions = Invoke-RestMethod -Uri "$baseUrl/$contactsubmissionEntitySet`?`$select=${publisherPrefix}_name,${publisherPrefix}_email&`$expand=${publisherPrefix}_statusid(`$select=${publisherPrefix}_name)" -Headers $headers+$submissions.value | ForEach-Object {+ Write-Host " $($_."${publisherPrefix}_name") ($($_."${publisherPrefix}_email")) - Status: $($_."${publisherPrefix}_statusid"."${publisherPrefix}_name")"+}++# Verify testimonials with their linked products+$testimonialEntitySet = Get-EntitySet "testimonial"+Write-Host "`nTestimonials with Products (from $testimonialEntitySet):" -ForegroundColor Cyan+$testimonials = Invoke-RestMethod -Uri "$baseUrl/$testimonialEntitySet`?`$select=${publisherPrefix}_name,${publisherPrefix}_company&`$expand=${publisherPrefix}_productid(`$select=${publisherPrefix}_name)" -Headers $headers+$testimonials.value | ForEach-Object {+ $productName = if ($_."${publisherPrefix}_productid") { $_."${publisherPrefix}_productid"."${publisherPrefix}_name" } else { "(General)" }+ Write-Host " $($_."${publisherPrefix}_name") from $($_."${publisherPrefix}_company") - Product: $productName"+}+```++## Update Records++```powershell+function Update-DataverseRecord {+ param(+ [string]$EntitySetName,+ [string]$RecordId,+ [hashtable]$Data+ )++ $body = $Data | ConvertTo-Json -Depth 5+ Invoke-RestMethod -Uri "$baseUrl/$EntitySetName($RecordId)" -Method Patch -Headers $headers -Body $body+}++# Example: Update a product's price+Update-DataverseRecord -EntitySetName "${publisherPrefix}_products" -RecordId $productIds['Starter Kit'] -Data @{+ "${publisherPrefix}_price" = 129.99+}+```++## Delete Records++```powershell+function Remove-DataverseRecord {+ param(+ [string]$EntitySetName,+ [string]$RecordId+ )++ Invoke-RestMethod -Uri "$baseUrl/$EntitySetName($RecordId)" -Method Delete -Headers $headers+}++# CAUTION: Delete records in reverse dependency order (TIER 2 -> TIER 1 -> TIER 0)+```diff --git a/plugins/power-pages/skills/add-seo/SKILL.md b/plugins/power-pages/skills/add-seo/SKILL.mdnew file mode 100644index 000000000..b779715c5--- /dev/null+++ b/plugins/power-pages/skills/add-seo/SKILL.md@@ -0,0 +1,97 @@+---+name: adding-seo+description: Adds SEO assets to Power Pages sites including meta tags, robots.txt, sitemap.xml, and favicon. Use when adding search engine optimization, social sharing images, or meta tags.+user-invocable: true+allowed-tools: ["Read", "Write", "Grep", "Glob", "Bash", "AskUserQuestion"]+model: haiku+---++**📋 [Shared Instructions](${CLAUDE_PLUGIN_ROOT}/shared/shared-instructions.md)** - Read before starting.++# Add SEO Assets++**References:** [seo](./references/seo-reference.md)++Adds search engine optimization assets to an existing Power Pages code site.++## Prerequisites++- Site created with `/create-site`+- `index.html` exists in project root++## Workflow++1. **Gather Info** → Ask site name, description, subdomain, primary color+2. **Update Meta Tags** → Add SEO and Open Graph meta tags to `index.html`+3. **Create robots.txt** → Search engine crawl directives+4. **Create sitemap.xml** → Site structure for search engines+5. **Add Favicon** → Placeholder favicon files (user replaces with actual assets)+6. **Build and Upload** → Deploy changes++---++## Step 1: Gather Info++Use `AskUserQuestion` to collect:+1. Site name (for title and og:site_name)+2. Site description (150-160 chars for meta description)+3. Expected subdomain (for canonical URLs)+4. Primary brand color (hex, for theme-color)++---++## Step 2: Update Meta Tags++See [seo-reference.md](./references/seo-reference.md#meta-tags-template).++Update `index.html` with:+- Primary meta tags (title, description, keywords, author, robots)+- Canonical URL+- Open Graph tags (og:title, og:description, og:image, etc.)+- Twitter card tags+- Favicon links+- Theme color++---++## Step 3: Create robots.txt++Create `public/robots.txt`:++```txt+User-agent: *+Allow: /+Sitemap: https://[subdomain].powerappsportals.com/sitemap.xml+```++---++## Step 4: Create sitemap.xml++Create `public/sitemap.xml` with entries for each page. See [seo-reference.md](./references/seo-reference.md#sitemapxml) for format.++Priority guidelines: Homepage=1.0, Main sections=0.8, Secondary=0.7, Blog=0.6, Legal=0.3++---++## Step 5: Add Favicon Placeholders++Create placeholder files in `public/`:+- `favicon.ico` (48x48)+- `favicon-32x32.png` (32x32)+- `favicon-16x16.png` (16x16)+- `apple-touch-icon.png` (180x180)+- `og-image.png` (1200x630) - social sharing image++Tell user to replace these with actual brand assets.++---++## Step 6: Build and Upload++```powershell+npm run build+pac pages upload-code-site --rootPath "<PROJECT_ROOT>"+```++Update memory-bank.md with SEO status.diff --git a/plugins/power-pages/skills/create-site/seo-reference.md b/plugins/power-pages/skills/add-seo/references/seo-reference.mdsimilarity index 62%rename from plugins/power-pages/skills/create-site/seo-reference.mdrename to plugins/power-pages/skills/add-seo/references/seo-reference.mdindex 7ab9aa2fd..517923957 100644--- a/plugins/power-pages/skills/create-site/seo-reference.md+++ b/plugins/power-pages/skills/add-seo/references/seo-reference.md@@ -1,7 +1,5 @@# SEO Reference-This document describes how to add SEO assets to your Power Pages code site.-## Meta Tags TemplateEnsure the `index.html` file includes comprehensive meta tags for SEO and social sharing:@@ -59,16 +57,6 @@ Ensure the `index.html` file includes comprehensive meta tags for SEO and social</head>```-## Framework-Specific Locations--| Framework | index.html Location |-|-----------|---------------------|-| React (Vite) | Project root `index.html` |-| React (CRA) | `public/index.html` |-| Vue | Project root `index.html` |-| Angular | `src/index.html` |-| Astro | `src/layouts/Layout.astro` or use `<head>` slot |-## Required SEO AssetsPlace these assets in the `public/` folder:@@ -104,25 +92,6 @@ Sitemap: https://[subdomain].powerappsportals.com/sitemap.xml# Disallow: /private/```-### robots.txt Directives--| Directive | Purpose |-|-----------|---------|-| `User-agent: *` | Applies rules to all search engine bots |-| `Allow: /` | Permits crawling of all pages |-| `Disallow: /path/` | Blocks crawling of specific paths |-| `Sitemap:` | Points crawlers to your sitemap |--### Framework-Specific Location (robots.txt)--| Framework | robots.txt Location |-|-----------|---------------------|-| React (Vite) | `public/robots.txt` |-| React (CRA) | `public/robots.txt` |-| Vue | `public/robots.txt` |-| Angular | `src/robots.txt` (add to `angular.json` assets) |-| Astro | `public/robots.txt` |----## sitemap.xml@@ -168,49 +137,16 @@ Create `sitemap.xml` in the `public/` folder:</urlset>```-### Sitemap Elements--| Element | Required | Description |-|---------|----------|-------------|-| `<loc>` | Yes | Full URL of the page (must be absolute URL) |-| `<lastmod>` | Recommended | Last modification date in YYYY-MM-DD format |-| `<changefreq>` | Optional | How often the page changes: `always`, `hourly`, `daily`, `weekly`, `monthly`, `yearly`, `never` |-| `<priority>` | Optional | Priority relative to other pages: `0.0` to `1.0` (default: `0.5`) |--### Priority Guidelines+**Priority guidelines**: Homepage=1.0, Main sections=0.8, Secondary pages=0.7, Blog=0.6, Legal=0.3-| Page Type | Recommended Priority |-|-----------|---------------------|-| Homepage | `1.0` |-| Main sections (About, Services, Products) | `0.8` |-| Secondary pages (Contact, FAQ) | `0.7` |-| Blog posts, articles | `0.6` |-| Legal pages (Privacy, Terms) | `0.3` |+**SPA note**: Use history mode routing (`/about`) not hash routing (`/#/about`) for proper indexing.-### SPA Routing Considerations--For Single Page Applications with client-side routing:--1. **List all accessible routes** - Include every URL path that users can navigate to-2. **Use hash routing carefully** - If using hash routing (`/#/about`), search engines may not index these properly. Prefer history mode routing (`/about`)-3. **Ensure server redirects** - Configure your hosting to redirect all routes to `index.html` for proper SPA routing--### Framework-Specific Location (sitemap.xml)--| Framework | sitemap.xml Location |-|-----------|----------------------|-| React (Vite) | `public/sitemap.xml` |-| React (CRA) | `public/sitemap.xml` |-| Vue | `public/sitemap.xml` |-| Angular | `src/sitemap.xml` (add to `angular.json` assets) |-| Astro | `public/sitemap.xml` |--### Verify After Deployment--After the site is active, verify the sitemap is accessible:--```-https://[subdomain].powerappsportals.com/sitemap.xml-```+## Framework-Specific Paths-Update the sitemap whenever you add new pages to your site.+| Framework | index.html | public/ folder |+|-----------|------------|----------------|+| React (Vite) | Project root | `public/` |+| React (CRA) | `public/` | `public/` |+| Vue | Project root | `public/` |+| Angular | `src/` | `src/` (add to `angular.json` assets) |+| Astro | Layout component | `public/` |diff --git a/plugins/power-pages/skills/add-tests/SKILL.md b/plugins/power-pages/skills/add-tests/SKILL.mdnew file mode 100644index 000000000..11824f1af--- /dev/null+++ b/plugins/power-pages/skills/add-tests/SKILL.md@@ -0,0 +1,122 @@+---+name: adding-tests+description: Adds unit tests (Vitest) and E2E tests (Playwright) to Power Pages sites. Use when setting up testing infrastructure, writing tests, or adding test coverage.+user-invocable: true+allowed-tools: ["Read", "Write", "Grep", "Glob", "Bash", "AskUserQuestion"]+model: opus+---++**📋 [Shared Instructions](${CLAUDE_PLUGIN_ROOT}/shared/shared-instructions.md)** - Read before starting.++# Add Tests++**References:** [testing](./references/testing-reference.md)++Adds testing infrastructure to an existing Power Pages code site.++## Prerequisites++- Site created with `/create-site`+- Framework identified (React/Vue/Angular/Astro)++## Workflow++1. **Check Context** → Read memory bank, identify framework+2. **Setup Unit Tests** → Install Vitest, configure, write component tests+3. **Setup E2E Tests** → Install Playwright, configure, write page tests+4. **Run Tests** → Verify all tests pass+5. **Update CI (Optional)** → Add test scripts to package.json++---++## Step 1: Check Context++Read `memory-bank.md` and `package.json` to identify:+- Framework (React, Vue, Angular, Astro)+- Build tool (Vite, CRA, Angular CLI)+- Existing test setup (if any)++---++## Step 2: Setup Unit Tests++See [testing-reference.md](./references/testing-reference.md#unit-tests).++### Install Dependencies++```powershell+# React (Vite)+npm install -D vitest @testing-library/react @testing-library/jest-dom @testing-library/user-event jsdom++# Vue (Vite)+npm install -D vitest @vue/test-utils @testing-library/vue jsdom+```++### Configure Vitest++Add test config to `vite.config.ts` and create `src/test/setup.ts`.++### Write Tests++Create tests for key components:+- `src/components/Header.test.tsx`+- `src/components/[MainComponent].test.tsx`+- `src/utils/[utility].test.ts`++---++## Step 3: Setup E2E Tests++See [testing-reference.md](./references/testing-reference.md#end-to-end-tests-playwright).++### Install Playwright++```powershell+npm install -D @playwright/test+npx playwright install+```++### Configure Playwright++Create `playwright.config.ts` with correct baseURL for framework.++### Write E2E Tests++Create tests in `e2e/` folder:+- `e2e/home.spec.ts` - Homepage tests+- `e2e/navigation.spec.ts` - Navigation tests+- `e2e/accessibility.spec.ts` - A11y checks++---++## Step 4: Run Tests++```powershell+# Unit tests+npm run test:run++# E2E tests+npm run test:e2e+```++**All tests must pass before completing this skill.**++---++## Step 5: Update Package Scripts++Ensure `package.json` has test scripts:++```json+{+ "scripts": {+ "test": "vitest",+ "test:run": "vitest run",+ "test:coverage": "vitest run --coverage",+ "test:e2e": "playwright test",+ "test:e2e:ui": "playwright test --ui"+ }+}+```++Update memory-bank.md with testing status.diff --git a/plugins/power-pages/skills/create-site/testing-reference.md b/plugins/power-pages/skills/add-tests/references/testing-reference.mdsimilarity index 87%rename from plugins/power-pages/skills/create-site/testing-reference.mdrename to plugins/power-pages/skills/add-tests/references/testing-reference.mdindex d6e5c659c..95be4890d 100644--- a/plugins/power-pages/skills/create-site/testing-reference.md+++ b/plugins/power-pages/skills/add-tests/references/testing-reference.md@@ -1,10 +1,8 @@# Testing Reference-This document describes how to set up and write unit tests and end-to-end tests for your Power Pages code site.-## Unit Tests-### Install Testing Dependencies+### Install Dependencies```powershell# React (Vite) - Vitest + React Testing Library@@ -64,33 +62,6 @@ Add test scripts to `package.json`:}```-### What to Test--| Category | What to Test |-|----------|--------------|-| Components | Rendering, user interactions, props |-| Utility functions | Data transformations, validators, formatters |-| Custom hooks | State management, side effects |-| Form validation | Validation rules, error messages |-| API services | Dataverse Web API wrapper functions (mock the API) |--### Test File Structure--```text-/src-├── components/-│ ├── Header.tsx-│ └── Header.test.tsx # Component test-├── utils/-│ ├── formatters.ts-│ └── formatters.test.ts # Utility test-├── hooks/-│ ├── useDataverse.ts-│ └── useDataverse.test.ts # Hook test-└── test/- └── setup.ts # Test setup file-```-### Example Component Test (React)```typescript@@ -252,17 +223,6 @@ Add E2E test scripts to `package.json`:└── test-data.ts # Shared test data```-### What to Test with E2E--| Category | What to Test |-|----------|--------------|-| Page Navigation | All links work, routes load correctly |-| Form Submissions | Contact forms, search, filters work end-to-end |-| Responsive Design | Site works on mobile, tablet, and desktop |-| Interactive Elements | Modals, dropdowns, accordions function properly |-| Accessibility | Keyboard navigation, focus states |-| Error States | Error pages and validation messages |-### Example: Home Page Test```typescriptdiff --git a/plugins/power-pages/skills/create-site/SKILL.md b/plugins/power-pages/skills/create-site/SKILL.mdindex 946d6b8c0..4c5dabdbc 100644--- a/plugins/power-pages/skills/create-site/SKILL.md+++ b/plugins/power-pages/skills/create-site/SKILL.md@@ -1,268 +1,112 @@----description: Create a Power Pages code site, website, portal, or SPA using modern frontend frameworks like React, Angular, Vue, or Astro. Use this skill when you need to create a new Power Pages site, build a website, set up a portal, scaffold a project, design pages, upload site to Power Pages, or activate a site for public access.+name: creating-power-pages-site+description: Creates Power Pages code sites (SPAs) using React, Angular, Vue, or Astro. Use when creating sites, portals, building websites, scaffolding projects, uploading to Power Pages, or activating sites.user-invocable: true-allowed-tools: Bash(pac:*), Bash(az:*)+allowed-tools: ["Read", "Write", "Grep", "Glob", "Bash", "TodoWrite", "AskUserQuestion", "Skill", "Task"]model: opus----# Create Power Pages Code Site--This skill guides makers through creating a complete Power Pages code site (Single Page Application) from scratch, deploying it to Power Pages, and activating it for public access.--## Reference Documentation--This skill uses modular reference files for detailed instructions:--| File | Purpose |-|------|---------|-| [requirements-reference.md](./requirements-reference.md) | Framework options, features, design preferences |-| [site-creation-reference.md](./site-creation-reference.md) | Project structure, powerpages.config.json, memory bank |-| [seo-reference.md](./seo-reference.md) | Meta tags, robots.txt, sitemap.xml, favicons |-| [testing-reference.md](./testing-reference.md) | Unit tests (Vitest) and E2E tests (Playwright) |-| [upload-activation-reference.md](./upload-activation-reference.md) | Prerequisites, PAC CLI upload, API activation |-| [troubleshooting.md](./troubleshooting.md) | Common issues and solutions |--## Memory Bank--This skill uses a **memory bank** (`memory-bank.md`) to persist context across sessions.--**Follow the instructions in `${CLAUDE_PLUGIN_ROOT}/shared/memory-bank.md`** for:-- Checking and reading the memory bank before starting-- Skipping completed steps and resuming progress-- Updating the memory bank after each major step--## Workflow Overview--```text-┌─────────────────────────────────────────────────────────────────────────────┐-│ STEP 1: Gather Requirements │-│ ───────────────────────────────────────────────────────────────────────── │-│ • Frontend framework selection (React, Angular, Vue, Astro) │-│ • Site features and functionality │-│ • Design preferences and style │-└─────────────────────────────────────────────────────────────────────────────┘- ↓-┌─────────────────────────────────────────────────────────────────────────────┐-│ STEP 2: Create the Site │-│ ───────────────────────────────────────────────────────────────────────── │-│ • Use frontend-design skill to build production-grade UI │-│ • Generate complete SPA with chosen framework │-│ • Add SEO assets (meta tags, robots.txt, sitemap.xml, favicon) │-│ • Write unit tests for components and utilities │-│ • Write end-to-end tests with Playwright │-│ • Build the project for production │-└─────────────────────────────────────────────────────────────────────────────┘- ↓-┌─────────────────────────────────────────────────────────────────────────────┐-│ STEP 3: Check Prerequisites │-│ ───────────────────────────────────────────────────────────────────────── │-│ • Verify PAC CLI is installed (install if missing) │-│ • Verify Azure CLI is installed (install if missing) │-│ • Ensure authentication is configured │-└─────────────────────────────────────────────────────────────────────────────┘- ↓-┌─────────────────────────────────────────────────────────────────────────────┐-│ STEP 4: Upload to Power Pages (Inactive) │-│ ───────────────────────────────────────────────────────────────────────── │-│ • Use PAC CLI: pac pages upload-code-site │-│ • Site uploaded in INACTIVE mode │-│ • Get websiteRecordId for activation │-└─────────────────────────────────────────────────────────────────────────────┘- ↓-┌─────────────────────────────────────────────────────────────────────────────┐-│ STEP 5: Preview Locally │-│ ───────────────────────────────────────────────────────────────────────── │-│ • Run the app locally to verify it works │-│ • Test all features before activation │-└─────────────────────────────────────────────────────────────────────────────┘- ↓-┌─────────────────────────────────────────────────────────────────────────────┐-│ STEP 6: Activate Website │-│ ───────────────────────────────────────────────────────────────────────── │-│ • Ask user for subdomain preference │-│ • Call Power Platform CreateWebsite API via az rest │-│ • Monitor operation status until complete │-│ • Fallback: Manual activation via Power Pages portal │-└─────────────────────────────────────────────────────────────────────────────┘-```-----+**📋 [Shared Instructions](${CLAUDE_PLUGIN_ROOT}/shared/shared-instructions.md)** - Read before starting.-## STEP 1: Gather Requirements--**📖 Detailed reference: [requirements-reference.md](./requirements-reference.md)**--**IMPORTANT**: Before creating anything, ask the maker the following questions using the AskUserQuestion tool.--### Questions to Ask+# Create Power Pages Code Site-1. **What do you want to build?** - Site purpose, key functionality, target audience-2. **Frontend framework** - React (recommended), Angular, Vue, or Astro-3. **Site features** - Landing page, navigation, forms, authentication, data display-4. **Design preferences** - Style, color scheme, special requirements+**References:** [requirements](./references/requirements-reference.md) | [site-creation](./references/site-creation-reference.md) | [upload-activation](./references/upload-activation-reference.md) | [troubleshooting](./references/troubleshooting.md)-### Key Points+## Workflow-- Only use frameworks that build to static HTML/CSS/JS files-- **NOT supported**: Next.js, Nuxt.js, Remix, SvelteKit, Liquid templates-- Power Pages code sites are static SPAs served from Azure CDN+1. **Gather Requirements** → Ask framework, features, design preferences+2. **Create Site** → Use frontend-design skill, configure for Power Pages+3. **Preview & Approve** → User reviews site locally before upload+4. **Check Prerequisites** → Verify PAC CLI and Azure CLI+5. **Upload (Inactive)** → `pac pages upload-code-site`+6. **Activate** → Call CreateWebsite API or manual activation----## STEP 2: Create the Site+## Step 1: Gather Requirements-**📖 Detailed references:**-- [site-creation-reference.md](./site-creation-reference.md) - Project structure, config-- [seo-reference.md](./seo-reference.md) - Meta tags, robots.txt, sitemap.xml-- [testing-reference.md](./testing-reference.md) - Unit and E2E tests+Use `AskUserQuestion` to ask:+1. Site purpose and target audience+2. Framework: React (recommended), Angular, Vue, or Astro+3. Features: landing page, forms, auth, data display+4. Design preferences-### Quick Summary+**Constraint**: Only static SPA frameworks. NOT supported: Next.js, Nuxt.js, Remix, SvelteKit, Liquid.-1. **Invoke the frontend-design skill** with gathered requirements-2. **Create powerpages.config.json** in project root-3. **Add SEO assets** - meta tags, robots.txt, sitemap.xml, favicons-4. **Write unit tests** - components, utilities, hooks-5. **Write E2E tests** - Playwright for critical user journeys-6. **Build the project** - `npm run build`-7. **Initialize memory bank** - Create `memory-bank.md`+----### Actions+## Step 2: Create the Site-1. Use frontend-design skill with explicit constraints (Vite, no SSR)+1. Invoke `frontend-design` skill with Vite + no SSR constraints2. Create `powerpages.config.json` with correct `compiledPath`-3. Add meta tags to index.html (see seo-reference.md)-4. Create robots.txt and sitemap.xml in public folder-5. Set up Vitest and write unit tests-6. Set up Playwright and write E2E tests-7. Run all tests - **all must pass before proceeding**-8. Build the project-9. Create memory-bank.md+3. `npm run build`+4. Create `memory-bank.md`----## STEP 3: Check Prerequisites+## Step 3: Preview & Approve-**📖 Detailed reference: [upload-activation-reference.md](./upload-activation-reference.md)**--### Quick Summary--Verify CLI tools are installed and authenticated before uploading.--### Actions--1. Check PAC CLI: `pac help`- - If missing: `dotnet tool install --global Microsoft.PowerApps.CLI.Tool`--2. Check Azure CLI: `az --version`- - If missing: `winget install -e --id Microsoft.AzureCLI`--3. Verify authentication:- - `pac auth list` (create with `pac auth create` if needed)- - `az account show` (login with `az login` if needed)--4. Verify environment: `pac org who`+1. Run `npm run dev` to start local server+2. **Ask user to preview** using `AskUserQuestion`: "Please review the site at http://localhost:xxxx. Ready to proceed with upload?"+3. User must confirm before continuing to upload----## STEP 4: Upload to Power Pages (Inactive)--**📖 Detailed reference: [upload-activation-reference.md](./upload-activation-reference.md)**--### Quick Summary+## Step 4: Check Prerequisites-Upload the built site to Power Pages as an inactive site.+```powershell+# PAC CLI (install if missing: dotnet tool install --global Microsoft.PowerApps.CLI.Tool)+pac help-### Actions+# Azure CLI (install if missing: winget install -e --id Microsoft.AzureCLI)+az --version-1. **Confirm account**: Run `pac auth list` and ask user to confirm-2. **Upload**: `pac pages upload-code-site --rootPath "<PROJECT_ROOT>"`-3. **Get Website ID**: `pac pages list --verbose`+# Auth+pac auth list # create with: pac auth create+az account show # login with: az login+pac org who+```----## STEP 5: Preview Locally--**📖 Detailed reference: [upload-activation-reference.md](./upload-activation-reference.md)**--### Quick Summary--Run the site locally to verify everything works before activation.--### Actions+## Step 5: Upload to Power Pages-1. Run dev server: `npm run dev` (or framework-specific command)-2. Test all pages and navigation-3. Verify forms and interactive elements-4. Check responsive design+1. Run `pac auth list` to show available environments+2. **Ask user which environment** to upload to using `AskUserQuestion` (show org names from auth list)+3. If needed, switch auth: `pac auth select --index <n>` or `pac auth create`+4. **Build before upload**: `npm run build`+5. `pac pages upload-code-site --rootPath "<PROJECT_ROOT>"` (creates `.powerpages-site` folder)+6. **Create AI site settings** in `.powerpages-site/site-settings/` (see [authoring-tool-reference.md](${CLAUDE_PLUGIN_ROOT}/shared/authoring-tool-reference.md)):+ - `Site/AI/AuthoringTool` - ClaudeCodeCLI or ClaudeCodeVSCode+ - `Site/AI/CreateSite` - true (skill tracking)+7. **Build and upload again**: `npm run build && pac pages upload-code-site --rootPath "<PROJECT_ROOT>"`+8. `pac pages list --verbose` to get Website ID----## STEP 6: Activate Website--**📖 Detailed reference: [upload-activation-reference.md](./upload-activation-reference.md)**--### Quick Summary--Activate the uploaded site using Power Platform API or manual activation.--### Actions--1. **Ask for subdomain** using AskUserQuestion tool-2. **Get IDs**: `pac org who` for environment and organization IDs-3. **Activate via API**: Use `az rest` to call CreateWebsite API-4. **Monitor status**: Poll operation URL until complete-5. **Verify**: `pac pages list --verbose` to confirm active status-6. **Fallback**: Manual activation via make.powerpages.microsoft.com if API fails+## Step 6: Activate Website-### Update Memory Bank+1. Ask user for subdomain via `AskUserQuestion`+2. Get IDs: `pac org who`+3. Call CreateWebsite API via `az rest` (see [upload-activation-reference.md](./references/upload-activation-reference.md))+4. Poll operation status until complete+5. Verify: `pac pages list --verbose`+6. Fallback: Manual activation at make.powerpages.microsoft.com-After activation, update memory-bank.md with:-- Website ID-- Site URL-- All completed steps marked `[x]`-- Next step: `/setup-dataverse`+Update memory-bank.md with Website ID, URL, completed steps.-### Cleanup Helper Files--**📖 See: [cleanup-reference.md](${CLAUDE_PLUGIN_ROOT}/shared/cleanup-reference.md)**--Remove any temporary helper files created during this skill's execution.+Cleanup helper files per [cleanup-reference.md](${CLAUDE_PLUGIN_ROOT}/shared/cleanup-reference.md).----## Next Steps--After the site is active, suggest the maker proceed with:--### Setup Dataverse Tables+## Optional Enhancements-> **Recommended Next Step**: Set up Dataverse tables to store and manage your site's data.->-> This will allow your site to:-> - Store contact form submissions, user feedback, and other data-> - Display dynamic content from Dataverse (products, team members, testimonials)-> - Create, update, and delete records via Web API->-> Run `/setup-dataverse` or type "Set up Dataverse tables for my site" to continue.--### Additional Enhancements--- **Authentication**: Set up Microsoft Entra ID for user sign-in-- **Custom styling**: Further refine the design-- **Performance optimization**: Enable caching and CDN+After site creation, suggest these optional skills:+- `/add-seo` - Add SEO assets (meta tags, robots.txt, sitemap.xml, favicon)+- `/add-tests` - Add unit tests (Vitest) and E2E tests (Playwright)----## Troubleshooting--**📖 Detailed reference: [troubleshooting.md](./troubleshooting.md)**+## Next Steps-Common issues covered:-- Upload fails with JavaScript error-- Site shows as inactive after upload-- Next.js or SSR framework used-- Liquid templates not working-- Unit tests failing-- E2E tests failing-- Authentication issues-- Build issues+Suggest `/setup-dataverse` to create tables for dynamic content (forms, products, team members).diff --git a/plugins/power-pages/skills/create-site/references/requirements-reference.md b/plugins/power-pages/skills/create-site/references/requirements-reference.mdnew file mode 100644index 000000000..8990e8583--- /dev/null+++ b/plugins/power-pages/skills/create-site/references/requirements-reference.md@@ -0,0 +1,33 @@+# Requirements Reference++## 1. Site Purpose++Ask the user (if not already specified):+- Purpose (portal, self-service, directory, etc.)+- Key functionality needed+- Target audience++## 2. Frontend Framework++Ask the maker which frontend framework they want to use:++| Option | Description |+|--------|-------------|+| **React (Recommended)** | Most popular choice with excellent ecosystem. Best for complex interactive UIs. |+| **Angular** | Full-featured framework by Google. Great for enterprise applications with built-in state management. |+| **Vue** | Progressive framework, easy to learn. Good balance of simplicity and power. |+| **Astro** | Modern static site generator with partial hydration. Best for content-focused sites with minimal JS. |++**Unsupported**: Next.js, Nuxt.js, Remix, SvelteKit, Liquid templates, server-side APIs, React Server Components (all require server runtime - only static HTML/CSS/JS supported).++## 3. Site Features++**Content**: Landing page, navigation, about, services/products, gallery, blog+**Interactive**: Contact form, search, filtering/sorting+**Data**: Authentication (Entra ID), Dataverse Web API, form submissions++## 4. Design Preferences++**Styles**: Modern/Minimalist, Corporate/Professional, Creative/Bold, Elegant/Luxury+**Colors**: User's brand colors or suggest based on industry (consider WCAG 2.1 AA contrast)+**Special**: Accessibility, mobile-first, branding guidelines, RTL supportdiff --git a/plugins/power-pages/skills/create-site/references/site-creation-reference.md b/plugins/power-pages/skills/create-site/references/site-creation-reference.mdnew file mode 100644index 000000000..8a1145934--- /dev/null+++ b/plugins/power-pages/skills/create-site/references/site-creation-reference.md@@ -0,0 +1,70 @@+# Site Creation Reference++## Using frontend-design Skill++Invoke with gathered requirements. **Constraints**:+- Use Vite for React/Vue (not Next.js, Nuxt.js, Remix, or SSR frameworks)+- No Liquid templates+- Output must be static HTML/CSS/JS only++## Required Project Structure++```text+/site-project+├── src/ # Source code+├── public/ # Static assets+├── build/ or dist/ # Compiled output (after build)+├── package.json # Dependencies+├── powerpages.config.json # Power Pages configuration (create this)+└── README.md+```++## powerpages.config.json++Create this configuration file in the project root:++```json+{+ "siteName": "<SITE_NAME>",+ "defaultLandingPage": "index.html",+ "compiledPath": "./build"+}+```++### Framework-Specific compiledPath++| Framework | compiledPath |+|-----------|--------------|+| React (Vite) | `"./dist"` |+| React (CRA) | `"./build"` |+| Vue | `"./dist"` |+| Angular | `"./dist/<project-name>"` |+| Astro | `"./dist"` |++## Build Commands++Run the appropriate build command for your framework:++```powershell+# React (Create React App or Vite)+npm run build++# Angular+ng build --configuration production++# Vue+npm run build++# Astro+npm run build+```++## Memory Bank Initialization++Create `memory-bank.md` in project root with:+- Project overview (name, path, framework, date, status)+- User preferences (style, colors, features)+- Completed steps checklist for `/create-site`+- Current status and next step++Update after each subsequent step is completed.diff --git a/plugins/power-pages/skills/create-site/troubleshooting.md b/plugins/power-pages/skills/create-site/references/troubleshooting.mdsimilarity index 98%rename from plugins/power-pages/skills/create-site/troubleshooting.mdrename to plugins/power-pages/skills/create-site/references/troubleshooting.mdindex 6b0eab253..793f5d610 100644--- a/plugins/power-pages/skills/create-site/troubleshooting.md+++ b/plugins/power-pages/skills/create-site/references/troubleshooting.md@@ -1,7 +1,5 @@# Troubleshooting-This document covers common issues and solutions when creating Power Pages code sites.-## Upload Issues### Upload Fails with JavaScript Errordiff --git a/plugins/power-pages/skills/create-site/upload-activation-reference.md b/plugins/power-pages/skills/create-site/references/upload-activation-reference.mdsimilarity index 93%rename from plugins/power-pages/skills/create-site/upload-activation-reference.mdrename to plugins/power-pages/skills/create-site/references/upload-activation-reference.mdindex d5c3c1e1e..275d512a3 100644--- a/plugins/power-pages/skills/create-site/upload-activation-reference.md+++ b/plugins/power-pages/skills/create-site/references/upload-activation-reference.md@@ -1,7 +1,5 @@# Upload and Activation Reference-This document describes how to verify prerequisites, upload your site to Power Pages, and activate it.-## Prerequisites### Check PAC CLI@@ -66,6 +64,14 @@ pac org who## Upload to Power Pages+### Create Authoring Tool Site Setting++**Before uploading**, create a site setting to track which Claude Code tool created the site.++**📖 See: [authoring-tool-reference.md](${CLAUDE_PLUGIN_ROOT}/shared/authoring-tool-reference.md)**++Follow the instructions in the shared reference to create the `Site/AuthoringTool` setting with value `ClaudeCodeCLI` or `ClaudeCodeVSCode` based on the environment.+### Confirm Connected Account**Before uploading**, confirm the connected account:diff --git a/plugins/power-pages/skills/create-site/requirements-reference.md b/plugins/power-pages/skills/create-site/requirements-reference.mddeleted file mode 100644index 32e44ff3b..000000000--- a/plugins/power-pages/skills/create-site/requirements-reference.md+++ /dev/null@@ -1,91 +0,0 @@-# Requirements Reference--This document describes the questions to ask users when gathering requirements for a Power Pages code site.--## Question 1: What Do You Want to Build?--If the user has not already specified what they want to build, ask them to describe their site:--- What is the purpose of the site? (e.g., company portal, customer self-service, employee directory, event registration)-- What key functionality do they need?-- Who is the target audience?--This helps inform framework selection and feature recommendations.--## Question 2: Frontend Framework--Ask the maker which frontend framework they want to use:--| Option | Description |-|--------|-------------|-| **React (Recommended)** | Most popular choice with excellent ecosystem. Best for complex interactive UIs. |-| **Angular** | Full-featured framework by Google. Great for enterprise applications with built-in state management. |-| **Vue** | Progressive framework, easy to learn. Good balance of simplicity and power. |-| **Astro** | Modern static site generator with partial hydration. Best for content-focused sites with minimal JS. |--### Unsupported Technologies--Power Pages code sites are **static SPAs** served from Azure CDN. The following technologies are **NOT supported**:--| Technology | Reason |-|------------|--------|-| **Next.js** | Requires Node.js server runtime (SSR/ISR not available) |-| **Nuxt.js** | Requires Node.js server runtime |-| **Remix** | Requires server-side rendering |-| **SvelteKit** | Server features not supported |-| **Liquid templates** | Power Pages code sites don't use Liquid (only classic Power Pages sites do) |-| **Server-side APIs** | No Node.js/Express backend; use Dataverse Web API instead |-| **Server components** | React Server Components not supported |--**Only use frameworks that can build to static HTML/CSS/JS files.**--## Question 3: Site Features--Ask what features the maker wants in their site. Common options:--### Content Features--- Landing page / Hero section-- Navigation menu-- About page-- Services/Products showcase-- Image gallery-- Blog/News section--### Interactive Features--- Contact form-- Search functionality-- Filtering and sorting--### Data Features--- User authentication (Microsoft Entra ID)-- Data display from Dataverse (Web API)-- Form submissions to Dataverse--## Question 4: Design Preferences--Ask about design preferences:--### Style Options--| Style | Description |-|-------|-------------|-| **Modern/Minimalist** | Clean lines, lots of whitespace, simple color palette |-| **Corporate/Professional** | Traditional business look, structured layouts |-| **Creative/Bold** | Vibrant colors, unique typography, dynamic layouts |-| **Elegant/Luxury** | Sophisticated, refined aesthetics with premium feel |--### Color Scheme--- Let the user specify brand colors-- Or suggest based on their industry/purpose-- Consider accessibility (WCAG 2.1 AA contrast requirements)--### Special Requirements--- Accessibility compliance (WCAG 2.1)-- Mobile-first design-- Specific branding guidelines-- RTL language supportdiff --git a/plugins/power-pages/skills/create-site/site-creation-reference.md b/plugins/power-pages/skills/create-site/site-creation-reference.mddeleted file mode 100644index 5a6bad1b8..000000000--- a/plugins/power-pages/skills/create-site/site-creation-reference.md+++ /dev/null@@ -1,132 +0,0 @@-# Site Creation Reference--This document describes how to create the site using the frontend-design skill and configure it for Power Pages.--## Using the Frontend-Design Skill--After gathering requirements, use the **frontend-design skill** to create the site.--### Instructions--1. **Invoke the frontend-design skill** with the gathered requirements-2. The skill will create a production-grade, distinctive UI-3. Ensure the project structure follows Power Pages code site requirements--### Critical Constraints--When invoking the frontend-design skill, explicitly specify:--- Use **Vite** as the build tool for React/Vue projects-- Use **Create React App** only if Vite is not preferred-- **DO NOT use Next.js, Nuxt.js, Remix, or any SSR framework**-- **DO NOT use Liquid templates** - they are not supported in code sites-- The output must be **purely static files** (HTML, CSS, JS) that can be served from a CDN--## Required Project Structure--```text-/site-project-├── src/ # Source code-├── public/ # Static assets-├── build/ or dist/ # Compiled output (after build)-├── package.json # Dependencies-├── powerpages.config.json # Power Pages configuration (create this)-└── README.md-```--## powerpages.config.json--Create this configuration file in the project root:--```json-{- "siteName": "<SITE_NAME>",- "defaultLandingPage": "index.html",- "compiledPath": "./build"-}-```--### Framework-Specific compiledPath--| Framework | compiledPath |-|-----------|--------------|-| React (Vite) | `"./dist"` |-| React (CRA) | `"./build"` |-| Vue | `"./dist"` |-| Angular | `"./dist/<project-name>"` |-| Astro | `"./dist"` |--## Build Commands--Run the appropriate build command for your framework:--```powershell-# React (Create React App or Vite)-npm run build--# Angular-ng build --configuration production--# Vue-npm run build--# Astro-npm run build-```--## Memory Bank Initialization--After the site is created, create `memory-bank.md` in the project root:--```markdown-# Power Pages Project Memory Bank--> Last Updated: [CURRENT_TIMESTAMP]--## Project Overview--| Property | Value |-|----------|-------|-| Project Name | [SITE_NAME from powerpages.config.json] |-| Project Path | [FULL_PROJECT_PATH] |-| Framework | [CHOSEN_FRAMEWORK] |-| Created Date | [CURRENT_DATE] |-| Status | Site Created |--## User Preferences--### Design Preferences-- Style: [USER'S STYLE CHOICE]-- Color Scheme: [USER'S COLOR CHOICE]-- Special Requirements: [ANY SPECIAL REQUIREMENTS]--### Site Features-[LIST ALL FEATURES USER REQUESTED]--## Completed Steps--### /create-site-- [x] Requirements gathered-- [x] Framework selected: [FRAMEWORK]-- [x] Site created with features: [FEATURE_LIST]-- [x] powerpages.config.json created-- [x] SEO assets added (meta tags, favicon, robots.txt, sitemap.xml)-- [x] Unit tests written and passing-- [x] E2E tests written and passing (Playwright)-- [x] Project built successfully-- [ ] Prerequisites verified (PAC CLI, Azure CLI)-- [ ] Uploaded to Power Pages-- [ ] Site activated--## Current Status--**Last Action**: Site created, all tests passing, and built successfully--**Next Step**: Verify prerequisites (PAC CLI, Azure CLI) then upload to Power Pages--## Notes--- [CURRENT_DATE]: Project initialized with [FRAMEWORK] framework-```--**Update this file after each subsequent step is completed.**diff --git a/plugins/power-pages/skills/integrate-webapi/SKILL.md b/plugins/power-pages/skills/integrate-webapi/SKILL.mdnew file mode 100644index 000000000..926bea8e1--- /dev/null+++ b/plugins/power-pages/skills/integrate-webapi/SKILL.md@@ -0,0 +1,143 @@+---+name: integrating-webapi+description: Integrates Web API into frontend code, replacing mock data with Dataverse API calls. Use when connecting frontend to Web API, replacing static data, or creating API services.+user-invocable: true+allowed-tools: ["Read", "Write", "Grep", "Glob", "Bash", "AskUserQuestion"]+model: opus+---++**📋 [Shared Instructions](${CLAUDE_PLUGIN_ROOT}/shared/shared-instructions.md)** - Read before starting.++# Integrate Web API++**References:** [frontend-integration](./references/frontend-integration-reference.md)++Connects frontend code to Power Pages Web API, replacing all mock/static data.++## Prerequisites++- Web API permissions configured with `/setup-webapi`+- Site settings created for tables+- Table permissions and web roles configured++## Workflow++1. **Check Context** → Read memory bank, get table mapping and publisher prefix+2. **Create Web API Service** → `src/services/webApi.ts` with CSRF handling+3. **Create Type Definitions** → TypeScript interfaces for entities+4. **Create Entity Services** → Typed wrappers per table+5. **Find Mock Data** → Search for all static/mock data+6. **Replace Mock Data** → Update components to use API+7. **Delete Mock Files** → Remove unused data files+8. **Build and Upload** → Deploy and verify++---++## Step 1: Check Context++Read `memory-bank.md` for:+- Table name mapping (actual logical names and entity sets)+- Publisher prefix (for column names)+- Fields configured in site settings++---++## Step 2: Create Web API Service++Create `src/services/webApi.ts` with:+- CSRF token fetching from `/_layout/tokenhtml`+- Token caching and refresh on 403+- Generic CRUD operations (getAll, getById, create, update, delete)++See [frontend-integration-reference.md](./references/frontend-integration-reference.md#power-pages-web-api-service-typescript).++---++## Step 3: Create Type Definitions++Create `src/types/entities.ts` with interfaces for each table:++```typescript+export interface Product {+ ${prefix}_productid: string;+ ${prefix}_name: string;+ // ... fields from site settings+}+```++---++## Step 4: Create Entity Services++Create typed wrappers that include `$select` with allowed fields:++```typescript+export const productsApi = {+ getAll: () => webApi.getAll<Product>('${prefix}_products', {+ select: ['${prefix}_productid', '${prefix}_name', ...],+ }),+};+```++---++## Step 5: Find Mock Data++**CRITICAL**: Find ALL mock data before replacing.++```powershell+# Mock folders+Get-ChildItem -Path ./src -Directory -Recurse | Where-Object { $_.Name -match "^(mock|data|fixtures)$" }++# Data files+Get-ChildItem -Path ./src -Recurse -Include "*.data.ts","*mock*.ts"++# Inline arrays+Select-String -Path "src\**\*.ts","src\**\*.tsx" -Pattern "const\s+\w+\s*=\s*\[" | Where-Object { $_.Line -match "\{" }+```++---++## Step 6: Replace Mock Data++For each component using static data:++**Before:**+```tsx+const products = [{ id: 1, name: 'Widget' }];+```++**After:**+```tsx+const [products, setProducts] = useState<Product[]>([]);+useEffect(() => {+ productsApi.getActive().then(setProducts);+}, []);+```++See [frontend-integration-reference.md](./references/frontend-integration-reference.md#mock-data-replacement-guide).++---++## Step 7: Delete Mock Files++After replacing all usages:+1. Delete mock data files+2. Remove empty mock folders+3. Update barrel exports++---++## Step 8: Build and Upload++```powershell+npm run build+pac pages upload-code-site --rootPath "<PROJECT_ROOT>"+```++**Test in browser console:**+```javascript+fetch('/_api/${prefix}_products').then(r => r.json()).then(console.log)+```++Update memory-bank.md with integration status.diff --git a/plugins/power-pages/skills/setup-webapi/frontend-integration-reference.md b/plugins/power-pages/skills/integrate-webapi/references/frontend-integration-reference.mdsimilarity index 72%rename from plugins/power-pages/skills/setup-webapi/frontend-integration-reference.mdrename to plugins/power-pages/skills/integrate-webapi/references/frontend-integration-reference.mdindex 27e48285c..aa7a5df2d 100644--- a/plugins/power-pages/skills/setup-webapi/frontend-integration-reference.md+++ b/plugins/power-pages/skills/integrate-webapi/references/frontend-integration-reference.md@@ -1,24 +1,30 @@# Frontend Integration Reference-This document provides code patterns for integrating Power Pages Web API into frontend applications.-## Web API Endpoint Format-The Power Pages Web API follows OData conventions:+The Power Pages Web API follows OData conventions.++**IMPORTANT - Table Names**: Use the **actual table logical names** from the `$tableMap` built in `/setup-dataverse`:+- For **reused/extended tables**: Use the existing logical name from Dataverse (e.g., `contoso_items`, `existing_productcategory`)+- For **new tables**: Use `{prefix}_tablename` pattern (e.g., `cr_product`)++The entity set name (used in URLs) is typically the pluralized form of the logical name.++**NOTE**: Replace `{prefix}` with your publisher prefix from `Initialize-DataverseApi` (e.g., `cr`, `contoso`, `new`).```textBase URL: https://<site-url>/_api/<entity-set-name>Examples:-GET /_api/cr_products # List all products-GET /_api/cr_products(<guid>) # Get single product-GET /_api/cr_products?$select=cr_name,cr_price # Select specific fields-GET /_api/cr_products?$filter=cr_isactive eq true # Filter records-GET /_api/cr_products?$orderby=cr_name # Order results-GET /_api/cr_products?$top=10 # Limit results-POST /_api/cr_products # Create new product-PATCH /_api/cr_products(<guid>) # Update product-DELETE /_api/cr_products(<guid>) # Delete product+GET /_api/{prefix}_products # List all products+GET /_api/{prefix}_products(<guid>) # Get single product+GET /_api/{prefix}_products?$select={prefix}_name,{prefix}_price # Select specific fields+GET /_api/{prefix}_products?$filter={prefix}_isactive eq true # Filter records+GET /_api/{prefix}_products?$orderby={prefix}_name # Order results+GET /_api/{prefix}_products?$top=10 # Limit results+POST /_api/{prefix}_products # Create new product+PATCH /_api/{prefix}_products(<guid>) # Update product+DELETE /_api/{prefix}_products(<guid>) # Delete product```## CSRF Token Requirement@@ -203,113 +209,120 @@ Create typed wrappers for each entity.**IMPORTANT**: Always include `$select` with the fields configured in site settings. Power Pages Web API returns an error if you request fields not listed in the `Webapi/<table>/fields` site setting. Omitting `$select` attempts to fetch all fields, which fails.+**NOTE**: Replace `{prefix}` with your publisher prefix (e.g., `cr`, `contoso`, `new`). The prefix is determined by your Dataverse environment's default publisher.+```typescript// Entity-specific services// IMPORTANT: The 'select' array must match the fields in your Webapi/<table>/fields site setting+// NOTE: Replace {prefix} with your actual publisher prefix (e.g., 'cr', 'contoso', 'new')export const productsApi = {getAll: (options?: QueryOptions) =>- webApi.getAll<Product>('cr_products', {- select: ['cr_productid', 'cr_name', 'cr_description', 'cr_price', 'cr_category', 'cr_imageurl', 'cr_isactive'],+ webApi.getAll<Product>('{prefix}_products', {+ select: ['{prefix}_productid', '{prefix}_name', '{prefix}_description', '{prefix}_price', '{prefix}_category', '{prefix}_imageurl', '{prefix}_isactive'],...options,}),getById: (id: string) =>- webApi.getById<Product>('cr_products', id, {- select: ['cr_productid', 'cr_name', 'cr_description', 'cr_price', 'cr_category', 'cr_imageurl', 'cr_isactive'],+ webApi.getById<Product>('{prefix}_products', id, {+ select: ['{prefix}_productid', '{prefix}_name', '{prefix}_description', '{prefix}_price', '{prefix}_category', '{prefix}_imageurl', '{prefix}_isactive'],}),getActive: () =>- webApi.getAll<Product>('cr_products', {- select: ['cr_productid', 'cr_name', 'cr_description', 'cr_price', 'cr_category', 'cr_imageurl', 'cr_isactive'],- filter: 'cr_isactive eq true',- orderBy: 'cr_name',+ webApi.getAll<Product>('{prefix}_products', {+ select: ['{prefix}_productid', '{prefix}_name', '{prefix}_description', '{prefix}_price', '{prefix}_category', '{prefix}_imageurl', '{prefix}_isactive'],+ filter: '{prefix}_isactive eq true',+ orderBy: '{prefix}_name',}),};export const teamMembersApi = {getAll: () =>- webApi.getAll<TeamMember>('cr_teammembers', {- select: ['cr_teammemberid', 'cr_name', 'cr_title', 'cr_email', 'cr_bio', 'cr_photourl', 'cr_linkedin', 'cr_displayorder'],- orderBy: 'cr_displayorder',+ webApi.getAll<TeamMember>('{prefix}_teammembers', {+ select: ['{prefix}_teammemberid', '{prefix}_name', '{prefix}_title', '{prefix}_email', '{prefix}_bio', '{prefix}_photourl', '{prefix}_linkedin', '{prefix}_displayorder'],+ orderBy: '{prefix}_displayorder',}),};export const testimonialsApi = {getActive: () =>- webApi.getAll<Testimonial>('cr_testimonials', {- select: ['cr_testimonialid', 'cr_name', 'cr_quote', 'cr_company', 'cr_role', 'cr_rating', 'cr_photourl', 'cr_isactive'],- filter: 'cr_isactive eq true',+ webApi.getAll<Testimonial>('{prefix}_testimonials', {+ select: ['{prefix}_testimonialid', '{prefix}_name', '{prefix}_quote', '{prefix}_company', '{prefix}_role', '{prefix}_rating', '{prefix}_photourl', '{prefix}_isactive'],+ filter: '{prefix}_isactive eq true',}),};export const faqsApi = {getActive: () =>- webApi.getAll<FAQ>('cr_faqs', {- select: ['cr_faqid', 'cr_question', 'cr_answer', 'cr_category', 'cr_displayorder', 'cr_isactive'],- filter: 'cr_isactive eq true',- orderBy: 'cr_displayorder',+ webApi.getAll<FAQ>('{prefix}_faqs', {+ select: ['{prefix}_faqid', '{prefix}_question', '{prefix}_answer', '{prefix}_category', '{prefix}_displayorder', '{prefix}_isactive'],+ filter: '{prefix}_isactive eq true',+ orderBy: '{prefix}_displayorder',}),};export const contactApi = {submit: (data: ContactSubmission) =>- webApi.create<ContactSubmission>('cr_contactsubmissions', {+ webApi.create<ContactSubmission>('{prefix}_contactsubmissions', {...data,- cr_submissiondate: new Date().toISOString(),- cr_status: 1, // New+ {prefix}_submissiondate: new Date().toISOString(),+ {prefix}_status: 1, // New}),};```## Type Definitions+**NOTE**: Replace `{prefix}` with your publisher prefix (e.g., `cr`, `contoso`, `new`).+```typescript+// NOTE: Replace {prefix} with your actual publisher prefix+export interface Product {- cr_productid: string;- cr_name: string;- cr_description: string;- cr_price: number;- cr_category: string;- cr_imageurl: string;- cr_isactive: boolean;+ {prefix}_productid: string;+ {prefix}_name: string;+ {prefix}_description: string;+ {prefix}_price: number;+ {prefix}_category: string;+ {prefix}_imageurl: string;+ {prefix}_isactive: boolean;}export interface TeamMember {- cr_teammemberid: string;- cr_name: string;- cr_title: string;- cr_email: string;- cr_bio: string;- cr_photourl: string;- cr_linkedin: string;- cr_displayorder: number;+ {prefix}_teammemberid: string;+ {prefix}_name: string;+ {prefix}_title: string;+ {prefix}_email: string;+ {prefix}_bio: string;+ {prefix}_photourl: string;+ {prefix}_linkedin: string;+ {prefix}_displayorder: number;}export interface Testimonial {- cr_testimonialid: string;- cr_name: string;- cr_quote: string;- cr_company: string;- cr_role: string;- cr_rating: number;- cr_photourl: string;- cr_isactive: boolean;+ {prefix}_testimonialid: string;+ {prefix}_name: string;+ {prefix}_quote: string;+ {prefix}_company: string;+ {prefix}_role: string;+ {prefix}_rating: number;+ {prefix}_photourl: string;+ {prefix}_isactive: boolean;}export interface FAQ {- cr_faqid: string;- cr_question: string;- cr_answer: string;- cr_category: string;- cr_displayorder: number;- cr_isactive: boolean;+ {prefix}_faqid: string;+ {prefix}_question: string;+ {prefix}_answer: string;+ {prefix}_category: string;+ {prefix}_displayorder: number;+ {prefix}_isactive: boolean;}export interface ContactSubmission {- cr_name: string;- cr_email: string;- cr_message: string;- cr_submissiondate?: string;- cr_status?: number;+ {prefix}_name: string;+ {prefix}_email: string;+ {prefix}_message: string;+ {prefix}_submissiondate?: string;+ {prefix}_status?: number;}```@@ -357,8 +370,8 @@ export function useWebApi<T>(return { data, loading, error, refetch: fetchData };}-// Usage example:-// const { data: products, loading, error } = useWebApi<Product>('cr_products', { filter: 'cr_isactive eq true' });+// Usage example (replace {prefix} with your publisher prefix):+// const { data: products, loading, error } = useWebApi<Product>('{prefix}_products', { filter: '{prefix}_isactive eq true' });```## Component Examples@@ -415,7 +428,7 @@ function ProductList() {return (<div className="products-grid">{products.map(product => (- <ProductCard key={product.cr_productid} product={product} />+ <ProductCard key={product.{prefix}_productid} product={product} />))}</div>);@@ -429,10 +442,11 @@ import { useState } from 'react';import { contactApi, ContactSubmission } from '../services/webApi';function ContactForm() {+ // NOTE: Replace {prefix} with your actual publisher prefixconst [formData, setFormData] = useState<ContactSubmission>({- cr_name: '',- cr_email: '',- cr_message: '',+ {prefix}_name: '',+ {prefix}_email: '',+ {prefix}_message: '',});const [submitting, setSubmitting] = useState(false);const [submitted, setSubmitted] = useState(false);@@ -446,7 +460,7 @@ function ContactForm() {try {await contactApi.submit(formData);setSubmitted(true);- setFormData({ cr_name: '', cr_email: '', cr_message: '' });+ setFormData({ {prefix}_name: '', {prefix}_email: '', {prefix}_message: '' });} catch (err) {setError(err instanceof Error ? err.message : 'Failed to submit form');} finally {@@ -473,8 +487,8 @@ function ContactForm() {<inputid="name"type="text"- value={formData.cr_name}- onChange={e => setFormData({ ...formData, cr_name: e.target.value })}+ value={formData.{prefix}_name}+ onChange={e => setFormData({ ...formData, {prefix}_name: e.target.value })}required/></div>@@ -484,8 +498,8 @@ function ContactForm() {<inputid="email"type="email"- value={formData.cr_email}- onChange={e => setFormData({ ...formData, cr_email: e.target.value })}+ value={formData.{prefix}_email}+ onChange={e => setFormData({ ...formData, {prefix}_email: e.target.value })}required/></div>@@ -494,8 +508,8 @@ function ContactForm() {<label htmlFor="message">Message</label><textareaid="message"- value={formData.cr_message}- onChange={e => setFormData({ ...formData, cr_message: e.target.value })}+ value={formData.{prefix}_message}+ onChange={e => setFormData({ ...formData, {prefix}_message: e.target.value })}requiredrows={5}/>@@ -612,7 +626,7 @@ function ProductList() {}, []);if (loading) return <LoadingSpinner />;- return products.map(p => <ProductCard key={p.cr_productid} product={p} />);+ return products.map(p => <ProductCard key={p.{prefix}_productid} product={p} />);}```@@ -679,27 +693,29 @@ Track replacements in the memory bank:## OData Query Reference+**NOTE**: Replace `{prefix}` with your publisher prefix (e.g., `cr`, `contoso`, `new`).+| Operation | Query String | Example ||-----------|-------------|---------|-| Select fields | `$select=field1,field2` | `$select=cr_name,cr_price` |-| Filter | `$filter=condition` | `$filter=cr_isactive eq true` |-| Order by | `$orderby=field [asc\|desc]` | `$orderby=cr_name desc` |+| Select fields | `$select=field1,field2` | `$select={prefix}_name,{prefix}_price` |+| Filter | `$filter=condition` | `$filter={prefix}_isactive eq true` |+| Order by | `$orderby=field [asc\|desc]` | `$orderby={prefix}_name desc` || Top N | `$top=N` | `$top=10` || Skip | `$skip=N` | `$skip=20` |-| Expand | `$expand=relationship` | `$expand=cr_category` |+| Expand | `$expand=relationship` | `$expand={prefix}_category` |### Filter Operators| Operator | Description | Example ||----------|-------------|---------|-| `eq` | Equal | `cr_isactive eq true` |-| `ne` | Not equal | `cr_status ne 0` |-| `gt` | Greater than | `cr_price gt 100` |-| `ge` | Greater or equal | `cr_price ge 100` |-| `lt` | Less than | `cr_price lt 50` |-| `le` | Less or equal | `cr_price le 50` |-| `and` | Logical AND | `cr_isactive eq true and cr_price gt 0` |-| `or` | Logical OR | `cr_category eq 'A' or cr_category eq 'B'` |-| `contains` | Contains string | `contains(cr_name,'search')` |-| `startswith` | Starts with | `startswith(cr_name,'Pro')` |-| `endswith` | Ends with | `endswith(cr_email,'@example.com')` |+| `eq` | Equal | `{prefix}_isactive eq true` |+| `ne` | Not equal | `{prefix}_status ne 0` |+| `gt` | Greater than | `{prefix}_price gt 100` |+| `ge` | Greater or equal | `{prefix}_price ge 100` |+| `lt` | Less than | `{prefix}_price lt 50` |+| `le` | Less or equal | `{prefix}_price le 50` |+| `and` | Logical AND | `{prefix}_isactive eq true and {prefix}_price gt 0` |+| `or` | Logical OR | `{prefix}_category eq 'A' or {prefix}_category eq 'B'` |+| `contains` | Contains string | `contains({prefix}_name,'search')` |+| `startswith` | Starts with | `startswith({prefix}_name,'Pro')` |+| `endswith` | Ends with | `endswith({prefix}_email,'@example.com')` |diff --git a/plugins/power-pages/skills/setup-auth/SKILL.md b/plugins/power-pages/skills/setup-auth/SKILL.mdindex 9afab8fa6..f5ac9596f 100644--- a/plugins/power-pages/skills/setup-auth/SKILL.md+++ b/plugins/power-pages/skills/setup-auth/SKILL.md@@ -1,414 +1,112 @@----description: Configure authentication, login, logout, and role-based authorization for Power Pages. Use this skill when you need to set up user login, implement authentication, configure Azure AD/Entra ID login, add logout functionality, manage user sessions, implement role-based access control, protect routes, or add conditional UI rendering based on user roles and permissions.+name: setting-up-authentication+description: Configures authentication (login/logout) and role-based authorization for Power Pages. Use when setting up user login, Azure AD/Entra ID auth, logout, role-based access control, route protection, or conditional UI based on roles.user-invocable: true-allowed-tools: Bash(pac:*), Bash(az:*), Bash(dotnet:*)-model: sonnet+allowed-tools: ["Read", "Write", "Grep", "Glob", "Bash", "TodoWrite", "AskUserQuestion", "Skill", "Task"]+model: opus----# Setup Authentication & Authorization--This skill guides makers through implementing authentication (user login/logout) and authorization (role-based access control) for their Power Pages site. It uses Power Pages' built-in server-side authentication with Azure Active Directory and role-based UI conditional rendering.--## Reference Documentation--This skill uses modular reference files for detailed instructions:--| File | Purpose |-|------|---------|-| [authentication-reference.md](./authentication-reference.md) | Auth service code, login/logout flow, user info retrieval |-| [authorization-reference.md](./authorization-reference.md) | Role-based access control, conditional rendering, route protection |--## Memory Bank--This skill uses a **memory bank** (`memory-bank.md`) to persist context across sessions.--**Follow the instructions in `${CLAUDE_PLUGIN_ROOT}/shared/memory-bank.md`** for:-- Checking and reading the memory bank before starting-- Skipping completed steps and resuming progress-- Updating the memory bank after each major step--## Workflow Overview--```text-┌─────────────────────────────────────────────────────────────────────────────┐-│ STEP 1: Resume or Start Fresh │-│ ───────────────────────────────────────────────────────────────────────── │-│ • Check memory bank for project context │-│ • Verify /setup-webapi was completed │-│ • Identify authentication requirements │-└─────────────────────────────────────────────────────────────────────────────┘- ↓-┌─────────────────────────────────────────────────────────────────────────────┐-│ STEP 2: Create Authentication Service │-│ ───────────────────────────────────────────────────────────────────────── │-│ • Create auth service with login/logout methods │-│ • Implement user info retrieval from Power Pages portal object │-│ • Handle authentication state management │-│ 📖 See: authentication-reference.md │-└─────────────────────────────────────────────────────────────────────────────┘- ↓-┌─────────────────────────────────────────────────────────────────────────────┐-│ STEP 3: Create Authorization Utilities │-│ ───────────────────────────────────────────────────────────────────────── │-│ • Create role checking utilities │-│ • Implement conditional rendering components │-│ • Create route protection (if applicable) │-│ 📖 See: authorization-reference.md │-└─────────────────────────────────────────────────────────────────────────────┘- ↓-┌─────────────────────────────────────────────────────────────────────────────┐-│ STEP 4: Create Auth UI Components │-│ ───────────────────────────────────────────────────────────────────────── │-│ • Create login/logout button component │-│ • Create user profile display component │-│ • Integrate with site navigation │-└─────────────────────────────────────────────────────────────────────────────┘- ↓-┌─────────────────────────────────────────────────────────────────────────────┐-│ STEP 5: Implement Role-Based UI │-│ ───────────────────────────────────────────────────────────────────────── │-│ • Identify components needing role-based visibility │-│ • Apply conditional rendering based on user roles │-│ • Test with different user roles │-└─────────────────────────────────────────────────────────────────────────────┘- ↓-┌─────────────────────────────────────────────────────────────────────────────┐-│ STEP 6: Build and Upload │-│ ───────────────────────────────────────────────────────────────────────── │-│ • Build the project │-│ • Upload to Power Pages │-│ • Verify authentication is working │-└─────────────────────────────────────────────────────────────────────────────┘-```-------## STEP 1: Resume or Start Fresh--### Check Memory Bank First--**Before asking questions**, check if a memory bank exists:--1. If continuing from `/setup-webapi` in the same session, use the known project path-2. Otherwise, ask the user for the project path-3. Read `<PROJECT_PATH>/memory-bank.md` if it exists-4. Extract:- - Project name and framework- - Website ID and environment URL- - Web roles configured (Anonymous Users, Authenticated Users)- - Any previously configured authentication settings--If the memory bank shows `/setup-auth` steps already completed:--- Inform the user what was done-- Ask if they want to modify settings or add role-based features+**📋 [Shared Instructions](${CLAUDE_PLUGIN_ROOT}/shared/shared-instructions.md)** - Read before starting.-### Check Prerequisites--**Verify Web API setup is complete:**--The authentication system depends on having:-- Site uploaded to Power Pages (required for `/_layout/tokenhtml` endpoint)-- Web roles created (Authenticated Users role must exist)--If `/setup-webapi` was not completed, suggest running it first:--> **Prerequisites Required**->-> Authentication requires your site to be uploaded to Power Pages with Web API configured.->-> Please run `/setup-webapi` first to complete the prerequisites.+# Setup Authentication & Authorization-### Gather Requirements+**References:** [authentication](./references/authentication-reference.md) | [authorization](./references/authorization-reference.md)-Use the `AskUserQuestion` tool to understand authentication needs:+## Workflow-| Question | Options |-|----------|---------|-| **Which features need authentication?** | Login/Logout only, User profile display, Role-based content, All of the above |-| **What roles need conditional UI?** | None, Admin only sections, Member-only content, Multiple role levels |+1. **Check Prerequisites** → Verify `/setup-webapi` completed, site uploaded+2. **Create Auth Service** → Login/logout methods, user info retrieval+3. **Create Authorization Utils** → Role checking, conditional rendering+4. **Create Auth UI** → Login/logout button, user profile+5. **Implement Role-Based UI** → Wrap components with role checks+6. **Build and Upload** → Deploy and verify----## STEP 2: Create Authentication Service--**📖 Detailed reference: [authentication-reference.md](./authentication-reference.md)**--### Quick Summary--Create an authentication service that handles:--1. **Login**: Server-side form submission to `/Account/Login/ExternalLogin`-2. **Logout**: Redirect to `/Account/Login/LogOff`-3. **User Info**: Retrieve from `window.Microsoft.Dynamic365.Portal.User`--### Key Points+## Step 1: Check Prerequisites-- Power Pages uses **server-side authentication** (not client-side tokens)-- Anti-forgery token required from `/_layout/tokenhtml`-- User info is available in the global `window.Microsoft.Dynamic365.Portal` object-- Authentication state is session-based (cookies)+Read `memory-bank.md` for project context. Requires:+- Site uploaded to Power Pages (`/_layout/tokenhtml` endpoint needed)+- Web roles created (Authenticated Users must exist)-### Power Pages Portal Object+If `/setup-webapi` not completed, tell user to run it first.-The portal object provides user information:--```typescript-window.Microsoft.Dynamic365.Portal.User = {- userName: string; // Login username- firstName: string; // First name- lastName: string; // Last name- email: string; // Email address- contactId: string; // Dataverse contact ID- userRoles: string[]; // Array of role names-}-```--### Actions--1. Create `src/services/authService.ts` (copy from reference)-2. Create `src/types/powerPages.d.ts` for TypeScript declarations-3. Test that user info is accessible when logged in+Use `AskUserQuestion`:+- Which features? (Login/Logout only, User profile, Role-based content, All)+- Which roles need conditional UI? (None, Admin sections, Member content, Multiple)----## STEP 3: Create Authorization Utilities--**📖 Detailed reference: [authorization-reference.md](./authorization-reference.md)**--### Quick Summary+## Step 2: Create Auth Service-Create utilities for role-based access control:+See [authentication-reference.md](./references/authentication-reference.md).-1. **Role Checking**: Functions to check if user has specific roles-2. **Conditional Rendering**: Components that show/hide based on roles-3. **Route Protection**: Guards for protected routes (if using client-side routing)+Power Pages auth is **server-side** (session cookies, not client tokens):+- **Login**: POST to `/Account/Login/ExternalLogin` with anti-forgery token from `/_layout/tokenhtml`+- **Logout**: Redirect to `/Account/Login/LogOff`+- **User Info**: `window.Microsoft.Dynamic365.Portal.User` (userName, firstName, lastName, email, contactId, userRoles[])-### Key Points--- User roles are in `window.Microsoft.Dynamic365.Portal.User.userRoles`-- Roles are returned as an array of role names (strings)-- Common roles: "Administrators", "Authenticated Users", custom roles-- Role checks should be case-insensitive--### Actions--1. Create `src/utils/authorization.ts` with role checking functions-2. Create wrapper components for conditional rendering-3. Create route guard component (if using React Router, Vue Router, etc.)+Create:+1. `src/services/authService.ts`+2. `src/types/powerPages.d.ts`----## STEP 4: Create Auth UI Components--### Login/Logout Button Component--Create a component that:+## Step 3: Create Authorization Utils-- Shows "Sign In" button when not authenticated-- Shows user name and "Sign Out" button when authenticated-- Handles the login/logout flow+See [authorization-reference.md](./references/authorization-reference.md).-The component should:+Create `src/utils/authorization.ts`:+- Role checking functions (case-insensitive)+- Common roles: "Administrators", "Authenticated Users"-1. Check authentication state on mount-2. Display appropriate UI based on state-3. Handle login button click (redirect to AAD)-4. Handle logout button click (redirect to logout endpoint)--### User Profile Component (Optional)--If user profile display is needed:--- Show user avatar/initials-- Display user name and email-- Show user roles (for debugging/admin purposes)--### Navigation Integration--Integrate auth components into the site header/navigation:--1. Read current navigation component-2. Add auth button to appropriate location-3. Ensure responsive design (mobile menu handling)+Create wrapper components:+- `RequireRole` - conditional rendering+- Route guard (if using client-side routing)----## STEP 5: Implement Role-Based UI--### Identify Components Needing Role-Based Access--Work with the user to identify:+## Step 4: Create Auth UI-- Admin-only sections (dashboard, settings)-- Member-only content (premium features, downloads)-- Role-specific navigation items-- Edit/delete buttons for content owners+Create login/logout button component:+- Shows "Sign In" when unauthenticated+- Shows user name + "Sign Out" when authenticated-### Apply Conditional Rendering+Integrate into site navigation. Optionally create user profile component.-For each identified component:+----1. Import authorization utilities-2. Wrap content with role-checking component-3. Provide fallback UI if needed (login prompt, access denied)+## Step 5: Implement Role-Based UI-### Example Pattern+Identify components needing role-based visibility with user. Apply:```tsx-// Show only to users with "Administrators" role-<RequireRole roles={["Administrators"]}>- <AdminDashboard />-</RequireRole>--// Show only to authenticated users-<RequireAuth>- <MemberContent />-</RequireAuth>--// Show different content based on role-{hasRole("Administrators") ? (- <EditButton onClick={handleEdit} />-) : null}+<RequireRole roles={["Administrators"]}><AdminDashboard /></RequireRole>+<RequireAuth><MemberContent /></RequireAuth>+{hasRole("Administrators") && <EditButton />}```----## STEP 6: Build and Upload--### Build the Project+## Step 6: Build and Upload```powershell-cd <PROJECT_ROOT>-npm install # if needed-npm run build+pac auth list # Show available environments```-### Confirm Connected Account--**IMPORTANT**: Before uploading, you MUST confirm which account the user is connected with.--1. Run the following command to show the connected account:--```powershell-pac auth list-```--2. Display the connected account information to the user, including:- - The active profile (marked with `*`)- - The environment URL- - The user email/account--3. Use the `AskUserQuestion` tool to confirm:--| Question | Options |-|----------|---------|-| **You are about to upload the site to the account shown above. Do you want to proceed?** | **Yes, upload to this account** - Proceed with the upload; **No, let me switch accounts** - User will run `pac auth create` to connect to a different account |--4. **Only proceed with upload after the user confirms.** If the user selects "No", guide them to authenticate to the correct account:--```powershell-# Create new authentication profile-pac auth create-```--Then run `pac auth list` again to verify and ask for confirmation again.--### Upload to Power Pages+**Ask user which environment** to upload to using `AskUserQuestion` (show org names from auth list). Switch if needed: `pac auth select --index <n>`.+**Create skill tracking setting, build, and upload:**```powershell+New-SkillTrackingSetting -ProjectRoot $projectRoot -SkillName "SetupAuth"+npm run build # Always build before uploadpac pages upload-code-site --rootPath "<PROJECT_ROOT>"```-### Configure Site Settings--**IMPORTANT**: Configure the following site setting to ensure users are redirected to your app's home page after login (instead of Power Pages' default profile page):--| Setting | Value | Purpose |-|---------|-------|---------|-| `Authentication/Registration/ProfileRedirectEnabled` | `false` | Redirect to home page instead of profile page after login |--**📖 See [authentication-reference.md](./authentication-reference.md#site-settings)** for detailed instructions on how to configure this setting via Power Pages Admin Center, PAC CLI, or Dataverse Web API.--### Verify Authentication--1. Open the site in a browser-2. Click "Sign In" - should redirect to AAD login-3. After login, verify:- - User name displays correctly- - User roles are accessible- - Role-based UI shows/hides correctly-4. Click "Sign Out" - should log out and redirect to home--### Test Role-Based Features--1. Log in with different users having different roles-2. Verify conditional UI works correctly:- - Admin features visible only to admins- - Member content visible only to members- - Public content visible to all+See [authoring-tool-reference.md](${CLAUDE_PLUGIN_ROOT}/shared/authoring-tool-reference.md) for helper function.-### Troubleshooting+**Required site setting**: `Authentication/Registration/ProfileRedirectEnabled` = `false` (redirects to home instead of profile after login). See [authentication-reference.md](./references/authentication-reference.md#site-settings).-**Login button doesn't work:**-- Ensure site is uploaded to Power Pages (not local dev)-- Check browser console for errors-- Verify anti-forgery token endpoint is accessible+**Verify**: Sign in → check user name displays → check roles → sign out.-**User info not available:**-- User must be logged in for `window.Microsoft.Dynamic365.Portal.User` to be populated-- Check if user has a Contact record in Dataverse--**Roles not showing:**-- Verify user's Contact record is associated with web roles in Power Pages portal-- Check for typos in role names (case-insensitive comparison recommended)-------## Cleanup Helper Files--**📖 See: [cleanup-reference.md](${CLAUDE_PLUGIN_ROOT}/shared/cleanup-reference.md)**--Remove any temporary helper files created during this skill's execution. Verify authentication is working correctly before cleanup.-------## Update Memory Bank--After completing this skill, update `memory-bank.md`:--```markdown-### /setup-auth-- [x] Authentication service created-- [x] PowerPages type declarations added-- [x] Authorization utilities created-- [x] Auth UI components created (login/logout button)-- [x] Role-based conditional rendering implemented-- [x] Project built successfully-- [x] Uploaded to Power Pages-- [x] Authentication verified working--## Created Resources--### Auth Files--| File | Purpose |-|------|---------|-| src/services/authService.ts | Authentication service |-| src/types/powerPages.d.ts | TypeScript declarations |-| src/utils/authorization.ts | Role checking utilities |-| src/components/AuthButton.tsx | Login/logout component |--### Role-Based Components--| Component | Roles Required | Purpose |-|-----------|----------------|---------|-| AdminDashboard | Administrators | Admin-only section |-| [ADD MORE AS IMPLEMENTED] |--## Current Status--**Last Action**: Authentication and authorization configured--**Next Step**: Test with different user accounts and roles-```+Update memory-bank.md. Cleanup per [cleanup-reference.md](${CLAUDE_PLUGIN_ROOT}/shared/cleanup-reference.md).diff --git a/plugins/power-pages/skills/setup-auth/authentication-reference.md b/plugins/power-pages/skills/setup-auth/references/authentication-reference.mdsimilarity index 92%rename from plugins/power-pages/skills/setup-auth/authentication-reference.mdrename to plugins/power-pages/skills/setup-auth/references/authentication-reference.mdindex 6851dea27..8ce2293ea 100644--- a/plugins/power-pages/skills/setup-auth/authentication-reference.md+++ b/plugins/power-pages/skills/setup-auth/references/authentication-reference.md@@ -1,30 +1,12 @@# Authentication Reference-This document provides code patterns for implementing server-side authentication in Power Pages sites.--## How Power Pages Authentication Works--Power Pages uses **server-side session-based authentication** with Azure Active Directory (AAD):--1. **Login Flow**: Form submission to `/Account/Login/ExternalLogin` with anti-forgery token-2. **Session Management**: Server maintains session via cookies-3. **User Info**: Available in `window.Microsoft.Dynamic365.Portal.User` after login-4. **Logout**: Redirect to `/Account/Login/LogOff`--```text-┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐-│ User clicks │────>│ Fetch token │────>│ POST to login │-│ "Sign In" │ │ /_layout/ │ │ /Account/Login │-│ │ │ tokenhtml │ │ /ExternalLogin │-└─────────────────┘ └─────────────────┘ └────────┬────────┘- │- v-┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐-│ User info │<────│ Redirect to │<────│ AAD Login │-│ available in │ │ site with │ │ Page │-│ Portal object │ │ session │ │ │-└─────────────────┘ └─────────────────┘ └─────────────────┘-```+## Login Flow++1. Fetch anti-forgery token from `/_layout/tokenhtml`+2. POST to `/Account/Login/ExternalLogin` with token, provider, returnUrl+3. User authenticates via AAD → session established+4. User info available in `window.Microsoft.Dynamic365.Portal.User`+5. Logout: redirect to `/Account/Login/LogOff`## TypeScript Declarationsdiff --git a/plugins/power-pages/skills/setup-auth/authorization-reference.md b/plugins/power-pages/skills/setup-auth/references/authorization-reference.mdsimilarity index 84%rename from plugins/power-pages/skills/setup-auth/authorization-reference.mdrename to plugins/power-pages/skills/setup-auth/references/authorization-reference.mdindex 573f8ae1e..bb589fe55 100644--- a/plugins/power-pages/skills/setup-auth/authorization-reference.md+++ b/plugins/power-pages/skills/setup-auth/references/authorization-reference.md@@ -1,35 +1,8 @@# Authorization Reference-This document provides code patterns for implementing role-based access control in Power Pages sites.+User roles available at `window.Microsoft.Dynamic365.Portal.User.userRoles` (array of role names).-## How Power Pages Authorization Works--Power Pages provides user roles through the portal object:--```javascript-window.Microsoft.Dynamic365.Portal.User.userRoles // Array of role names-```--Common built-in roles:-- **Anonymous Users** - Unauthenticated visitors-- **Authenticated Users** - Any logged-in user-- **Administrators** - Full admin access--Custom roles can be created in Power Pages Portal Management app.--```text-┌─────────────────────────────────────────────────────────────────┐-│ User Roles in Power Pages │-├─────────────────────────────────────────────────────────────────┤-│ │-│ window.Microsoft.Dynamic365.Portal.User.userRoles = [ │-│ "Authenticated Users", │-│ "Administrators", │-│ "Premium Members" │-│ ] │-│ │-└─────────────────────────────────────────────────────────────────┘-```+**Built-in roles**: Anonymous Users, Authenticated Users, Administrators. Custom roles via Portal Management app.## Authorization Utilities@@ -843,34 +816,12 @@ function Dashboard() {## Security Considerations-### Client-Side Authorization is for UX Only--**IMPORTANT**: Client-side role checks are for **user experience** only, not security.--- They hide/show UI elements based on roles-- They do NOT prevent unauthorized access to data-- All data access must be protected by **table permissions** in Power Pages--### Always Enforce Server-Side--```text-┌─────────────────────────────────────────────────────────────────┐-│ Security Layers │-├─────────────────────────────────────────────────────────────────┤-│ │-│ CLIENT-SIDE (UX only) SERVER-SIDE (Security) │-│ ───────────────────── ───────────────────── │-│ • Hide admin buttons • Table permissions │-│ • Show/hide nav items • Entity permissions │-│ • Conditional rendering • Web roles in Power Pages │-│ • Route guards (redirect) • Actual data access control │-│ │-│ If bypassed: Bad UX If bypassed: Security breach │-│ │-└─────────────────────────────────────────────────────────────────┘-```+**Client-side authorization is for UX only, not security.**++- Client-side: Hide/show UI elements (if bypassed: bad UX)+- Server-side: Table permissions enforce actual data access (if bypassed: security breach)-### Example: Proper Security Setup+### Proper Security Setup1. **Client-side** (this reference): Hide edit button for non-admins2. **Server-side** (via `/setup-webapi`): Table permission allows only Administrators to PATCH recordsdiff --git a/plugins/power-pages/skills/setup-dataverse/SKILL.md b/plugins/power-pages/skills/setup-dataverse/SKILL.mdindex fad4e3b3d..1200c1cbd 100644--- a/plugins/power-pages/skills/setup-dataverse/SKILL.md+++ b/plugins/power-pages/skills/setup-dataverse/SKILL.md@@ -1,394 +1,169 @@----description: Setup Dataverse tables, schema, entities, and data model for Power Pages. Use this skill when you need to create Dataverse tables, define table columns, set up entity relationships, create lookup fields, design database schema, add sample data, or configure table structure for your Power Pages site.+name: setting-up-dataverse-tables+description: Creates Dataverse tables, columns, and relationships for Power Pages. Use when creating tables, defining schema, setting up entity relationships, or lookup fields.user-invocable: true-allowed-tools: Bash(pac:*), Bash(az:*)-model: sonnet+allowed-tools: ["Read", "Write", "Grep", "Glob", "Bash", "TodoWrite", "AskUserQuestion", "Skill", "Task"]+model: opus----# Setup Dataverse Tables--This skill guides makers through setting up Dataverse tables and schema for their Power Pages site. It analyzes the site created in the previous step, recommends appropriate tables, and helps create them with sample data.--**IMPORTANT**: This skill takes a **data architecture approach** - it analyzes table relationships, builds a dependency graph, and creates tables in the correct topological order (referenced tables first, then dependent tables). This ensures referential integrity and follows enterprise data modeling best practices.--## Reference Documentation--This skill uses modular reference files for detailed instructions:--| File | Purpose |-|------|---------|-| [data-architecture-reference.md](./data-architecture-reference.md) | Entity relationships, table tiers, dependency graphs |-| [api-authentication-reference.md](./api-authentication-reference.md) | OData Web API setup, Azure CLI authentication |-| [table-management-reference.md](./table-management-reference.md) | Table creation, columns, helper functions |-| [relationship-reference.md](./relationship-reference.md) | Lookups, 1:N and N:N relationships |-| [sample-data-reference.md](./sample-data-reference.md) | Data insertion with referential integrity |-| [troubleshooting.md](./troubleshooting.md) | Common issues and solutions |--## Memory Bank--This skill uses a **memory bank** (`memory-bank.md`) to persist context across sessions.--**Follow the instructions in `${CLAUDE_PLUGIN_ROOT}/shared/memory-bank.md`** for:-- Checking and reading the memory bank before starting-- Skipping completed steps and resuming progress-- Updating the memory bank after each major step--## Workflow Overview--```text-+-----------------------------------------------------------------------------+-| STEP 1: Resume or Start Fresh |-| - Check if continuing from /create-site |-| - Identify existing site project path |-| - Offer to proceed or show resume command |-+-----------------------------------------------------------------------------+- |- v-+-----------------------------------------------------------------------------+-| STEP 2: Analyze Site & Design Data Architecture |-| - Read site source code and configuration |-| - Identify data requirements from components |-| - Design entity-relationship model with proper normalization |-| - Document table relationships (1:N, N:N, self-referential) |-| See: data-architecture-reference.md |-+-----------------------------------------------------------------------------+- |- v-+-----------------------------------------------------------------------------+-| STEP 3: Build Dependency Graph & Determine Creation Order |-| - Analyze foreign key relationships |-| - Perform topological sort to determine creation order |-| - Identify reference/lookup tables (create first) |-| - Identify dependent tables (create after their references) |-| See: data-architecture-reference.md |-+-----------------------------------------------------------------------------+- |- v-+-----------------------------------------------------------------------------+-| STEP 4: Set Up OData Web API Authentication |-| - Configure Azure CLI authentication |-| - Get environment URL and access token |-| - Set up API headers for Dataverse calls |-| See: api-authentication-reference.md |-+-----------------------------------------------------------------------------+- |- v-+-----------------------------------------------------------------------------+-| STEP 5: Review Existing Tables & Identify Reusable Tables |-| - Query all existing custom tables in the environment |-| - Compare existing tables against recommended schema |-| - Identify tables that can be reused (matching or similar schema) |-| - Present options: reuse existing, extend existing, or create new |-| See: table-management-reference.md |-+-----------------------------------------------------------------------------+- |- v-+-----------------------------------------------------------------------------+-| STEP 6: Create/Extend Tables in Dependency Order |-| - Skip tables marked for reuse |-| - Extend existing tables with missing columns if needed |-| - Create only new tables that don't exist |-| - Add relationship columns (lookups) after both tables exist |-| See: table-management-reference.md, relationship-reference.md |-+-----------------------------------------------------------------------------+- |- v-+-----------------------------------------------------------------------------+-| STEP 7: Add Sample Data with Referential Integrity |-| - Check for existing data in reused tables |-| - Insert reference/lookup data first (skip if exists) |-| - Insert dependent records with valid foreign keys |-| - Verify relationships are correctly established |-| See: sample-data-reference.md |-+-----------------------------------------------------------------------------+- |- v- Next: /setup-webapi skill-```-------## STEP 1: Resume or Start Fresh--### Check Memory Bank First--**Before asking questions**, check if a memory bank exists:+**📋 [Shared Instructions](${CLAUDE_PLUGIN_ROOT}/shared/shared-instructions.md)** - Read before starting.-1. If continuing from `/create-site` in the same session, use the known project path-2. Otherwise, ask the user for the project path-3. Read `<PROJECT_PATH>/memory-bank.md` if it exists-4. Extract:- - Project name and framework- - Site features (to recommend appropriate tables)- - Any previously chosen preferences- - Whether this skill was already partially completed--If the memory bank shows `/setup-dataverse` steps already completed:--- Inform the user what was done-- Ask if they want to add more tables, modify existing ones, or skip to next steps--### Check Context--**If continuing from create-site:**--Show this message:+# Setup Dataverse Tables-> **Ready for Next Step!**->-> Your Power Pages site has been created. Now let's set up the Dataverse tables to store and manage your site's data.->-> Would you like to proceed with setting up Dataverse tables for your site?+**References:** [data-architecture](./references/data-architecture-reference.md) | [api-auth](./references/api-authentication-reference.md) | [table-management](./references/table-management-reference.md) | [relationships](./references/relationship-reference.md) | [troubleshooting](./references/troubleshooting.md)-Use the `AskUserQuestion` tool with these options:+Tables are created in **topological order** (referenced tables first) to maintain referential integrity.-| Option | Description |-|--------|-------------|-| **Yes, proceed** | Continue to analyze the site and set up tables |-| **Show me the command** | Display the command to run this skill later: `/setup-dataverse` |-| **Not now** | Exit and save progress for later |+## Workflow-**If starting fresh (no prior context):**+1. **Check Context** → Read memory bank, get project path+2. **Analyze Site** → Identify data patterns from components+3. **Build Dependency Graph** → Determine creation order+4. **Setup API Auth** → Get token and publisher prefix+5. **Review Existing Tables** → Reuse, extend, or create new+6. **Create Tables** → In dependency order with relationships-Ask the user:+----> To set up Dataverse tables, I need to know about your Power Pages site.->-> Do you have an existing site project, or would you like to create one first?+## Step 1: Check Context-| Option | Description |-|--------|-------------|-| **I have an existing site** | Provide the path to your site project |-| **Create a site first** | Run `/create-site` to create a new Power Pages site |+Read `memory-bank.md`. If continuing from `/create-site`, proceed. Otherwise ask for project path or suggest `/create-site` first.----## STEP 2: Analyze Site & Design Data Architecture+## Step 2: Analyze Site-**See: [data-architecture-reference.md](./data-architecture-reference.md)**+Read `powerpages.config.json` and scan components for data patterns:-### Quick Summary+| Pattern | Table | Relationships |+|---------|-------|---------------|+| Contact form | `{prefix}_contactsubmission` | → status |+| Products | `{prefix}_product` | → category |+| Team members | `{prefix}_teammember` | → department |+| Testimonials | `{prefix}_testimonial` | → product (optional) |+| Blog | `{prefix}_blogpost` | → category, author |+| FAQ | `{prefix}_faq` | → faqcategory |-1. **Read powerpages.config.json** to get site name and structure-2. **Scan component files** for data patterns:- - Forms (contact forms, registration forms)- - Lists/Tables (product listings, team members)- - Cards (testimonials, portfolio items)+**Use standard Dataverse tables instead of creating new ones:**-### Data Pattern Recognition+| Need | Use This | NOT This |+|------|----------|----------|+| User profiles, customers | `contact` (standard) | `{prefix}_user` or `{prefix}_customer` |+| Organizations, companies | `account` (standard) | `{prefix}_company` |-| Pattern | Recommended Table | Likely Relationships |-|---------|-------------------|---------------------|-| Contact form | `cr_contactsubmission` | -> `cr_contactstatus` (lookup) |-| Product/service cards | `cr_product` | -> `cr_category` (lookup) |-| Team member section | `cr_teammember` | -> `cr_department` (lookup) |-| Testimonials/Reviews | `cr_testimonial` | -> `cr_product` (optional) |-| Blog/News section | `cr_blogpost` | -> `cr_category`, -> `cr_author` |-| FAQ section | `cr_faq` | -> `cr_faqcategory` (lookup) |+The `contact` table is already integrated with Power Pages authentication - portal users are linked to Contact records. Extend it with custom columns if needed rather than creating a separate user table.-### Actions--1. Design a complete ER model identifying all entities and relationships-2. Classify tables into tiers (TIER 0 reference tables, TIER 1 primary entities, etc.)-3. Present architecture recommendations using `AskUserQuestion`+Design ER model, classify into tiers (TIER 0 = reference tables, TIER 1 = primary entities, etc.), present to user.----## STEP 3: Build Dependency Graph & Validate Creation Order--**See: [data-architecture-reference.md](./data-architecture-reference.md)**--### Quick Summary--Before creating any tables, validate the creation order:+## Step 3: Build Dependency Graph-1. List all tables and their lookup columns-2. Build adjacency list: for each table, list tables it depends on-3. Perform topological sort to get valid creation order-4. Group tables by tier for parallel creation where possible--### Validation Rules--- **No circular dependencies** - A cannot depend on B if B depends on A-- **All referenced tables exist** - Either in schema or as system tables-- **Self-references are handled** - Table created first, then self-lookup added+Topologically sort tables. Rules:+- No circular dependencies+- All referenced tables exist+- Self-references: create table first, add lookup after----## STEP 4: Set Up OData Web API Authentication--**See: [api-authentication-reference.md](./api-authentication-reference.md)**--### Quick Summary+## Step 4: Setup API Auth```powershell-# Verify Azure CLI is logged inaz account show--# Get environment URLpac org who-# Get access token-$envUrl = "https://<org>.crm.dynamics.com"-$token = (az account get-access-token --resource $envUrl --query accessToken -o tsv)--# Set up headers-$headers = @{- "Authorization" = "Bearer $token"- "Content-Type" = "application/json"- "OData-MaxVersion" = "4.0"- "OData-Version" = "4.0"- "Prefer" = "return=representation"-}--$baseUrl = "$envUrl/api/data/v9.2"+$api = Initialize-DataverseApi -EnvironmentUrl "https://<org>.crm.dynamics.com"+$headers = $api.Headers+$baseUrl = $api.BaseUrl+$publisherPrefix = $api.PublisherPrefix # Use for all schema names```----## STEP 5: Review Existing Tables & Identify Reusable Tables+## Step 5: Review Existing Tables-**See: [table-management-reference.md](./table-management-reference.md)**+**ALWAYS query existing tables first before recommending creation:**-### Quick Summary+```powershell+# 1. Get ALL existing custom tables+$existingTables = Invoke-RestMethod -Uri "$baseUrl/EntityDefinitions?`$filter=IsCustomEntity eq true&`$select=SchemaName,LogicalName,DisplayName" -Headers $headers-**CRITICAL**: Before creating any tables, review existing tables in the environment to prevent duplicates and leverage existing schema.+# 2. Use Find-SimilarTables to match by purpose (category, product, team, etc.)+# 3. Use Compare-TableSchemas to check if columns match requirements+```-### Actions+**Always recommend standard Dataverse tables for common needs:**+- `contact` - For users, customers, people (already linked to Power Pages auth)+- `account` - For organizations, companies, partners-1. Query all existing custom tables using `EntityDefinitions` API-2. Compare existing tables against recommended schema-3. Present reuse options to user:- - **Reuse as-is**: Table has all required columns- - **Extend**: Table exists but needs additional columns- - **Create new**: Table doesn't exist+These exist in every environment - extend with custom columns instead of creating new tables.-### Present Options+**Present findings to user with `AskUserQuestion`:**+- Show which existing tables can be reused (and what columns they have)+- Show which need extension (missing columns)+- Show which must be created new (no match found)-Use `AskUserQuestion`:+Options:+- **Use recommendations** - Reuse existing, extend where needed, create only new+- **Create all new** - Unique names for all tables+- **Review each** - Decide individually-| Option | Description |-|--------|-------------|-| **Use recommendations** | Reuse existing tables, extend where needed, create only new |-| **Create all new** | Create new tables with unique names |-| **Review each table** | Decide for each table individually |+Build `$tableMap` with `Build-TableNameMapping` - **critical for later steps**:+```powershell+$tableMap["category"].LogicalName # Actual table name (may be existing table)+$tableMap["category"].EntitySetName # For OData queries+$tableMap["category"].Source # "Reused", "Extended", or "Created"+```----## STEP 6: Create/Extend Tables in Dependency Order+## Step 6: Create Tables-**See: [table-management-reference.md](./table-management-reference.md) and [relationship-reference.md](./relationship-reference.md)**+**Present the plan and get explicit confirmation before creating:**-### Quick Summary+Use `AskUserQuestion` to show:+- Tables to be reused (no changes)+- Tables to be extended (list columns to add)+- Tables to be created (list all columns)+- Relationships to be created-Based on STEP 5 decisions, create only new tables and extend existing tables as needed.+Options:+- **Proceed** - Create/extend tables as planned+- **Modify** - Let me adjust the plan+- **Cancel** - Don't make any changes-### Protocol+**Only after user confirms "Proceed"**, create in dependency order using:+- `New-DataverseTableIfNotExists`+- `Add-DataverseColumnIfNotExists`+- `Add-DataverseLookupIfNotExists`-1. **PHASE 1**: Process tables based on decisions (skip reusable, extend, create new)-2. **PHASE 2**: Add non-lookup columns to new and extended tables-3. **PHASE 3**: Create/verify relationships (lookup columns)--### Key Functions--- `New-DataverseTableIfNotExists` - Create table only if it doesn't exist-- `Add-DataverseColumnIfNotExists` - Add column only if it doesn't exist-- `Add-DataverseLookupIfNotExists` - Create relationship only if it doesn't exist+**Phases**: Skip reusable → Extend existing → Create new → Add lookups----## STEP 7: Add Sample Data with Referential Integrity--**See: [sample-data-reference.md](./sample-data-reference.md)**--### Quick Summary+## Step 7: Create Skill Tracking Setting and Upload-Insert data **in the correct order** to maintain referential integrity.--### Protocol--1. Check for existing data in reused tables-2. Insert TIER 0 data first (categories, statuses, departments)-3. Insert TIER 1 data with valid TIER 0 lookups (products, team members)-4. Insert TIER 2 data with valid lookups (testimonials, submissions)--### Foreign Key Syntax+Create `Site/AI/SetupDataverse` site setting to track skill usage:```powershell-# Use @odata.bind to reference related records-$product = @{- cr_name = "Professional Consultation"- "[email protected]" = "/cr_categories($categoryId)"-}+New-SkillTrackingSetting -ProjectRoot $projectRoot -SkillName "SetupDataverse"+npm run build # Always build before upload+pac pages upload-code-site --rootPath "<PROJECT_ROOT>"```-### Verify Data+See [authoring-tool-reference.md](${CLAUDE_PLUGIN_ROOT}/shared/authoring-tool-reference.md) for helper function.-After inserting, verify relationships using `$expand`:--```powershell-$products = Invoke-RestMethod -Uri "$baseUrl/cr_products?`$expand=cr_categoryid(`$select=cr_name)" -Headers $headers-```+Cleanup per [cleanup-reference.md](${CLAUDE_PLUGIN_ROOT}/shared/cleanup-reference.md).----## STEP 8: Cleanup Helper Files+## Optional Enhancements-**📖 See: [cleanup-reference.md](${CLAUDE_PLUGIN_ROOT}/shared/cleanup-reference.md)**--Remove any temporary helper files created during this skill's execution. Verify tables are created and data is inserted correctly before cleanup.+After table creation, suggest:+- `/add-sample-data` - Insert sample data with proper foreign key relationships---## Next Steps-After setting up Dataverse tables with sample data, configure table permissions so Power Pages can access the data.--> **Next Skill**: Run `/setup-webapi` to configure table permissions and enable Web API access for your Power Pages site.-------## Update Memory Bank--After completing this skill, update `memory-bank.md`:--```markdown-### /setup-dataverse-- [x] Site analyzed for data requirements-- [x] Data architecture designed with dependency graph-- [x] Existing tables reviewed and analyzed-- [x] Reuse decisions made (reuse/extend/create)-- [x] Tables created/extended in dependency order-- [x] Relationships (lookups) established-- [x] Sample data inserted with referential integrity--## Data Architecture--### Tables by Tier--| Tier | Tables |-|------|--------|-| TIER 0 | cr_category, cr_status, cr_department |-| TIER 1 | cr_product, cr_teammember |-| TIER 2 | cr_testimonial, cr_contactsubmission |--### Relationships--| Source | Target | Lookup Column |-|--------|--------|---------------|-| cr_product | cr_category | cr_categoryid |-| cr_teammember | cr_department | cr_departmentid |-| cr_testimonial | cr_product | cr_productid |--## Current Status--**Last Action**: Dataverse tables and relationships created with sample data--**Next Step**: Run `/setup-webapi` to configure table permissions-```-------## Troubleshooting--**See: [troubleshooting.md](./troubleshooting.md)** for common issues and solutions.+Run `/setup-webapi` to configure table permissions.diff --git a/plugins/power-pages/skills/setup-dataverse/data-architecture-reference.md b/plugins/power-pages/skills/setup-dataverse/data-architecture-reference.mddeleted file mode 100644index 294d30e68..000000000--- a/plugins/power-pages/skills/setup-dataverse/data-architecture-reference.md+++ /dev/null@@ -1,179 +0,0 @@-# Data Architecture Reference--This document covers data architecture principles for designing Dataverse table schemas for Power Pages sites.--## Entity-Relationship Analysis--Identify all entities and their relationships before creating any tables:--```text-RELATIONSHIP TYPES IN DATAVERSE--1:N (One-to-Many) - Most common- - Parent table referenced by child table via Lookup column- - Example: Category (1) -> Products (N)- - Parent must exist before child can reference it--N:N (Many-to-Many)- - Junction/intersection table created automatically- - Example: Products <-> Tags- - Both tables must exist before creating the relationship--Self-Referential- - Table references itself- - Example: Employee -> Manager (also an Employee)- - Table must exist before adding self-referential lookup--Polymorphic (Customer/Regarding)- - Single column can reference multiple table types- - Example: Activity regarding Contact OR Account OR Lead- - All target tables must exist before creating polymorphic lookup-```--## Table Classification--Classify tables into tiers based on their dependencies:--```text-TABLE DEPENDENCY TIERS--TIER 0: Reference/Lookup Tables (Create FIRST)- - No foreign keys to other custom tables- - Examples: Category, Status, Country, Department, Tag- - These are the "dictionaries" of your data model--TIER 1: Primary Entity Tables (Create SECOND)- - Only reference Tier 0 tables or system tables- - Examples: Product (->Category), Employee (->Department)- - Core business entities--TIER 2: Dependent/Transaction Tables (Create THIRD)- - Reference Tier 1 tables- - Examples: Order (->Customer), OrderLine (->Order, ->Product)- - Often transactional or junction tables--TIER 3: Deeply Nested Tables (Create LAST)- - Reference Tier 2 tables- - Examples: OrderLineDetail (->OrderLine), PaymentAllocation (->Payment)- - Rare in typical Power Pages sites-```--## Dependency Graph Documentation--**Always document the dependency graph before creating tables:**--```text-Example: E-Commerce Site Data Architecture-- +-------------+- | Category | TIER 0- | (lookup) |- +------+------+- |- +---------------+---------------+- v v v- +--------------+ +--------------+ +--------------+- | Product | | Supplier | | Customer | TIER 1- | (->Category) | | | | |- +------+-------+ +------+-------+ +------+-------+- | | |- +---------------+---------------+- v- +--------------+- | Order | TIER 2- | (->Customer) |- +------+-------+- |- v- +--------------+- | OrderLine | TIER 3- |(->Order, |- | ->Product) |- +--------------+--Creation Order: Category -> Product, Supplier, Customer -> Order -> OrderLine-```--## Common Relationship Patterns for Power Pages Sites--| Site Feature | Tables | Relationships |-|--------------|--------|---------------|-| **Blog** | Category, Author, BlogPost, Comment | Category(0) -> BlogPost(1) -> Comment(2); Author(0) -> BlogPost(1) |-| **E-commerce** | Category, Product, Customer, Order, OrderLine | Category(0) -> Product(1); Customer(1) -> Order(2) -> OrderLine(3) <- Product(1) |-| **Event Registration** | EventType, Event, Attendee, Registration | EventType(0) -> Event(1); Attendee(1) -> Registration(2) <- Event(1) |-| **Support Portal** | Category, Priority, Ticket, Comment | Category(0), Priority(0) -> Ticket(1) -> Comment(2) |-| **Directory/Listing** | Category, Location, Listing, Review | Category(0), Location(0) -> Listing(1) -> Review(2) |-| **Job Board** | Department, JobType, JobPosting, Application | Department(0), JobType(0) -> JobPosting(1) -> Application(2) |--## Dependency Analysis Algorithm--```text-1. List all tables and their lookup columns-2. Build adjacency list: for each table, list tables it depends on-3. Perform topological sort to get valid creation order-4. If cycle detected, report error (invalid schema design)-5. Group tables by tier for parallel creation where possible-```--### Example Dependency Resolution--```powershell-# Example: Building dependency graph in PowerShell-$tables = @{- "cr_category" = @() # No dependencies - TIER 0- "cr_status" = @() # No dependencies - TIER 0- "cr_department" = @() # No dependencies - TIER 0- "cr_product" = @("cr_category") # Depends on category - TIER 1- "cr_teammember" = @("cr_department") # Depends on department - TIER 1- "cr_testimonial" = @("cr_product") # Depends on product - TIER 2- "cr_contactsubmission" = @("cr_status") # Depends on status - TIER 1-}--# Topological sort result (creation order):-# 1. cr_category, cr_status, cr_department (can be parallel)-# 2. cr_product, cr_teammember, cr_contactsubmission (after their deps)-# 3. cr_testimonial (after cr_product)-```--## Validation Rules--Before proceeding to table creation, validate:--1. **No circular dependencies** - A cannot depend on B if B depends on A-2. **All referenced tables exist** - Either in schema or as system tables-3. **Lookup targets are valid** - Table being referenced must have a primary key-4. **Self-references are handled** - Table created first, then self-lookup added--## Example Analysis Output Format--```text-DATA ARCHITECTURE FOR: [Site Name]--TIER 0 - Reference Tables (No Dependencies)- 1. cr_category - Product/content categories- 2. cr_status - Status values for various entities- 3. cr_department - Team member departments--TIER 1 - Primary Entity Tables- 4. cr_product - Products (-> cr_category)- 5. cr_teammember - Team members (-> cr_department)- 6. cr_blogpost - Blog posts (-> cr_category)--TIER 2 - Dependent Tables- 7. cr_testimonial - Testimonials (-> cr_product, optional)- 8. cr_contactsubmission - Contact submissions (-> cr_status)--RELATIONSHIP DIAGRAM-- cr_category --+---> cr_product ---> cr_testimonial- +---> cr_blogpost-- cr_department ---> cr_teammember-- cr_status -------> cr_contactsubmission--CREATION ORDER- 1. cr_category, cr_status, cr_department (parallel - no deps)- 2. cr_product, cr_teammember, cr_blogpost (after tier 0)- 3. cr_testimonial, cr_contactsubmission (after their references)-```diff --git a/plugins/power-pages/skills/setup-dataverse/api-authentication-reference.md b/plugins/power-pages/skills/setup-dataverse/references/api-authentication-reference.mdsimilarity index 78%rename from plugins/power-pages/skills/setup-dataverse/api-authentication-reference.mdrename to plugins/power-pages/skills/setup-dataverse/references/api-authentication-reference.mdindex d830be4e5..89257b706 100644--- a/plugins/power-pages/skills/setup-dataverse/api-authentication-reference.md+++ b/plugins/power-pages/skills/setup-dataverse/references/api-authentication-reference.md@@ -1,15 +1,6 @@# API Authentication Reference-This document covers setting up authentication for the Dataverse OData Web API.--## Overview--This skill uses the Dataverse OData Web API for all table and data operations:--1. **Dataverse Web API** for table creation, schema management, and data operations-2. **Azure CLI** for authentication (`az account get-access-token`)-3. **PowerShell** for scripting API calls-4. **Client-side `/_api/` calls** from the Power Pages site for runtime data access+Uses Dataverse OData Web API with Azure CLI authentication (`az account get-access-token`).## Prerequisites@@ -68,6 +59,37 @@ $baseUrl = "$envUrl/api/data/v9.2"| `MSCRM.SolutionUniqueName` | Solution name | Add created items to a solution || `Prefer` | `return=representation` | Return created record with ID |+## Get Default Publisher Prefix++The publisher prefix is used for naming custom tables and columns. Fetch it dynamically to ensure consistency:++```powershell+function Get-DefaultPublisherPrefix {+ param(+ [Parameter(Mandatory=$true)]+ [string]$BaseUrl,++ [Parameter(Mandatory=$true)]+ [hashtable]$Headers+ )++ # Query the CDS Default Publisher directly+ $defaultPublisher = Invoke-RestMethod -Uri "$BaseUrl/publishers?`$filter=friendlyname eq 'CDS Default Publisher'&`$select=customizationprefix,friendlyname" -Headers $Headers++ if ($defaultPublisher.value.Count -eq 0) {+ throw "Could not find CDS Default Publisher in the environment"+ }++ $prefix = $defaultPublisher.value[0].customizationprefix+ $publisherName = $defaultPublisher.value[0].friendlyname++ Write-Host "Default Publisher: $publisherName" -ForegroundColor Cyan+ Write-Host "Customization Prefix: $prefix" -ForegroundColor Cyan++ return $prefix+}+```+## Complete Setup Script```powershell@@ -102,17 +124,23 @@ function Initialize-DataverseApi {$baseUrl = "$EnvironmentUrl/api/data/v9.2"+ # Get the default publisher prefix+ $publisherPrefix = Get-DefaultPublisherPrefix -BaseUrl $baseUrl -Headers $headers+# Store in script-level variables for reuse$script:DataverseHeaders = $headers$script:DataverseBaseUrl = $baseUrl+ $script:PublisherPrefix = $publisherPrefixWrite-Host "Dataverse API initialized successfully" -ForegroundColor GreenWrite-Host " Environment: $EnvironmentUrl" -ForegroundColor CyanWrite-Host " Base URL: $baseUrl" -ForegroundColor Cyan+ Write-Host " Publisher Prefix: $publisherPrefix" -ForegroundColor Cyanreturn @{Headers = $headersBaseUrl = $baseUrl+ PublisherPrefix = $publisherPrefix}}@@ -120,6 +148,7 @@ function Initialize-DataverseApi {# $api = Initialize-DataverseApi -EnvironmentUrl "https://orgname.crm.dynamics.com"# $headers = $api.Headers# $baseUrl = $api.BaseUrl+# $publisherPrefix = $api.PublisherPrefix```## Token Refreshdiff --git a/plugins/power-pages/skills/setup-dataverse/references/data-architecture-reference.md b/plugins/power-pages/skills/setup-dataverse/references/data-architecture-reference.mdnew file mode 100644index 000000000..a1827005e--- /dev/null+++ b/plugins/power-pages/skills/setup-dataverse/references/data-architecture-reference.md@@ -0,0 +1,34 @@+# Data Architecture Reference++## Relationship Types++- **1:N (One-to-Many)**: Parent table referenced by child via Lookup. Parent must exist first.+- **N:N (Many-to-Many)**: Junction table created automatically. Both tables must exist first.+- **Self-Referential**: Table references itself. Table must exist before adding self-lookup.++## Dependency Tiers++Create tables in order by their dependencies:+- **Tier 0**: Reference/lookup tables (no dependencies) - Category, Status, Department+- **Tier 1**: Primary entities (reference Tier 0) - Product→Category, Employee→Department+- **Tier 2**: Dependent/transaction tables (reference Tier 1) - Order→Customer, OrderLine→Order+- **Tier 3**: Deeply nested tables (rare)++## Common Relationship Patterns++| Site Feature | Tables | Relationships |+|--------------|--------|---------------|+| **Blog** | Category, Author, BlogPost, Comment | Category(0) -> BlogPost(1) -> Comment(2); Author(0) -> BlogPost(1) |+| **E-commerce** | Category, Product, Customer, Order, OrderLine | Category(0) -> Product(1); Customer(1) -> Order(2) -> OrderLine(3) <- Product(1) |+| **Event Registration** | EventType, Event, Attendee, Registration | EventType(0) -> Event(1); Attendee(1) -> Registration(2) <- Event(1) |+| **Support Portal** | Category, Priority, Ticket, Comment | Category(0), Priority(0) -> Ticket(1) -> Comment(2) |+| **Directory/Listing** | Category, Location, Listing, Review | Category(0), Location(0) -> Listing(1) -> Review(2) |+| **Job Board** | Department, JobType, JobPosting, Application | Department(0), JobType(0) -> JobPosting(1) -> Application(2) |++## Validation Rules++Before table creation, validate:+1. No circular dependencies+2. All referenced tables exist+3. Lookup targets have primary keys+4. Self-references: create table first, then add self-lookupdiff --git a/plugins/power-pages/skills/setup-dataverse/relationship-reference.md b/plugins/power-pages/skills/setup-dataverse/references/relationship-reference.mdsimilarity index 71%rename from plugins/power-pages/skills/setup-dataverse/relationship-reference.mdrename to plugins/power-pages/skills/setup-dataverse/references/relationship-reference.mdindex b8b029bcf..4568feb47 100644--- a/plugins/power-pages/skills/setup-dataverse/relationship-reference.md+++ b/plugins/power-pages/skills/setup-dataverse/references/relationship-reference.md@@ -1,7 +1,5 @@# Relationship Reference-This document covers creating and managing relationships between Dataverse tables.-## Relationship Types| Type | Description | Use Case |@@ -196,19 +194,31 @@ When creating relationships, you can configure cascade behavior:## Relationship Naming Conventions-Follow this naming pattern for consistency:+Follow this naming pattern for consistency, using the `$publisherPrefix` retrieved from `Initialize-DataverseApi`:```text-{publisher}_{targetTable}_{sourceTable}+{publisherPrefix}_{targetTable}_{sourceTable}-Examples:-- cr_category_product (Product -> Category)-- cr_department_teammember (TeamMember -> Department)-- cr_status_contactsubmission (ContactSubmission -> Status)+Examples (where $publisherPrefix = "cr"):+- {publisherPrefix}_category_product (Product -> Category)+- {publisherPrefix}_department_teammember (TeamMember -> Department)+- {publisherPrefix}_status_contactsubmission (ContactSubmission -> Status)```## Complete Example: Creating Relationships in Dependency Order+**IMPORTANT**: Use the `$tableMap` from `Build-TableNameMapping` to get the correct table names. This ensures:+- **Reused/Extended tables**: Use their actual logical names from Dataverse+- **New tables**: Use the publisher prefix pattern++```powershell+$api = Initialize-DataverseApi -EnvironmentUrl "https://orgname.crm.dynamics.com"+$publisherPrefix = $api.PublisherPrefix++# $tableMap should be built in STEP 5 using Build-TableNameMapping+# It maps table purposes to actual logical names+```+```powershell# ============================================# PHASE 3: Create Relationships@@ -216,57 +226,74 @@ Examples:Write-Host "`n=== Processing Relationships ===" -ForegroundColor Magenta+# Helper to get actual table name from mapping+function Get-TableName { param([string]$Purpose) return $tableMap[$Purpose].LogicalName }+# --- TIER 1 -> TIER 0 Relationships ---Write-Host "Processing TIER 1 -> TIER 0 relationships..." -ForegroundColor Cyan-# Product -> Category-Add-DataverseLookupIfNotExists -SourceTable "cr_product" -TargetTable "cr_category" `- -LookupSchemaName "cr_categoryid" -LookupDisplayName "Category" `- -RelationshipName "cr_category_product"+# Product -> Category (uses actual table names from mapping)+$productTable = Get-TableName "product"+$categoryTable = Get-TableName "category"+Add-DataverseLookupIfNotExists -SourceTable $productTable -TargetTable $categoryTable `+ -LookupSchemaName "${publisherPrefix}_categoryid" -LookupDisplayName "Category" `+ -RelationshipName "${publisherPrefix}_${categoryTable}_${productTable}"# Team Member -> Department-Add-DataverseLookupIfNotExists -SourceTable "cr_teammember" -TargetTable "cr_department" `- -LookupSchemaName "cr_departmentid" -LookupDisplayName "Department" `- -RelationshipName "cr_department_teammember"+$teammemberTable = Get-TableName "teammember"+$departmentTable = Get-TableName "department"+Add-DataverseLookupIfNotExists -SourceTable $teammemberTable -TargetTable $departmentTable `+ -LookupSchemaName "${publisherPrefix}_departmentid" -LookupDisplayName "Department" `+ -RelationshipName "${publisherPrefix}_${departmentTable}_${teammemberTable}"# Contact Submission -> Status-Add-DataverseLookupIfNotExists -SourceTable "cr_contactsubmission" -TargetTable "cr_status" `- -LookupSchemaName "cr_statusid" -LookupDisplayName "Status" `- -RelationshipName "cr_status_contactsubmission"+$contactsubmissionTable = Get-TableName "contactsubmission"+$statusTable = Get-TableName "status"+Add-DataverseLookupIfNotExists -SourceTable $contactsubmissionTable -TargetTable $statusTable `+ -LookupSchemaName "${publisherPrefix}_statusid" -LookupDisplayName "Status" `+ -RelationshipName "${publisherPrefix}_${statusTable}_${contactsubmissionTable}"# --- TIER 2 -> TIER 1 Relationships ---Write-Host "`nProcessing TIER 2 -> TIER 1 relationships..." -ForegroundColor Cyan# Testimonial -> Product (optional relationship)-Add-DataverseLookupIfNotExists -SourceTable "cr_testimonial" -TargetTable "cr_product" `- -LookupSchemaName "cr_productid" -LookupDisplayName "Related Product" `- -RelationshipName "cr_product_testimonial"+$testimonialTable = Get-TableName "testimonial"+Add-DataverseLookupIfNotExists -SourceTable $testimonialTable -TargetTable $productTable `+ -LookupSchemaName "${publisherPrefix}_productid" -LookupDisplayName "Related Product" `+ -RelationshipName "${publisherPrefix}_${productTable}_${testimonialTable}"Write-Host "`n=== Relationship processing complete ===" -ForegroundColor Green```+**NOTE**: When reusing existing tables, their logical names may differ from the expected pattern:+- New table: `cr_category` (follows `${publisherPrefix}_purpose` pattern)+- Reused table: `contoso_productcategory` or `existing_categories` (actual name from Dataverse)++The `$tableMap` handles this automatically by storing the actual logical names.+## Self-Referential LookupsFor tables that reference themselves (e.g., Employee -> Manager):```powershell# First, create the table-New-DataverseTable -SchemaName "cr_employee" -DisplayName "Employee" -PluralDisplayName "Employees"+New-DataverseTable -SchemaName "${publisherPrefix}_employee" -DisplayName "Employee" -PluralDisplayName "Employees"# Add regular columns-Add-DataverseColumn -TableName "cr_employee" -SchemaName "cr_title" -DisplayName "Job Title" -Type "String"+Add-DataverseColumn -TableName "${publisherPrefix}_employee" -SchemaName "${publisherPrefix}_title" -DisplayName "Job Title" -Type "String"# Then add self-referential lookup (table must exist first!)-Add-DataverseLookup -SourceTable "cr_employee" -TargetTable "cr_employee" `- -LookupSchemaName "cr_managerid" -LookupDisplayName "Manager" `- -RelationshipName "cr_employee_manager"+Add-DataverseLookup -SourceTable "${publisherPrefix}_employee" -TargetTable "${publisherPrefix}_employee" `+ -LookupSchemaName "${publisherPrefix}_managerid" -LookupDisplayName "Manager" `+ -RelationshipName "${publisherPrefix}_employee_manager"```## Verifying Relationships```powershell# Check if a relationship exists-$relations = Invoke-RestMethod -Uri "$baseUrl/RelationshipDefinitions?`$filter=SchemaName eq 'cr_category_product'" -Headers $headers+$relationshipName = "${publisherPrefix}_category_product"+$relations = Invoke-RestMethod -Uri "$baseUrl/RelationshipDefinitions?`$filter=SchemaName eq '$relationshipName'" -Headers $headersif ($relations.value.Count -gt 0) {Write-Host "Relationship exists" -ForegroundColor GreenWrite-Host " Referenced Entity: $($relations.value[0].ReferencedEntity)"@@ -276,8 +303,9 @@ if ($relations.value.Count -gt 0) {}# List all relationships for a table-$tableRelations = Invoke-RestMethod -Uri "$baseUrl/EntityDefinitions(LogicalName='cr_product')/ManyToOneRelationships" -Headers $headers-Write-Host "Lookups on cr_product:" -ForegroundColor Cyan+$tableName = "${publisherPrefix}_product"+$tableRelations = Invoke-RestMethod -Uri "$baseUrl/EntityDefinitions(LogicalName='$tableName')/ManyToOneRelationships" -Headers $headers+Write-Host "Lookups on ${tableName}:" -ForegroundColor Cyan$tableRelations.value | ForEach-Object {Write-Host " $($_.SchemaName): -> $($_.ReferencedEntity)"}diff --git a/plugins/power-pages/skills/setup-dataverse/table-management-reference.md b/plugins/power-pages/skills/setup-dataverse/references/table-management-reference.mdsimilarity index 59%rename from plugins/power-pages/skills/setup-dataverse/table-management-reference.mdrename to plugins/power-pages/skills/setup-dataverse/references/table-management-reference.mdindex c4dc45434..62cda6a9d 100644--- a/plugins/power-pages/skills/setup-dataverse/table-management-reference.md+++ b/plugins/power-pages/skills/setup-dataverse/references/table-management-reference.md@@ -1,7 +1,5 @@# Table Management Reference-This document covers querying, creating, and managing Dataverse tables via the OData Web API.-## Query Existing Custom TablesBefore creating tables, review existing custom tables in the environment:@@ -48,7 +46,7 @@ function Get-TableSchema {```powershellfunction Compare-TableSchemas {param(- [hashtable]$RequiredTables, # Schema name -> array of required columns+ [hashtable]$RequiredTables, # Purpose name -> array of required columns (e.g., "category", "product")[array]$ExistingTables # From EntityDefinitions query)@@ -58,26 +56,31 @@ function Compare-TableSchemas {CreateNew = @() # Tables that don't exist and must be created}- foreach ($tableName in $RequiredTables.Keys) {- $existing = $ExistingTables | Where-Object { $_.SchemaName -eq $tableName -or $_.LogicalName -eq $tableName }+ foreach ($tablePurpose in $RequiredTables.Keys) {+ # Search for existing tables that match this purpose (by name patterns)+ $existing = Find-SimilarTables -Purpose $tablePurpose -ExistingTables $ExistingTables | Select-Object -First 1if ($existing) {# Table exists - check if it has all required columns$tableSchema = Get-TableSchema -TableLogicalName $existing.LogicalName$existingColumns = $tableSchema.Attributes | Select-Object -ExpandProperty SchemaName- $requiredColumns = $RequiredTables[$tableName]+ $requiredColumns = $RequiredTables[$tablePurpose]$missingColumns = $requiredColumns | Where-Object { $_ -notin $existingColumns }if ($missingColumns.Count -eq 0) {$comparison.Reusable += @{- TableName = $tableName+ TablePurpose = $tablePurpose # Intended purpose (e.g., "category")+ ActualLogicalName = $existing.LogicalName # Actual name in Dataverse (e.g., "cr_productcategory")+ ActualSchemaName = $existing.SchemaName # Schema name (e.g., "cr_ProductCategory")ExistingTable = $existingMessage = "All required columns present"}} else {$comparison.Extendable += @{- TableName = $tableName+ TablePurpose = $tablePurpose+ ActualLogicalName = $existing.LogicalName+ ActualSchemaName = $existing.SchemaNameExistingTable = $existingMissingColumns = $missingColumnsMessage = "Missing columns: $($missingColumns -join ', ')"@@ -85,8 +88,11 @@ function Compare-TableSchemas {}} else {$comparison.CreateNew += @{- TableName = $tableName- RequiredColumns = $RequiredTables[$tableName]+ TablePurpose = $tablePurpose+ # New tables will use the publisher prefix pattern+ NewSchemaName = "${publisherPrefix}_$tablePurpose"+ NewLogicalName = "${publisherPrefix}_$tablePurpose".ToLower()+ RequiredColumns = $RequiredTables[$tablePurpose]}}}@@ -95,6 +101,73 @@ function Compare-TableSchemas {}```+## Build Table Name Mapping++After comparing tables and getting user decisions, build a mapping that tracks the actual logical names to use for each table purpose. This is **critical** for correctly referencing tables throughout the workflow.++```powershell+function Build-TableNameMapping {+ param(+ [object]$ComparisonResult, # From Compare-TableSchemas+ [string]$PublisherPrefix # From Initialize-DataverseApi+ )++ # Maps table purpose -> actual logical name and entity set name+ # This ensures we use existing table names when reusing, and new names when creating+ $tableMapping = @{}++ # Tables being reused - use their ACTUAL logical names+ foreach ($table in $ComparisonResult.Reusable) {+ $tableMapping[$table.TablePurpose] = @{+ LogicalName = $table.ActualLogicalName+ SchemaName = $table.ActualSchemaName+ EntitySetName = $table.ActualLogicalName + "es" # Pluralized for OData (may need adjustment)+ Source = "Reused"+ }+ Write-Host " [REUSE] $($table.TablePurpose) -> $($table.ActualLogicalName)" -ForegroundColor Yellow+ }++ # Tables being extended - use their ACTUAL logical names+ foreach ($table in $ComparisonResult.Extendable) {+ $tableMapping[$table.TablePurpose] = @{+ LogicalName = $table.ActualLogicalName+ SchemaName = $table.ActualSchemaName+ EntitySetName = $table.ActualLogicalName + "es"+ Source = "Extended"+ }+ Write-Host " [EXTEND] $($table.TablePurpose) -> $($table.ActualLogicalName)" -ForegroundColor Cyan+ }++ # Tables being created - use the publisher prefix pattern+ foreach ($table in $ComparisonResult.CreateNew) {+ $logicalName = "${PublisherPrefix}_$($table.TablePurpose)".ToLower()+ $schemaName = "${PublisherPrefix}_$($table.TablePurpose)"+ $tableMapping[$table.TablePurpose] = @{+ LogicalName = $logicalName+ SchemaName = $schemaName+ EntitySetName = $logicalName + "s" # Standard pluralization for new tables+ Source = "Created"+ }+ Write-Host " [CREATE] $($table.TablePurpose) -> $logicalName" -ForegroundColor Green+ }++ return $tableMapping+}++# Example usage:+# $comparison = Compare-TableSchemas -RequiredTables $requiredTables -ExistingTables $existingTables.value+# $tableMap = Build-TableNameMapping -ComparisonResult $comparison -PublisherPrefix $publisherPrefix+#+# # Later, when referencing tables, use the mapping:+# $categoryTable = $tableMap["category"].LogicalName # e.g., "existing_productcategory" or "cr_category"+# $categoryEntitySet = $tableMap["category"].EntitySetName # e.g., "existing_productcategories" or "cr_categorys"+```++**IMPORTANT**: Always use the `$tableMap` to get the correct table names throughout the workflow:+- For relationships: `$tableMap["product"].LogicalName` instead of `"${publisherPrefix}_product"`+- For data queries: `$tableMap["category"].EntitySetName` instead of `"${publisherPrefix}_categories"`+- For column additions: `$tableMap["teammember"].LogicalName` instead of `"${publisherPrefix}_teammember"`+## Find Similar TablesSearch for tables with similar purposes but different names:@@ -171,6 +244,8 @@ function Test-ColumnExists {## Create Table Helper Function+**IMPORTANT**: Use the `$publisherPrefix` variable (retrieved via `Initialize-DataverseApi`) for all table and column schema names. Never hardcode prefixes.+```powershellfunction New-DataverseTable {param(@@ -178,7 +253,7 @@ function New-DataverseTable {[string]$DisplayName,[string]$PluralDisplayName,[string]$Description = "",- [string]$PrimaryColumnName = "cr_name",+ [string]$PrimaryColumnName = "${publisherPrefix}_name",[string]$PrimaryColumnDisplayName = "Name")@@ -231,7 +306,7 @@ function New-DataverseTableIfNotExists {[string]$DisplayName,[string]$PluralDisplayName,[string]$Description = "",- [string]$PrimaryColumnName = "cr_name",+ [string]$PrimaryColumnName = "${publisherPrefix}_name",[string]$PrimaryColumnDisplayName = "Name")@@ -360,7 +435,7 @@ function Add-DataversePicklist {}# Example usage:-# Add-DataversePicklist -TableName "cr_contactsubmission" -SchemaName "cr_status" -DisplayName "Status" -Options @(+# Add-DataversePicklist -TableName "${publisherPrefix}_contactsubmission" -SchemaName "${publisherPrefix}_status" -DisplayName "Status" -Options @(# @{ Value = 1; Label = "New" },# @{ Value = 2; Label = "Reviewed" },# @{ Value = 3; Label = "Responded" },@@ -370,60 +445,66 @@ function Add-DataversePicklist {## Common Table Templates+**NOTE**: All examples below use `$publisherPrefix` variable. Initialize it first using:+```powershell+$api = Initialize-DataverseApi -EnvironmentUrl "https://orgname.crm.dynamics.com"+$publisherPrefix = $api.PublisherPrefix # e.g., "cr", "contoso", "new"+```+### Product/Service Table```powershell-New-DataverseTable -SchemaName "cr_product" -DisplayName "Product" -PluralDisplayName "Products" -Description "Products and services offered"+New-DataverseTable -SchemaName "${publisherPrefix}_product" -DisplayName "Product" -PluralDisplayName "Products" -Description "Products and services offered"-Add-DataverseColumn -TableName "cr_product" -SchemaName "cr_description" -DisplayName "Description" -Type "Memo" -MaxLength 4000-Add-DataverseColumn -TableName "cr_product" -SchemaName "cr_price" -DisplayName "Price" -Type "Money"-Add-DataverseColumn -TableName "cr_product" -SchemaName "cr_imageurl" -DisplayName "Image URL" -Type "Url"-Add-DataverseColumn -TableName "cr_product" -SchemaName "cr_isactive" -DisplayName "Is Active" -Type "Boolean"+Add-DataverseColumn -TableName "${publisherPrefix}_product" -SchemaName "${publisherPrefix}_description" -DisplayName "Description" -Type "Memo" -MaxLength 4000+Add-DataverseColumn -TableName "${publisherPrefix}_product" -SchemaName "${publisherPrefix}_price" -DisplayName "Price" -Type "Money"+Add-DataverseColumn -TableName "${publisherPrefix}_product" -SchemaName "${publisherPrefix}_imageurl" -DisplayName "Image URL" -Type "Url"+Add-DataverseColumn -TableName "${publisherPrefix}_product" -SchemaName "${publisherPrefix}_isactive" -DisplayName "Is Active" -Type "Boolean"```### Team Member Table```powershell-New-DataverseTable -SchemaName "cr_teammember" -DisplayName "Team Member" -PluralDisplayName "Team Members" -Description "Team members displayed on the website"--Add-DataverseColumn -TableName "cr_teammember" -SchemaName "cr_title" -DisplayName "Job Title" -Type "String"-Add-DataverseColumn -TableName "cr_teammember" -SchemaName "cr_email" -DisplayName "Email" -Type "Email"-Add-DataverseColumn -TableName "cr_teammember" -SchemaName "cr_bio" -DisplayName "Bio" -Type "Memo" -MaxLength 4000-Add-DataverseColumn -TableName "cr_teammember" -SchemaName "cr_photourl" -DisplayName "Photo URL" -Type "Url"-Add-DataverseColumn -TableName "cr_teammember" -SchemaName "cr_linkedin" -DisplayName "LinkedIn" -Type "Url"-Add-DataverseColumn -TableName "cr_teammember" -SchemaName "cr_displayorder" -DisplayName "Display Order" -Type "Integer"+New-DataverseTable -SchemaName "${publisherPrefix}_teammember" -DisplayName "Team Member" -PluralDisplayName "Team Members" -Description "Team members displayed on the website"++Add-DataverseColumn -TableName "${publisherPrefix}_teammember" -SchemaName "${publisherPrefix}_title" -DisplayName "Job Title" -Type "String"+Add-DataverseColumn -TableName "${publisherPrefix}_teammember" -SchemaName "${publisherPrefix}_email" -DisplayName "Email" -Type "Email"+Add-DataverseColumn -TableName "${publisherPrefix}_teammember" -SchemaName "${publisherPrefix}_bio" -DisplayName "Bio" -Type "Memo" -MaxLength 4000+Add-DataverseColumn -TableName "${publisherPrefix}_teammember" -SchemaName "${publisherPrefix}_photourl" -DisplayName "Photo URL" -Type "Url"+Add-DataverseColumn -TableName "${publisherPrefix}_teammember" -SchemaName "${publisherPrefix}_linkedin" -DisplayName "LinkedIn" -Type "Url"+Add-DataverseColumn -TableName "${publisherPrefix}_teammember" -SchemaName "${publisherPrefix}_displayorder" -DisplayName "Display Order" -Type "Integer"```### Testimonial Table```powershell-New-DataverseTable -SchemaName "cr_testimonial" -DisplayName "Testimonial" -PluralDisplayName "Testimonials" -Description "Customer testimonials and reviews"--Add-DataverseColumn -TableName "cr_testimonial" -SchemaName "cr_quote" -DisplayName "Quote" -Type "Memo" -MaxLength 2000-Add-DataverseColumn -TableName "cr_testimonial" -SchemaName "cr_company" -DisplayName "Company" -Type "String"-Add-DataverseColumn -TableName "cr_testimonial" -SchemaName "cr_role" -DisplayName "Role" -Type "String"-Add-DataverseColumn -TableName "cr_testimonial" -SchemaName "cr_rating" -DisplayName "Rating" -Type "Integer"-Add-DataverseColumn -TableName "cr_testimonial" -SchemaName "cr_photourl" -DisplayName "Photo URL" -Type "Url"-Add-DataverseColumn -TableName "cr_testimonial" -SchemaName "cr_isactive" -DisplayName "Is Active" -Type "Boolean"+New-DataverseTable -SchemaName "${publisherPrefix}_testimonial" -DisplayName "Testimonial" -PluralDisplayName "Testimonials" -Description "Customer testimonials and reviews"++Add-DataverseColumn -TableName "${publisherPrefix}_testimonial" -SchemaName "${publisherPrefix}_quote" -DisplayName "Quote" -Type "Memo" -MaxLength 2000+Add-DataverseColumn -TableName "${publisherPrefix}_testimonial" -SchemaName "${publisherPrefix}_company" -DisplayName "Company" -Type "String"+Add-DataverseColumn -TableName "${publisherPrefix}_testimonial" -SchemaName "${publisherPrefix}_role" -DisplayName "Role" -Type "String"+Add-DataverseColumn -TableName "${publisherPrefix}_testimonial" -SchemaName "${publisherPrefix}_rating" -DisplayName "Rating" -Type "Integer"+Add-DataverseColumn -TableName "${publisherPrefix}_testimonial" -SchemaName "${publisherPrefix}_photourl" -DisplayName "Photo URL" -Type "Url"+Add-DataverseColumn -TableName "${publisherPrefix}_testimonial" -SchemaName "${publisherPrefix}_isactive" -DisplayName "Is Active" -Type "Boolean"```### Contact Submission Table```powershell-New-DataverseTable -SchemaName "cr_contactsubmission" -DisplayName "Contact Submission" -PluralDisplayName "Contact Submissions" -Description "Contact form submissions from the website"+New-DataverseTable -SchemaName "${publisherPrefix}_contactsubmission" -DisplayName "Contact Submission" -PluralDisplayName "Contact Submissions" -Description "Contact form submissions from the website"-Add-DataverseColumn -TableName "cr_contactsubmission" -SchemaName "cr_email" -DisplayName "Email" -Type "Email"-Add-DataverseColumn -TableName "cr_contactsubmission" -SchemaName "cr_message" -DisplayName "Message" -Type "Memo" -MaxLength 4000-Add-DataverseColumn -TableName "cr_contactsubmission" -SchemaName "cr_submissiondate" -DisplayName "Submission Date" -Type "DateTime"+Add-DataverseColumn -TableName "${publisherPrefix}_contactsubmission" -SchemaName "${publisherPrefix}_email" -DisplayName "Email" -Type "Email"+Add-DataverseColumn -TableName "${publisherPrefix}_contactsubmission" -SchemaName "${publisherPrefix}_message" -DisplayName "Message" -Type "Memo" -MaxLength 4000+Add-DataverseColumn -TableName "${publisherPrefix}_contactsubmission" -SchemaName "${publisherPrefix}_submissiondate" -DisplayName "Submission Date" -Type "DateTime"```### FAQ Table```powershell-New-DataverseTable -SchemaName "cr_faq" -DisplayName "FAQ" -PluralDisplayName "FAQs" -Description "Frequently asked questions" -PrimaryColumnName "cr_question" -PrimaryColumnDisplayName "Question"+New-DataverseTable -SchemaName "${publisherPrefix}_faq" -DisplayName "FAQ" -PluralDisplayName "FAQs" -Description "Frequently asked questions" -PrimaryColumnName "${publisherPrefix}_question" -PrimaryColumnDisplayName "Question"-Add-DataverseColumn -TableName "cr_faq" -SchemaName "cr_answer" -DisplayName "Answer" -Type "Memo" -MaxLength 4000-Add-DataverseColumn -TableName "cr_faq" -SchemaName "cr_category" -DisplayName "Category" -Type "String"-Add-DataverseColumn -TableName "cr_faq" -SchemaName "cr_displayorder" -DisplayName "Display Order" -Type "Integer"-Add-DataverseColumn -TableName "cr_faq" -SchemaName "cr_isactive" -DisplayName "Is Active" -Type "Boolean"+Add-DataverseColumn -TableName "${publisherPrefix}_faq" -SchemaName "${publisherPrefix}_answer" -DisplayName "Answer" -Type "Memo" -MaxLength 4000+Add-DataverseColumn -TableName "${publisherPrefix}_faq" -SchemaName "${publisherPrefix}_category" -DisplayName "Category" -Type "String"+Add-DataverseColumn -TableName "${publisherPrefix}_faq" -SchemaName "${publisherPrefix}_displayorder" -DisplayName "Display Order" -Type "Integer"+Add-DataverseColumn -TableName "${publisherPrefix}_faq" -SchemaName "${publisherPrefix}_isactive" -DisplayName "Is Active" -Type "Boolean"```diff --git a/plugins/power-pages/skills/setup-dataverse/troubleshooting.md b/plugins/power-pages/skills/setup-dataverse/references/troubleshooting.mdsimilarity index 72%rename from plugins/power-pages/skills/setup-dataverse/troubleshooting.mdrename to plugins/power-pages/skills/setup-dataverse/references/troubleshooting.mdindex b811f1f80..8efc7ddb3 100644--- a/plugins/power-pages/skills/setup-dataverse/troubleshooting.md+++ b/plugins/power-pages/skills/setup-dataverse/references/troubleshooting.md@@ -1,7 +1,5 @@# Troubleshooting-This document covers common issues and solutions when setting up Dataverse tables.-## Existing Table Detection Issues### Tables not found@@ -11,15 +9,19 @@ This document covers common issues and solutions when setting up Dataverse table### Wrong publisher prefix-Tables may have different prefixes depending on the solution:+Tables may have different prefixes depending on the solution. **Always use `Initialize-DataverseApi` to fetch the correct prefix dynamically:**```powershell+# Get the default publisher prefix+$api = Initialize-DataverseApi -EnvironmentUrl $envUrl+$publisherPrefix = $api.PublisherPrefix # e.g., "cr", "contoso", "new"+# Search for tables with any custom prefix$allCustomTables = Invoke-RestMethod -Uri "$baseUrl/EntityDefinitions?`$filter=IsCustomEntity eq true" -Headers $headers$allCustomTables.value | ForEach-Object { Write-Host $_.SchemaName }```-Common prefixes: `cr_`, `new_`, `contoso_`, `msft_`+Common prefixes: `cr_`, `new_`, `contoso_`, `msft_` - but always fetch dynamically to ensure consistency.### System tables included@@ -39,7 +41,7 @@ Table logical names are case-insensitive but schema names preserve case. AlwaysIf the existing table's schema is too different:-- Consider creating a new table with a unique name (e.g., `cr_site_category` instead of `cr_category`)+- Consider creating a new table with a unique name (e.g., `${publisherPrefix}_site_category` instead of `${publisherPrefix}_category`)- Or extend the existing table and use only the columns you need### Column type mismatch@@ -55,7 +57,7 @@ Cannot change column types after creation. Options:Verify existing relationships don't prevent your intended lookups:```powershell-Get-TableRelationships -TableLogicalName "cr_product"+Get-TableRelationships -TableLogicalName "${publisherPrefix}_product"```### Missing required columns on reused table@@ -138,7 +140,7 @@ Error: "The schema name is invalid"**Solutions:**-- Verify schema name uses valid publisher prefix (e.g., `cr_`)+- Verify schema name uses the correct publisher prefix from `Initialize-DataverseApi` (e.g., `${publisherPrefix}_tablename`)- Schema names must start with a letter- Only alphanumeric characters and underscores allowed- Maximum 128 characters@@ -175,7 +177,7 @@ Ensure all required metadata fields are included:### Referenced entity not found```text-Error: "Referenced entity 'cr_category' not found"+Error: "Referenced entity '{prefix}_category' not found"```**Solutions:**@@ -183,6 +185,7 @@ Error: "Referenced entity 'cr_category' not found"- Ensure the target table exists BEFORE creating the lookup- Check creation order: TIER 0 tables must exist before TIER 1, etc.- Verify the table logical name is correct (case-insensitive)+- Ensure you're using the correct publisher prefix from `Initialize-DataverseApi`### Duplicate relationship name@@ -213,10 +216,10 @@ Error: "Invalid target entity for relationship"```powershell# Step 1: Create table-New-DataverseTable -SchemaName "cr_employee" ...+New-DataverseTable -SchemaName "${publisherPrefix}_employee" ...# Step 2: Add self-referential lookup (table now exists)-Add-DataverseLookup -SourceTable "cr_employee" -TargetTable "cr_employee" ...+Add-DataverseLookup -SourceTable "${publisherPrefix}_employee" -TargetTable "${publisherPrefix}_employee" ...```## Sample Data Insertion Fails@@ -244,33 +247,34 @@ Error: "Invalid @odata.bind value"Format must be exactly: `/entitysetname(guid)````powershell-# Correct-"[email protected]" = "/cr_categories(12345678-1234-1234-1234-123456789012)"+# Correct (using $publisherPrefix variable)+"${publisherPrefix}[email protected]" = "/${publisherPrefix}_categories(12345678-1234-1234-1234-123456789012)"# Wrong - missing leading slash-"[email protected]" = "cr_categories(12345678-1234-1234-1234-123456789012)"+"${publisherPrefix}[email protected]" = "${publisherPrefix}_categories(12345678-1234-1234-1234-123456789012)"# Wrong - using logical name instead of entity set name-"[email protected]" = "/cr_category(12345678-1234-1234-1234-123456789012)"+"${publisherPrefix}[email protected]" = "/${publisherPrefix}_category(12345678-1234-1234-1234-123456789012)"```### Entity set not found```text-Error: "Resource not found for segment 'cr_product'"+Error: "Resource not found for segment '{prefix}_product'"```**Solutions:**Use the plural entity set name, not the logical name:-- Table `cr_product` has entity set `cr_products` (usually adds 's')-- Table `cr_category` has entity set `cr_categories` (adds 'ies')+- Table `{prefix}_product` has entity set `{prefix}_products` (usually adds 's')+- Table `{prefix}_category` has entity set `{prefix}_categories` (adds 'ies')Find the correct entity set name:```powershell-$table = Invoke-RestMethod -Uri "$baseUrl/EntityDefinitions(LogicalName='cr_product')?`$select=EntitySetName" -Headers $headers+$tableName = "${publisherPrefix}_product"+$table = Invoke-RestMethod -Uri "$baseUrl/EntityDefinitions(LogicalName='$tableName')?`$select=EntitySetName" -Headers $headersWrite-Host "Entity set name: $($table.EntitySetName)"```@@ -289,9 +293,9 @@ If reusing tables, always query for current record IDs; don't use cached values:```powershell# Always get fresh IDs before inserting dependent records-$categories = Invoke-RestMethod -Uri "$baseUrl/cr_categories?`$select=cr_categoryid,cr_name" -Headers $headers+$categories = Invoke-RestMethod -Uri "$baseUrl/${publisherPrefix}_categories?`$select=${publisherPrefix}_categoryid,${publisherPrefix}_name" -Headers $headers$categoryIds = @{}-$categories.value | ForEach-Object { $categoryIds[$_.cr_name] = $_.cr_categoryid }+$categories.value | ForEach-Object { $categoryIds[$_."${publisherPrefix}_name"] = $_."${publisherPrefix}_categoryid" }```### Data format differences@@ -308,9 +312,9 @@ When reusing tables, verify that lookup values still exist:```powershell# Check for orphaned references-$products = Invoke-RestMethod -Uri "$baseUrl/cr_products?`$select=cr_name&`$expand=cr_categoryid(`$select=cr_name)" -Headers $headers-$products.value | Where-Object { $_.cr_categoryid -eq $null } | ForEach-Object {- Write-Host "Orphaned product (no category): $($_.cr_name)" -ForegroundColor Yellow+$products = Invoke-RestMethod -Uri "$baseUrl/${publisherPrefix}_products?`$select=${publisherPrefix}_name&`$expand=${publisherPrefix}_categoryid(`$select=${publisherPrefix}_name)" -Headers $headers+$products.value | Where-Object { $_."${publisherPrefix}_categoryid" -eq $null } | ForEach-Object {+ Write-Host "Orphaned product (no category): $($_."${publisherPrefix}_name")" -ForegroundColor Yellow}```@@ -318,7 +322,8 @@ $products.value | Where-Object { $_.cr_categoryid -eq $null } | ForEach-Object {```powershell# Check if a relationship exists-$relations = Invoke-RestMethod -Uri "$baseUrl/RelationshipDefinitions?`$filter=SchemaName eq 'cr_category_product'" -Headers $headers+$relationshipName = "${publisherPrefix}_category_product"+$relations = Invoke-RestMethod -Uri "$baseUrl/RelationshipDefinitions?`$filter=SchemaName eq '$relationshipName'" -Headers $headersif ($relations.value.Count -gt 0) {Write-Host "Relationship exists"} else {@@ -326,7 +331,8 @@ if ($relations.value.Count -gt 0) {}# List all relationships for a table-$tableRelations = Invoke-RestMethod -Uri "$baseUrl/EntityDefinitions(LogicalName='cr_product')/OneToManyRelationships" -Headers $headers+$tableName = "${publisherPrefix}_product"+$tableRelations = Invoke-RestMethod -Uri "$baseUrl/EntityDefinitions(LogicalName='$tableName')/OneToManyRelationships" -Headers $headers$tableRelations.value | ForEach-Object { Write-Host $_.SchemaName }```diff --git a/plugins/power-pages/skills/setup-dataverse/sample-data-reference.md b/plugins/power-pages/skills/setup-dataverse/sample-data-reference.mddeleted file mode 100644index 3355950f1..000000000--- a/plugins/power-pages/skills/setup-dataverse/sample-data-reference.md+++ /dev/null@@ -1,426 +0,0 @@-# Sample Data Reference--This document covers inserting sample data into Dataverse tables while maintaining referential integrity.--## Data Insertion Protocol--```text-SAMPLE DATA INSERTION ORDER (WITH EXISTING DATA CHECKS)--0. Check for existing data in reused tables- - Query record counts in each table- - If data exists, ask user: skip, add more, or replace- - Collect existing record IDs for use as foreign keys--1. Insert TIER 0 data (reference/lookup tables)- - Categories, Statuses, Departments, etc.- - Skip if records with same name already exist- - Store the returned/existing record IDs for use in foreign keys--2. Insert TIER 1 data with valid lookups- - Products (with Category lookup)- - Team Members (with Department lookup)- - Use the IDs from step 1 for lookup values--3. Insert TIER 2 data with valid lookups- - Testimonials (with Product lookup)- - Contact Submissions (with Status lookup)- - Use IDs from steps 1 and 2 for lookup values--IMPORTANT: Never insert records with invalid/non-existent lookup values!-```--## Check Existing Data--```powershell-function Get-ExistingRecordCount {- param([string]$EntitySetName)-- $result = Invoke-RestMethod -Uri "$baseUrl/$EntitySetName/`$count" -Headers $headers- return [int]$result-}--function Get-ExistingRecordByName {- param(- [string]$EntitySetName,- [string]$NameColumn, # Usually "cr_name" or the primary name attribute- [string]$NameValue- )-- $filter = "$NameColumn eq '$NameValue'"- $result = Invoke-RestMethod -Uri "$baseUrl/$EntitySetName`?`$filter=$filter&`$top=1" -Headers $headers-- if ($result.value.Count -gt 0) {- return $result.value[0]- }- return $null-}--# Check existing data counts-Write-Host "`nChecking existing data in tables..." -ForegroundColor Cyan-$existingDataCounts = @{- "cr_categories" = Get-ExistingRecordCount -EntitySetName "cr_categories"- "cr_statuses" = Get-ExistingRecordCount -EntitySetName "cr_statuses"- "cr_departments" = Get-ExistingRecordCount -EntitySetName "cr_departments"- "cr_products" = Get-ExistingRecordCount -EntitySetName "cr_products"- "cr_teammembers" = Get-ExistingRecordCount -EntitySetName "cr_teammembers"- "cr_testimonials" = Get-ExistingRecordCount -EntitySetName "cr_testimonials"- "cr_contactsubmissions" = Get-ExistingRecordCount -EntitySetName "cr_contactsubmissions"-}--Write-Host "`nExisting record counts:" -ForegroundColor Yellow-$existingDataCounts.GetEnumerator() | ForEach-Object {- $status = if ($_.Value -gt 0) { "[!]" } else { "[OK]" }- Write-Host " $status $($_.Key): $($_.Value) records"-}-```--## Create Record Helper Function--```powershell-function New-DataverseRecord {- param(- [string]$EntitySetName,- [hashtable]$Data- )-- $body = $Data | ConvertTo-Json -Depth 5- $response = Invoke-RestMethod -Uri "$baseUrl/$EntitySetName" -Method Post -Headers $headers -Body $body- return $response-}-```--## Safe Record Creation (Skip If Exists)--```powershell-function New-DataverseRecordIfNotExists {- param(- [string]$EntitySetName,- [hashtable]$Data,- [string]$NameColumn = "cr_name"- )-- $nameValue = $Data[$NameColumn]- $existing = Get-ExistingRecordByName -EntitySetName $EntitySetName -NameColumn $NameColumn -NameValue $nameValue-- if ($existing) {- Write-Host " [SKIP] Record '$nameValue' already exists - using existing" -ForegroundColor Yellow- return @{- Skipped = $true- Record = $existing- }- }-- Write-Host " [CREATE] Creating record '$nameValue'..." -ForegroundColor Cyan- $body = $Data | ConvertTo-Json -Depth 5- $response = Invoke-RestMethod -Uri "$baseUrl/$EntitySetName" -Method Post -Headers $headers -Body $body- Write-Host " [OK] Record '$nameValue' created" -ForegroundColor Green-- return @{- Skipped = $false- Record = $response- }-}-```--## Foreign Key Syntax--When inserting records with lookup values, use the `@odata.bind` syntax:--```powershell-# Format: "[email protected]" = "/entitysetname(guid)"--$product = @{- cr_name = "Professional Consultation"- cr_description = "One-on-one consultation with our expert team."- cr_price = 299.99- # Reference category by its ID- "[email protected]" = "/cr_categories($categoryId)"-}-```--## Complete Sample Data Script--```powershell-# ============================================-# TIER 0: Insert Reference/Lookup Data FIRST-# ============================================--Write-Host "`n=== TIER 0: Processing Reference/Lookup Data ===" -ForegroundColor Magenta--# --- Categories ----$categoryIds = @{}--$categories = @(- @{ cr_name = "Services"; cr_description = "Professional services"; cr_displayorder = 1; cr_isactive = $true },- @{ cr_name = "Packages"; cr_description = "Bundled offerings"; cr_displayorder = 2; cr_isactive = $true },- @{ cr_name = "Products"; cr_description = "Physical and digital products"; cr_displayorder = 3; cr_isactive = $true }-)--Write-Host "Processing categories..." -ForegroundColor Cyan-foreach ($cat in $categories) {- $result = New-DataverseRecordIfNotExists -EntitySetName "cr_categories" -Data $cat -NameColumn "cr_name"- $categoryIds[$cat.cr_name] = $result.Record.cr_categoryid-}--# --- Statuses ----$statusIds = @{}--$statuses = @(- @{ cr_name = "New"; cr_displayorder = 1 },- @{ cr_name = "Reviewed"; cr_displayorder = 2 },- @{ cr_name = "Responded"; cr_displayorder = 3 },- @{ cr_name = "Closed"; cr_displayorder = 4 }-)--Write-Host "`nProcessing statuses..." -ForegroundColor Cyan-foreach ($status in $statuses) {- $result = New-DataverseRecordIfNotExists -EntitySetName "cr_statuses" -Data $status -NameColumn "cr_name"- $statusIds[$status.cr_name] = $result.Record.cr_statusid-}--# --- Departments ----$departmentIds = @{}--$departments = @(- @{ cr_name = "Executive"; cr_code = "EXEC" },- @{ cr_name = "Engineering"; cr_code = "ENG" },- @{ cr_name = "Customer Success"; cr_code = "CS" },- @{ cr_name = "Sales"; cr_code = "SALES" }-)--Write-Host "`nProcessing departments..." -ForegroundColor Cyan-foreach ($dept in $departments) {- $result = New-DataverseRecordIfNotExists -EntitySetName "cr_departments" -Data $dept -NameColumn "cr_name"- $departmentIds[$dept.cr_name] = $result.Record.cr_departmentid-}--# ============================================-# TIER 1: Insert Primary Entity Data-# ============================================--Write-Host "`n=== TIER 1: Processing Primary Entity Data ===" -ForegroundColor Magenta--# --- Products (with Category lookup) ----$productIds = @{}--$products = @(- @{- cr_name = "Professional Consultation"- cr_description = "One-on-one consultation with our expert team."- cr_price = 299.99- cr_imageurl = "https://images.unsplash.com/photo-1553877522-43269d4ea984?w=400"- cr_isactive = $true- "[email protected]" = "/cr_categories($($categoryIds['Services']))"- },- @{- cr_name = "Enterprise Solution Package"- cr_description = "Complete enterprise solution with 12 months support."- cr_price = 4999.99- cr_imageurl = "https://images.unsplash.com/photo-1460925895917-afdab827c52f?w=400"- cr_isactive = $true- "[email protected]" = "/cr_categories($($categoryIds['Packages']))"- },- @{- cr_name = "Starter Kit"- cr_description = "Perfect for small businesses getting started."- cr_price = 99.99- cr_imageurl = "https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=400"- cr_isactive = $true- "[email protected]" = "/cr_categories($($categoryIds['Packages']))"- }-)--Write-Host "Processing products..." -ForegroundColor Cyan-foreach ($product in $products) {- $result = New-DataverseRecordIfNotExists -EntitySetName "cr_products" -Data $product -NameColumn "cr_name"- $productIds[$product.cr_name] = $result.Record.cr_productid-}--# --- Team Members (with Department lookup) ----$teamMemberIds = @{}--$team = @(- @{- cr_name = "Emily Rodriguez"- cr_title = "Chief Executive Officer"- cr_email = "[email protected]"- cr_bio = "Emily has over 15 years of experience in technology leadership."- cr_photourl = "https://images.unsplash.com/photo-1573496359142-b8d87734a5a2?w=300"- cr_linkedin = "https://linkedin.com/in/emilyrodriguez"- cr_displayorder = 1- "[email protected]" = "/cr_departments($($departmentIds['Executive']))"- },- @{- cr_name = "David Kim"- cr_title = "Chief Technology Officer"- cr_email = "[email protected]"- cr_bio = "David brings deep technical expertise from his decade at leading tech companies."- cr_photourl = "https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=300"- cr_linkedin = "https://linkedin.com/in/davidkim"- cr_displayorder = 2- "[email protected]" = "/cr_departments($($departmentIds['Engineering']))"- },- @{- cr_name = "Lisa Thompson"- cr_title = "Head of Customer Success"- cr_email = "[email protected]"- cr_bio = "Lisa ensures our customers achieve their goals."- cr_photourl = "https://images.unsplash.com/photo-1580489944761-15a19d654956?w=300"- cr_linkedin = "https://linkedin.com/in/lisathompson"- cr_displayorder = 3- "[email protected]" = "/cr_departments($($departmentIds['Customer Success']))"- }-)--Write-Host "`nProcessing team members..." -ForegroundColor Cyan-foreach ($member in $team) {- $result = New-DataverseRecordIfNotExists -EntitySetName "cr_teammembers" -Data $member -NameColumn "cr_name"- $teamMemberIds[$member.cr_name] = $result.Record.cr_teammemberid-}--# ============================================-# TIER 2: Insert Dependent Data-# ============================================--Write-Host "`n=== TIER 2: Processing Dependent Data ===" -ForegroundColor Magenta--# --- Contact Submissions (with Status lookup) ----$contacts = @(- @{- cr_name = "John Smith"- cr_email = "[email protected]"- cr_message = "I'm interested in learning more about your services."- cr_submissiondate = (Get-Date).ToString("yyyy-MM-ddTHH:mm:ssZ")- "[email protected]" = "/cr_statuses($($statusIds['New']))"- },- @{- cr_name = "Sarah Johnson"- cr_email = "[email protected]"- cr_message = "Looking for a partner for our upcoming project."- cr_submissiondate = (Get-Date).AddDays(-2).ToString("yyyy-MM-ddTHH:mm:ssZ")- "[email protected]" = "/cr_statuses($($statusIds['Reviewed']))"- },- @{- cr_name = "Michael Chen"- cr_email = "[email protected]"- cr_message = "Questions about pricing and availability."- cr_submissiondate = (Get-Date).AddDays(-5).ToString("yyyy-MM-ddTHH:mm:ssZ")- "[email protected]" = "/cr_statuses($($statusIds['Responded']))"- }-)--Write-Host "Processing contact submissions..." -ForegroundColor Cyan-foreach ($contact in $contacts) {- New-DataverseRecordIfNotExists -EntitySetName "cr_contactsubmissions" -Data $contact -NameColumn "cr_name"-}--# --- Testimonials (with optional Product lookup) ----$testimonials = @(- @{- cr_name = "Amanda Foster"- cr_quote = "Their solution increased our efficiency by 40%."- cr_company = "TechStart Inc."- cr_role = "Operations Director"- cr_rating = 5- cr_photourl = "https://images.unsplash.com/photo-1494790108377-be9c29b29330?w=200"- cr_isactive = $true- "[email protected]" = "/cr_products($($productIds['Enterprise Solution Package']))"- },- @{- cr_name = "Robert Martinez"- cr_quote = "The best investment we've made this year."- cr_company = "Global Solutions Ltd"- cr_role = "CEO"- cr_rating = 5- cr_photourl = "https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=200"- cr_isactive = $true- "[email protected]" = "/cr_products($($productIds['Professional Consultation']))"- },- @{- cr_name = "Jennifer Wu"- cr_quote = "Delivered beyond expectations. Highly recommend."- cr_company = "Innovate Partners"- cr_role = "Managing Partner"- cr_rating = 5- cr_photourl = "https://images.unsplash.com/photo-1438761681033-6461ffad8d80?w=200"- cr_isactive = $true- # General testimonial - no specific product linked- }-)--Write-Host "`nProcessing testimonials..." -ForegroundColor Cyan-foreach ($testimonial in $testimonials) {- New-DataverseRecordIfNotExists -EntitySetName "cr_testimonials" -Data $testimonial -NameColumn "cr_name"-}--Write-Host "`n=== Sample data processing complete ===" -ForegroundColor Green-```--## Verify Data and Relationships--```powershell-# Verify products with their categories (expanded relationship)-Write-Host "Products with Categories:" -ForegroundColor Cyan-$products = Invoke-RestMethod -Uri "$baseUrl/cr_products?`$select=cr_name,cr_price&`$expand=cr_categoryid(`$select=cr_name)" -Headers $headers-$products.value | ForEach-Object {- Write-Host " $($_.cr_name) - `$$($_.cr_price) - Category: $($_.cr_categoryid.cr_name)"-}--# Verify team members with their departments-Write-Host "`nTeam Members with Departments:" -ForegroundColor Cyan-$members = Invoke-RestMethod -Uri "$baseUrl/cr_teammembers?`$select=cr_name,cr_title&`$expand=cr_departmentid(`$select=cr_name)" -Headers $headers-$members.value | ForEach-Object {- Write-Host " $($_.cr_name) ($($_.cr_title)) - Dept: $($_.cr_departmentid.cr_name)"-}--# Verify contact submissions with their statuses-Write-Host "`nContact Submissions with Statuses:" -ForegroundColor Cyan-$submissions = Invoke-RestMethod -Uri "$baseUrl/cr_contactsubmissions?`$select=cr_name,cr_email&`$expand=cr_statusid(`$select=cr_name)" -Headers $headers-$submissions.value | ForEach-Object {- Write-Host " $($_.cr_name) ($($_.cr_email)) - Status: $($_.cr_statusid.cr_name)"-}--# Verify testimonials with their linked products-Write-Host "`nTestimonials with Products:" -ForegroundColor Cyan-$testimonials = Invoke-RestMethod -Uri "$baseUrl/cr_testimonials?`$select=cr_name,cr_company&`$expand=cr_productid(`$select=cr_name)" -Headers $headers-$testimonials.value | ForEach-Object {- $productName = if ($_.cr_productid) { $_.cr_productid.cr_name } else { "(General)" }- Write-Host " $($_.cr_name) from $($_.cr_company) - Product: $productName"-}-```--## Update Records--```powershell-function Update-DataverseRecord {- param(- [string]$EntitySetName,- [string]$RecordId,- [hashtable]$Data- )-- $body = $Data | ConvertTo-Json -Depth 5- Invoke-RestMethod -Uri "$baseUrl/$EntitySetName($RecordId)" -Method Patch -Headers $headers -Body $body-}--# Example: Update a product's price-Update-DataverseRecord -EntitySetName "cr_products" -RecordId $productIds['Starter Kit'] -Data @{- cr_price = 129.99-}-```--## Delete Records--```powershell-function Remove-DataverseRecord {- param(- [string]$EntitySetName,- [string]$RecordId- )-- Invoke-RestMethod -Uri "$baseUrl/$EntitySetName($RecordId)" -Method Delete -Headers $headers-}--# CAUTION: Delete records in reverse dependency order (TIER 2 -> TIER 1 -> TIER 0)-```diff --git a/plugins/power-pages/skills/setup-webapi/SKILL.md b/plugins/power-pages/skills/setup-webapi/SKILL.mdindex 5ca8b43e1..ac4864d1f 100644--- a/plugins/power-pages/skills/setup-webapi/SKILL.md+++ b/plugins/power-pages/skills/setup-webapi/SKILL.md@@ -1,473 +1,115 @@----description: Configure Web API access, table permissions, entity permissions, and web roles for Power Pages. Use this skill when you need to set up table permissions, create entity permissions, configure web roles, enable API access, set CRUD permissions (read/write/create/delete), create site settings for Web API, or update frontend code to fetch data from Dataverse tables.+name: setting-up-web-api+description: Configures Web API access, table permissions, web roles, and site settings for Power Pages. Use when setting up table permissions, entity permissions, CRUD access, or site settings for Web API.user-invocable: true-allowed-tools: Bash(pac:*), Bash(az:*), Bash(dotnet:*)-model: sonnet+allowed-tools: ["Read", "Write", "Grep", "Glob", "Bash", "TodoWrite", "AskUserQuestion", "Skill", "Task"]+model: opus----# Setup Web API--This skill guides makers through configuring Web API access for their Power Pages site. It creates site settings to enable data access via the `/_api` endpoint and updates the frontend code to fetch data dynamically.--## Reference Documentation--This skill uses modular reference files for detailed instructions:--| File | Purpose |-|------|---------|-| [site-settings-reference.md](./site-settings-reference.md) | YAML format, naming conventions, PowerShell scripts |-| [web-roles-reference.md](./web-roles-reference.md) | Web role selection, creation, and user assignment |-| [table-permissions-reference.md](./table-permissions-reference.md) | Dataverse API for entity permissions, scopes, web roles |-| [frontend-integration-reference.md](./frontend-integration-reference.md) | Web API service code, React hooks, component patterns |-| [troubleshooting.md](./troubleshooting.md) | Common issues and solutions |--## Memory Bank--This skill uses a **memory bank** (`memory-bank.md`) to persist context across sessions.--**Follow the instructions in `${CLAUDE_PLUGIN_ROOT}/shared/memory-bank.md`** for:-- Checking and reading the memory bank before starting-- Skipping completed steps and resuming progress-- Updating the memory bank after each major step--## Workflow Overview--```text-┌─────────────────────────────────────────────────────────────────────────────┐-│ STEP 1: Resume or Start Fresh │-│ ───────────────────────────────────────────────────────────────────────── │-│ • Check memory bank for project context │-│ • Identify tables created in /setup-dataverse │-│ • Verify site is uploaded to Power Pages │-└─────────────────────────────────────────────────────────────────────────────┘- ↓-┌─────────────────────────────────────────────────────────────────────────────┐-│ STEP 2: Create Site Settings Files │-│ ───────────────────────────────────────────────────────────────────────── │-│ • Create .powerpages-site/site-settings folder structure │-│ • Generate UUID for each site setting │-│ • Enable Web API for each table (Webapi/{table}/enabled) │-│ • Configure allowed fields (Webapi/{table}/fields) │-│ 📖 See: site-settings-reference.md │-└─────────────────────────────────────────────────────────────────────────────┘- ↓-┌─────────────────────────────────────────────────────────────────────────────┐-│ STEP 3: Create Web Roles │-│ ───────────────────────────────────────────────────────────────────────── │-│ • Determine required web roles based on site features │-│ • Verify default roles exist (Anonymous, Authenticated, Administrators) │-│ • Create custom roles if needed (Customers, Partners, etc.) │-│ 📖 See: web-roles-reference.md │-└─────────────────────────────────────────────────────────────────────────────┘- ↓-┌─────────────────────────────────────────────────────────────────────────────┐-│ STEP 4: Create Table Permissions │-│ ───────────────────────────────────────────────────────────────────────── │-│ • Create entity permission records for Web API access │-│ • Configure scope (Global/Parent/Self) based on requirements │-│ • Set appropriate CRUD permissions │-│ • Associate permissions with web roles from Step 3 │-│ 📖 See: table-permissions-reference.md │-└─────────────────────────────────────────────────────────────────────────────┘- ↓-┌─────────────────────────────────────────────────────────────────────────────┐-│ STEP 5: Update Frontend Code │-│ ───────────────────────────────────────────────────────────────────────── │-│ • Create API service/utility for /_api calls │-│ • Update components to fetch data dynamically │-│ • Replace ALL mock/static data with Web API calls │-│ • Verify no hardcoded data remains for configured tables │-│ 📖 See: frontend-integration-reference.md │-└─────────────────────────────────────────────────────────────────────────────┘- ↓-┌─────────────────────────────────────────────────────────────────────────────┐-│ STEP 6: Build and Upload │-│ ───────────────────────────────────────────────────────────────────────── │-│ • Build the project │-│ • Upload to Power Pages │-│ • Verify Web API is working │-└─────────────────────────────────────────────────────────────────────────────┘-```-------## STEP 1: Resume or Start Fresh--### Check Memory Bank First--**Before asking questions**, check if a memory bank exists:--1. If continuing from `/setup-dataverse` in the same session, use the known project path-2. Otherwise, ask the user for the project path-3. Read `<PROJECT_PATH>/memory-bank.md` if it exists-4. Extract:- - Project name and framework- - Tables created in `/setup-dataverse`- - Website ID and environment URL- - Any previously configured Web API settings--If the memory bank shows `/setup-webapi` steps already completed:--- Inform the user what was done-- Ask if they want to add more tables, modify settings, or skip to next steps--### Check Context--**If continuing from setup-dataverse:**+**📋 [Shared Instructions](${CLAUDE_PLUGIN_ROOT}/shared/shared-instructions.md)** - Read before starting.-Show this message:--> **Ready for Web API Configuration!**->-> Your Dataverse tables have been created. Now let's enable Web API access so your site can fetch and modify data via the `/_api` endpoint.->-> Tables to configure: [LIST FROM MEMORY BANK]->-> Would you like to proceed?--Use the `AskUserQuestion` tool with these options:--| Option | Description |-|--------|-------------|-| **Yes, proceed** | Configure Web API for all tables |-| **Select tables** | Choose which tables to enable for Web API |-| **Show me the command** | Display `/setup-webapi` to run later |+# Setup Web API-**If starting fresh (no prior context):**+**References:** [site-settings](./references/site-settings-reference.md) | [web-roles](./references/web-roles-reference.md) | [table-permissions](./references/table-permissions-reference.md) | [troubleshooting](./references/troubleshooting.md)-Ask the user for:+## Workflow-1. Project path (where the Power Pages site is located)-2. Tables to enable for Web API (if not in memory bank)+1. **Check Context** → Read memory bank, get table name mapping from `/setup-dataverse`+2. **Create Site Settings** → `Webapi/{table}/enabled` and `fields` for each table+3. **Create Web Roles** → Verify/create Anonymous, Authenticated, custom roles+4. **Create Table Permissions** → Link to web roles with appropriate scope+5. **Build and Upload** → Deploy and verify----## STEP 2: Create Site Settings Files--**📖 Detailed reference: [site-settings-reference.md](./site-settings-reference.md)**--### Quick Summary--For each table that needs Web API access, create two site setting files:+## Step 1: Check Context-1. **Enable setting**: `Webapi-<table>-enabled.sitesetting.yml`-2. **Fields setting**: `Webapi-<table>-fields.sitesetting.yml`+Read `memory-bank.md`. **Critical**: Get the **Table Name Mapping** - use actual logical names (may differ from `{prefix}_tablename` for reused tables).-### Key Points--- Files go in `.powerpages-site/site-settings/` folder-- Each file needs a unique UUID-- **SECURITY**: Always specify explicit field names (never use `*`)-- Optionally enable `Webapi/error/innererror` for debugging--### Actions--1. Create the site-settings folder if it doesn't exist-2. Use the PowerShell `New-WebApiSiteSettings` function from the reference-3. Create settings for each table from the memory bank-4. Create error setting for development+If continuing from `/setup-dataverse`, list tables to configure. Otherwise ask for project path and tables.----## STEP 3: Create Web Roles--**📖 Detailed reference: [web-roles-reference.md](./web-roles-reference.md)**--### Quick Summary--Web roles define user groups with specific access levels. They must be created **before** table permissions because permissions are linked to roles.+## Step 2: Create Site Settings-### Key Points+See [site-settings-reference.md](./references/site-settings-reference.md).-- **Anonymous Users**: Unauthenticated visitors (public content, read-only)-- **Authenticated Users**: Signed-in users (member features, form submissions)-- **Administrators**: Full site management access-- **Custom roles**: Create for specific user groups (Customers, Partners, Employees)+For each table, create in `.powerpages-site/site-settings/`:+1. `Webapi-<table>-enabled.sitesetting.yml`+2. `Webapi-<table>-fields.sitesetting.yml` - **explicit field names only, never `*`**-### Determine Required Roles--Use this decision matrix:--| Site Feature | Required Role |-|--------------|---------------|-| Public landing page, product catalog | Anonymous Users |-| Contact form submission | Anonymous Users (create-only) |-| User dashboard, profile | Authenticated Users |-| Order history, support tickets | Custom role (e.g., Customers) |-| Partner portal | Custom role (e.g., Partners) |-| Admin panel | Administrators |--### Actions--1. Get environment URL and token (same as Step 2)-2. Get Website ID from memory bank or `pac pages list`-3. Verify default roles exist using `Get-WebRoles` function-4. Create custom roles if needed using `New-WebRole` function-5. Record role IDs for use in Step 4 (table permissions)--### Example: Create Custom Roles--```powershell-# For a customer portal-$customerRoleId = New-WebRole -Name "Customers" -WebsiteId $websiteId -Description "Registered customers"--# For a partner portal-$partnerRoleId = New-WebRole -Name "Partners" -WebsiteId $websiteId -Description "Business partners"-```+Also create authoring tool setting per [authoring-tool-reference.md](${CLAUDE_PLUGIN_ROOT}/shared/authoring-tool-reference.md).----## STEP 4: Create Table Permissions--**📖 Detailed reference: [table-permissions-reference.md](./table-permissions-reference.md)**--### Quick Summary--Table permissions control which users can access data. Create via Dataverse API and link to web roles from Step 3.--### Key Points+## Step 3: Create Web Roles-- Use **Global scope** for public data (products, FAQs)-- Use **Self scope** for user-specific data-- Link permissions to appropriate web roles created in Step 3:- - **Anonymous Users** for public access- - **Authenticated Users** for logged-in users- - **Custom roles** for specific user groups+See [web-roles-reference.md](./references/web-roles-reference.md).-### Common Patterns+Create roles **before** table permissions using YAML files in `.powerpages-site/web-roles/`.-| Data Type | Scope | Permissions | Web Role |-|-----------|-------|-------------|----------|-| Public content | Global | Read only | Anonymous Users |-| Form submissions | Global | Create only | Anonymous Users |-| User profiles | Self | Read, Write | Authenticated Users |-| Orders | Contact | Read, Write | Customers (custom) |+| Feature | Role |+|---------|------|+| Public content | Anonymous Users |+| Form submissions | Anonymous Users (create-only) |+| User dashboard | Authenticated Users |+| Customer portal | Custom role |-### Actions--1. Get environment URL and token-2. Get Website ID from memory bank or `pac pages list`-3. Get web role IDs from Step 3 or using `Get-WebRoleId` function-4. Create permissions using `New-TablePermission` function-5. Associate permissions with web roles+**Steps:**+1. Check existing roles in `.powerpages-site/web-roles/` (created after first upload)+2. Create custom role YAML files as needed:+ ```yaml+ anonymoususersrole: false+ authenticatedusersrole: false+ id: <GENERATE_UUID>+ name: Customers+ ```+3. Upload to apply: `pac pages upload-code-site`----## STEP 5: Update Frontend Code--**📖 Detailed reference: [frontend-integration-reference.md](./frontend-integration-reference.md)**--### Quick Summary--Update the frontend to use Power Pages Web API instead of mock data.--**CRITICAL**: This step is NOT complete until ALL mock/static data has been replaced with Web API calls. Do not proceed to Step 6 until verification is complete.--### Key Points--- Create `webApi.ts` service with CRUD operations-- Implement CSRF token handling for write operations-- Create typed wrappers for each entity-- Replace **ALL** static/mock data with API calls-- **VERIFY** no hardcoded data remains+## Step 4: Create Table Permissions-### CSRF Token Requirement+See [table-permissions-reference.md](./references/table-permissions-reference.md).-POST, PATCH, DELETE requests require `__RequestVerificationToken` header. The reference includes a complete token handling implementation.--### Actions--1. Create `src/services/webApi.ts` (copy from reference)-2. Create type definitions for your entities-3. Create entity-specific API wrappers-4. Optionally create `useWebApi` React hook-5. **Systematically search for ALL mock data** (see below)-6. Update each component to use Web API-7. **Delete mock data files/folders** after replacement-8. **Run verification checks** before proceeding--### Mock Data Search (REQUIRED)--You MUST search for and replace ALL mock data. Use these searches:--```powershell-# 1. Find mock data folders-Get-ChildItem -Path ./src -Directory -Recurse | Where-Object { $_.Name -match "^(mock|data|fixtures|fake|dummy)$" }+| Data Type | Scope | Permissions | Role |+|-----------|-------|-------------|------|+| Public content | Global | Read | Anonymous |+| Form submissions | Global | Create | Anonymous |+| User data | Self | Read, Write | Authenticated |-# 2. Find data files-Get-ChildItem -Path ./src -Recurse -Include "*.data.ts","*.data.js","*mock*.ts","*mock*.js"--# 3. Find inline array declarations (review each match)-Select-String -Path "src\**\*.ts","src\**\*.tsx" -Pattern "const\s+\w+\s*=\s*\[" | Where-Object { $_.Line -match "\{" }--# 4. Find JSON imports-Select-String -Path "src\**\*.ts","src\**\*.tsx" -Pattern "from ['\"].*\.json['\"]"-```--### Mock Data Verification (REQUIRED)--Before proceeding to Step 6, verify:--- [ ] No `src/data/` or `src/mock/` folders exist (or are empty)-- [ ] No `*.data.ts` or `*mock*.ts` files remain with active exports-- [ ] No components have inline hardcoded arrays for configured tables-- [ ] No JSON files are imported as data sources for configured tables-- [ ] All components displaying data use the `webApi` service-- [ ] All form components use the `webApi` service for submissions--**If any mock data remains, replace it before continuing.**--### Entity-Specific Checklist--For each table configured for Web API, verify:--| Table | Mock Data Replaced | Component Updated | Verified Working |-|-------|-------------------|-------------------|------------------|-| Products | [ ] | [ ] | [ ] |-| Team Members | [ ] | [ ] | [ ] |-| Testimonials | [ ] | [ ] | [ ] |-| FAQs | [ ] | [ ] | [ ] |-| Contact Form | [ ] | [ ] | [ ] |+Use `New-TablePermission` and link to web roles from Step 3.----## STEP 6: Build and Upload--### Build the Project--```powershell-cd <PROJECT_ROOT>-npm install # if needed-npm run build-```--### Confirm Connected Account--**IMPORTANT**: Before uploading, you MUST confirm which account the user is connected with.--1. Run the following command to show the connected account:+## Step 5: Build and Upload```powershell-pac auth list+pac auth list # Show available environments```-2. Display the connected account information to the user, including:- - The active profile (marked with `*`)- - The environment URL- - The user email/account--3. Use the `AskUserQuestion` tool to confirm:--| Question | Options |-|----------|---------|-| **You are about to upload the site to the account shown above. Do you want to proceed?** | **Yes, upload to this account** - Proceed with the upload; **No, let me switch accounts** - User will run `pac auth create` to connect to a different account |--4. **Only proceed with upload after the user confirms.** If the user selects "No", guide them to authenticate to the correct account:--```powershell-# Create new authentication profile-pac auth create-```--Then run `pac auth list` again to verify and ask for confirmation again.--### Upload to Power Pages+**Ask user which environment** to upload to using `AskUserQuestion` (show org names from auth list). Switch if needed: `pac auth select --index <n>`.+**Create skill tracking setting, build, and upload:**```powershell+New-SkillTrackingSetting -ProjectRoot $projectRoot -SkillName "SetupWebApi"+npm run build # Always build before uploadpac pages upload-code-site --rootPath "<PROJECT_ROOT>"```-### Verify the Upload--```powershell-pac pages list --verbose-```--### Test Web API Access--1. Open browser developer tools (F12)-2. Navigate to your site-3. Test a Web API call in the console:+See [authoring-tool-reference.md](${CLAUDE_PLUGIN_ROOT}/shared/authoring-tool-reference.md) for helper function.+**Test in browser console:**```javascript-fetch('/_api/cr_products')- .then(r => r.json())- .then(data => console.log('Products:', data.value))- .catch(err => console.error('Error:', err));+fetch('/_api/{prefix}_products').then(r => r.json()).then(d => console.log(d.value))```-### Troubleshooting--**📖 If you encounter issues, see: [troubleshooting.md](./troubleshooting.md)**+Update memory-bank.md. Cleanup per [cleanup-reference.md](${CLAUDE_PLUGIN_ROOT}/shared/cleanup-reference.md).----## STEP 7: Cleanup Helper Files--**📖 See: [cleanup-reference.md](${CLAUDE_PLUGIN_ROOT}/shared/cleanup-reference.md)**--Remove any temporary helper files created during this skill's execution. Verify the setup is working before cleanup.-------## Update Memory Bank--After completing this skill, update `memory-bank.md`:--```markdown-### /setup-webapi-- [x] Site settings folder created-- [x] Web API enabled for tables: [LIST]-- [x] Web roles verified/created-- [x] Table permissions created-- [x] Frontend code updated with Web API service-- [x] All mock/static data replaced with Web API calls-- [x] Project built successfully-- [x] Uploaded to Power Pages-- [x] Web API verified working--## Created Resources+## Next Steps-### Site Settings+Run `/integrate-webapi` to connect frontend code to the Web API (replace mock data with API calls).-| Setting | Value | File |-|---------|-------|------|-| Webapi/cr_product/enabled | true | Webapi-cr_product-enabled.sitesetting.yml |-| [ADD MORE AS CREATED] |--### Web Roles--| Role Name | Role ID | Type |-|-----------|---------|------|-| Anonymous Users | [GUID] | Default |-| Authenticated Users | [GUID] | Default |-| Customers | [GUID] | Custom |-| [ADD MORE AS CREATED] |--### Table Permissions--| Table | Scope | Permissions | Web Role |-|-------|-------|-------------|----------|-| cr_product | Global | Read | Anonymous Users |-| [ADD MORE AS CREATED] |--### Modified Files--| File | Changes |-|------|---------|-| src/services/webApi.ts | Created Power Pages Web API service |-| [ADD MORE AS MODIFIED] |--### Removed/Replaced Mock Data--| Location | Description | Replaced With |-|----------|-------------|---------------|-| src/data/products.ts | Static product array | productsApi.getActive() |-| [ADD MORE AS REPLACED] |--## Current Status--**Last Action**: Web API configured and site uploaded--**Next Step**: Test all Web API endpoints and verify data displays correctly-```+Then run `/setup-auth` to add authentication and authorization.diff --git a/plugins/power-pages/skills/setup-webapi/site-settings-reference.md b/plugins/power-pages/skills/setup-webapi/references/site-settings-reference.mdsimilarity index 62%rename from plugins/power-pages/skills/setup-webapi/site-settings-reference.mdrename to plugins/power-pages/skills/setup-webapi/references/site-settings-reference.mdindex 438db370d..09f7cfe29 100644--- a/plugins/power-pages/skills/setup-webapi/site-settings-reference.md+++ b/plugins/power-pages/skills/setup-webapi/references/site-settings-reference.md@@ -1,18 +1,20 @@# Site Settings Reference-This document describes how to create and configure site settings for Power Pages code sites.-## Folder StructureSite settings in Power Pages code sites are stored in the `.powerpages-site/site-settings` folder. Each setting is a separate YAML file with a unique ID.+**IMPORTANT**: Use the **actual table logical names** from the `$tableMap` built in `/setup-dataverse`:+- For **reused/extended tables**: Use the existing logical name (e.g., `contoso_items`, `existing_productcategory`)+- For **new tables**: Use `{prefix}_tablename` pattern (e.g., `cr_product`)+```text<PROJECT_ROOT>/├── .powerpages-site/│ ├── site-settings/-│ │ ├── Webapi-cr_product-enabled.sitesetting.yml-│ │ ├── Webapi-cr_product-fields.sitesetting.yml-│ │ ├── Webapi-cr_teammember-enabled.sitesetting.yml+│ │ ├── Webapi-{actual_product_table}-enabled.sitesetting.yml+│ │ ├── Webapi-{actual_product_table}-fields.sitesetting.yml+│ │ ├── Webapi-{actual_teammember_table}-enabled.sitesetting.yml│ │ └── ...│ └── ...```@@ -41,29 +43,19 @@ value: <SETTING_VALUE>**File naming convention**: `<SETTING_NAME_WITH_DASHES>.sitesetting.yml`- Replace `/` with `-` in the setting name-- Example: Setting `Webapi/cr_product/enabled` → File `Webapi-cr_product-enabled.sitesetting.yml`+- Example: Setting `Webapi/{prefix}_product/enabled` → File `Webapi-{prefix}_product-enabled.sitesetting.yml`### Generating Unique IDsEach site setting must have a unique `id` field (UUID/GUID format: `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx`).-**When creating YAML files directly**: Generate a valid UUID where each `x` is a hexadecimal character (0-9, a-f).--**PowerShell**:-```powershell-[guid]::NewGuid().ToString()-```--**Bash/Linux/Mac**:-```bash-uuidgen | tr '[:upper:]' '[:lower:]'-```+**Claude Code MUST generate UUIDs by running a CLI command** - never write UUID values directly. Use the Bash tool to execute the appropriate command based on the user's shell/platform:-**Python**:-```python-import uuid-print(str(uuid.uuid4()))-```+| Shell/Platform | Command |+|----------------|---------|+| **PowerShell** (Windows) | `[guid]::NewGuid().ToString()` |+| **Bash** (Linux) | `cat /proc/sys/kernel/random/uuid` |+| **Bash/Zsh** (macOS) | `uuidgen \| tr '[:upper:]' '[:lower:]'` |## Required Site Settings for Each Table@@ -80,13 +72,13 @@ name: Webapi/<TABLE_LOGICAL_NAME>/enabledvalue: true```-**Example** for `cr_product` table:+**Example** for `{prefix}_product` table:-**File**: `.powerpages-site/site-settings/Webapi-cr_product-enabled.sitesetting.yml`+**File**: `.powerpages-site/site-settings/Webapi-{prefix}_product-enabled.sitesetting.yml````yaml-description: Enable Web API access for the cr_product table+description: Enable Web API access for the {prefix}_product tableid: a1b2c3d4-e5f6-7890-abcd-ef1234567890-name: Webapi/cr_product/enabled+name: Webapi/{prefix}_product/enabledvalue: true```@@ -100,7 +92,7 @@ value: truedescription: Allowed fields for Web API accessid: <GENERATE_UUID>name: Webapi/<TABLE_LOGICAL_NAME>/fields-value: cr_name,cr_description,cr_price,cr_imageurl,cr_isactive+value: {prefix}_name,{prefix}_description,{prefix}_price,{prefix}_imageurl,{prefix}_isactive```Specify comma-separated field logical names that your frontend actually needs.@@ -185,24 +177,43 @@ value: $Fields### Example Usage+**IMPORTANT**: Use the `$tableMap` from `/setup-dataverse` to get the actual table logical names:+- For **reused/extended tables**: Use the existing logical name from Dataverse+- For **new tables**: Use `${publisherPrefix}_tablename` pattern+```powershell$projectRoot = "<PROJECT_ROOT>" # Replace with actual path+# Get the publisher prefix first+$api = Initialize-DataverseApi -EnvironmentUrl $envUrl+$publisherPrefix = $api.PublisherPrefix++# The $tableMap should be retrieved from memory-bank.md or rebuilt from /setup-dataverse+# It maps table purposes to actual logical names+function Get-TableLogicalName { param([string]$Purpose) return $tableMap[$Purpose].LogicalName }++$productTable = Get-TableLogicalName "product"+$teammemberTable = Get-TableLogicalName "teammember"+$testimonialTable = Get-TableLogicalName "testimonial"+$faqTable = Get-TableLogicalName "faq"+$contactsubmissionTable = Get-TableLogicalName "contactsubmission"+# Configure each table with EXPLICIT field lists (never use *)-New-WebApiSiteSettings -ProjectRoot $projectRoot -TableLogicalName "cr_product" `- -Fields "cr_name,cr_description,cr_price,cr_category,cr_imageurl,cr_isactive"+# NOTE: Use the actual table logical names from the mapping+New-WebApiSiteSettings -ProjectRoot $projectRoot -TableLogicalName $productTable `+ -Fields "${publisherPrefix}_name,${publisherPrefix}_description,${publisherPrefix}_price,${publisherPrefix}_category,${publisherPrefix}_imageurl,${publisherPrefix}_isactive"-New-WebApiSiteSettings -ProjectRoot $projectRoot -TableLogicalName "cr_teammember" `- -Fields "cr_name,cr_title,cr_email,cr_bio,cr_photourl,cr_linkedin,cr_displayorder"+New-WebApiSiteSettings -ProjectRoot $projectRoot -TableLogicalName $teammemberTable `+ -Fields "${publisherPrefix}_name,${publisherPrefix}_title,${publisherPrefix}_email,${publisherPrefix}_bio,${publisherPrefix}_photourl,${publisherPrefix}_linkedin,${publisherPrefix}_displayorder"-New-WebApiSiteSettings -ProjectRoot $projectRoot -TableLogicalName "cr_testimonial" `- -Fields "cr_name,cr_quote,cr_company,cr_role,cr_rating,cr_photourl,cr_isactive"+New-WebApiSiteSettings -ProjectRoot $projectRoot -TableLogicalName $testimonialTable `+ -Fields "${publisherPrefix}_name,${publisherPrefix}_quote,${publisherPrefix}_company,${publisherPrefix}_role,${publisherPrefix}_rating,${publisherPrefix}_photourl,${publisherPrefix}_isactive"-New-WebApiSiteSettings -ProjectRoot $projectRoot -TableLogicalName "cr_faq" `- -Fields "cr_question,cr_answer,cr_category,cr_displayorder,cr_isactive"+New-WebApiSiteSettings -ProjectRoot $projectRoot -TableLogicalName $faqTable `+ -Fields "${publisherPrefix}_question,${publisherPrefix}_answer,${publisherPrefix}_category,${publisherPrefix}_displayorder,${publisherPrefix}_isactive"-New-WebApiSiteSettings -ProjectRoot $projectRoot -TableLogicalName "cr_contactsubmission" `- -Fields "cr_name,cr_email,cr_message,cr_submissiondate,cr_status"+New-WebApiSiteSettings -ProjectRoot $projectRoot -TableLogicalName $contactsubmissionTable `+ -Fields "${publisherPrefix}_name,${publisherPrefix}_email,${publisherPrefix}_message,${publisherPrefix}_submissiondate,${publisherPrefix}_status"```### Create Error Setting@@ -239,8 +250,24 @@ New-WebApiErrorSetting -ProjectRoot $projectRoot -Enabled $true| Setting | Purpose | Example Value ||---------|---------|---------------|| `Webapi/<table>/enabled` | Enable Web API for table | `true` |-| `Webapi/<table>/fields` | Allowed fields (comma-separated) | `cr_name,cr_price` |+| `Webapi/<table>/fields` | Allowed fields (comma-separated) | `{prefix}_name,{prefix}_price` || `Webapi/error/innererror` | Show detailed errors (dev only) | `true` |+| `Site/AI/AuthoringTool` | Tracks which tool created the site | `ClaudeCodeCLI` or `ClaudeCodeVSCode` |+| `Site/AI/<SkillName>` | Tracks which skills were used | `true` |++## AI Site Settings++When a site is created or modified using Claude Code, site settings track the tooling:++**📖 See: [authoring-tool-reference.md](${CLAUDE_PLUGIN_ROOT}/shared/authoring-tool-reference.md)**++| Setting | Purpose |+|---------|---------|+| `Site/AI/AuthoringTool` | CLI or VS Code |+| `Site/AI/CreateSite` | /create-site skill used |+| `Site/AI/SetupDataverse` | /setup-dataverse skill used |+| `Site/AI/SetupWebApi` | /setup-webapi skill used |+| `Site/AI/SetupAuth` | /setup-auth skill used |## Validation Checklistdiff --git a/plugins/power-pages/skills/setup-webapi/references/table-permissions-reference.md b/plugins/power-pages/skills/setup-webapi/references/table-permissions-reference.mdnew file mode 100644index 000000000..5bf0f3b66--- /dev/null+++ b/plugins/power-pages/skills/setup-webapi/references/table-permissions-reference.md@@ -0,0 +1,305 @@+# Table Permissions Reference++Table permissions control Web API data access. Create YAML files in `.powerpages-site/table-permissions/` and link to web roles.++## Permission Scopes++| Scope | Value | Description | Use Case |+|-------|-------|-------------|----------|+| **Global** | 756150000 | All records accessible | Public data (products, FAQs, testimonials) |+| **Contact** | 756150001 | Records linked to current contact | User-specific data |+| **Account** | 756150002 | Records linked to user's account | Organization data |+| **Parent** | 756150003 | Records linked via parent relationship | Hierarchical data |+| **Self** | 756150004 | Only records owned by current user | Private user data |++## CRUD Permissions++| Field | Description |+|-------|-------------|+| `read` | Can retrieve/query records |+| `create` | Can create new records |+| `write` | Can update existing records |+| `delete` | Can delete records |+| `append` | Can associate records to this entity |+| `appendto` | Can associate this entity to other records |++## Folder Structure++```+<PROJECT_ROOT>/+├── .powerpages-site/+│ ├── table-permissions/+│ │ ├── Product-Read-Permission.tablepermission.yml+│ │ ├── Contact-Self-Access.tablepermission.yml+│ │ └── ...+│ ├── web-roles/+│ │ ├── Anonymous-Users.webrole.yml+│ │ ├── Authenticated-Users.webrole.yml+│ │ └── ...+│ └── ...+```++## File Naming Convention++```+<Permission-Name>.tablepermission.yml+```++Example: `Product-Read-Permission.tablepermission.yml`++## YAML File Structure++```yaml+accountrelationship:+adx_entitypermission_webrole:+- f0323770-7314-4f33-b904-21523abfbcb7+append: false+appendto: false+contactrelationship:+create: false+delete: false+entitylogicalname: cr_product+entityname: Product Read Permission+id: b5d8334f-45fa-464c-ac1d-f7088325f697+parententitypermission:+parentrelationship:+read: true+scope: 756150000+write: false+```++**Important**:+- Fields are alphabetically sorted+- Field names do NOT include the `adx_` prefix (use `read` not `adx_read`)+- Exception: `adx_entitypermission_webrole` retains the full name (many-to-many relationship)++## YAML Field Reference++| Field | Type | Required | Description |+|-------|------|----------|-------------|+| `id` | GUID | Yes | Unique identifier for this permission |+| `entitylogicalname` | string | Yes | Dataverse table logical name |+| `entityname` | string | Yes | Display name for the permission |+| `scope` | int | Yes | Permission scope (see values above) |+| `read` | bool | No | Can retrieve/query records |+| `create` | bool | No | Can create new records |+| `write` | bool | No | Can update existing records |+| `delete` | bool | No | Can delete records |+| `append` | bool | No | Can associate records to this entity |+| `appendto` | bool | No | Can associate this entity to other records |+| `adx_entitypermission_webrole` | list | No | GUIDs of web roles with this permission |+| `parententitypermission` | GUID | No | Parent permission ID for hierarchical access |+| `parentrelationship` | string | No | Relationship name for parent scope |+| `accountrelationship` | string | No | Relationship name for account filtering |+| `contactrelationship` | string | No | Relationship name for contact filtering |++## Generating Unique IDs++**IMPORTANT**: Every table permission YAML file must have a unique `id` field (UUID/GUID format).++**Claude Code MUST generate UUIDs by running a CLI command** - never write UUID values directly. Use the Bash tool to execute the appropriate command based on the user's shell/platform:++| Shell/Platform | Command |+|----------------|---------|+| **PowerShell** (Windows) | `[guid]::NewGuid().ToString()` |+| **Bash** (Linux) | `cat /proc/sys/kernel/random/uuid` |+| **Bash/Zsh** (macOS) | `uuidgen \| tr '[:upper:]' '[:lower:]'` |++**Workflow:**+1. Run the UUID generation command via Bash tool+2. Capture the output+3. Use that value when writing the YAML file++## Getting Web Role GUIDs++Before creating table permissions, get the web role GUID from `.powerpages-site/web-roles/`. Each web role has a `.webrole.yml` file containing its `id`.++**Example web role file** (`.powerpages-site/web-roles/Anonymous-Users.webrole.yml`):+```yaml+anonymoususersrole: true+authenticatedusersrole: false+id: f0323770-7314-4f33-b904-21523abfbcb7+name: Anonymous Users+```++| Role | Description | Use Case |+|------|-------------|----------|+| **Anonymous Users** | Unauthenticated visitors | Public content access |+| **Authenticated Users** | Any logged-in user | Basic member features |+| **Administrators** | Full admin access | Site management |++## Using Table Name Mapping++**IMPORTANT**: Use the `$tableMap` from `/setup-dataverse` (stored in `memory-bank.md`) to get the correct table logical names:+- **Reused/Extended tables**: Use existing logical name (e.g., `contoso_items`)+- **New tables**: Use `{prefix}_tablename` pattern (e.g., `cr_product`)++## Common Permission Patterns++### Read-Only Public Data (Global Scope)++For tables like products, testimonials, FAQs that should be publicly readable.++**File**: `.powerpages-site/table-permissions/Product-Anonymous-Read.tablepermission.yml`+```yaml+adx_entitypermission_webrole:+- <ANONYMOUS_USERS_ROLE_ID>+append: false+appendto: false+create: false+delete: false+entitylogicalname: <TABLE_LOGICAL_NAME>+entityname: Product - Anonymous Read+id: <GENERATE_UUID>+parententitypermission:+read: true+scope: 756150000+write: false+```++### Create-Only (Form Submissions)++For contact forms where users can submit but not read others' submissions.++**File**: `.powerpages-site/table-permissions/Contact-Submission-Create.tablepermission.yml`+```yaml+adx_entitypermission_webrole:+- <ANONYMOUS_USERS_ROLE_ID>+append: false+appendto: false+create: true+delete: false+entitylogicalname: <TABLE_LOGICAL_NAME>+entityname: Contact Submission - Create Only+id: <GENERATE_UUID>+parententitypermission:+read: false+scope: 756150000+write: false+```++### User-Specific Data (Self Scope)++For data that users should only see their own records.++**File**: `.powerpages-site/table-permissions/User-Profile-Self-Access.tablepermission.yml`+```yaml+adx_entitypermission_webrole:+- <AUTHENTICATED_USERS_ROLE_ID>+append: false+appendto: false+create: true+delete: false+entitylogicalname: <TABLE_LOGICAL_NAME>+entityname: User Profile - Self Access+id: <GENERATE_UUID>+parententitypermission:+read: true+scope: 756150004+write: true+```++### Full CRUD Access++For authenticated users who need complete control (use with caution).++**File**: `.powerpages-site/table-permissions/Order-Full-Access.tablepermission.yml`+```yaml+adx_entitypermission_webrole:+- <AUTHENTICATED_USERS_ROLE_ID>+append: true+appendto: true+create: true+delete: true+entitylogicalname: <TABLE_LOGICAL_NAME>+entityname: Order - Full Access+id: <GENERATE_UUID>+parententitypermission:+read: true+scope: 756150001+write: true+```++## Parent-Child Table Permissions++When tables have relationships (e.g., Order → Order Items), use hierarchical permissions with the `parententitypermission` field and `Parent` scope.++**Creation Order:**+1. Create parent table permission first (e.g., for `{prefix}_order`)+2. Note the parent permission's `id` (GUID)+3. Create child permission with `parententitypermission` set to parent's ID+4. Set child's `scope` to `756150003` (Parent)+5. Set `parentrelationship` to the relationship name between child and parent tables++### Example: Parent Permission (Order)++**File**: `.powerpages-site/table-permissions/Order-User-Access.tablepermission.yml`+```yaml+adx_entitypermission_webrole:+- <AUTHENTICATED_USERS_ROLE_ID>+append: true+appendto: false+create: true+delete: false+entitylogicalname: {prefix}_order+entityname: Order - User Access+id: a1b2c3d4-e5f6-7890-abcd-ef1234567890+parententitypermission:+parentrelationship:+read: true+scope: 756150001+write: true+```++### Example: Child Permission (Order Items)++**File**: `.powerpages-site/table-permissions/Order-Item-Parent-Access.tablepermission.yml`+```yaml+adx_entitypermission_webrole:+- <AUTHENTICATED_USERS_ROLE_ID>+append: false+appendto: true+create: true+delete: true+entitylogicalname: {prefix}_orderitem+entityname: Order Item - Parent Access+id: b2c3d4e5-f6a7-8901-bcde-fa2345678901+parententitypermission: a1b2c3d4-e5f6-7890-abcd-ef1234567890+parentrelationship: {prefix}_order_orderitems+read: true+scope: 756150003+write: true+```++Users can only access order items that belong to orders they have access to.++## Validation Checklist++Before uploading:++- [ ] All YAML files have valid syntax+- [ ] Each file has a unique UUID for the `id` field (generated via CLI command)+- [ ] Fields are alphabetically sorted+- [ ] File extensions are `.yml` (not `.yaml`)+- [ ] Field names do NOT include `adx_` prefix (except `adx_entitypermission_webrole`)+- [ ] Boolean values are unquoted (`true` not `"true"`)+- [ ] All GUIDs are valid UUID format (lowercase with hyphens)+- [ ] Web role GUIDs exist in `.powerpages-site/web-roles/` folder++## Security Best Practices++1. **Least Privilege**: Grant only the minimum permissions needed+2. **Avoid Global Scope for Write**: Use Contact/Account/Self scopes for write operations+3. **Separate Read and Write**: Create different permissions for reading vs. modifying data+4. **Audit Regularly**: Review permissions periodically+5. **Test as Anonymous**: Verify anonymous users can only access intended data++## Permission Decision Matrix++| Data Type | Recommended Scope | Read | Create | Write | Delete |+|-----------|-------------------|------|--------|-------|--------|+| Public content (products, FAQs) | Global | Yes | No | No | No |+| Form submissions | Global | No | Yes | No | No |+| User profiles | Self | Yes | Yes | Yes | No |+| User's own orders | Contact | Yes | Yes | Yes | No |+| Admin data | N/A (via app) | No | No | No | No |diff --git a/plugins/power-pages/skills/setup-webapi/troubleshooting.md b/plugins/power-pages/skills/setup-webapi/references/troubleshooting.mdsimilarity index 84%rename from plugins/power-pages/skills/setup-webapi/troubleshooting.mdrename to plugins/power-pages/skills/setup-webapi/references/troubleshooting.mdindex 3d3775f55..833d892bf 100644--- a/plugins/power-pages/skills/setup-webapi/troubleshooting.md+++ b/plugins/power-pages/skills/setup-webapi/references/troubleshooting.md@@ -1,6 +1,6 @@# Troubleshooting Guide-This document covers common issues when setting up Power Pages Web API and their solutions.+**NOTE**: Replace `{prefix}` with your publisher prefix from `Initialize-DataverseApi`.## Quick Reference@@ -27,7 +27,7 @@ This document covers common issues when setting up Power Pages Web API and their```yaml# Correctid: a1b2c3d4-e5f6-7890-abcd-ef1234567890- name: Webapi/cr_product/enabled+ name: Webapi/{prefix}_product/enabledvalue: true# Incorrect (missing quotes can cause issues in some cases)@@ -63,7 +63,7 @@ This document covers common issues when setting up Power Pages Web API and their```powershell# Check permissions in Dataverse$baseUrl = "<ENV_URL>/api/data/v9.2"- Invoke-RestMethod -Uri "$baseUrl/adx_entitypermissions?`$filter=adx_entitylogicalname eq 'cr_product'" -Headers $headers+ Invoke-RestMethod -Uri "$baseUrl/adx_entitypermissions?`$filter=adx_entitylogicalname eq '{prefix}_product'" -Headers $headers```2. **Check permission is linked to correct web role**@@ -92,7 +92,7 @@ This document covers common issues when setting up Power Pages Web API and theirconst token = match ? match[1] : null;// Include in request- fetch('/_api/cr_products', {+ fetch('/_api/{prefix}_products', {method: 'POST',headers: {'Content-Type': 'application/json',@@ -141,13 +141,13 @@ fetch('/_layout/tokenhtml')1. **Verify site setting exists and is enabled**```yaml- name: Webapi/cr_product/enabled+ name: Webapi/{prefix}_product/enabledvalue: true # Must be boolean true, not string "true"```2. **Check entity set name is correct**- Use pluralized logical name- - Example: `cr_product` table → `cr_products` entity set+ - Example: `{prefix}_product` table → `{prefix}_products` entity set3. **Ensure table exists in Dataverse**@@ -170,10 +170,10 @@ fetch('/_layout/tokenhtml')```text# Incorrect- /_api/cr_products?filter=cr_isactive eq true+ /_api/{prefix}_products?filter={prefix}_isactive eq true# Correct ($ prefix required)- /_api/cr_products?$filter=cr_isactive eq true+ /_api/{prefix}_products?$filter={prefix}_isactive eq true```2. **Missing $select when fields are restricted** (Most Common)@@ -182,25 +182,25 @@ fetch('/_layout/tokenhtml')```text# Site setting- name: Webapi/cr_product/fields- value: cr_name,cr_price,cr_isactive+ name: Webapi/{prefix}_product/fields+ value: {prefix}_name,{prefix}_price,{prefix}_isactive# Incorrect (no $select - tries to fetch all fields)- /_api/cr_products- /_api/cr_products?$filter=cr_isactive eq true+ /_api/{prefix}_products+ /_api/{prefix}_products?$filter={prefix}_isactive eq true# Correct (only requests allowed fields)- /_api/cr_products?$select=cr_name,cr_price,cr_isactive- /_api/cr_products?$select=cr_name,cr_price,cr_isactive&$filter=cr_isactive eq true+ /_api/{prefix}_products?$select={prefix}_name,{prefix}_price,{prefix}_isactive+ /_api/{prefix}_products?$select={prefix}_name,{prefix}_price,{prefix}_isactive&$filter={prefix}_isactive eq true```**Solution**: Always include `$select` with fields that match your `Webapi/<table>/fields` site setting:```typescript// Always specify select with allowed fields- webApi.getAll<Product>('cr_products', {- select: ['cr_name', 'cr_price', 'cr_isactive'],- filter: 'cr_isactive eq true',+ webApi.getAll<Product>('{prefix}_products', {+ select: ['{prefix}_name', '{prefix}_price', '{prefix}_isactive'],+ filter: '{prefix}_isactive eq true',});```@@ -212,20 +212,20 @@ fetch('/_layout/tokenhtml')```text# Incorrect (string needs quotes)- $filter=cr_category eq Electronics+ $filter={prefix}_category eq Electronics# Correct- $filter=cr_category eq 'Electronics'+ $filter={prefix}_category eq 'Electronics'```4. **Invalid data type in request body**```javascript// Incorrect- { "cr_price": "99.99" } // String instead of number+ { "{prefix}_price": "99.99" } // String instead of number// Correct- { "cr_price": 99.99 }+ { "{prefix}_price": 99.99 }```## Web API Returns 500 Server Error@@ -267,10 +267,10 @@ Power Pages Web API should not have CORS issues when called from the same origin```javascript// Correct- fetch('/_api/cr_products')+ fetch('/_api/{prefix}_products')// Incorrect (may cause CORS issues)- fetch('https://site.powerappsportals.com/_api/cr_products')+ fetch('https://site.powerappsportals.com/_api/{prefix}_products')```2. **Check HTTP vs HTTPS**@@ -292,18 +292,18 @@ Power Pages Web API should not have CORS issues when called from the same origin3. **Test API directly in browser**```text- https://<site-url>/_api/cr_products+ https://<site-url>/_api/{prefix}_products```4. **Check field name mapping**- Ensure frontend uses Dataverse column logical names- - Example: `cr_productid` not `id`+ - Example: `{prefix}_productid` not `id`5. **Verify data exists in Dataverse**```powershell# Query via Dataverse API- Invoke-RestMethod -Uri "$baseUrl/cr_products" -Headers $headers+ Invoke-RestMethod -Uri "$baseUrl/{prefix}_products" -Headers $headers```## Debug Checklistdiff --git a/plugins/power-pages/skills/setup-webapi/references/web-roles-reference.md b/plugins/power-pages/skills/setup-webapi/references/web-roles-reference.mdnew file mode 100644index 000000000..a646ee692--- /dev/null+++ b/plugins/power-pages/skills/setup-webapi/references/web-roles-reference.md@@ -0,0 +1,218 @@+# Web Roles Reference++Web roles define user groups with access levels. Create roles before table permissions.++## Built-in Web Roles++Power Pages creates these default web roles when a site is provisioned:++| Web Role | Description | Typical Use Case |+|----------|-------------|------------------|+| **Anonymous Users** | Unauthenticated site visitors | Public content, read-only product catalogs, FAQs |+| **Authenticated Users** | Any user who has signed in | Basic member features, form submissions |+| **Administrators** | Full administrative access | Site management, content editing |++### Role Hierarchy++Administrators → Authenticated Users (+ custom roles) → Anonymous Users++## Web Role YAML Files++Web roles are stored as YAML files in `.powerpages-site/web-roles/`.++### Folder Structure++```+<PROJECT_ROOT>/+├── .powerpages-site/+│ ├── web-roles/+│ │ ├── Anonymous-Users.webrole.yml+│ │ ├── Authenticated-Users.webrole.yml+│ │ ├── Administrators.webrole.yml+│ │ └── Customers.webrole.yml # Custom role+│ └── ...+```++### YAML Format++```yaml+anonymoususersrole: false+authenticatedusersrole: false+id: <GENERATE_UUID>+name: <ROLE_NAME>+```++### Field Reference++| Field | Type | Required | Description |+|-------|------|----------|-------------|+| `id` | GUID | Yes | Unique identifier for this role |+| `name` | string | Yes | Display name of the role |+| `anonymoususersrole` | bool | Yes | `true` only for Anonymous Users role |+| `authenticatedusersrole` | bool | Yes | `true` only for Authenticated Users role |++### Built-in Role Examples++**Anonymous-Users.webrole.yml**+```yaml+anonymoususersrole: true+authenticatedusersrole: false+id: f0323770-7314-4f33-b904-21523abfbcb7+name: Anonymous Users+```++**Authenticated-Users.webrole.yml**+```yaml+anonymoususersrole: false+authenticatedusersrole: true+id: ecac9573-effb-4d63-9b27-15861f70f3de+name: Authenticated Users+```++**Administrators.webrole.yml**+```yaml+anonymoususersrole: false+authenticatedusersrole: false+id: 4e4ee36e-6535-4657-b62a-c4972d932558+name: Administrators+```++### Custom Role Examples++**Customers.webrole.yml**+```yaml+anonymoususersrole: false+authenticatedusersrole: false+id: 7a8b9c0d-1e2f-3456-7890-abcdef123456+name: Customers+```++**Premium-Members.webrole.yml**+```yaml+anonymoususersrole: false+authenticatedusersrole: false+id: 1b2c3d4e-5f6a-7890-bcde-f12345678901+name: Premium Members+```++### Generating Unique IDs++Each web role must have a unique `id` (UUID/GUID format).++**Claude Code MUST generate UUIDs by running a CLI command** - never write UUID values directly. Use the Bash tool to execute the appropriate command based on the user's shell/platform:++| Shell/Platform | Command |+|----------------|---------|+| **PowerShell** (Windows) | `[guid]::NewGuid().ToString()` |+| **Bash** (Linux) | `cat /proc/sys/kernel/random/uuid` |+| **Bash/Zsh** (macOS) | `uuidgen \| tr '[:upper:]' '[:lower:]'` |++## Creating Web Roles++### Step 1: Check Existing Roles++After the first upload, check what roles exist in `.powerpages-site/web-roles/`:++```powershell+Get-ChildItem -Path ".powerpages-site\web-roles" -Filter "*.webrole.yml"+```++### Step 2: Create Custom Role YAML++Create a new `.webrole.yml` file for each custom role needed:++```powershell+$roleName = "Customers"+$roleId = [guid]::NewGuid().ToString()++$content = @"+anonymoususersrole: false+authenticatedusersrole: false+id: $roleId+name: $roleName+"@++$fileName = "$roleName.webrole.yml"+$filePath = ".powerpages-site\web-roles\$fileName"+Set-Content -Path $filePath -Value $content -Encoding UTF8+Write-Host "Created: $filePath"+```++### Step 3: Upload to Apply++```powershell+pac pages upload-code-site --rootPath "<PROJECT_ROOT>"+```++## Role Selection by Feature++| Site Feature | Required Roles |+|--------------|----------------|+| Public landing page | Anonymous Users |+| Product/Service catalog | Anonymous Users |+| Contact form submission | Anonymous Users (create-only) |+| User dashboard | Authenticated Users |+| Order history | Customers (custom) |+| Admin panel | Administrators |+| Premium content | Premium Members (custom) |++## Common Role Patterns++### Pattern 1: Public Website+- Anonymous Users (default)+- Administrators (default)++### Pattern 2: Member Portal+- Anonymous Users+- Authenticated Users+- Administrators++### Pattern 3: Customer Portal+- Anonymous Users+- Customers (custom)+- Support Agents (custom)+- Administrators++### Pattern 4: Subscription Site+- Anonymous Users+- Free Members (custom)+- Premium Members (custom)+- Administrators++## Querying Existing Roles (API)++To query existing roles from Dataverse (for verification):++```powershell+$envUrl = (pac org who --json | ConvertFrom-Json).OrgUrl+$token = (az account get-access-token --resource $envUrl --query accessToken -o tsv)+$headers = @{+ "Authorization" = "Bearer $token"+ "Content-Type" = "application/json"+}+$baseUrl = "$envUrl/api/data/v9.2"++# List all web roles for the website (use mspp_webroles, not adx_webroles)+$websiteId = "<WEBSITE_ID>"+$roles = Invoke-RestMethod `+ -Uri "$baseUrl/mspp_webroles?`$filter=_mspp_websiteid_value eq $websiteId&`$select=mspp_webroleid,mspp_name" `+ -Headers $headers++$roles.value | ForEach-Object {+ Write-Host "Role: $($_.mspp_name) | ID: $($_.mspp_webroleid)"+}+```++## Validation Checklist++Before uploading:++- [ ] All YAML files have valid syntax+- [ ] Each file has a unique UUID for the `id` field+- [ ] File extension is `.yml` (not `.yaml`)+- [ ] `anonymoususersrole` and `authenticatedusersrole` are both `false` for custom roles+- [ ] Role names are descriptive and unique++## Next Steps++After creating web roles, create table permissions that reference these role IDs. See [table-permissions-reference.md](./table-permissions-reference.md).diff --git a/plugins/power-pages/skills/setup-webapi/table-permissions-reference.md b/plugins/power-pages/skills/setup-webapi/table-permissions-reference.mddeleted file mode 100644index 9bd61a3d8..000000000--- a/plugins/power-pages/skills/setup-webapi/table-permissions-reference.md+++ /dev/null@@ -1,571 +0,0 @@-# Table Permissions Reference--This document describes how to create table permissions (entity permissions) for Power Pages Web API access.--## Understanding Table Permissions--Table permissions control which users can access data through the Web API. These must be created in Dataverse and linked to web roles.--### Permission Scopes--| Scope | Value | Description | Use Case |-|-------|-------|-------------|----------|-| **Global** | 756150000 | All records accessible | Public data (products, FAQs, testimonials) |-| **Contact** | 756150001 | Records linked to current contact | User-specific data |-| **Account** | 756150002 | Records linked to user's account | Organization data |-| **Parent** | 756150003 | Records linked via parent relationship | Hierarchical data |-| **Self** | 756150004 | Only records owned by current user | Private user data |--### CRUD Permissions--| Permission | Description |-|------------|-------------|-| `adx_read` | Can retrieve/query records |-| `adx_create` | Can create new records |-| `adx_write` | Can update existing records |-| `adx_delete` | Can delete records |-| `adx_append` | Can associate records to this entity |-| `adx_appendto` | Can associate this entity to other records |--## Prerequisites--Before creating table permissions, ensure you have:--1. Environment URL from `pac org who`-2. Website ID from `pac pages list --verbose`-3. Azure CLI authenticated (`az login`)--## PowerShell Setup--```powershell-# Get environment URL and access token-$envUrl = (pac org who --json | ConvertFrom-Json).OrgUrl-$token = (az account get-access-token --resource $envUrl --query accessToken -o tsv)--$headers = @{- "Authorization" = "Bearer $token"- "Content-Type" = "application/json"- "OData-MaxVersion" = "4.0"- "OData-Version" = "4.0"-}--$baseUrl = "$envUrl/api/data/v9.2"--# Set your Website ID (from pac pages list)-$websiteId = "<WEBSITE_ID_FROM_MEMORY_BANK>"-```--## Create Table Permission Function--```powershell-function New-TablePermission {- param(- [string]$Name,- [string]$TableLogicalName,- [string]$WebsiteId,- [int]$Scope = 756150000, # Global- [bool]$Read = $true,- [bool]$Create = $false,- [bool]$Write = $false,- [bool]$Delete = $false,- [bool]$Append = $false,- [bool]$AppendTo = $false- )-- # Generate unique ID for the permission- $permissionId = [guid]::NewGuid().ToString()-- $permission = @{- "adx_entitypermissionid" = $permissionId- "adx_entityname" = $TableLogicalName- "adx_entitylogicalname" = $TableLogicalName- "adx_scope" = $Scope- "adx_read" = $Read- "adx_create" = $Create- "adx_write" = $Write- "adx_delete" = $Delete- "adx_append" = $Append- "adx_appendto" = $AppendTo- "[email protected]" = "/adx_websites($WebsiteId)"- }-- $body = $permission | ConvertTo-Json -Depth 5-- try {- $result = Invoke-RestMethod -Uri "$baseUrl/adx_entitypermissions" -Method Post -Headers $headers -Body $body- Write-Host "Created table permission for: $TableLogicalName (ID: $permissionId)"- return @{- "Id" = $permissionId- "Result" = $result- }- }- catch {- Write-Host "Error creating permission for $TableLogicalName : $_"- return $null- }-}-```--## Common Permission Patterns--### Read-Only Public Data--For tables like products, testimonials, FAQs that should be publicly readable:--```powershell-# Read-only Global scope for public data-New-TablePermission -Name "Product Read" -TableLogicalName "cr_product" -WebsiteId $websiteId -Read $true-New-TablePermission -Name "Team Member Read" -TableLogicalName "cr_teammember" -WebsiteId $websiteId -Read $true-New-TablePermission -Name "Testimonial Read" -TableLogicalName "cr_testimonial" -WebsiteId $websiteId -Read $true-New-TablePermission -Name "FAQ Read" -TableLogicalName "cr_faq" -WebsiteId $websiteId -Read $true-```--### Create-Only (Form Submissions)--For contact forms where users can submit but not read others' submissions:--```powershell-# Create only - users can submit but not read others-New-TablePermission -Name "Contact Submission Create" `- -TableLogicalName "cr_contactsubmission" `- -WebsiteId $websiteId `- -Read $false `- -Create $true-```--### User-Specific Data (Self Scope)--For data that users should only see their own records:--```powershell-# Self scope - users see only their own records-New-TablePermission -Name "User Profile" `- -TableLogicalName "cr_userprofile" `- -WebsiteId $websiteId `- -Scope 756150004 ` # Self- -Read $true `- -Write $true-```--### Full CRUD Access--For authenticated users who need complete control:--```powershell-# Full CRUD access (use with caution)-New-TablePermission -Name "Admin Orders" `- -TableLogicalName "cr_order" `- -WebsiteId $websiteId `- -Read $true `- -Create $true `- -Write $true `- -Delete $true-```--## Assign Permissions to Web Roles--Table permissions must be linked to web roles to take effect.--### Get or Create Web Role--**IMPORTANT**: Always use `mspp_webroles` (not `adx_webroles`) for fetching web role IDs. If the role doesn't exist, create it first before proceeding with table permissions.--```powershell-function Get-OrCreateWebRole {- param(- [Parameter(Mandatory=$true)]- [string]$RoleName,- [Parameter(Mandatory=$true)]- [string]$WebsiteId,- [string]$Description = ""- )-- # Try to get existing role using mspp_webroles- try {- $existingRole = Invoke-RestMethod `- -Uri "$baseUrl/mspp_webroles?`$filter=mspp_name eq '$RoleName' and _mspp_websiteid_value eq $WebsiteId&`$select=mspp_webroleid" `- -Headers $headers-- if ($existingRole.value.Count -gt 0) {- $roleId = $existingRole.value[0].mspp_webroleid- Write-Host "Found existing web role '$RoleName' with ID: $roleId"- return $roleId- }- }- catch {- Write-Host "Error checking for existing role: $_"- }-- # Role doesn't exist - create it- Write-Host "Web role '$RoleName' not found. Creating..."-- $newRoleId = [guid]::NewGuid().ToString()- $webRole = @{- "mspp_webroleid" = $newRoleId- "mspp_name" = $RoleName- "mspp_description" = $Description- "[email protected]" = "/mspp_websites($WebsiteId)"- }-- try {- Invoke-RestMethod -Uri "$baseUrl/mspp_webroles" -Method Post -Headers $headers -Body ($webRole | ConvertTo-Json -Depth 5)- Write-Host "Created web role '$RoleName' with ID: $newRoleId"- return $newRoleId- }- catch {- Write-Host "Error creating web role '$RoleName': $_"- return $null- }-}--# Example: Get or create Anonymous Users role-$roleId = Get-OrCreateWebRole -RoleName "Anonymous Users" -WebsiteId $websiteId -Description "Unauthenticated site visitors"--if (-not $roleId) {- Write-Host "ERROR: Unable to get or create web role. Cannot proceed with table permission creation." -ForegroundColor Red- return-}--Write-Host "Web Role ID: $roleId"-```--### Associate Permission with Role--**IMPORTANT**: Only create table permissions if you have a valid web role ID. If role retrieval/creation fails, do NOT create the permission.--```powershell-function Add-PermissionToRole {- param(- [Parameter(Mandatory=$true)]- [string]$PermissionId,- [Parameter(Mandatory=$true)]- [string]$RoleId- )-- if (-not $RoleId) {- Write-Host "ERROR: No valid role ID provided. Cannot associate permission." -ForegroundColor Red- return $false- }-- $association = @{- "@odata.id" = "$baseUrl/mspp_webroles($RoleId)"- }-- try {- Invoke-RestMethod `- -Uri "$baseUrl/adx_entitypermissions($PermissionId)/adx_webrole_entitypermission/`$ref" `- -Method Post `- -Headers $headers `- -Body ($association | ConvertTo-Json)- Write-Host "Associated permission $PermissionId with role $RoleId"- return $true- }- catch {- Write-Host "Error associating permission: $_"- return $false- }-}-```--### Complete Example: Associate Permission--```powershell-# Get permission ID for a specific table-$permissions = Invoke-RestMethod `- -Uri "$baseUrl/adx_entitypermissions?`$filter=adx_entitylogicalname eq 'cr_product'&`$select=adx_entitypermissionid" `- -Headers $headers--if ($permissions.value.Count -gt 0) {- $permissionId = $permissions.value[0].adx_entitypermissionid-- # Associate with Anonymous Users role- Add-PermissionToRole -PermissionId $permissionId -RoleId $roleId-}-```--## Web Roles Reference--| Role | Description | Use Case |-|------|-------------|----------|-| **Anonymous Users** | Unauthenticated visitors | Public content access |-| **Authenticated Users** | Any logged-in user | Basic member features |-| **Administrators** | Full admin access | Site management |--## Verify Permissions--### List Existing Permissions--```powershell-# List all table permissions for the website-$existingPermissions = Invoke-RestMethod `- -Uri "$baseUrl/adx_entitypermissions?`$filter=_adx_websiteid_value eq $websiteId&`$select=adx_entitylogicalname,adx_scope,adx_read,adx_create,adx_write,adx_delete" `- -Headers $headers--$existingPermissions.value | ForEach-Object {- Write-Host "Table: $($_.adx_entitylogicalname), Read: $($_.adx_read), Create: $($_.adx_create)"-}-```--### Check Role Associations--```powershell-# Check which roles are linked to a permission-$permissionId = "<PERMISSION_ID>"-$linkedRoles = Invoke-RestMethod `- -Uri "$baseUrl/adx_entitypermissions($permissionId)/adx_webrole_entitypermission" `- -Headers $headers--$linkedRoles.value | ForEach-Object {- Write-Host "Linked Role: $($_.adx_name)"-}-```--## Code Site Table Permission Files--Table permissions for Power Pages code sites are stored as YAML files in the `.powerpages-site/table-permissions/` folder.--### Folder Structure--```-<PROJECT_ROOT>/-├── .powerpages-site/-│ ├── table-permissions/-│ │ ├── Product-Read-Permission.tablepermission.yml-│ │ ├── Contact-Self-Access.tablepermission.yml-│ │ └── ...-│ └── ...-```--### File Naming Convention--```-<Permission-Name>.tablepermission.yml-```--Example: `Product-Read-Permission.tablepermission.yml`--### YAML File Structure--```yaml-accountrelationship:-adx_entitypermission_webrole:-- f0323770-7314-4f33-b904-21523abfbcb7-append: false-appendto: false-contactrelationship:-create: false-delete: false-entitylogicalname: cr_product-entityname: Product Read Permission-id: b5d8334f-45fa-464c-ac1d-f7088325f697-parententitypermission:-parentrelationship:-read: true-scope: 756150000-write: false-```--**Important**: Field names do NOT include the `adx_` prefix (e.g., use `read` not `adx_read`), EXCEPT for many-to-many relationship fields like `adx_entitypermission_webrole` which retain the full name.--### YAML Field Reference--| Field | Type | Required | Description |-|-------|------|----------|-------------|-| `id` | GUID | Yes | Unique identifier for this permission |-| `entitylogicalname` | string | Yes | Dataverse table logical name (e.g., `cr_product`) |-| `entityname` | string | Yes | Display name for the permission |-| `scope` | int | Yes | Permission scope (see values below) |-| `read` | bool | No | Can retrieve/query records |-| `create` | bool | No | Can create new records |-| `write` | bool | No | Can update existing records |-| `delete` | bool | No | Can delete records |-| `append` | bool | No | Can associate records to this entity |-| `appendto` | bool | No | Can associate this entity to other records |-| `adx_entitypermission_webrole` | list | No | GUIDs of web roles with this permission |-| `parententitypermission` | GUID | No | Parent permission ID for hierarchical access |-| `parentrelationship` | string | No | Relationship name for parent scope |-| `accountrelationship` | string | No | Relationship name for account filtering |-| `contactrelationship` | string | No | Relationship name for contact filtering |--### Scope Values for YAML--| Scope Name | Value | Description |-|------------|-------|-------------|-| Global | 756150000 | All records accessible |-| Contact | 756150001 | Records linked to current contact |-| Account | 756150002 | Records linked to user's account |-| Parent | 756150003 | Records linked via parent relationship |-| Self | 756150004 | Only records owned by current user |--### Generating Unique IDs--**IMPORTANT**: Every table permission YAML file must have a unique `id` field (UUID/GUID format).--**When creating YAML files directly**: Generate a valid UUID in the format `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx` where each `x` is a hexadecimal character (0-9, a-f). Each permission must have a different UUID.--**PowerShell** (if running scripts):-```powershell-[guid]::NewGuid().ToString()-```--**Bash/Linux/Mac**:-```bash-uuidgen | tr '[:upper:]' '[:lower:]'-# or-cat /proc/sys/kernel/random/uuid-```--**Python**:-```python-import uuid-print(str(uuid.uuid4()))-```--**Online**: Use any UUID generator website--**Example UUIDs** (do NOT reuse these - generate new ones):-- `71ecf203-dfe2-4c1e-9db2-112ed3925a52`-- `82fde314-eff3-5d2f-0ec3-223fe4036b63`-- `93gef425-fgg4-6e3g-1fd4-334gf5147c74`--### Example: Read-Only Public Permission--**Before creating**, get the web role GUID from the `.powerpages-site/web-roles/` folder. Each web role has a `.webrole.yml` file containing its `id`.--**Web Role File Format** (`.powerpages-site/web-roles/Anonymous-Users.webrole.yml`):-```yaml-anonymoususersrole: true-authenticatedusersrole: false-id: f0323770-7314-4f33-b904-21523abfbcb7-name: Anonymous Users-```--**Table Permission File** (`.powerpages-site/table-permissions/Product-Anonymous-Read.tablepermission.yml`):-```yaml-adx_entitypermission_webrole:-- f0323770-7314-4f33-b904-21523abfbcb7-append: false-appendto: false-create: false-delete: false-entitylogicalname: cr_product-entityname: Product - Anonymous Read-id: 71ecf203-dfe2-4c1e-9db2-112ed3925a52-parententitypermission:-read: true-scope: 756150000-write: false-```--### Example: User Self-Access Permission--**Web Role File** (`.powerpages-site/web-roles/Authenticated-Users.webrole.yml`):-```yaml-anonymoususersrole: false-authenticatedusersrole: true-id: ecac9573-effb-4d63-9b27-15861f70f3de-name: Authenticated Users-```--**Table Permission File** (`.powerpages-site/table-permissions/User-Profile-Self-Access.tablepermission.yml`):-```yaml-adx_entitypermission_webrole:-- ecac9573-effb-4d63-9b27-15861f70f3de-append: false-appendto: false-create: true-delete: false-entitylogicalname: cr_userprofile-entityname: User Profile - Self Access-id: 82fde314-eff3-5d2f-0ec3-223fe4036b63-parententitypermission:-read: true-scope: 756150004-write: true-```--### Parent-Child Table Permissions--When tables have relationships (e.g., Order → Order Items), you can create hierarchical permissions using the `parententitypermission` field and `Parent` scope.--> **Important**: Parent permissions must be created before child permissions. The child permission references the parent's ID in the `parententitypermission` field.--**Creation Order:**-1. Create the parent table permission first (e.g., for `cr_order`)-2. Note the parent permission's `id` (GUID)-3. Create child permission with `parententitypermission` set to parent's ID-4. Set child's `scope` to `756150003` (Parent)-5. Set `parentrelationship` to the relationship name between child and parent tables--#### Example: Parent Permission (Order)--**File**: `.powerpages-site/table-permissions/Order-User-Access.tablepermission.yml`-```yaml-adx_entitypermission_webrole:-- ecac9573-effb-4d63-9b27-15861f70f3de-append: true-appendto: false-create: true-delete: false-entitylogicalname: cr_order-entityname: Order - User Access-id: a1b2c3d4-e5f6-7890-abcd-ef1234567890-parententitypermission:-parentrelationship:-read: true-scope: 756150001-write: true-```--#### Example: Child Permission (Order Items)--**File**: `.powerpages-site/table-permissions/Order-Item-Parent-Access.tablepermission.yml`-```yaml-adx_entitypermission_webrole:-- ecac9573-effb-4d63-9b27-15861f70f3de-append: false-appendto: true-create: true-delete: true-entitylogicalname: cr_orderitem-entityname: Order Item - Parent Access-id: b2c3d4e5-f6a7-8901-bcde-fa2345678901-parententitypermission: a1b2c3d4-e5f6-7890-abcd-ef1234567890-parentrelationship: cr_order_orderitems-read: true-scope: 756150003-write: true-```--In this example, users can only access order items that belong to orders they have access to.--## Validation Checklist--Before uploading:--- [ ] All YAML files have valid syntax-- [ ] Each file has a unique UUID for the `id` field-- [ ] Fields are alphabetically sorted in the YAML file-- [ ] File extensions are `.yml` (not `.yaml`)-- [ ] Field names do NOT include `adx_` prefix (except `adx_entitypermission_webrole`)-- [ ] Boolean values are unquoted (`true` not `"true"`)-- [ ] All GUIDs are valid UUID format (lowercase with hyphens)-- [ ] Web role GUIDs exist in `.powerpages-site/web-roles/` folder--## Security Best Practices--1. **Least Privilege**: Grant only the minimum permissions needed-2. **Avoid Global Scope for Write**: Use Contact/Account/Self scopes for write operations-3. **Separate Read and Write**: Create different permissions for reading vs. modifying data-4. **Audit Regularly**: Review permissions periodically-5. **Test as Anonymous**: Verify anonymous users can only access intended data--## Permission Decision Matrix--| Data Type | Recommended Scope | Read | Create | Write | Delete |-|-----------|-------------------|------|--------|-------|--------|-| Public content (products, FAQs) | Global | Yes | No | No | No |-| Form submissions | Global | No | Yes | No | No |-| User profiles | Self | Yes | Yes | Yes | No |-| User's own orders | Contact | Yes | Yes | Yes | No |-| Admin data | N/A (via app) | No | No | No | No |diff --git a/plugins/power-pages/skills/setup-webapi/web-roles-reference.md b/plugins/power-pages/skills/setup-webapi/web-roles-reference.mddeleted file mode 100644index c5e99d5b5..000000000--- a/plugins/power-pages/skills/setup-webapi/web-roles-reference.md+++ /dev/null@@ -1,554 +0,0 @@-# Web Roles Reference--This document describes how to create and configure web roles for Power Pages sites. Web roles control access to content and data, and must be created before table permissions.--## Understanding Web Roles--Web roles define user groups with specific access levels. They are the foundation of Power Pages security model and determine:--- Which pages users can access-- What data users can read/write via Web API-- Which site features are available to users--### Built-in Web Roles--Power Pages creates these default web roles when a site is provisioned:--| Web Role | Description | Typical Use Case |-|----------|-------------|------------------|-| **Anonymous Users** | Unauthenticated site visitors | Public content, read-only product catalogs, FAQs |-| **Authenticated Users** | Any user who has signed in | Basic member features, form submissions |-| **Administrators** | Full administrative access | Site management, content editing |--### Custom Web Roles--Create custom web roles for granular access control:--| Custom Role Example | Description | Use Case |-|---------------------|-------------|----------|-| **Customers** | Registered customers | View orders, submit support tickets |-| **Partners** | Business partners | Access partner portal, view deals |-| **Employees** | Internal staff | HR portal, internal tools |-| **Premium Members** | Paid subscribers | Access premium content, features |-| **Moderators** | Content moderators | Approve submissions, manage comments |-| **Support Agents** | Customer support team | View/respond to tickets |--## Prerequisites--Before creating web roles, ensure you have:--1. Environment URL from `pac org who`-2. Website ID from `pac pages list --verbose`-3. Azure CLI authenticated (`az login`)--## PowerShell Setup--```powershell-# Get environment URL and access token-$envUrl = (pac org who --json | ConvertFrom-Json).OrgUrl-$token = (az account get-access-token --resource $envUrl --query accessToken -o tsv)--$headers = @{- "Authorization" = "Bearer $token"- "Content-Type" = "application/json"- "OData-MaxVersion" = "4.0"- "OData-Version" = "4.0"-}--$baseUrl = "$envUrl/api/data/v9.2"--# Set your Website ID (from pac pages list)-$websiteId = "<WEBSITE_ID_FROM_MEMORY_BANK>"-```--## Determine Appropriate Web Roles--Use this decision matrix to determine which web roles you need:--### Role Selection by Feature--| Site Feature | Required Roles | Notes |-|--------------|----------------|-------|-| Public landing page | Anonymous Users | No authentication needed |-| Product/Service catalog | Anonymous Users | Read-only public data |-| Contact form submission | Anonymous Users | Create-only permission |-| User registration | Anonymous Users → Authenticated Users | Transition after sign-up |-| User dashboard | Authenticated Users | Requires sign-in |-| Order history | Customers (custom) | User-specific data |-| Admin panel | Administrators | Restricted access |-| Partner portal | Partners (custom) | Business partner access |-| Premium content | Premium Members (custom) | Subscription-based |--### Role Selection by Operation--| Operation | Minimum Role | Recommended Role | Security Notes |-|-----------|--------------|------------------|----------------|-| View public content | Anonymous Users | Anonymous Users | Safe for all visitors |-| Submit forms | Anonymous Users | Anonymous Users | Create-only, no read |-| View own data | Authenticated Users | Custom role (e.g., Customers) | Self scope |-| Edit own data | Authenticated Users | Custom role (e.g., Customers) | Self scope |-| View all records | Administrators | Custom admin role | Global scope, audit access |-| Delete records | Administrators | Custom admin role | Highly restricted |--### Role Hierarchy Example--```text-┌─────────────────────────────────────────────────────────────────┐-│ ADMINISTRATORS │-│ • Full site access │-│ • Manage all content and users │-│ • Global scope permissions │-└─────────────────────────────────────────────────────────────────┘- ↓ inherits-┌─────────────────────────────────────────────────────────────────┐-│ AUTHENTICATED USERS │-│ • Signed-in users │-│ • Access protected pages │-│ • Self/Contact scope permissions │-├─────────────────────────────────────────────────────────────────┤-│ Custom roles (same level): │-│ • Customers - Order management, support tickets │-│ • Partners - Partner portal, deal management │-│ • Employees - Internal HR, tools │-│ • Premium Members - Premium content access │-└─────────────────────────────────────────────────────────────────┘- ↓ base level-┌─────────────────────────────────────────────────────────────────┐-│ ANONYMOUS USERS │-│ • Public visitors (no sign-in) │-│ • Read public content only │-│ • Submit forms (create-only) │-│ • Global scope, read-only │-└─────────────────────────────────────────────────────────────────┘-```--## Create Web Role Function--**IMPORTANT**: Always use `mspp_webroles` (not `adx_webroles`) for creating and querying web roles.--```powershell-function New-WebRole {- param(- [Parameter(Mandatory=$true)]- [string]$Name,-- [Parameter(Mandatory=$true)]- [string]$WebsiteId,-- [string]$Description = "",-- [bool]$AuthenticatedUsersRole = $false,-- [bool]$AnonymousUsersRole = $false- )-- # Generate unique ID for the web role (see alternatives below for non-PowerShell)- $webRoleId = [guid]::NewGuid().ToString()-- $webRole = @{- "mspp_webroleid" = $webRoleId- "mspp_name" = $Name- "mspp_description" = $Description- "mspp_authenticatedusersrole" = $AuthenticatedUsersRole- "mspp_anonymoususersrole" = $AnonymousUsersRole- "[email protected]" = "/mspp_websites($WebsiteId)"- }-- $body = $webRole | ConvertTo-Json -Depth 5-- try {- Invoke-RestMethod -Uri "$baseUrl/mspp_webroles" -Method Post -Headers $headers -Body $body- Write-Host "Created web role '$Name' with ID: $webRoleId"- return $webRoleId- }- catch {- Write-Host "Error creating web role '$Name': $_"- return $null- }-}-```--### Alternative UUID Generation Methods--If not using PowerShell, generate UUIDs using:--**Bash/Linux/Mac**:-```bash-uuidgen | tr '[:upper:]' '[:lower:]'-```--**Python**:-```python-import uuid-print(str(uuid.uuid4()))-```--**Online**: Use any UUID generator website--## Common Web Role Patterns--### Pattern 1: Public Website (Anonymous + Admin)--For simple public websites with admin management:--```powershell-# Anonymous Users - already exists, just verify (use mspp_webroles)-$anonymousRole = Invoke-RestMethod `- -Uri "$baseUrl/mspp_webroles?`$filter=mspp_name eq 'Anonymous Users' and _mspp_websiteid_value eq $websiteId" `- -Headers $headers--# Administrators - already exists, just verify-$adminRole = Invoke-RestMethod `- -Uri "$baseUrl/mspp_webroles?`$filter=mspp_name eq 'Administrators' and _mspp_websiteid_value eq $websiteId" `- -Headers $headers--Write-Host "Using existing roles: Anonymous Users, Administrators"-```--### Pattern 2: Member Portal (Add Authenticated Users)--For sites requiring user sign-in:--```powershell-# Verify Authenticated Users role exists (use mspp_webroles)-$authRole = Invoke-RestMethod `- -Uri "$baseUrl/mspp_webroles?`$filter=mspp_name eq 'Authenticated Users' and _mspp_websiteid_value eq $websiteId" `- -Headers $headers--if ($authRole.value.Count -eq 0) {- # Create Authenticated Users role- New-WebRole -Name "Authenticated Users" `- -WebsiteId $websiteId `- -Description "Users who have signed in to the site" `- -AuthenticatedUsersRole $true-}-```--### Pattern 3: Customer Portal (Custom Customer Role)--For customer-facing portals with order management:--```powershell-# Create Customers role-$customerRoleId = New-WebRole -Name "Customers" `- -WebsiteId $websiteId `- -Description "Registered customers with access to orders and support"--# Create Support Agents role (for customer service team)-$supportRoleId = New-WebRole -Name "Support Agents" `- -WebsiteId $websiteId `- -Description "Customer support team members"-```--### Pattern 4: Partner Portal (Custom Partner Role)--For B2B partner portals:--```powershell-# Create Partners role-$partnerRoleId = New-WebRole -Name "Partners" `- -WebsiteId $websiteId `- -Description "Business partners with access to partner portal"--# Create Partner Managers role-$partnerManagerRoleId = New-WebRole -Name "Partner Managers" `- -WebsiteId $websiteId `- -Description "Internal team managing partner relationships"-```--### Pattern 5: Subscription Site (Premium Members)--For sites with premium/paid content:--```powershell-# Create Premium Members role-$premiumRoleId = New-WebRole -Name "Premium Members" `- -WebsiteId $websiteId `- -Description "Users with active premium subscription"--# Create Free Members role-$freeRoleId = New-WebRole -Name "Free Members" `- -WebsiteId $websiteId `- -Description "Users with free tier access"-```--### Pattern 6: Employee Portal (Internal Staff)--For internal company portals:--```powershell-# Create Employees role-$employeeRoleId = New-WebRole -Name "Employees" `- -WebsiteId $websiteId `- -Description "Internal company employees"--# Create Managers role-$managerRoleId = New-WebRole -Name "Managers" `- -WebsiteId $websiteId `- -Description "Department managers with elevated access"--# Create HR role-$hrRoleId = New-WebRole -Name "HR Team" `- -WebsiteId $websiteId `- -Description "Human resources team members"-```--## Get Existing Web Roles--### List All Web Roles--```powershell-function Get-WebRoles {- param(- [Parameter(Mandatory=$true)]- [string]$WebsiteId- )-- # Use mspp_webroles (not adx_webroles)- $roles = Invoke-RestMethod `- -Uri "$baseUrl/mspp_webroles?`$filter=_mspp_websiteid_value eq $WebsiteId&`$select=mspp_webroleid,mspp_name,mspp_description,mspp_authenticatedusersrole,mspp_anonymoususersrole" `- -Headers $headers-- return $roles.value-}--# Get all roles for the website-$allRoles = Get-WebRoles -WebsiteId $websiteId-$allRoles | ForEach-Object {- Write-Host "Role: $($_.mspp_name) | ID: $($_.mspp_webroleid) | Auth Required: $($_.mspp_authenticatedusersrole) | Anonymous: $($_.mspp_anonymoususersrole)"-}-```--### Get Specific Web Role ID--```powershell-function Get-WebRoleId {- param(- [Parameter(Mandatory=$true)]- [string]$RoleName,-- [Parameter(Mandatory=$true)]- [string]$WebsiteId- )-- # Use mspp_webroles (not adx_webroles)- $role = Invoke-RestMethod `- -Uri "$baseUrl/mspp_webroles?`$filter=mspp_name eq '$RoleName' and _mspp_websiteid_value eq $WebsiteId&`$select=mspp_webroleid" `- -Headers $headers-- if ($role.value.Count -gt 0) {- return $role.value[0].mspp_webroleid- }- return $null-}--# Example usage-$anonymousRoleId = Get-WebRoleId -RoleName "Anonymous Users" -WebsiteId $websiteId-$authRoleId = Get-WebRoleId -RoleName "Authenticated Users" -WebsiteId $websiteId-$adminRoleId = Get-WebRoleId -RoleName "Administrators" -WebsiteId $websiteId-```--## Assign Users to Web Roles--### Associate Contact with Web Role--```powershell-function Add-ContactToWebRole {- param(- [Parameter(Mandatory=$true)]- [string]$ContactId,-- [Parameter(Mandatory=$true)]- [string]$WebRoleId- )-- $association = @{- "@odata.id" = "$baseUrl/contacts($ContactId)"- }-- try {- # Use mspp_webroles (not adx_webroles)- Invoke-RestMethod `- -Uri "$baseUrl/mspp_webroles($WebRoleId)/mspp_webrole_contact/`$ref" `- -Method Post `- -Headers $headers `- -Body ($association | ConvertTo-Json)- Write-Host "Added contact $ContactId to web role $WebRoleId"- }- catch {- Write-Host "Error adding contact to role: $_"- }-}--# Example: Add a contact to Customers role-# $contactId = "<CONTACT_GUID>"-# $customersRoleId = Get-WebRoleId -RoleName "Customers" -WebsiteId $websiteId-# Add-ContactToWebRole -ContactId $contactId -WebRoleId $customersRoleId-```--### Remove Contact from Web Role--```powershell-function Remove-ContactFromWebRole {- param(- [Parameter(Mandatory=$true)]- [string]$ContactId,-- [Parameter(Mandatory=$true)]- [string]$WebRoleId- )-- try {- # Use mspp_webroles (not adx_webroles)- Invoke-RestMethod `- -Uri "$baseUrl/mspp_webroles($WebRoleId)/mspp_webrole_contact($ContactId)/`$ref" `- -Method Delete `- -Headers $headers- Write-Host "Removed contact $ContactId from web role $WebRoleId"- }- catch {- Write-Host "Error removing contact from role: $_"- }-}-```--## Web Role and Table Permission Matrix--After creating web roles, use this matrix to plan table permissions:--| Table Type | Anonymous Users | Authenticated Users | Custom Role | Administrators |-|------------|-----------------|---------------------|-------------|----------------|-| Products (public) | Read | Read | Read | Full CRUD |-| FAQs (public) | Read | Read | Read | Full CRUD |-| Contact submissions | Create | Create | Create | Read, Delete |-| User profiles | - | Read/Write (Self) | Read/Write (Self) | Full CRUD |-| Orders | - | - | Read/Write (Contact) | Full CRUD |-| Support tickets | - | Create | Read/Write (Self) | Full CRUD |-| Partner deals | - | - | Read/Write (Account) | Full CRUD |-| Admin settings | - | - | - | Full CRUD |--## Complete Setup Script--Here's a complete script to set up web roles for a typical site:--```powershell-# ============================================-# Power Pages Web Roles Setup Script-# ============================================--param(- [Parameter(Mandatory=$true)]- [string]$WebsiteId,-- [Parameter(Mandatory=$false)]- [string[]]$CustomRoles = @()-)--# Setup authentication-$envUrl = (pac org who --json | ConvertFrom-Json).OrgUrl-$token = (az account get-access-token --resource $envUrl --query accessToken -o tsv)--$headers = @{- "Authorization" = "Bearer $token"- "Content-Type" = "application/json"- "OData-MaxVersion" = "4.0"- "OData-Version" = "4.0"-}--$baseUrl = "$envUrl/api/data/v9.2"--# Verify default roles exist (use mspp_webroles)-Write-Host "`n=== Verifying Default Web Roles ===" -ForegroundColor Cyan--$defaultRoles = @("Anonymous Users", "Authenticated Users", "Administrators")-$roleIds = @{}--foreach ($roleName in $defaultRoles) {- $role = Invoke-RestMethod `- -Uri "$baseUrl/mspp_webroles?`$filter=mspp_name eq '$roleName' and _mspp_websiteid_value eq $WebsiteId" `- -Headers $headers-- if ($role.value.Count -gt 0) {- $roleIds[$roleName] = $role.value[0].mspp_webroleid- Write-Host "✓ Found: $roleName (ID: $($roleIds[$roleName]))" -ForegroundColor Green- } else {- Write-Host "✗ Missing: $roleName" -ForegroundColor Yellow- }-}--# Create custom roles if specified-if ($CustomRoles.Count -gt 0) {- Write-Host "`n=== Creating Custom Web Roles ===" -ForegroundColor Cyan-- foreach ($customRole in $CustomRoles) {- $existingRole = Invoke-RestMethod `- -Uri "$baseUrl/mspp_webroles?`$filter=mspp_name eq '$customRole' and _mspp_websiteid_value eq $WebsiteId" `- -Headers $headers-- if ($existingRole.value.Count -eq 0) {- $roleId = New-WebRole -Name $customRole -WebsiteId $WebsiteId -Description "Custom role: $customRole"- if ($roleId) {- $roleIds[$customRole] = $roleId- Write-Host "✓ Created: $customRole" -ForegroundColor Green- }- } else {- $roleIds[$customRole] = $existingRole.value[0].mspp_webroleid- Write-Host "→ Already exists: $customRole" -ForegroundColor Yellow- }- }-}--# Output summary-Write-Host "`n=== Web Roles Summary ===" -ForegroundColor Cyan-$roleIds.GetEnumerator() | ForEach-Object {- Write-Host " $($_.Key): $($_.Value)"-}--return $roleIds-```--### Usage Examples--```powershell-# Basic setup (verify default roles only)-$roleIds = .\Setup-WebRoles.ps1 -WebsiteId $websiteId--# Customer portal setup-$roleIds = .\Setup-WebRoles.ps1 -WebsiteId $websiteId -CustomRoles @("Customers", "Support Agents")--# Partner portal setup-$roleIds = .\Setup-WebRoles.ps1 -WebsiteId $websiteId -CustomRoles @("Partners", "Partner Managers")--# Full enterprise setup-$roleIds = .\Setup-WebRoles.ps1 -WebsiteId $websiteId -CustomRoles @(- "Customers",- "Partners",- "Employees",- "Premium Members",- "Support Agents"-)-```--## Security Best Practices--1. **Principle of Least Privilege**: Assign users the minimum role needed for their tasks-2. **Avoid Administrator Role**: Create specific roles instead of broadly using Administrators-3. **Separate Read and Write Roles**: Consider separate roles for viewing vs. modifying data-4. **Regular Audits**: Review role assignments periodically-5. **Document Role Purposes**: Maintain clear descriptions for each custom role-6. **Test Role Permissions**: Verify access levels before production deployment--## Next Steps--After creating web roles:--1. **Create Table Permissions**: Use `table-permissions-reference.md` to set up data access-2. **Associate Permissions with Roles**: Link table permissions to appropriate web roles-3. **Configure Site Settings**: Enable Web API for required tables-4. **Test Access Levels**: Verify each role has correct access--## Reference Documentation--- [Configure web roles - Microsoft Learn](https://learn.microsoft.com/en-us/power-pages/security/create-web-roles)-- [Table permissions - Microsoft Learn](https://learn.microsoft.com/en-us/power-pages/security/table-permissions)-- [Web API security - Microsoft Learn](https://learn.microsoft.com/en-us/power-pages/configure/web-api-security)