Skip to content

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.

Update skills and marketplace (#2)

Priyanshu Agrawalec4053d817cf
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json
new file mode 100644
index 000000000..e9d205a0c
--- /dev/null
+++ b/.claude-plugin/marketplace.json
@@ -0,0 +1,38 @@
+{
+ "name": "power-platform-claude-plugins-official",
+ "description": "Directory of Claude Code extensions for Power Platform development",
+ "owner": {
+ "name": "Microsoft"
+ },
+ "plugins": [
+ {
+ "name": "power-pages",
+ "description": "Power Pages development and management plugin for Claude Code",
+ "version": "1.0.0",
+ "author": {
+ "name": "Microsoft"
+ },
+ "source": "./plugins/power-pages",
+ "category": "development",
+ "strict": false,
+ "lspServers": {
+ "typescript": {
+ "command": "typescript-language-server",
+ "args": [
+ "--stdio"
+ ],
+ "extensionToLanguage": {
+ ".ts": "typescript",
+ ".tsx": "typescriptreact",
+ ".js": "javascript",
+ ".jsx": "javascriptreact",
+ ".mts": "typescript",
+ ".cts": "typescript",
+ ".mjs": "javascript",
+ ".cjs": "javascript"
+ }
+ }
+ }
+ }
+ ]
+}
diff --git a/.claude/CLAUDE.md b/.claude/CLAUDE.md
new file mode 120000
index 000000000..be77ac83a
--- /dev/null
+++ b/.claude/CLAUDE.md
@@ -0,0 +1 @@
+../AGENTS.md
\ No newline at end of file
diff --git a/AGENTS.md b/AGENTS.md
new file mode 100644
index 000000000..667e3710c
--- /dev/null
+++ b/AGENTS.md
@@ -0,0 +1,114 @@
+# Power Platform Claude Plugins - Development Guidelines
+
+This file provides instructions for Claude Code when working on this plugin marketplace.
+
+## Official Documentation
+
+**Always refer to official Claude Code documentation when modifying plugin structure:**
+
+- **Skills**: https://code.claude.com/docs/en/skills
+- **Plugins Reference**: https://code.claude.com/docs/en/plugins-reference
+
+## Repository Structure
+
+This repository is a **plugin marketplace** containing multiple plugins:
+
+```
+power-platform-claude-plugin/
+├── .claude-plugin/
+│ └── marketplace.json # Marketplace manifest (lists all available plugins)
+├── plugins/ # Directory containing individual plugins
+│ └── power-pages/ # Power Pages plugin
+│ ├── .claude-plugin/
+│ │ └── plugin.json # Plugin manifest
+│ ├── .mcp.json # MCP server configuration
+│ ├── agents/ # Agent persona files
+│ ├── commands/ # Command entry points
+│ ├── shared/ # Shared resources and documentation
+│ └── skills/ # Skill workflows (SKILL.md in subdirectories)
+├── AGENTS.md # Development guidelines
+└── 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
+- Plugin components (agents, commands, skills, shared) must be at the plugin root, not inside `.claude-plugin/`
+
+## When Modifying Skills
+
+Skills use YAML frontmatter. Reference the official docs for all available fields:
+
+```yaml
+---
+name: skill-name # Optional: defaults to directory name
+description: What this skill does # Recommended: Claude uses for auto-loading
+user-invocable: true # Optional: default true
+disable-model-invocation: false # Optional: default false
+allowed-tools: Read, Bash(pac:*) # Optional: tool restrictions
+argument-hint: [project-path] # Optional: autocomplete hint
+context: fork # Optional: run in subagent
+agent: Explore # Optional: subagent type
+model: opus # Optional: model override
+---
+```
+
+## When Modifying Agents
+
+Agents support optional frontmatter:
+
+```yaml
+---
+description: What this agent specializes in
+capabilities: ["task1", "task2"]
+---
+```
+
+## When Modifying plugin.json
+
+Refer to https://code.claude.com/docs/en/plugins-reference for all available fields.
+
+Required: `name`
+Recommended: `version`, `description`, `author`, `license`, `keywords`
+
+## Environment Variables
+
+Use these in skills, hooks, and scripts:
+
+- `${CLAUDE_PLUGIN_ROOT}` - Absolute path to plugin directory
+- `${CLAUDE_SESSION_ID}` - Current session ID
+- `$ARGUMENTS` - Arguments passed to skill
+
+## Memory Bank System
+
+Plugins use a memory bank (`memory-bank.md`) to persist state across sessions.
+
+- 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
+
+## Tool Restrictions
+
+Skills in this plugin use restricted tools for security:
+
+- `Bash(pac:*)` - PAC CLI commands only
+- `Bash(az:*)` - Azure CLI commands only
+- `Bash(dotnet:*)` - .NET CLI commands only
+
+## Testing Changes
+
+After modifying plugin files:
+
+1. Run `claude --debug` to see plugin loading details
+2. Test skill invocation with `/skill-name`
+3. Verify tool restrictions work as expected
+
+## Adding a New Plugin
+
+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
diff --git a/README.md b/README.md
index 87f122599..f8747ccbb 100644
--- a/README.md
+++ b/README.md
@@ -1,96 +1,75 @@
-# Power Pages Site Builder Plugin (v3)
+# Power Platform Claude Plugins
-Create and deploy Power Pages sites using modern development approaches.
-
-**Currently supported**: Code Sites (SPAs) with React, Angular, Vue, or Astro
-**Coming soon**: Standard sites, Enhanced data model sites, Templates
+Official Claude Code extensions for Power Platform development by Microsoft.
## Overview
-This plugin enables makers to:
-
-1. **Create** a Power Pages code site using their preferred frontend framework
-2. **Design** production-grade UI with the frontend-design skill
-3. **Upload** the site to Power Pages using PAC CLI
-4. **Activate** the website via Power Pages REST API
-5. **Verify** deployment and get the live URL
+This repository is a **plugin marketplace** containing Claude Code plugins for Power Platform services. Each plugin provides skills, agents, and commands to help developers build on the Power Platform.
-## Quick Start
+## Repository Structure
-Run the skill:
```
-/create-code-site
+power-platform-claude-plugin/
+├── .claude-plugin/
+│ └── marketplace.json # Marketplace manifest (lists all plugins)
+├── plugins/
+│ └── power-pages/ # Individual plugin directory
+│ ├── .claude-plugin/
+│ │ └── plugin.json # Plugin manifest
+│ ├── .mcp.json # MCP server configuration
+│ ├── agents/ # Agent persona files
+│ ├── commands/ # Command entry points
+│ ├── shared/ # Shared resources
+│ └── skills/ # Skill workflows
+├── AGENTS.md # Development guidelines
+└── README.md
```
-The skill will guide you through:
-- Choosing a frontend framework (React, Angular, Vue, Astro)
-- Defining site features and design preferences
-- Building and deploying the site
-
-## Prerequisites
-
-- **PAC CLI** (v1.44+) installed and authenticated
-- **Azure CLI** installed for API authentication
-- **Node.js** (v18+) for building frontend projects
-- Power Pages environment with admin privileges
+## Available Plugins
-## Workflow
+### Power Pages (`plugins/power-pages`)
-```
-┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐
-│ 1. Design │ ──▶ │ 2. Build │ ──▶ │ 3. Upload │ ──▶ │ 4. Activate │
-│ & Create │ │ Project │ │ (Inactive) │ │ (Go Live) │
-└─────────────┘ └─────────────┘ └─────────────┘ └─────────────┘
-```
+Create and deploy Power Pages sites using modern development approaches.
-## Available Skills
+**Currently supported**: Code Sites (SPAs) with React, Angular, Vue, or Astro
| Skill | Description |
|-------|-------------|
-| `create-code-site` | Full workflow to create, upload, and activate a Power Pages code site |
-
-## Supported Frameworks
+| `/create-site` | Create, upload, and activate a Power Pages code site |
+| `/setup-dataverse` | Configure Dataverse tables and relationships |
+| `/setup-webapi` | Set up Web API integration for data access |
+
+**Prerequisites:**
+- PAC CLI (v1.44+) installed and authenticated
+- Azure CLI installed for API authentication
+- Node.js (v18+) for building frontend projects
+- Power Pages environment with admin privileges
-| Framework | Recommended For | Build Output |
-|-----------|-----------------|--------------|
-| **React** (Recommended) | Complex interactive UIs | `/build` |
-| **Angular** | Enterprise applications | `/dist/<project>` |
-| **Vue** | Balanced simplicity/power | `/dist` |
-| **Astro** | Content-focused sites | `/dist` |
+## Installation
-## Key Commands
+To use a plugin from this marketplace, reference it in your Claude Code configuration:
-### PAC CLI - Upload Code Site
-```bash
-pac pages upload-code-site \
- --rootPath "./my-site" \
- --compiledPath "./build" \
- --siteName "My Site"
+```json
+{
+ "plugins": ["./plugins/power-pages"]
+}
```
-### Power Pages API - Activate Website
-```
-POST https://api.powerplatform.com/powerpages/environments/{envId}/websites
-```
+## Workflow Example (Power Pages)
-### Power Pages API - Check Status
```
-GET https://api.powerplatform.com/powerpages/environments/{envId}/websites
+┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐
+│ 1. Design │ ──▶ │ 2. Build │ ──▶ │ 3. Upload │ ──▶ │ 4. Activate │
+│ & Create │ │ Project │ │ (Inactive) │ │ (Go Live) │
+└─────────────┘ └─────────────┘ └─────────────┘ └─────────────┘
```
-## Next Steps After Deployment
-
-After your site is live, consider:
-
-1. **Web API Integration** - Connect to Dataverse data
-2. **Authentication** - Enable Microsoft Entra ID sign-in
-3. **Table Permissions** - Configure data access security
-
## Documentation
- [Power Pages Code Sites](https://learn.microsoft.com/en-us/power-pages/configure/create-code-sites)
- [Power Pages REST API](https://learn.microsoft.com/en-us/rest/api/power-platform/powerpages/websites)
- [PAC CLI Reference](https://learn.microsoft.com/en-us/power-platform/developer/cli/reference/pages)
+- [Claude Code Plugins](https://code.claude.com/docs/en/plugins-reference)
## Contributing
diff --git a/.claude-plugin/plugin.json b/plugins/.claude-plugin/plugin.json
similarity index 90%
rename from .claude-plugin/plugin.json
rename to plugins/.claude-plugin/plugin.json
index 1f666ff4b..a515a8f26 100644
--- a/.claude-plugin/plugin.json
+++ b/plugins/.claude-plugin/plugin.json
@@ -19,6 +19,10 @@
"vue",
"astro",
"pac-cli",
- "dataverse"
+ "dataverse",
+ "odata",
+ "web-api",
+ "tables",
+ "schema"
]
}
diff --git a/plugins/.mcp.json b/plugins/.mcp.json
new file mode 100644
index 000000000..54b3fe926
--- /dev/null
+++ b/plugins/.mcp.json
@@ -0,0 +1,8 @@
+{
+ "playwright": {
+ "command": "npx",
+ "args": [
+ "@playwright/mcp@latest"
+ ]
+ }
+}
diff --git a/agents/code-site-architect.md b/plugins/agents/code-site-architect.md
similarity index 100%
rename from agents/code-site-architect.md
rename to plugins/agents/code-site-architect.md
diff --git a/commands/create-site.md b/plugins/commands/create-site.md
similarity index 100%
rename from commands/create-site.md
rename to plugins/commands/create-site.md
diff --git a/plugins/commands/setup-dataverse.md b/plugins/commands/setup-dataverse.md
new file mode 100644
index 000000000..1d38284cf
--- /dev/null
+++ b/plugins/commands/setup-dataverse.md
@@ -0,0 +1,5 @@
+# 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.
+
+DO NOT summarize the skill instructions. Follow them step by step, using the tools available to you as directed.
diff --git a/plugins/commands/setup-webapi.md b/plugins/commands/setup-webapi.md
new file mode 100644
index 000000000..bc19808f8
--- /dev/null
+++ b/plugins/commands/setup-webapi.md
@@ -0,0 +1,5 @@
+# Setup Web API
+
+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.
+
+DO NOT summarize the skill instructions. Follow them step by step, using the tools available to you as directed.
diff --git a/plugins/shared/memory-bank.md b/plugins/shared/memory-bank.md
new file mode 100644
index 000000000..cb58d3721
--- /dev/null
+++ b/plugins/shared/memory-bank.md
@@ -0,0 +1,255 @@
+# Memory Bank Instructions
+
+This document defines the memory bank system used to persist context across conversations and skill invocations. **All skills in this plugin follow these instructions.**
+
+## Overview
+
+The memory bank (`memory-bank.md`) is a markdown file stored in the project root that tracks:
+
+- Project configuration and metadata
+- Completed steps and progress
+- User decisions and preferences
+- Created resources (tables, permissions, etc.)
+- Current status and next steps
+
+## File Location
+
+The memory bank is always stored at: `<PROJECT_ROOT>/memory-bank.md`
+
+---
+
+## Before Starting Any Skill
+
+**IMPORTANT**: Every skill MUST check for and read the memory bank before proceeding.
+
+### Step 1: Locate the Memory Bank
+
+1. If the user has specified a project path, check `<PROJECT_PATH>/memory-bank.md`
+2. If continuing from a previous skill in the same session, use the known project path
+3. If no path is known, ask the user for the project path
+
+### Step 2: Read and Parse Context
+
+If the memory bank exists, extract:
+
+| Information | Purpose |
+|-------------|---------|
+| Project path, name, framework | Know what you're working with |
+| Completed steps (checkboxes) | Skip steps already done |
+| User preferences | Don't re-ask answered questions |
+| Created resources | Know what tables/settings exist |
+| Current status | Understand where to resume |
+
+### Step 3: Resume or Continue
+
+- **If the current skill's steps are already marked complete**: Ask if they want to modify, add more, or skip to next steps
+- **If partially complete**: Inform the user and resume from the incomplete step
+- **If not started**: Begin from the first step
+
+### Step 4: Inform the User
+
+Always tell the user what you found:
+
+> "I found your project memory bank. [Summary: project name, framework, what's been completed]. Let's continue from [next step]."
+
+---
+
+## After Each Major Step
+
+Update the memory bank immediately after completing each major step. This ensures progress is saved even if the session ends unexpectedly.
+
+### What to Update
+
+1. **Mark completed steps** with `[x]`
+2. **Record created resources** (tables, settings, files)
+3. **Save user decisions** (framework choice, integration approach, etc.)
+4. **Update current status** and next step
+5. **Add timestamp** to "Last Updated"
+6. **Add notes** for important context or decisions
+
+### Update Frequency
+
+Update after:
+
+- Completing any workflow step
+- User makes a significant decision
+- Creating or modifying resources
+- Encountering errors or issues worth noting
+- Before ending a session
+
+---
+
+## When to Create vs Update
+
+| Scenario | Action |
+|----------|--------|
+| Memory bank doesn't exist | Create it after the first major step (e.g., after site creation) |
+| Memory bank exists | Update it - preserve existing content, add new information |
+| Continuing previous session | Read first, then update as you progress |
+
+## Template Structure
+
+```markdown
+# Power Pages Project Memory Bank
+
+> Last Updated: [TIMESTAMP]
+> Session: [SESSION_ID or conversation context]
+
+## Project Overview
+
+| Property | Value |
+|----------|-------|
+| Project Name | [SITE_NAME] |
+| Project Path | [FULL_PATH] |
+| Framework | [React/Angular/Vue/Astro] |
+| Created Date | [DATE] |
+| Status | [In Progress/Site Created/Tables Setup/Deployed] |
+
+## User Preferences
+
+### Design Preferences
+- Style: [Modern/Corporate/Creative/Elegant]
+- Color Scheme: [Description or hex codes]
+- Special Requirements: [Accessibility, mobile-first, etc.]
+
+### Technical Preferences
+- Data Integration: [MCP Server/OData API]
+- Authentication: [Enabled/Disabled] - [Provider if enabled]
+
+## Completed Steps
+
+### /create-site
+- [x] Requirements gathered
+- [x] Framework selected: [FRAMEWORK]
+- [x] Site created with features: [LIST]
+- [x] powerpages.config.json created
+- [x] Project built successfully
+- [x] Prerequisites verified (PAC CLI, Azure CLI)
+- [x] Uploaded to Power Pages (Inactive)
+- [x] Site activated
+- Website ID: [GUID]
+- Site URL: [URL]
+
+### /setup-dataverse
+- [x] Site analyzed
+- [x] Schema recommended
+- [x] Integration approach chosen: [MCP/OData]
+- [x] Tables created: [LIST]
+- [x] Sample data inserted
+
+### /setup-webapi
+- [x] Site settings created for Web API
+- [x] Table permissions configured
+- [x] Frontend code updated
+- [x] Project built and uploaded
+
+## Created Resources
+
+### 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 |
+
+### Site Settings
+
+| Setting | Value |
+|---------|-------|
+| Webapi/cr_product/enabled | true |
+| Webapi/cr_product/fields | cr_name,cr_description,cr_price,cr_category |
+
+## Current Status
+
+**Last Action**: [Description of last completed action]
+
+**Next Step**: [What the user should do next]
+
+**Pending Items**:
+- [ ] [Item 1]
+- [ ] [Item 2]
+
+## Notes & Issues
+
+### Session Notes
+- [Date]: [Note about decisions, issues, or context]
+
+### Known Issues
+- [Issue description and any workarounds]
+
+## Quick Resume
+
+To continue working on this project:
+
+1. **Create Site**: `/create-site` (creates new site or updates existing)
+2. **Setup Dataverse Tables**: `/setup-dataverse` (creates tables and sample data)
+3. **Setup Web API**: `/setup-webapi` (enables Web API access and updates frontend)
+4. **Manual**: Navigate to [PROJECT_PATH] and continue development
+```
+
+## Reading the Memory Bank
+
+When reading the memory bank, extract:
+
+1. **Project context**: Path, framework, name
+2. **Completed work**: Check checkboxes to know what's done
+3. **User preferences**: Apply these without re-asking
+4. **Created resources**: Know what tables/settings exist
+5. **Current status**: Understand where to resume
+
+## Writing Guidelines
+
+1. **Be concise**: Use tables and lists, not paragraphs
+2. **Be specific**: Include exact values, paths, GUIDs
+3. **Timestamp updates**: Always update "Last Updated"
+4. **Preserve history**: Add to notes, don't overwrite
+5. **Track decisions**: Record why choices were made
+
+## Example: Checking Memory Bank
+
+```text
+At the start of /setup-dataverse:
+
+1. Read memory-bank.md from project root
+2. Check if /setup-dataverse steps are already marked complete
+3. If tables are already created, ask user if they want to:
+ - Add more tables
+ - Modify existing tables
+ - Add more sample data
+ - Skip to next step
+4. Apply saved preferences (e.g., MCP vs OData choice)
+```
+
+## Integration with Skills
+
+Both skills should include these instructions:
+
+### At Skill Start
+
+```text
+### Check Memory Bank
+
+Before proceeding, check if a memory bank exists:
+
+1. Look for `memory-bank.md` in the project root
+2. If found, read it to understand:
+ - What steps have been completed
+ - What user preferences were chosen
+ - What resources already exist
+3. Adjust your workflow to skip completed steps
+4. Inform the user what you found and where you'll resume
+```
+
+### At Skill End / After Major Steps
+
+```text
+### Update Memory Bank
+
+After completing this step, update the memory bank:
+
+1. Create or update `memory-bank.md` in the project root
+2. Mark completed steps with [x]
+3. Record any new resources created
+4. Update the "Current Status" section
+5. Add any relevant notes
+```
diff --git a/plugins/skills/create-site/SKILL.md b/plugins/skills/create-site/SKILL.md
new file mode 100644
index 000000000..94bc69a77
--- /dev/null
+++ b/plugins/skills/create-site/SKILL.md
@@ -0,0 +1,1338 @@
+---
+description: Create a Power Pages code site (SPA) using modern frontend frameworks like React, Angular, Vue, or Astro. Guides through design, build, upload, and activation.
+user-invocable: true
+allowed-tools: Bash(pac:*), Bash(az:*)
+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.
+
+## 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 │
+└─────────────────────────────────────────────────────────────────────────────┘
+```
+
+---
+
+## STEP 1: Gather Requirements
+
+**IMPORTANT**: Before creating anything, you MUST ask the maker the following questions using the AskUserQuestion tool.
+
+### 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
+
+Based on what they want to build, 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. |
+
+> **⚠️ IMPORTANT: Unsupported Technologies**
+>
+> Power Pages code sites are **static SPAs** served from Azure CDN. The following technologies are **NOT supported**:
+>
+> - **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:
+
+- Landing page / Hero section
+- Navigation menu
+- Contact form
+- About page
+- Services/Products showcase
+- Image gallery
+- Blog/News section
+- User authentication (Microsoft Entra ID)
+- Data display from Dataverse (Web API)
+
+### Question 4: Design Preferences
+
+Ask about design preferences:
+
+- **Style**: Modern/Minimalist, Corporate/Professional, Creative/Bold, Elegant/Luxury
+- **Color scheme**: Let them specify or suggest based on their brand
+- **Special requirements**: Accessibility, mobile-first, specific branding guidelines
+
+---
+
+## STEP 2: Create the Site
+
+After gathering requirements, use the **frontend-design skill** to create the site.
+
+### Instructions for Site Creation
+
+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**: 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
+```
+
+### Create powerpages.config.json
+
+After the site is created, add this configuration file:
+
+```json
+{
+ "siteName": "<SITE_NAME>",
+ "defaultLandingPage": "index.html",
+ "compiledPath": "./build"
+}
+```
+
+For Vue/Astro projects, change `compiledPath` to `"./dist"`.
+
+### Add SEO Meta Tags
+
+**IMPORTANT**: Ensure the `index.html` file includes comprehensive meta tags for SEO and social sharing. Update the `<head>` section with the following:
+
+```html
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <!-- Character encoding and viewport -->
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+
+ <!-- Primary Meta Tags -->
+ <title>[SITE_NAME] - [Brief Description]</title>
+ <meta name="title" content="[SITE_NAME] - [Brief Description]" />
+ <meta name="description" content="[150-160 character description of the site's purpose and value proposition]" />
+ <meta name="keywords" content="[keyword1], [keyword2], [keyword3], [relevant keywords]" />
+ <meta name="author" content="[Company/Author Name]" />
+ <meta name="robots" content="index, follow" />
+
+ <!-- Canonical URL -->
+ <link rel="canonical" href="https://[subdomain].powerappsportals.com/" />
+
+ <!-- Open Graph / Facebook -->
+ <meta property="og:type" content="website" />
+ <meta property="og:url" content="https://[subdomain].powerappsportals.com/" />
+ <meta property="og:title" content="[SITE_NAME] - [Brief Description]" />
+ <meta property="og:description" content="[Description for social sharing]" />
+ <meta property="og:image" content="https://[subdomain].powerappsportals.com/og-image.png" />
+ <meta property="og:image:width" content="1200" />
+ <meta property="og:image:height" content="630" />
+ <meta property="og:site_name" content="[SITE_NAME]" />
+ <meta property="og:locale" content="en_US" />
+
+ <!-- Twitter -->
+ <meta name="twitter:card" content="summary_large_image" />
+ <meta name="twitter:url" content="https://[subdomain].powerappsportals.com/" />
+ <meta name="twitter:title" content="[SITE_NAME] - [Brief Description]" />
+ <meta name="twitter:description" content="[Description for Twitter sharing]" />
+ <meta name="twitter:image" content="https://[subdomain].powerappsportals.com/og-image.png" />
+
+ <!-- Favicon -->
+ <link rel="icon" type="image/x-icon" href="/favicon.ico" />
+ <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png" />
+ <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png" />
+ <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png" />
+
+ <!-- Theme Color (for mobile browsers) -->
+ <meta name="theme-color" content="#[PRIMARY_COLOR_HEX]" />
+ <meta name="msapplication-TileColor" content="#[PRIMARY_COLOR_HEX]" />
+
+ <!-- Additional SEO -->
+ <meta name="format-detection" content="telephone=no" />
+ <meta http-equiv="X-UA-Compatible" content="IE=edge" />
+</head>
+```
+
+#### SEO Checklist
+
+Ensure the following assets are created and placed in the `public/` folder:
+
+| Asset | Size/Format | Purpose |
+|-------|-------------|---------|
+| `og-image.png` | 1200×630px | Social media sharing preview |
+| `favicon.ico` | 48×48px | Browser tab icon |
+| `favicon-32x32.png` | 32×32px | Modern browsers |
+| `favicon-16x16.png` | 16×16px | Small displays |
+| `apple-touch-icon.png` | 180×180px | iOS home screen |
+| `robots.txt` | Text file | Search engine crawl directives |
+| `sitemap.xml` | XML file | Site structure for search engines |
+
+#### Framework-Specific Notes
+
+**React (Vite)**: Edit `index.html` in the project root.
+
+**React (CRA)**: Edit `public/index.html`.
+
+**Vue**: Edit `index.html` in the project root.
+
+**Angular**: Edit `src/index.html` and update `angular.json` for favicon assets.
+
+**Astro**: Add meta tags in `src/layouts/Layout.astro` or use `<head>` slot.
+
+> **Note**: Replace all placeholder values (`[SITE_NAME]`, `[subdomain]`, etc.) with actual values based on user requirements gathered in Step 1.
+
+### Add robots.txt
+
+Create a `robots.txt` file in the `public/` folder to control search engine crawling:
+
+```txt
+# robots.txt for [SITE_NAME]
+# https://[subdomain].powerappsportals.com/robots.txt
+
+User-agent: *
+Allow: /
+
+# Sitemap location
+Sitemap: https://[subdomain].powerappsportals.com/sitemap.xml
+
+# Disallow admin or private paths (if any)
+# Disallow: /admin/
+# Disallow: /private/
+```
+
+#### robots.txt Best Practices
+
+| 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` |
+
+### Add sitemap.xml
+
+**IMPORTANT**: Create a `sitemap.xml` file to help search engines discover and crawl all pages on your site. This is essential for SEO.
+
+Create `sitemap.xml` in the `public/` folder:
+
+```xml
+<?xml version="1.0" encoding="UTF-8"?>
+<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
+ <!-- Homepage -->
+ <url>
+ <loc>https://[subdomain].powerappsportals.com/</loc>
+ <lastmod>[YYYY-MM-DD]</lastmod>
+ <changefreq>weekly</changefreq>
+ <priority>1.0</priority>
+ </url>
+
+ <!-- About Page -->
+ <url>
+ <loc>https://[subdomain].powerappsportals.com/about</loc>
+ <lastmod>[YYYY-MM-DD]</lastmod>
+ <changefreq>monthly</changefreq>
+ <priority>0.8</priority>
+ </url>
+
+ <!-- Contact Page -->
+ <url>
+ <loc>https://[subdomain].powerappsportals.com/contact</loc>
+ <lastmod>[YYYY-MM-DD]</lastmod>
+ <changefreq>monthly</changefreq>
+ <priority>0.8</priority>
+ </url>
+
+ <!-- Services/Products Page -->
+ <url>
+ <loc>https://[subdomain].powerappsportals.com/services</loc>
+ <lastmod>[YYYY-MM-DD]</lastmod>
+ <changefreq>monthly</changefreq>
+ <priority>0.7</priority>
+ </url>
+
+ <!-- Add all public pages in your SPA -->
+</urlset>
+```
+
+#### Sitemap Elements Reference
+
+| 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
+
+| 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 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 Sitemap After Deployment
+
+After the site is active, verify the sitemap is accessible:
+
+```
+https://[subdomain].powerappsportals.com/sitemap.xml
+```
+
+> **Note**: Update the sitemap whenever you add new pages to your site. Replace `[subdomain]` with your actual subdomain and `[YYYY-MM-DD]` with the current date.
+
+### Write Unit Tests
+
+**IMPORTANT**: Before building for production, write unit tests for the generated site to ensure code quality and prevent regressions.
+
+#### Set Up Testing Framework
+
+Install the appropriate testing dependencies based on the chosen framework:
+
+```powershell
+# React (Vite) - Vitest + React Testing Library
+npm install -D vitest @testing-library/react @testing-library/jest-dom @testing-library/user-event jsdom
+
+# React (Create React App) - Already includes Jest + RTL
+# No additional installation needed
+
+# Angular - Already includes Jasmine + Karma
+# No additional installation needed
+
+# Vue (Vite) - Vitest + Vue Test Utils
+npm install -D vitest @vue/test-utils @testing-library/vue jsdom
+
+# Astro - Vitest
+npm install -D vitest
+```
+
+#### Configure Testing (Vite Projects)
+
+For Vite-based projects, add test configuration to `vite.config.ts`:
+
+```typescript
+/// <reference types="vitest" />
+import { defineConfig } from 'vite'
+import react from '@vitejs/plugin-react' // or vue()
+
+export default defineConfig({
+ plugins: [react()],
+ test: {
+ globals: true,
+ environment: 'jsdom',
+ setupFiles: './src/test/setup.ts',
+ coverage: {
+ provider: 'v8',
+ reporter: ['text', 'html'],
+ },
+ },
+})
+```
+
+Create `src/test/setup.ts`:
+
+```typescript
+import '@testing-library/jest-dom'
+```
+
+Add test scripts to `package.json`:
+
+```json
+{
+ "scripts": {
+ "test": "vitest",
+ "test:run": "vitest run",
+ "test:coverage": "vitest run --coverage"
+ }
+}
+```
+
+#### What to Test
+
+Write tests for the following:
+
+1. **Components** - Test rendering, user interactions, and props
+2. **Utility functions** - Test data transformations, validators, formatters
+3. **Custom hooks** (React/Vue) - Test state management and side effects
+4. **Form validation** - Test validation rules and error messages
+5. **API service functions** - Test Dataverse Web API wrapper functions (mock the API)
+
+#### Example Test 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
+// src/components/Header.test.tsx
+import { render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { Header } from './Header'
+
+describe('Header', () => {
+ it('renders the site title', () => {
+ render(<Header title="My Site" />)
+ expect(screen.getByRole('banner')).toHaveTextContent('My Site')
+ })
+
+ it('toggles mobile menu on button click', async () => {
+ const user = userEvent.setup()
+ render(<Header title="My Site" />)
+
+ const menuButton = screen.getByRole('button', { name: /menu/i })
+ await user.click(menuButton)
+
+ expect(screen.getByRole('navigation')).toBeVisible()
+ })
+})
+```
+
+#### Example Utility Test
+
+```typescript
+// src/utils/formatters.test.ts
+import { formatDate, formatCurrency } from './formatters'
+
+describe('formatDate', () => {
+ it('formats ISO date to readable string', () => {
+ expect(formatDate('2024-01-15')).toBe('January 15, 2024')
+ })
+
+ it('returns empty string for invalid date', () => {
+ expect(formatDate('invalid')).toBe('')
+ })
+})
+
+describe('formatCurrency', () => {
+ it('formats number as USD currency', () => {
+ expect(formatCurrency(1234.56)).toBe('$1,234.56')
+ })
+})
+```
+
+#### Run Tests
+
+Execute tests before building:
+
+```powershell
+# Run all tests
+npm test
+
+# Run tests once (CI mode)
+npm run test:run
+
+# Run with coverage report
+npm run test:coverage
+```
+
+**All unit tests must pass before proceeding to E2E tests.**
+
+### Write End-to-End Tests (Playwright)
+
+**IMPORTANT**: After unit tests pass, write end-to-end tests using Playwright to verify the complete user experience.
+
+#### Install Playwright
+
+```powershell
+# Install Playwright
+npm install -D @playwright/test
+
+# Install browsers (Chromium, Firefox, WebKit)
+npx playwright install
+```
+
+#### Configure Playwright
+
+Create `playwright.config.ts` in the project root:
+
+```typescript
+import { defineConfig, devices } from '@playwright/test'
+
+export default defineConfig({
+ testDir: './e2e',
+ fullyParallel: true,
+ forbidOnly: !!process.env.CI,
+ retries: process.env.CI ? 2 : 0,
+ workers: process.env.CI ? 1 : undefined,
+ reporter: 'html',
+ use: {
+ baseURL: 'http://localhost:5173', // Vite default, change for CRA (3000) or Angular (4200)
+ trace: 'on-first-retry',
+ screenshot: 'only-on-failure',
+ },
+ projects: [
+ {
+ name: 'chromium',
+ use: { ...devices['Desktop Chrome'] },
+ },
+ {
+ name: 'firefox',
+ use: { ...devices['Desktop Firefox'] },
+ },
+ {
+ name: 'webkit',
+ use: { ...devices['Desktop Safari'] },
+ },
+ {
+ name: 'Mobile Chrome',
+ use: { ...devices['Pixel 5'] },
+ },
+ {
+ name: 'Mobile Safari',
+ use: { ...devices['iPhone 12'] },
+ },
+ ],
+ webServer: {
+ command: 'npm run dev',
+ url: 'http://localhost:5173',
+ reuseExistingServer: !process.env.CI,
+ },
+})
+```
+
+> **Note**: Adjust `baseURL` and `webServer.url` based on your framework:
+> - **Vite (React/Vue)**: `http://localhost:5173`
+> - **Create React App**: `http://localhost:3000`
+> - **Angular**: `http://localhost:4200`
+> - **Astro**: `http://localhost:4321`
+
+Add E2E test scripts to `package.json`:
+
+```json
+{
+ "scripts": {
+ "test:e2e": "playwright test",
+ "test:e2e:ui": "playwright test --ui",
+ "test:e2e:headed": "playwright test --headed",
+ "test:e2e:report": "playwright show-report"
+ }
+}
+```
+
+#### E2E Test Structure
+
+```text
+/e2e
+├── home.spec.ts # Home page tests
+├── navigation.spec.ts # Navigation tests
+├── contact-form.spec.ts # Form submission tests
+├── responsive.spec.ts # Mobile responsiveness tests
+└── fixtures/
+ └── test-data.ts # Shared test data
+```
+
+#### What to Test with E2E
+
+Write E2E tests for critical user journeys:
+
+1. **Page Navigation** - All links work and routes load correctly
+2. **Form Submissions** - Contact forms, search, filters work end-to-end
+3. **Responsive Design** - Site works on mobile, tablet, and desktop
+4. **Interactive Elements** - Modals, dropdowns, accordions function properly
+5. **Accessibility** - Basic a11y checks (keyboard navigation, focus states)
+6. **Error States** - Error pages and validation messages display correctly
+
+#### Example E2E Tests
+
+**Home Page Test:**
+
+```typescript
+// e2e/home.spec.ts
+import { test, expect } from '@playwright/test'
+
+test.describe('Home Page', () => {
+ test('should display hero section with correct content', async ({ page }) => {
+ await page.goto('/')
+
+ // Check hero section
+ await expect(page.getByRole('heading', { level: 1 })).toBeVisible()
+ await expect(page.getByRole('banner')).toBeVisible()
+
+ // Check CTA button
+ const ctaButton = page.getByRole('link', { name: /get started/i })
+ await expect(ctaButton).toBeVisible()
+ })
+
+ test('should have valid meta tags', async ({ page }) => {
+ await page.goto('/')
+
+ // Check title
+ await expect(page).toHaveTitle(/My Site/)
+
+ // Check meta description
+ const metaDescription = page.locator('meta[name="description"]')
+ await expect(metaDescription).toHaveAttribute('content', /.+/)
+ })
+})
+```
+
+**Navigation Test:**
+
+```typescript
+// e2e/navigation.spec.ts
+import { test, expect } from '@playwright/test'
+
+test.describe('Navigation', () => {
+ test('should navigate to all main pages', async ({ page }) => {
+ await page.goto('/')
+
+ // Navigate to About page
+ await page.getByRole('link', { name: /about/i }).click()
+ await expect(page).toHaveURL(/.*about/)
+ await expect(page.getByRole('heading', { name: /about/i })).toBeVisible()
+
+ // Navigate to Contact page
+ await page.getByRole('link', { name: /contact/i }).click()
+ await expect(page).toHaveURL(/.*contact/)
+ await expect(page.getByRole('heading', { name: /contact/i })).toBeVisible()
+
+ // Navigate back to Home
+ await page.getByRole('link', { name: /home/i }).click()
+ await expect(page).toHaveURL('/')
+ })
+
+ test('should toggle mobile menu on small screens', async ({ page }) => {
+ // Set mobile viewport
+ await page.setViewportSize({ width: 375, height: 667 })
+ await page.goto('/')
+
+ // Menu should be hidden initially
+ const nav = page.getByRole('navigation')
+ await expect(nav).not.toBeVisible()
+
+ // Click hamburger menu
+ await page.getByRole('button', { name: /menu/i }).click()
+
+ // Menu should be visible
+ await expect(nav).toBeVisible()
+ })
+})
+```
+
+**Contact Form Test:**
+
+```typescript
+// e2e/contact-form.spec.ts
+import { test, expect } from '@playwright/test'
+
+test.describe('Contact Form', () => {
+ test.beforeEach(async ({ page }) => {
+ await page.goto('/contact')
+ })
+
+ test('should display validation errors for empty form', async ({ page }) => {
+ // Submit empty form
+ await page.getByRole('button', { name: /submit/i }).click()
+
+ // Check for validation errors
+ await expect(page.getByText(/name is required/i)).toBeVisible()
+ await expect(page.getByText(/email is required/i)).toBeVisible()
+ })
+
+ test('should show error for invalid email', async ({ page }) => {
+ await page.getByLabel(/name/i).fill('John Doe')
+ await page.getByLabel(/email/i).fill('invalid-email')
+ await page.getByLabel(/message/i).fill('Test message')
+
+ await page.getByRole('button', { name: /submit/i }).click()
+
+ await expect(page.getByText(/valid email/i)).toBeVisible()
+ })
+
+ test('should submit form successfully with valid data', async ({ page }) => {
+ await page.getByLabel(/name/i).fill('John Doe')
+ await page.getByLabel(/email/i).fill('[email protected]')
+ await page.getByLabel(/message/i).fill('This is a test message')
+
+ await page.getByRole('button', { name: /submit/i }).click()
+
+ // Check for success message
+ await expect(page.getByText(/thank you|success/i)).toBeVisible()
+ })
+})
+```
+
+**Accessibility Test:**
+
+```typescript
+// e2e/accessibility.spec.ts
+import { test, expect } from '@playwright/test'
+
+test.describe('Accessibility', () => {
+ test('should be navigable with keyboard', async ({ page }) => {
+ await page.goto('/')
+
+ // Tab through interactive elements
+ await page.keyboard.press('Tab')
+ const firstFocusable = page.locator(':focus')
+ await expect(firstFocusable).toBeVisible()
+
+ // Check skip link (if present)
+ const skipLink = page.getByRole('link', { name: /skip to/i })
+ if (await skipLink.isVisible()) {
+ await expect(skipLink).toBeFocused()
+ }
+ })
+
+ test('should have proper heading hierarchy', async ({ page }) => {
+ await page.goto('/')
+
+ // Check for h1
+ const h1 = page.getByRole('heading', { level: 1 })
+ await expect(h1).toHaveCount(1)
+
+ // Check headings don't skip levels
+ const headings = await page.getByRole('heading').all()
+ expect(headings.length).toBeGreaterThan(0)
+ })
+
+ test('should have alt text for images', async ({ page }) => {
+ await page.goto('/')
+
+ const images = await page.getByRole('img').all()
+ for (const img of images) {
+ const alt = await img.getAttribute('alt')
+ expect(alt).not.toBeNull()
+ expect(alt).not.toBe('')
+ }
+ })
+})
+```
+
+#### Run E2E Tests
+
+```powershell
+# Run all E2E tests
+npm run test:e2e
+
+# Run with UI mode (interactive debugging)
+npm run test:e2e:ui
+
+# Run in headed mode (see browser)
+npm run test:e2e:headed
+
+# Run specific test file
+npx playwright test e2e/home.spec.ts
+
+# Run tests in specific browser
+npx playwright test --project=chromium
+
+# View HTML report after tests
+npm run test:e2e:report
+```
+
+**All E2E tests must pass before proceeding to build.**
+
+### Build the Project
+
+Run the appropriate build command:
+
+```powershell
+# React (Create React App or Vite)
+npm run build
+
+# Angular
+ng build --configuration production
+
+# Vue
+npm run build
+
+# Astro
+npm run build
+```
+
+### Initialize Memory Bank
+
+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
+```
+
+**IMPORTANT**: Update this file after each subsequent step is completed.
+
+---
+
+## STEP 3: Check Prerequisites
+
+**IMPORTANT**: Before uploading, verify that all required CLI tools are installed on the user's machine.
+
+### Check PAC CLI
+
+Run the following command to check if PAC CLI is installed:
+
+```powershell
+pac help
+```
+
+**If the command fails or PAC CLI is not found**, install it using .NET tool:
+
+```powershell
+dotnet tool install --global Microsoft.PowerApps.CLI.Tool
+```
+
+If installation fails, guide the user based on the error.
+
+After installation, verify it works:
+
+```powershell
+pac help
+```
+
+### Check Azure CLI
+
+Run the following command to check if Azure CLI is installed:
+
+```powershell
+az --version
+```
+
+**If the command fails or Azure CLI is not found**, install it using winget:
+
+```powershell
+winget install -e --id Microsoft.AzureCLI
+```
+
+After installation, the user may need to restart their terminal. Then verify it works:
+
+```powershell
+az --version
+```
+
+### Verify Authentication
+
+Once both CLIs are installed, ensure the user is authenticated:
+
+```powershell
+# Check PAC CLI authentication
+pac auth list
+
+# If not authenticated, prompt user to authenticate
+pac auth create
+
+# Check Azure CLI authentication
+az account show
+
+# If not authenticated, prompt user to login
+az login
+```
+
+### Verify Environment Connection
+
+```powershell
+pac org who
+```
+
+---
+
+## STEP 4: Upload to Power Pages (Inactive)
+
+### Upload Command
+
+```powershell
+pac pages upload-code-site `
+ --rootPath "<PROJECT_ROOT_PATH>" `
+```
+
+**Example:**
+
+```powershell
+pac pages upload-code-site `
+ --rootPath "C:\repos\my-power-pages-site" `
+```
+
+### Get Website Record ID
+
+After upload, list sites to get the websiteRecordId:
+
+```powershell
+pac pages list --verbose
+```
+
+Note the **Website ID** (GUID) - this is needed for activation.
+
+---
+
+## STEP 5: Preview Locally
+
+Before activating the site, run it locally to verify everything works correctly.
+
+### Run the Development Server
+
+```powershell
+# React (Vite)
+npm run dev
+
+# React (Create React App)
+npm start
+
+# Angular
+ng serve
+
+# Vue
+npm run dev
+
+# Astro
+npm run dev
+```
+
+### Verify the Site
+
+1. Open the local URL (usually `http://localhost:5173` or `http://localhost:3000`)
+2. Test all pages and navigation
+3. Verify forms and interactive elements work
+4. Check responsive design on different screen sizes
+
+Once you're satisfied with the local preview, proceed to activate the site.
+
+---
+
+## STEP 6: Activate Website
+
+After uploading, your site appears as **Inactive** in Power Pages. Activate it using the Power Platform API.
+
+### Ask for Subdomain
+
+Before activating, ask the user for their preferred subdomain using the AskUserQuestion tool:
+
+- **Subdomain**: The URL prefix for their site (e.g., `my-site` → `my-site.powerappsportals.com`)
+- Subdomain must be unique, lowercase, and contain only letters, numbers, and hyphens
+
+### Get Required IDs
+
+First, retrieve the environment and organization IDs:
+
+```powershell
+# Get environment details
+pac org who
+```
+
+From the output, note:
+- **Environment ID** - The GUID of the environment
+- **Organization ID** - The Dataverse organization ID (same as environment ID in most cases)
+
+### Activate via API
+
+Call the CreateWebsite API using Azure CLI's `az rest` command:
+
+```powershell
+# Set variables (replace with actual values)
+$environmentId = "<ENVIRONMENT_ID>"
+$organizationId = "<ORGANIZATION_ID>"
+$websiteRecordId = "<WEBSITE_RECORD_ID_FROM_UPLOAD>"
+$siteName = "<SITE_NAME>"
+$subdomain = "<USER_CHOSEN_SUBDOMAIN>"
+
+# Create request body
+$body = @{
+ dataverseOrganizationId = $organizationId
+ name = $siteName
+ selectedBaseLanguage = 1033
+ subdomain = $subdomain
+ templateName = "DefaultPortalTemplate"
+ websiteRecordId = $websiteRecordId
+} | ConvertTo-Json -Compress
+
+# Call CreateWebsite API
+az rest `
+ --method POST `
+ --url "https://api.powerplatform.com/powerpages/environments/$environmentId/websites?api-version=2022-03-01-preview" `
+ --resource "https://api.powerplatform.com" `
+ --body $body `
+ --headers "Content-Type=application/json" `
+ --verbose
+```
+
+The `--resource` flag automatically handles authentication using your Azure CLI credentials.
+
+### Monitor Activation Status
+
+The API returns a `202 Accepted` response with an `Operation-Location` header. Poll this URL to check activation status:
+
+```powershell
+# Check operation status (URL from Operation-Location header in the response)
+$operationUrl = "<OPERATION_LOCATION_URL>"
+
+az rest `
+ --method GET `
+ --url $operationUrl `
+ --resource "https://api.powerplatform.com"
+```
+
+Wait until the operation status shows as completed (typically 2-5 minutes).
+
+### Verify Activation
+
+```powershell
+pac pages list --verbose
+```
+
+Your site should now show as **Active** with a URL.
+
+**API Reference**: [CreateWebsite API - Microsoft Learn](https://learn.microsoft.com/en-us/rest/api/power-platform/powerpages/websites/create-website)
+
+### Fallback: Manual Activation
+
+If the API activation fails (e.g., permissions issues, network errors), activate manually:
+
+1. **Go to Power Pages home page**
+ - Navigate to [make.powerpages.microsoft.com](https://make.powerpages.microsoft.com)
+ - Select your environment
+
+2. **Find your inactive site**
+ - Click on **Inactive sites** in the left navigation
+ - Your uploaded site will appear in the list
+
+3. **Reactivate the site**
+ - Click the **Reactivate** button next to your site
+
+4. **Configure site details**
+ - **Website name**: Enter or confirm the display name
+ - **Web address**: Enter the subdomain chosen earlier
+ - Click **Done**
+
+5. **Wait for provisioning**
+ - The site will take a few minutes to provision
+ - Once complete, it will appear in **Active sites**
+
+**Reference**: [Reactivate a website - Microsoft Learn](https://learn.microsoft.com/en-us/power-pages/admin/reactivate-website)
+
+### Update Memory Bank
+
+After activation, update `memory-bank.md`:
+
+1. Mark all `/create-site` steps as complete `[x]`
+2. Add the Website ID and Site URL
+3. Update status to "Site Activated"
+4. Set next step to "Setup Dataverse Tables"
+
+```markdown
+### /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
+- [x] Prerequisites verified (PAC CLI, Azure CLI)
+- [x] Uploaded to Power Pages (Inactive)
+- [x] Site activated
+- Website ID: [GUID_FROM_PAC_PAGES_LIST]
+- Site URL: [URL_FROM_ACTIVATION]
+
+## Current Status
+
+**Last Action**: Site activated successfully
+
+**Next Step**: Run `/setup-dataverse` to create Dataverse tables for your site
+```
+
+---
+
+## Next Steps
+
+After the site is active, suggest the maker proceed with:
+
+### Setup Dataverse Tables
+
+> **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
+
+---
+
+## Troubleshooting
+
+### Upload Fails with JavaScript Error
+
+Enable JavaScript file uploads:
+
+1. Go to Power Platform admin center
+2. Navigate to Environments → [Your Environment] → Settings
+3. Go to Product → Privacy + Security
+4. In "Blocked Attachments", remove `js` from the list
+5. Save changes
+
+### Site Shows as Inactive After Upload
+
+This is expected. The upload creates an INACTIVE record. Follow STEP 6 to manually activate it via the Power Pages home page.
+
+### Site Not Appearing in Inactive Sites
+
+- Verify the upload completed successfully
+- Check you're in the correct environment
+- Run `pac pages list --verbose` to confirm the site exists
+
+### Reactivation Fails
+
+Ensure your user has appropriate permissions:
+
+- System Administrator or System Customizer role in the environment
+- Power Pages administrator access
+
+### Next.js or SSR Framework Used
+
+Power Pages code sites **do not support** server-side rendering frameworks:
+
+- **Next.js**, **Nuxt.js**, **Remix**, **SvelteKit** require a Node.js server runtime
+- Power Pages serves only **static files** from Azure CDN
+- **Solution**: Recreate the project using Vite + React/Vue, or use Angular/Astro with static export
+
+### Liquid Templates Not Working
+
+Liquid templates are **only supported in classic Power Pages sites**, not in code sites:
+
+- Code sites are pure SPAs with no server-side templating
+- **Solution**: Use JavaScript/TypeScript to fetch data dynamically via Dataverse Web API
+- For dynamic content, call the Web API and render with your chosen framework
+
+### Unit Tests Failing
+
+If tests fail, investigate and fix before proceeding:
+
+- **Component tests failing**: Check that components render correctly and handle props
+- **Missing test dependencies**: Run `npm install` to ensure all dev dependencies are installed
+- **jsdom errors**: Ensure `environment: 'jsdom'` is set in Vitest config
+- **Import errors**: Check that test setup file imports `@testing-library/jest-dom`
+
+```powershell
+# Run tests in watch mode for debugging
+npm test
+
+# Run specific test file
+npm test -- src/components/Header.test.tsx
+
+# Run with verbose output
+npm test -- --reporter=verbose
+```
+
+**Do not skip tests or proceed with failing tests** - fix all issues before building.
+
+### E2E Tests Failing (Playwright)
+
+If Playwright tests fail, investigate and fix before proceeding:
+
+- **Browser not installed**: Run `npx playwright install` to install browsers
+- **Server not starting**: Check that `webServer.command` in `playwright.config.ts` matches your dev script
+- **Wrong port**: Ensure `baseURL` matches your dev server port (5173 for Vite, 3000 for CRA, 4200 for Angular)
+- **Element not found**: Use Playwright's UI mode to debug selectors: `npm run test:e2e:ui`
+- **Timeout errors**: Increase timeout in config or use `await expect().toBeVisible({ timeout: 10000 })`
+- **Flaky tests**: Add `await page.waitForLoadState('networkidle')` before assertions
+
+```powershell
+# Debug with UI mode (recommended)
+npm run test:e2e:ui
+
+# Debug with headed browser
+npm run test:e2e:headed
+
+# Run single test for debugging
+npx playwright test e2e/home.spec.ts --headed
+
+# Generate test code by recording actions
+npx playwright codegen http://localhost:5173
+
+# View trace for failed tests
+npx playwright show-trace trace.zip
+```
+
+**Do not skip E2E tests or proceed with failing tests** - fix all issues before building.
+
+---
+
+## Reference Documentation
+
+- [Create Code Sites in Power Pages](https://learn.microsoft.com/en-us/power-pages/configure/create-code-sites)
+- [Reactivate a Website](https://learn.microsoft.com/en-us/power-pages/admin/reactivate-website)
+- [PAC CLI Reference](https://learn.microsoft.com/en-us/power-platform/developer/cli/reference/pages)
+- [Playwright Documentation](https://playwright.dev/docs/intro)
+- [Vitest Documentation](https://vitest.dev/guide/)
diff --git a/plugins/skills/create-site/web-roles-reference.md b/plugins/skills/create-site/web-roles-reference.md
new file mode 100644
index 000000000..ed1706077
--- /dev/null
+++ b/plugins/skills/create-site/web-roles-reference.md
@@ -0,0 +1,525 @@
+# 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
+
+```powershell
+function New-WebRole {
+ param(
+ [Parameter(Mandatory=$true)]
+ [string]$Name,
+
+ [Parameter(Mandatory=$true)]
+ [string]$WebsiteId,
+
+ [string]$Description = "",
+
+ [bool]$AuthenticatedUsersRole = $false
+ )
+
+ $webRole = @{
+ "adx_name" = $Name
+ "adx_description" = $Description
+ "adx_authenticatedusersrole" = $AuthenticatedUsersRole
+ "[email protected]" = "/adx_websites($WebsiteId)"
+ }
+
+ $body = $webRole | ConvertTo-Json -Depth 5
+
+ try {
+ $response = Invoke-WebRequest -Uri "$baseUrl/adx_webroles" -Method Post -Headers $headers -Body $body
+ $roleId = $response.Headers["OData-EntityId"] -replace ".*\(([^)]+)\).*", '$1'
+ Write-Host "Created web role '$Name' with ID: $roleId"
+ return $roleId
+ }
+ catch {
+ Write-Host "Error creating web role '$Name': $_"
+ return $null
+ }
+}
+```
+
+## Common Web Role Patterns
+
+### Pattern 1: Public Website (Anonymous + Admin)
+
+For simple public websites with admin management:
+
+```powershell
+# Anonymous Users - already exists, just verify
+$anonymousRole = Invoke-RestMethod `
+ -Uri "$baseUrl/adx_webroles?`$filter=adx_name eq 'Anonymous Users' and _adx_websiteid_value eq $websiteId" `
+ -Headers $headers
+
+# Administrators - already exists, just verify
+$adminRole = Invoke-RestMethod `
+ -Uri "$baseUrl/adx_webroles?`$filter=adx_name eq 'Administrators' and _adx_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
+$authRole = Invoke-RestMethod `
+ -Uri "$baseUrl/adx_webroles?`$filter=adx_name eq 'Authenticated Users' and _adx_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
+ )
+
+ $roles = Invoke-RestMethod `
+ -Uri "$baseUrl/adx_webroles?`$filter=_adx_websiteid_value eq $WebsiteId&`$select=adx_webroleid,adx_name,adx_description,adx_authenticatedusersrole" `
+ -Headers $headers
+
+ return $roles.value
+}
+
+# Get all roles for the website
+$allRoles = Get-WebRoles -WebsiteId $websiteId
+$allRoles | ForEach-Object {
+ Write-Host "Role: $($_.adx_name) | ID: $($_.adx_webroleid) | Auth Required: $($_.adx_authenticatedusersrole)"
+}
+```
+
+### Get Specific Web Role ID
+
+```powershell
+function Get-WebRoleId {
+ param(
+ [Parameter(Mandatory=$true)]
+ [string]$RoleName,
+
+ [Parameter(Mandatory=$true)]
+ [string]$WebsiteId
+ )
+
+ $role = Invoke-RestMethod `
+ -Uri "$baseUrl/adx_webroles?`$filter=adx_name eq '$RoleName' and _adx_websiteid_value eq $WebsiteId&`$select=adx_webroleid" `
+ -Headers $headers
+
+ if ($role.value.Count -gt 0) {
+ return $role.value[0].adx_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 {
+ Invoke-RestMethod `
+ -Uri "$baseUrl/adx_webroles($WebRoleId)/adx_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 {
+ Invoke-RestMethod `
+ -Uri "$baseUrl/adx_webroles($WebRoleId)/adx_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
+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/adx_webroles?`$filter=adx_name eq '$roleName' and _adx_websiteid_value eq $WebsiteId" `
+ -Headers $headers
+
+ if ($role.value.Count -gt 0) {
+ $roleIds[$roleName] = $role.value[0].adx_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/adx_webroles?`$filter=adx_name eq '$customRole' and _adx_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].adx_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)
diff --git a/plugins/skills/setup-dataverse/SKILL.md b/plugins/skills/setup-dataverse/SKILL.md
new file mode 100644
index 000000000..f87767fa3
--- /dev/null
+++ b/plugins/skills/setup-dataverse/SKILL.md
@@ -0,0 +1,2055 @@
+---
+description: Setup Dataverse tables and schema for your Power Pages site. Analyzes your site to recommend tables, creates tables using OData Web API, and adds sample data.
+user-invocable: true
+allowed-tools: Bash(pac:*), Bash(az:*)
+model: sonnet
+---
+
+# 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.
+
+## 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 │
+└─────────────────────────────────────────────────────────────────────────────┘
+ ↓
+┌─────────────────────────────────────────────────────────────────────────────┐
+│ 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) │
+└─────────────────────────────────────────────────────────────────────────────┘
+ ↓
+┌─────────────────────────────────────────────────────────────────────────────┐
+│ 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) │
+└─────────────────────────────────────────────────────────────────────────────┘
+ ↓
+┌─────────────────────────────────────────────────────────────────────────────┐
+│ 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 │
+└─────────────────────────────────────────────────────────────────────────────┘
+ ↓
+┌─────────────────────────────────────────────────────────────────────────────┐
+│ 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 │
+└─────────────────────────────────────────────────────────────────────────────┘
+ ↓
+┌─────────────────────────────────────────────────────────────────────────────┐
+│ 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 │
+└─────────────────────────────────────────────────────────────────────────────┘
+ ↓
+┌─────────────────────────────────────────────────────────────────────────────┐
+│ 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 │
+└─────────────────────────────────────────────────────────────────────────────┘
+ ↓
+ Next: /setup-webapi skill
+```
+
+---
+
+## Data Architecture Principles
+
+**CRITICAL**: Before creating any tables, you MUST design a proper data architecture. This means:
+
+### 1. Entity-Relationship Analysis
+
+Identify all entities and their relationships:
+
+```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 │
+│ │
+└─────────────────────────────────────────────────────────────────────────────┘
+```
+
+### 2. 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 │
+│ │
+└─────────────────────────────────────────────────────────────────────────────┘
+```
+
+### 3. Dependency Graph Documentation
+
+**Always document the dependency graph before creating tables:**
+
+```text
+Example: E-Commerce Site Data Architecture
+
+ ┌─────────────┐
+ │ Category │ TIER 0
+ │ (lookup) │
+ └──────┬──────┘
+ │
+ ┌───────────────┼───────────────┐
+ ↓ ↓ ↓
+ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐
+ │ Product │ │ Supplier │ │ Customer │ TIER 1
+ │ (→Category) │ │ │ │ │
+ └──────┬───────┘ └──────┬───────┘ └──────┬───────┘
+ │ │ │
+ └───────────────┼───────────────┘
+ ↓
+ ┌──────────────┐
+ │ Order │ TIER 2
+ │ (→Customer) │
+ └──────┬───────┘
+ │
+ ↓
+ ┌──────────────┐
+ │ OrderLine │ TIER 3
+ │(→Order, │
+ │ →Product) │
+ └──────────────┘
+
+Creation Order: Category → Product, Supplier, Customer → Order → OrderLine
+```
+
+### 4. 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) |
+
+---
+
+## STEP 1: Resume or Start Fresh
+
+### Check Memory Bank First
+
+**Before asking questions**, check if a memory bank exists:
+
+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
+
+First, determine if the user is continuing from `/create-site` or starting fresh.
+
+**If continuing from create-site:**
+
+Show this message:
+
+> **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?
+
+Use the `AskUserQuestion` tool with these options:
+
+| 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 |
+
+**If starting fresh (no prior context):**
+
+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?
+
+| 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 |
+
+If they have an existing site, ask for the project path using `AskUserQuestion`.
+
+### Resume Command
+
+If the user selects "Show me the command", display:
+
+```text
+┌─────────────────────────────────────────────────────────────────────────────┐
+│ Resume Command │
+│ ───────────────────────────────────────────────────────────────────────── │
+│ │
+│ Run this command when you're ready to continue: │
+│ │
+│ /setup-dataverse │
+│ │
+│ Or type: "Set up Dataverse tables for my Power Pages site" │
+│ │
+└─────────────────────────────────────────────────────────────────────────────┘
+```
+
+---
+
+## STEP 2: Analyze Site & Design Data Architecture
+
+### Read Site Configuration
+
+Read the site's source code to understand data requirements:
+
+1. **Read powerpages.config.json** to get site name and structure
+2. **Scan component files** for data patterns:
+ - Forms (contact forms, registration forms, feedback forms)
+ - Lists/Tables (product listings, team members, services)
+ - Cards (testimonials, portfolio items, blog posts)
+ - User data (profiles, preferences, submissions)
+
+### Identify Data Requirements
+
+Look for these patterns in the code:
+
+| Pattern | Recommended Table | Likely Relationships |
+|---------|-------------------|---------------------|
+| Contact form with name, email, message | `cr_contactsubmission` | → `cr_contactstatus` (lookup) |
+| Product/service cards with categories | `cr_product` or `cr_service` | → `cr_category` (lookup) |
+| Team member section with departments | `cr_teammember` | → `cr_department` (lookup) |
+| Testimonials/Reviews | `cr_testimonial` | → `cr_product` or `cr_service` (optional) |
+| Blog/News section | `cr_blogpost` | → `cr_category`, → `cr_author` |
+| FAQ section with categories | `cr_faq` | → `cr_faqcategory` (lookup) |
+| Event listings | `cr_event` | → `cr_eventtype`, → `cr_location` |
+| Portfolio/Gallery items | `cr_portfolioitem` | → `cr_category` |
+| User feedback/Surveys | `cr_feedback` | → `cr_feedbacktype` (lookup) |
+
+### Design Entity-Relationship Model
+
+**CRITICAL**: Before recommending tables, design a complete ER model:
+
+1. **Identify all entities** (both main tables and lookup/reference tables)
+2. **Identify relationships** between entities
+3. **Normalize the data** (avoid storing the same data in multiple places)
+4. **Document the dependency graph**
+
+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) │
+│ │
+└─────────────────────────────────────────────────────────────────────────────┘
+```
+
+### Present Architecture Recommendations
+
+After analysis, present the complete data architecture using `AskUserQuestion`:
+
+> **Data Architecture for Your Site**
+>
+> Based on your site's features, I've designed the following data architecture:
+>
+> **Reference Tables (created first):**
+> - [List lookup/reference tables]
+>
+> **Primary Entity Tables:**
+> - [List main tables with their relationships]
+>
+> **Dependent Tables:**
+> - [List tables that depend on others]
+>
+> **Relationship Summary:**
+> - [Describe key relationships]
+>
+> Would you like to proceed with this architecture?
+
+| Option | Description |
+|--------|-------------|
+| **Yes, create these tables** | Proceed with recommended architecture |
+| **Modify the schema** | Let me adjust columns, tables, or relationships |
+| **Show me the full diagram** | Display complete ER diagram before proceeding |
+
+---
+
+## STEP 3: Build Dependency Graph & Validate Creation Order
+
+Before creating any tables, validate the creation order:
+
+### 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
+
+---
+
+## STEP 4: Set Up OData Web API Authentication
+
+This skill uses the Dataverse OData Web API for all table and data operations. Operations will use:
+
+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
+
+Ensure Azure CLI is authenticated before proceeding:
+
+```powershell
+# Verify Azure CLI is logged in
+az account show
+
+# If not logged in, run:
+az login
+```
+
+---
+
+## STEP 5: Review Existing Tables & Identify Reusable Tables
+
+**CRITICAL**: Before creating any tables, you MUST review existing tables in the Dataverse environment. This prevents duplicate tables, leverages existing schema, and follows best practices for enterprise data management.
+
+### Query Existing Custom Tables
+
+Use the Dataverse Web API to retrieve all existing custom tables:
+
+```powershell
+# Get all custom tables (entities) in the environment
+# Custom tables typically have a publisher prefix (e.g., cr_, new_, contoso_)
+
+$existingTables = Invoke-RestMethod -Uri "$baseUrl/EntityDefinitions?`$filter=IsCustomEntity eq true&`$select=SchemaName,LogicalName,DisplayName,Description,PrimaryNameAttribute" -Headers $headers
+
+Write-Host "Found $($existingTables.value.Count) custom tables in the environment:" -ForegroundColor Cyan
+$existingTables.value | ForEach-Object {
+ $displayName = $_.DisplayName.UserLocalizedLabel.Label
+ Write-Host " - $($_.SchemaName) ($displayName)" -ForegroundColor Yellow
+}
+```
+
+### Get Table Details with Columns
+
+For each potentially reusable table, retrieve its columns to compare against your schema:
+
+```powershell
+function Get-TableSchema {
+ param([string]$TableLogicalName)
+
+ # Get table metadata with attributes
+ $tableInfo = Invoke-RestMethod -Uri "$baseUrl/EntityDefinitions(LogicalName='$TableLogicalName')?`$expand=Attributes(`$select=SchemaName,LogicalName,AttributeType,DisplayName,MaxLength)" -Headers $headers
+
+ Write-Host "`nTable: $($tableInfo.SchemaName)" -ForegroundColor Cyan
+ Write-Host "Display Name: $($tableInfo.DisplayName.UserLocalizedLabel.Label)"
+ Write-Host "Primary Column: $($tableInfo.PrimaryNameAttribute)"
+ Write-Host "Columns:" -ForegroundColor Yellow
+
+ $tableInfo.Attributes | Where-Object {
+ # Filter out system columns
+ $_.SchemaName -notmatch '^(Created|Modified|Owner|State|Status|Version|Import|Overridden|TimeZone|UTCConversion|Traversed)'
+ } | ForEach-Object {
+ $displayName = if ($_.DisplayName.UserLocalizedLabel) { $_.DisplayName.UserLocalizedLabel.Label } else { $_.SchemaName }
+ Write-Host " - $($_.SchemaName) ($($_.AttributeType)) - $displayName"
+ }
+
+ return $tableInfo
+}
+
+# Example: Check if a category table already exists
+$existingCategory = Get-TableSchema -TableLogicalName "cr_category"
+```
+
+### Compare Existing vs Required Tables
+
+Build a comparison matrix to identify reusable tables:
+
+```powershell
+function Compare-TableSchemas {
+ param(
+ [hashtable]$RequiredTables, # Schema name -> array of required columns
+ [array]$ExistingTables # From EntityDefinitions query
+ )
+
+ $comparison = @{
+ Reusable = @() # Existing tables that match or exceed requirements
+ Extendable = @() # Existing tables that need additional columns
+ 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 }
+
+ if ($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]
+
+ $missingColumns = $requiredColumns | Where-Object { $_ -notin $existingColumns }
+
+ if ($missingColumns.Count -eq 0) {
+ $comparison.Reusable += @{
+ TableName = $tableName
+ ExistingTable = $existing
+ Message = "All required columns present"
+ }
+ } else {
+ $comparison.Extendable += @{
+ TableName = $tableName
+ ExistingTable = $existing
+ MissingColumns = $missingColumns
+ Message = "Missing columns: $($missingColumns -join ', ')"
+ }
+ }
+ } else {
+ $comparison.CreateNew += @{
+ TableName = $tableName
+ RequiredColumns = $RequiredTables[$tableName]
+ }
+ }
+ }
+
+ return $comparison
+}
+
+# Example usage
+$requiredTables = @{
+ "cr_category" = @("cr_name", "cr_description", "cr_displayorder", "cr_isactive")
+ "cr_product" = @("cr_name", "cr_description", "cr_price", "cr_imageurl", "cr_categoryid")
+ "cr_contactsubmission" = @("cr_name", "cr_email", "cr_message", "cr_submissiondate")
+}
+
+$comparison = Compare-TableSchemas -RequiredTables $requiredTables -ExistingTables $existingTables.value
+```
+
+### Present Reuse Options
+
+After comparing schemas, present the findings to the user:
+
+```text
+┌─────────────────────────────────────────────────────────────────────────────┐
+│ EXISTING TABLE ANALYSIS │
+├─────────────────────────────────────────────────────────────────────────────┤
+│ │
+│ ✅ REUSABLE (no changes needed): │
+│ ───────────────────────────────────────────────────────────────────────── │
+│ • cr_category - Has all required columns │
+│ • cr_status - Has all required columns │
+│ │
+│ 🔧 EXTENDABLE (need additional columns): │
+│ ───────────────────────────────────────────────────────────────────────── │
+│ • cr_product - Missing: cr_imageurl, cr_isactive │
+│ • cr_teammember - Missing: cr_linkedin, cr_displayorder │
+│ │
+│ 🆕 CREATE NEW (don't exist): │
+│ ───────────────────────────────────────────────────────────────────────── │
+│ • cr_testimonial │
+│ • cr_contactsubmission │
+│ │
+└─────────────────────────────────────────────────────────────────────────────┘
+```
+
+Use `AskUserQuestion` to confirm the approach:
+
+> **Existing Tables Found**
+>
+> I found existing tables that may be reused. Here's my recommendation:
+>
+> **Reuse as-is:** cr_category, cr_status
+> **Extend with new columns:** cr_product (needs: cr_imageurl, cr_isactive)
+> **Create new:** cr_testimonial, cr_contactsubmission
+>
+> How would you like to proceed?
+
+| Option | Description |
+|--------|-------------|
+| **Use recommendations** | Reuse existing tables, extend where needed, create only new tables |
+| **Create all new** | Create new tables with unique names (e.g., cr_site_category) |
+| **Review each table** | Let me decide for each table individually |
+
+### Check for Similar Tables
+
+Sometimes tables exist with different names but similar purposes. Search for these:
+
+```powershell
+function Find-SimilarTables {
+ param(
+ [string]$Purpose, # e.g., "category", "product", "contact"
+ [array]$ExistingTables
+ )
+
+ # Common naming patterns to search for
+ $patterns = @{
+ "category" = @("category", "categories", "type", "types", "classification")
+ "product" = @("product", "products", "item", "items", "service", "services", "offering")
+ "contact" = @("contact", "contacts", "submission", "inquiry", "lead", "leads")
+ "team" = @("team", "employee", "staff", "member", "person", "people")
+ "testimonial" = @("testimonial", "review", "feedback", "rating")
+ }
+
+ $searchTerms = $patterns[$Purpose]
+ if (-not $searchTerms) { $searchTerms = @($Purpose) }
+
+ $matches = $ExistingTables | Where-Object {
+ $tableName = $_.SchemaName.ToLower()
+ $displayName = $_.DisplayName.UserLocalizedLabel.Label.ToLower()
+
+ foreach ($term in $searchTerms) {
+ if ($tableName -match $term -or $displayName -match $term) {
+ return $true
+ }
+ }
+ return $false
+ }
+
+ return $matches
+}
+
+# Example: Find tables that might serve as category tables
+$similarCategories = Find-SimilarTables -Purpose "category" -ExistingTables $existingTables.value
+if ($similarCategories) {
+ Write-Host "Found similar tables that could be used for categories:" -ForegroundColor Yellow
+ $similarCategories | ForEach-Object {
+ Write-Host " - $($_.SchemaName): $($_.DisplayName.UserLocalizedLabel.Label)"
+ }
+}
+```
+
+### Check Existing Relationships
+
+When reusing tables, verify existing relationships don't conflict:
+
+```powershell
+function Get-TableRelationships {
+ param([string]$TableLogicalName)
+
+ # Get 1:N relationships where this table is referenced
+ $oneToMany = Invoke-RestMethod -Uri "$baseUrl/EntityDefinitions(LogicalName='$TableLogicalName')/OneToManyRelationships" -Headers $headers
+
+ # Get N:1 relationships where this table references others
+ $manyToOne = Invoke-RestMethod -Uri "$baseUrl/EntityDefinitions(LogicalName='$TableLogicalName')/ManyToOneRelationships" -Headers $headers
+
+ Write-Host "`nRelationships for $TableLogicalName:" -ForegroundColor Cyan
+
+ Write-Host " Referenced by (1:N):" -ForegroundColor Yellow
+ $oneToMany.value | ForEach-Object {
+ Write-Host " - $($_.ReferencingEntity).$($_.ReferencingAttribute)"
+ }
+
+ Write-Host " References (N:1):" -ForegroundColor Yellow
+ $manyToOne.value | ForEach-Object {
+ Write-Host " - $($_.ReferencedEntity) via $($_.ReferencingAttribute)"
+ }
+
+ return @{
+ OneToMany = $oneToMany.value
+ ManyToOne = $manyToOne.value
+ }
+}
+```
+
+### Update Memory Bank with Reuse Decisions
+
+Document which tables are being reused vs created:
+
+```markdown
+### Table Decisions
+
+| Required Table | Decision | Existing Table | Notes |
+|----------------|----------|----------------|-------|
+| cr_category | REUSE | cr_category | All columns present |
+| cr_product | EXTEND | cr_product | Adding cr_imageurl, cr_isactive |
+| cr_testimonial | CREATE | - | New table |
+| cr_contactsubmission | REUSE | cr_inquiry | Renaming to match site usage |
+```
+
+---
+
+## STEP 6: Create/Extend Tables in Dependency Order
+
+**CRITICAL**: Based on the analysis from STEP 5, create only new tables and extend existing tables as needed. Tables marked for reuse should be skipped.
+
+### Creation/Extension Protocol
+
+```text
+┌─────────────────────────────────────────────────────────────────────────────┐
+│ TABLE CREATION/EXTENSION PROTOCOL │
+├─────────────────────────────────────────────────────────────────────────────┤
+│ │
+│ PHASE 1: Process tables based on STEP 5 decisions │
+│ ───────────────────────────────────────────────────────────────────────── │
+│ • REUSABLE tables: Skip creation, use existing table │
+│ • EXTENDABLE tables: Add missing columns to existing table │
+│ • CREATE NEW tables: Create in dependency order (TIER 0 → TIER 1 → ...) │
+│ │
+│ PHASE 2: Add non-lookup columns │
+│ ───────────────────────────────────────────────────────────────────────── │
+│ • For NEW tables: Add all required columns │
+│ • For EXTENDED tables: Add only missing columns │
+│ • Skip columns that already exist │
+│ │
+│ PHASE 3: Create/verify relationships (lookup columns) │
+│ ───────────────────────────────────────────────────────────────────────── │
+│ • Check if relationship already exists before creating │
+│ • Create only missing relationships │
+│ • Verify existing relationships point to correct tables │
+│ │
+└─────────────────────────────────────────────────────────────────────────────┘
+```
+
+### Helper Function: Check If Table Exists
+
+```powershell
+function Test-TableExists {
+ param([string]$TableLogicalName)
+
+ try {
+ $result = Invoke-RestMethod -Uri "$baseUrl/EntityDefinitions(LogicalName='$TableLogicalName')?`$select=LogicalName" -Headers $headers -ErrorAction Stop
+ return $true
+ } catch {
+ if ($_.Exception.Response.StatusCode -eq 404) {
+ return $false
+ }
+ throw
+ }
+}
+
+function Test-ColumnExists {
+ param(
+ [string]$TableLogicalName,
+ [string]$ColumnLogicalName
+ )
+
+ try {
+ $result = Invoke-RestMethod -Uri "$baseUrl/EntityDefinitions(LogicalName='$TableLogicalName')/Attributes(LogicalName='$ColumnLogicalName')?`$select=LogicalName" -Headers $headers -ErrorAction Stop
+ return $true
+ } catch {
+ if ($_.Exception.Response.StatusCode -eq 404) {
+ return $false
+ }
+ throw
+ }
+}
+
+function Test-RelationshipExists {
+ param([string]$RelationshipSchemaName)
+
+ try {
+ $result = Invoke-RestMethod -Uri "$baseUrl/RelationshipDefinitions(SchemaName='$RelationshipSchemaName')?`$select=SchemaName" -Headers $headers -ErrorAction Stop
+ return $true
+ } catch {
+ if ($_.Exception.Response.StatusCode -eq 404) {
+ return $false
+ }
+ throw
+ }
+}
+```
+
+### Safe Table Creation (Skip If Exists)
+
+```powershell
+function New-DataverseTableIfNotExists {
+ param(
+ [string]$SchemaName,
+ [string]$DisplayName,
+ [string]$PluralDisplayName,
+ [string]$Description = "",
+ [string]$PrimaryColumnName = "cr_name",
+ [string]$PrimaryColumnDisplayName = "Name"
+ )
+
+ $logicalName = $SchemaName.ToLower()
+
+ if (Test-TableExists -TableLogicalName $logicalName) {
+ Write-Host " ⏭️ Table '$SchemaName' already exists - skipping creation" -ForegroundColor Yellow
+ return @{ Skipped = $true; Reason = "Already exists" }
+ }
+
+ Write-Host " 🆕 Creating table '$SchemaName'..." -ForegroundColor Cyan
+ $result = New-DataverseTable -SchemaName $SchemaName -DisplayName $DisplayName `
+ -PluralDisplayName $PluralDisplayName -Description $Description `
+ -PrimaryColumnName $PrimaryColumnName -PrimaryColumnDisplayName $PrimaryColumnDisplayName
+
+ Write-Host " ✅ Table '$SchemaName' created successfully" -ForegroundColor Green
+ return @{ Skipped = $false; Result = $result }
+}
+```
+
+### Safe Column Addition (Skip If Exists)
+
+```powershell
+function Add-DataverseColumnIfNotExists {
+ param(
+ [string]$TableName,
+ [string]$SchemaName,
+ [string]$DisplayName,
+ [string]$Type,
+ [int]$MaxLength = 100
+ )
+
+ $columnLogicalName = $SchemaName.ToLower()
+ $tableLogicalName = $TableName.ToLower()
+
+ if (Test-ColumnExists -TableLogicalName $tableLogicalName -ColumnLogicalName $columnLogicalName) {
+ Write-Host " ⏭️ Column '$SchemaName' already exists on '$TableName' - skipping" -ForegroundColor Yellow
+ return @{ Skipped = $true; Reason = "Already exists" }
+ }
+
+ Write-Host " 🆕 Adding column '$SchemaName' to '$TableName'..." -ForegroundColor Cyan
+ $result = Add-DataverseColumn -TableName $TableName -SchemaName $SchemaName `
+ -DisplayName $DisplayName -Type $Type -MaxLength $MaxLength
+
+ Write-Host " ✅ Column '$SchemaName' added successfully" -ForegroundColor Green
+ return @{ Skipped = $false; Result = $result }
+}
+```
+
+### Safe Relationship Creation (Skip If Exists)
+
+```powershell
+function Add-DataverseLookupIfNotExists {
+ param(
+ [string]$SourceTable,
+ [string]$TargetTable,
+ [string]$LookupSchemaName,
+ [string]$LookupDisplayName,
+ [string]$RelationshipName
+ )
+
+ if (Test-RelationshipExists -RelationshipSchemaName $RelationshipName) {
+ Write-Host " ⏭️ Relationship '$RelationshipName' already exists - skipping" -ForegroundColor Yellow
+ return @{ Skipped = $true; Reason = "Already exists" }
+ }
+
+ # Also check if the lookup column already exists (might be from a different relationship)
+ $lookupLogicalName = $LookupSchemaName.ToLower()
+ $sourceLogicalName = $SourceTable.ToLower()
+
+ if (Test-ColumnExists -TableLogicalName $sourceLogicalName -ColumnLogicalName $lookupLogicalName) {
+ Write-Host " ⏭️ Lookup column '$LookupSchemaName' already exists on '$SourceTable' - skipping" -ForegroundColor Yellow
+ return @{ Skipped = $true; Reason = "Lookup column already exists" }
+ }
+
+ Write-Host " 🆕 Creating relationship '$RelationshipName' ($SourceTable → $TargetTable)..." -ForegroundColor Cyan
+ $result = Add-DataverseLookup -SourceTable $SourceTable -TargetTable $TargetTable `
+ -LookupSchemaName $LookupSchemaName -LookupDisplayName $LookupDisplayName `
+ -RelationshipName $RelationshipName
+
+ Write-Host " ✅ Relationship '$RelationshipName' created successfully" -ForegroundColor Green
+ return @{ Skipped = $false; Result = $result }
+}
+```
+
+### Set Up API Connection
+
+Create tables using the Dataverse Web API. First, set up the API connection:
+
+```powershell
+# Get the environment URL
+pac org who
+
+# Get access token using Azure CLI
+$envUrl = "https://<org>.crm.dynamics.com" # Replace with your org URL
+$token = (az account get-access-token --resource $envUrl --query accessToken -o tsv)
+
+# Set up headers for API calls
+$headers = @{
+ "Authorization" = "Bearer $token"
+ "Content-Type" = "application/json"
+ "OData-MaxVersion" = "4.0"
+ "OData-Version" = "4.0"
+ "MSCRM.SolutionUniqueName" = "YourSolutionName" # Optional: add to a solution
+}
+
+$baseUrl = "$envUrl/api/data/v9.2"
+```
+
+#### Example: Create Contact Submission Table
+
+```powershell
+# Create the table (entity)
+$tableDefinition = @{
+ "@odata.type" = "Microsoft.Dynamics.CRM.EntityMetadata"
+ "SchemaName" = "cr_contactsubmission"
+ "DisplayName" = @{
+ "@odata.type" = "Microsoft.Dynamics.CRM.Label"
+ "LocalizedLabels" = @(
+ @{
+ "@odata.type" = "Microsoft.Dynamics.CRM.LocalizedLabel"
+ "Label" = "Contact Submission"
+ "LanguageCode" = 1033
+ }
+ )
+ }
+ "DisplayCollectionName" = @{
+ "@odata.type" = "Microsoft.Dynamics.CRM.Label"
+ "LocalizedLabels" = @(
+ @{
+ "@odata.type" = "Microsoft.Dynamics.CRM.LocalizedLabel"
+ "Label" = "Contact Submissions"
+ "LanguageCode" = 1033
+ }
+ )
+ }
+ "Description" = @{
+ "@odata.type" = "Microsoft.Dynamics.CRM.Label"
+ "LocalizedLabels" = @(
+ @{
+ "@odata.type" = "Microsoft.Dynamics.CRM.LocalizedLabel"
+ "Label" = "Stores contact form submissions from the website"
+ "LanguageCode" = 1033
+ }
+ )
+ }
+ "OwnershipType" = "UserOwned"
+ "HasNotes" = $false
+ "HasActivities" = $false
+ "PrimaryNameAttribute" = "cr_name"
+ "Attributes" = @(
+ @{
+ "@odata.type" = "Microsoft.Dynamics.CRM.StringAttributeMetadata"
+ "SchemaName" = "cr_name"
+ "AttributeType" = "String"
+ "FormatName" = @{ "Value" = "Text" }
+ "MaxLength" = 100
+ "DisplayName" = @{
+ "@odata.type" = "Microsoft.Dynamics.CRM.Label"
+ "LocalizedLabels" = @(
+ @{ "@odata.type" = "Microsoft.Dynamics.CRM.LocalizedLabel"; "Label" = "Name"; "LanguageCode" = 1033 }
+ )
+ }
+ "IsPrimaryName" = $true
+ }
+ )
+}
+
+$body = $tableDefinition | ConvertTo-Json -Depth 10
+Invoke-RestMethod -Uri "$baseUrl/EntityDefinitions" -Method Post -Headers $headers -Body $body
+```
+
+#### Add Columns to Existing Table
+
+```powershell
+# Add email column
+$emailColumn = @{
+ "@odata.type" = "Microsoft.Dynamics.CRM.StringAttributeMetadata"
+ "SchemaName" = "cr_email"
+ "AttributeType" = "String"
+ "FormatName" = @{ "Value" = "Email" }
+ "MaxLength" = 100
+ "DisplayName" = @{
+ "@odata.type" = "Microsoft.Dynamics.CRM.Label"
+ "LocalizedLabels" = @(
+ @{ "@odata.type" = "Microsoft.Dynamics.CRM.LocalizedLabel"; "Label" = "Email"; "LanguageCode" = 1033 }
+ )
+ }
+}
+
+# Get table's LogicalName or use EntitySetName
+$tableName = "cr_contactsubmission"
+Invoke-RestMethod -Uri "$baseUrl/EntityDefinitions(LogicalName='$tableName')/Attributes" -Method Post -Headers $headers -Body ($emailColumn | ConvertTo-Json -Depth 10)
+
+# Add message column (multiline text)
+$messageColumn = @{
+ "@odata.type" = "Microsoft.Dynamics.CRM.MemoAttributeMetadata"
+ "SchemaName" = "cr_message"
+ "AttributeType" = "Memo"
+ "MaxLength" = 4000
+ "DisplayName" = @{
+ "@odata.type" = "Microsoft.Dynamics.CRM.Label"
+ "LocalizedLabels" = @(
+ @{ "@odata.type" = "Microsoft.Dynamics.CRM.LocalizedLabel"; "Label" = "Message"; "LanguageCode" = 1033 }
+ )
+ }
+}
+Invoke-RestMethod -Uri "$baseUrl/EntityDefinitions(LogicalName='$tableName')/Attributes" -Method Post -Headers $headers -Body ($messageColumn | ConvertTo-Json -Depth 10)
+
+# Add submission date column
+$dateColumn = @{
+ "@odata.type" = "Microsoft.Dynamics.CRM.DateTimeAttributeMetadata"
+ "SchemaName" = "cr_submissiondate"
+ "AttributeType" = "DateTime"
+ "Format" = "DateAndTime"
+ "DisplayName" = @{
+ "@odata.type" = "Microsoft.Dynamics.CRM.Label"
+ "LocalizedLabels" = @(
+ @{ "@odata.type" = "Microsoft.Dynamics.CRM.LocalizedLabel"; "Label" = "Submission Date"; "LanguageCode" = 1033 }
+ )
+ }
+}
+Invoke-RestMethod -Uri "$baseUrl/EntityDefinitions(LogicalName='$tableName')/Attributes" -Method Post -Headers $headers -Body ($dateColumn | ConvertTo-Json -Depth 10)
+
+# Add status choice column
+$statusColumn = @{
+ "@odata.type" = "Microsoft.Dynamics.CRM.PicklistAttributeMetadata"
+ "SchemaName" = "cr_status"
+ "AttributeType" = "Picklist"
+ "DisplayName" = @{
+ "@odata.type" = "Microsoft.Dynamics.CRM.Label"
+ "LocalizedLabels" = @(
+ @{ "@odata.type" = "Microsoft.Dynamics.CRM.LocalizedLabel"; "Label" = "Status"; "LanguageCode" = 1033 }
+ )
+ }
+ "OptionSet" = @{
+ "@odata.type" = "Microsoft.Dynamics.CRM.OptionSetMetadata"
+ "IsGlobal" = $false
+ "OptionSetType" = "Picklist"
+ "Options" = @(
+ @{ "Value" = 1; "Label" = @{ "@odata.type" = "Microsoft.Dynamics.CRM.Label"; "LocalizedLabels" = @(@{ "@odata.type" = "Microsoft.Dynamics.CRM.LocalizedLabel"; "Label" = "New"; "LanguageCode" = 1033 }) } }
+ @{ "Value" = 2; "Label" = @{ "@odata.type" = "Microsoft.Dynamics.CRM.Label"; "LocalizedLabels" = @(@{ "@odata.type" = "Microsoft.Dynamics.CRM.LocalizedLabel"; "Label" = "Reviewed"; "LanguageCode" = 1033 }) } }
+ @{ "Value" = 3; "Label" = @{ "@odata.type" = "Microsoft.Dynamics.CRM.Label"; "LocalizedLabels" = @(@{ "@odata.type" = "Microsoft.Dynamics.CRM.LocalizedLabel"; "Label" = "Responded"; "LanguageCode" = 1033 }) } }
+ @{ "Value" = 4; "Label" = @{ "@odata.type" = "Microsoft.Dynamics.CRM.Label"; "LocalizedLabels" = @(@{ "@odata.type" = "Microsoft.Dynamics.CRM.LocalizedLabel"; "Label" = "Closed"; "LanguageCode" = 1033 }) } }
+ )
+ }
+}
+Invoke-RestMethod -Uri "$baseUrl/EntityDefinitions(LogicalName='$tableName')/Attributes" -Method Post -Headers $headers -Body ($statusColumn | ConvertTo-Json -Depth 10)
+```
+
+### Helper Function for Table Creation
+
+To simplify table creation, use this helper function:
+
+```powershell
+function New-DataverseTable {
+ param(
+ [string]$SchemaName,
+ [string]$DisplayName,
+ [string]$PluralDisplayName,
+ [string]$Description = "",
+ [string]$PrimaryColumnName = "cr_name",
+ [string]$PrimaryColumnDisplayName = "Name"
+ )
+
+ $tableDefinition = @{
+ "@odata.type" = "Microsoft.Dynamics.CRM.EntityMetadata"
+ "SchemaName" = $SchemaName
+ "DisplayName" = @{
+ "@odata.type" = "Microsoft.Dynamics.CRM.Label"
+ "LocalizedLabels" = @(@{ "@odata.type" = "Microsoft.Dynamics.CRM.LocalizedLabel"; "Label" = $DisplayName; "LanguageCode" = 1033 })
+ }
+ "DisplayCollectionName" = @{
+ "@odata.type" = "Microsoft.Dynamics.CRM.Label"
+ "LocalizedLabels" = @(@{ "@odata.type" = "Microsoft.Dynamics.CRM.LocalizedLabel"; "Label" = $PluralDisplayName; "LanguageCode" = 1033 })
+ }
+ "Description" = @{
+ "@odata.type" = "Microsoft.Dynamics.CRM.Label"
+ "LocalizedLabels" = @(@{ "@odata.type" = "Microsoft.Dynamics.CRM.LocalizedLabel"; "Label" = $Description; "LanguageCode" = 1033 })
+ }
+ "OwnershipType" = "UserOwned"
+ "HasNotes" = $false
+ "HasActivities" = $false
+ "PrimaryNameAttribute" = $PrimaryColumnName
+ "Attributes" = @(
+ @{
+ "@odata.type" = "Microsoft.Dynamics.CRM.StringAttributeMetadata"
+ "SchemaName" = $PrimaryColumnName
+ "AttributeType" = "String"
+ "FormatName" = @{ "Value" = "Text" }
+ "MaxLength" = 100
+ "DisplayName" = @{
+ "@odata.type" = "Microsoft.Dynamics.CRM.Label"
+ "LocalizedLabels" = @(@{ "@odata.type" = "Microsoft.Dynamics.CRM.LocalizedLabel"; "Label" = $PrimaryColumnDisplayName; "LanguageCode" = 1033 })
+ }
+ "IsPrimaryName" = $true
+ }
+ )
+ }
+
+ $body = $tableDefinition | ConvertTo-Json -Depth 10
+ Invoke-RestMethod -Uri "$baseUrl/EntityDefinitions" -Method Post -Headers $headers -Body $body
+}
+
+function Add-DataverseColumn {
+ param(
+ [string]$TableName,
+ [string]$SchemaName,
+ [string]$DisplayName,
+ [string]$Type, # String, Memo, Integer, Decimal, Money, DateTime, Boolean, Url
+ [int]$MaxLength = 100
+ )
+
+ $columnTypes = @{
+ "String" = @{ "@odata.type" = "Microsoft.Dynamics.CRM.StringAttributeMetadata"; "AttributeType" = "String"; "FormatName" = @{ "Value" = "Text" }; "MaxLength" = $MaxLength }
+ "Email" = @{ "@odata.type" = "Microsoft.Dynamics.CRM.StringAttributeMetadata"; "AttributeType" = "String"; "FormatName" = @{ "Value" = "Email" }; "MaxLength" = $MaxLength }
+ "Url" = @{ "@odata.type" = "Microsoft.Dynamics.CRM.StringAttributeMetadata"; "AttributeType" = "String"; "FormatName" = @{ "Value" = "Url" }; "MaxLength" = 200 }
+ "Memo" = @{ "@odata.type" = "Microsoft.Dynamics.CRM.MemoAttributeMetadata"; "AttributeType" = "Memo"; "MaxLength" = $MaxLength }
+ "Integer" = @{ "@odata.type" = "Microsoft.Dynamics.CRM.IntegerAttributeMetadata"; "AttributeType" = "Integer"; "MinValue" = -2147483648; "MaxValue" = 2147483647 }
+ "Money" = @{ "@odata.type" = "Microsoft.Dynamics.CRM.MoneyAttributeMetadata"; "AttributeType" = "Money"; "PrecisionSource" = 2 }
+ "DateTime" = @{ "@odata.type" = "Microsoft.Dynamics.CRM.DateTimeAttributeMetadata"; "AttributeType" = "DateTime"; "Format" = "DateAndTime" }
+ "Boolean" = @{ "@odata.type" = "Microsoft.Dynamics.CRM.BooleanAttributeMetadata"; "AttributeType" = "Boolean" }
+ }
+
+ $column = $columnTypes[$Type].Clone()
+ $column["SchemaName"] = $SchemaName
+ $column["DisplayName"] = @{
+ "@odata.type" = "Microsoft.Dynamics.CRM.Label"
+ "LocalizedLabels" = @(@{ "@odata.type" = "Microsoft.Dynamics.CRM.LocalizedLabel"; "Label" = $DisplayName; "LanguageCode" = 1033 })
+ }
+
+ Invoke-RestMethod -Uri "$baseUrl/EntityDefinitions(LogicalName='$TableName')/Attributes" -Method Post -Headers $headers -Body ($column | ConvertTo-Json -Depth 10)
+}
+
+function Add-DataverseLookup {
+ param(
+ [string]$SourceTable, # Table that will have the lookup column
+ [string]$TargetTable, # Table being referenced (must exist first!)
+ [string]$LookupSchemaName, # Schema name for the lookup column
+ [string]$LookupDisplayName, # Display name for the lookup column
+ [string]$RelationshipName # Unique name for the relationship
+ )
+
+ # Create a 1:N relationship (Many source records → One target record)
+ $relationship = @{
+ "@odata.type" = "Microsoft.Dynamics.CRM.OneToManyRelationshipMetadata"
+ "SchemaName" = $RelationshipName
+ "ReferencedEntity" = $TargetTable # The "one" side (parent/lookup target)
+ "ReferencingEntity" = $SourceTable # The "many" side (child/has lookup)
+ "Lookup" = @{
+ "@odata.type" = "Microsoft.Dynamics.CRM.LookupAttributeMetadata"
+ "SchemaName" = $LookupSchemaName
+ "DisplayName" = @{
+ "@odata.type" = "Microsoft.Dynamics.CRM.Label"
+ "LocalizedLabels" = @(
+ @{ "@odata.type" = "Microsoft.Dynamics.CRM.LocalizedLabel"; "Label" = $LookupDisplayName; "LanguageCode" = 1033 }
+ )
+ }
+ }
+ "CascadeConfiguration" = @{
+ "Assign" = "NoCascade"
+ "Delete" = "RemoveLink" # When parent deleted, clear the lookup (don't delete children)
+ "Merge" = "NoCascade"
+ "Reparent" = "NoCascade"
+ "Share" = "NoCascade"
+ "Unshare" = "NoCascade"
+ }
+ }
+
+ $body = $relationship | ConvertTo-Json -Depth 10
+ Invoke-RestMethod -Uri "$baseUrl/RelationshipDefinitions" -Method Post -Headers $headers -Body $body
+}
+
+function Add-DataverseManyToMany {
+ param(
+ [string]$Table1, # First table in the relationship
+ [string]$Table2, # Second table in the relationship
+ [string]$RelationshipName, # Unique name for the relationship
+ [string]$IntersectEntityName # Name for the junction table (auto-created)
+ )
+
+ # Create N:N relationship (junction table created automatically)
+ $relationship = @{
+ "@odata.type" = "Microsoft.Dynamics.CRM.ManyToManyRelationshipMetadata"
+ "SchemaName" = $RelationshipName
+ "Entity1LogicalName" = $Table1
+ "Entity2LogicalName" = $Table2
+ "IntersectEntityName" = $IntersectEntityName
+ "Entity1AssociatedMenuConfiguration" = @{
+ "Behavior" = "UseLabel"
+ "Group" = "Details"
+ "Label" = @{
+ "@odata.type" = "Microsoft.Dynamics.CRM.Label"
+ "LocalizedLabels" = @(@{ "@odata.type" = "Microsoft.Dynamics.CRM.LocalizedLabel"; "Label" = $Table2; "LanguageCode" = 1033 })
+ }
+ "Order" = 10000
+ }
+ "Entity2AssociatedMenuConfiguration" = @{
+ "Behavior" = "UseLabel"
+ "Group" = "Details"
+ "Label" = @{
+ "@odata.type" = "Microsoft.Dynamics.CRM.Label"
+ "LocalizedLabels" = @(@{ "@odata.type" = "Microsoft.Dynamics.CRM.LocalizedLabel"; "Label" = $Table1; "LanguageCode" = 1033 })
+ }
+ "Order" = 10000
+ }
+ }
+
+ $body = $relationship | ConvertTo-Json -Depth 10
+ Invoke-RestMethod -Uri "$baseUrl/RelationshipDefinitions" -Method Post -Headers $headers -Body $body
+}
+```
+
+---
+
+### Dependency-Ordered Creation Example (With Reuse Checks)
+
+Here's a complete example showing proper creation order with existing table checks:
+
+```powershell
+# ═══════════════════════════════════════════════════════════════════════════════
+# PHASE 1: Create/Skip tables based on STEP 5 decisions
+# ═══════════════════════════════════════════════════════════════════════════════
+
+Write-Host "`n════════════════════════════════════════════════════════════════" -ForegroundColor Magenta
+Write-Host "PHASE 1: Processing Tables (Create New / Skip Existing)" -ForegroundColor Magenta
+Write-Host "════════════════════════════════════════════════════════════════`n" -ForegroundColor Magenta
+
+# --- TIER 0: Reference/Lookup Tables (no dependencies) ---
+Write-Host "Processing TIER 0 tables (Reference/Lookup)..." -ForegroundColor Cyan
+
+New-DataverseTableIfNotExists -SchemaName "cr_category" -DisplayName "Category" -PluralDisplayName "Categories" `
+ -Description "Product and content categories"
+
+New-DataverseTableIfNotExists -SchemaName "cr_department" -DisplayName "Department" -PluralDisplayName "Departments" `
+ -Description "Organization departments"
+
+New-DataverseTableIfNotExists -SchemaName "cr_status" -DisplayName "Status" -PluralDisplayName "Statuses" `
+ -Description "Status values for various entities"
+
+# --- TIER 1: Primary Entity Tables (depend only on TIER 0) ---
+Write-Host "`nProcessing TIER 1 tables (Primary Entities)..." -ForegroundColor Cyan
+
+New-DataverseTableIfNotExists -SchemaName "cr_product" -DisplayName "Product" -PluralDisplayName "Products" `
+ -Description "Products and services offered"
+
+New-DataverseTableIfNotExists -SchemaName "cr_teammember" -DisplayName "Team Member" -PluralDisplayName "Team Members" `
+ -Description "Team members displayed on the website"
+
+# --- TIER 2: Dependent Tables (depend on TIER 1) ---
+Write-Host "`nProcessing TIER 2 tables (Dependent)..." -ForegroundColor Cyan
+
+New-DataverseTableIfNotExists -SchemaName "cr_testimonial" -DisplayName "Testimonial" -PluralDisplayName "Testimonials" `
+ -Description "Customer testimonials and reviews"
+
+New-DataverseTableIfNotExists -SchemaName "cr_contactsubmission" -DisplayName "Contact Submission" -PluralDisplayName "Contact Submissions" `
+ -Description "Contact form submissions from the website"
+
+# ═══════════════════════════════════════════════════════════════════════════════
+# PHASE 2: Add/Skip columns (only adds missing columns)
+# ═══════════════════════════════════════════════════════════════════════════════
+
+Write-Host "`n════════════════════════════════════════════════════════════════" -ForegroundColor Magenta
+Write-Host "PHASE 2: Processing Columns (Add Missing / Skip Existing)" -ForegroundColor Magenta
+Write-Host "════════════════════════════════════════════════════════════════`n" -ForegroundColor Magenta
+
+# Category columns
+Write-Host "Processing columns for cr_category..." -ForegroundColor Cyan
+Add-DataverseColumnIfNotExists -TableName "cr_category" -SchemaName "cr_description" -DisplayName "Description" -Type "Memo" -MaxLength 1000
+Add-DataverseColumnIfNotExists -TableName "cr_category" -SchemaName "cr_displayorder" -DisplayName "Display Order" -Type "Integer"
+Add-DataverseColumnIfNotExists -TableName "cr_category" -SchemaName "cr_isactive" -DisplayName "Is Active" -Type "Boolean"
+
+# Department columns
+Write-Host "`nProcessing columns for cr_department..." -ForegroundColor Cyan
+Add-DataverseColumnIfNotExists -TableName "cr_department" -SchemaName "cr_code" -DisplayName "Code" -Type "String" -MaxLength 10
+
+# Product columns (non-lookup)
+Write-Host "`nProcessing columns for cr_product..." -ForegroundColor Cyan
+Add-DataverseColumnIfNotExists -TableName "cr_product" -SchemaName "cr_description" -DisplayName "Description" -Type "Memo" -MaxLength 4000
+Add-DataverseColumnIfNotExists -TableName "cr_product" -SchemaName "cr_price" -DisplayName "Price" -Type "Money"
+Add-DataverseColumnIfNotExists -TableName "cr_product" -SchemaName "cr_imageurl" -DisplayName "Image URL" -Type "Url"
+Add-DataverseColumnIfNotExists -TableName "cr_product" -SchemaName "cr_isactive" -DisplayName "Is Active" -Type "Boolean"
+
+# Team Member columns (non-lookup)
+Write-Host "`nProcessing columns for cr_teammember..." -ForegroundColor Cyan
+Add-DataverseColumnIfNotExists -TableName "cr_teammember" -SchemaName "cr_title" -DisplayName "Job Title" -Type "String"
+Add-DataverseColumnIfNotExists -TableName "cr_teammember" -SchemaName "cr_email" -DisplayName "Email" -Type "Email"
+Add-DataverseColumnIfNotExists -TableName "cr_teammember" -SchemaName "cr_bio" -DisplayName "Bio" -Type "Memo" -MaxLength 4000
+
+# Testimonial columns (non-lookup)
+Write-Host "`nProcessing columns for cr_testimonial..." -ForegroundColor Cyan
+Add-DataverseColumnIfNotExists -TableName "cr_testimonial" -SchemaName "cr_quote" -DisplayName "Quote" -Type "Memo" -MaxLength 2000
+Add-DataverseColumnIfNotExists -TableName "cr_testimonial" -SchemaName "cr_company" -DisplayName "Company" -Type "String"
+Add-DataverseColumnIfNotExists -TableName "cr_testimonial" -SchemaName "cr_rating" -DisplayName "Rating" -Type "Integer"
+
+# Contact Submission columns (non-lookup)
+Write-Host "`nProcessing columns for cr_contactsubmission..." -ForegroundColor Cyan
+Add-DataverseColumnIfNotExists -TableName "cr_contactsubmission" -SchemaName "cr_email" -DisplayName "Email" -Type "Email"
+Add-DataverseColumnIfNotExists -TableName "cr_contactsubmission" -SchemaName "cr_message" -DisplayName "Message" -Type "Memo" -MaxLength 4000
+Add-DataverseColumnIfNotExists -TableName "cr_contactsubmission" -SchemaName "cr_submissiondate" -DisplayName "Submission Date" -Type "DateTime"
+
+# ═══════════════════════════════════════════════════════════════════════════════
+# PHASE 3: Create/Skip relationships (only creates missing relationships)
+# ═══════════════════════════════════════════════════════════════════════════════
+
+Write-Host "`n════════════════════════════════════════════════════════════════" -ForegroundColor Magenta
+Write-Host "PHASE 3: Processing Relationships (Create Missing / Skip Existing)" -ForegroundColor Magenta
+Write-Host "════════════════════════════════════════════════════════════════`n" -ForegroundColor Magenta
+
+# --- First: Lookups from TIER 1 → TIER 0 ---
+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"
+
+# Team Member → Department
+Add-DataverseLookupIfNotExists -SourceTable "cr_teammember" -TargetTable "cr_department" `
+ -LookupSchemaName "cr_departmentid" -LookupDisplayName "Department" `
+ -RelationshipName "cr_department_teammember"
+
+# Contact Submission → Status
+Add-DataverseLookupIfNotExists -SourceTable "cr_contactsubmission" -TargetTable "cr_status" `
+ -LookupSchemaName "cr_statusid" -LookupDisplayName "Status" `
+ -RelationshipName "cr_status_contactsubmission"
+
+# --- Then: Lookups from TIER 2 → TIER 1 ---
+Write-Host "`nProcessing TIER 2 → TIER 1 relationships..." -ForegroundColor Cyan
+
+# Testimonial → Product (optional relationship for product-specific testimonials)
+Add-DataverseLookupIfNotExists -SourceTable "cr_testimonial" -TargetTable "cr_product" `
+ -LookupSchemaName "cr_productid" -LookupDisplayName "Related Product" `
+ -RelationshipName "cr_product_testimonial"
+
+Write-Host "`n════════════════════════════════════════════════════════════════" -ForegroundColor Green
+Write-Host "Schema processing complete!" -ForegroundColor Green
+Write-Host "════════════════════════════════════════════════════════════════" -ForegroundColor Green
+```
+
+---
+
+### Common Table Templates (Updated with Relationships)
+
+#### Product/Service Table
+
+```powershell
+# Create Product table
+New-DataverseTable -SchemaName "cr_product" -DisplayName "Product" -PluralDisplayName "Products" -Description "Products and services offered"
+
+# Add columns
+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_category" -DisplayName "Category" -Type "String"
+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"
+```
+
+#### Team Member Table
+
+```powershell
+# Create Team Member table
+New-DataverseTable -SchemaName "cr_teammember" -DisplayName "Team Member" -PluralDisplayName "Team Members" -Description "Team members displayed on the website"
+
+# Add columns
+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"
+```
+
+#### Testimonial Table
+
+```powershell
+# Create Testimonial table
+New-DataverseTable -SchemaName "cr_testimonial" -DisplayName "Testimonial" -PluralDisplayName "Testimonials" -Description "Customer testimonials and reviews"
+
+# Add columns
+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"
+```
+
+#### FAQ Table
+
+```powershell
+# Create FAQ table
+New-DataverseTable -SchemaName "cr_faq" -DisplayName "FAQ" -PluralDisplayName "FAQs" -Description "Frequently asked questions" -PrimaryColumnName "cr_question" -PrimaryColumnDisplayName "Question"
+
+# Add columns
+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"
+```
+
+---
+
+## STEP 7: Add Sample Data with Referential Integrity
+
+After creating/extending tables and relationships, add sample data **in the correct order** to maintain referential integrity. If tables were reused, check for existing data first.
+
+**CRITICAL**: Insert data in the same order as table creation - reference/lookup data first, then dependent data with valid foreign keys.
+
+### 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 Before Inserting
+
+```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
+}
+
+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 " ⏭️ Record '$nameValue' already exists - using existing" -ForegroundColor Yellow
+ return @{
+ Skipped = $true
+ Record = $existing
+ }
+ }
+
+ Write-Host " 🆕 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 " ✅ Record '$nameValue' created" -ForegroundColor Green
+
+ return @{
+ Skipped = $false
+ Record = $response
+ }
+}
+
+# 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 { "✅" }
+ Write-Host " $status $($_.Key): $($_.Value) records"
+}
+```
+
+### Present Existing Data Options
+
+If existing data is found, use `AskUserQuestion`:
+
+> **Existing Data Found**
+>
+> Some tables already contain data:
+> - cr_categories: 5 records
+> - cr_products: 12 records
+>
+> How would you like to handle sample data?
+
+| Option | Description |
+|--------|-------------|
+| **Skip tables with data** | Only add sample data to empty tables |
+| **Add to existing data** | Add sample data alongside existing records (may create duplicates) |
+| **Replace existing data** | Clear existing records and insert fresh sample data (destructive!) |
+| **Skip all sample data** | Don't add any sample data, keep existing records |
+
+### Using OData API via PowerShell
+
+Create a PowerShell script to insert sample data:
+
+```powershell
+# Get access token
+$token = (az account get-access-token --resource "https://<org>.crm.dynamics.com" --query accessToken -o tsv)
+
+# Set headers (include Prefer header to get created record back)
+$headers = @{
+ "Authorization" = "Bearer $token"
+ "Content-Type" = "application/json"
+ "OData-MaxVersion" = "4.0"
+ "OData-Version" = "4.0"
+ "Prefer" = "return=representation" # Returns created record with ID
+}
+
+# Environment URL (get from pac org who)
+$baseUrl = "https://<org>.crm.dynamics.com/api/data/v9.2"
+
+# Helper function to create record and return its ID
+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
+}
+```
+
+### Complete Sample Data Script (Dependency-Ordered with Reuse)
+
+This script demonstrates proper insertion order with foreign key relationships, skipping records that already exist:
+
+```powershell
+# ═══════════════════════════════════════════════════════════════════════════════
+# TIER 0: Insert/Reuse Reference/Lookup Data FIRST
+# ═══════════════════════════════════════════════════════════════════════════════
+
+Write-Host "`n════════════════════════════════════════════════════════════════" -ForegroundColor Magenta
+Write-Host "TIER 0: Processing Reference/Lookup Data" -ForegroundColor Magenta
+Write-Host "════════════════════════════════════════════════════════════════`n" -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/Reuse Primary Entity Data (with TIER 0 lookups)
+# ═══════════════════════════════════════════════════════════════════════════════
+
+Write-Host "`n════════════════════════════════════════════════════════════════" -ForegroundColor Magenta
+Write-Host "TIER 1: Processing Primary Entity Data (with TIER 0 lookups)" -ForegroundColor Magenta
+Write-Host "════════════════════════════════════════════════════════════════`n" -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
+ # FOREIGN KEY: Reference the Category by its ID using @odata.bind syntax
+ "[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/Reuse Dependent Data (with TIER 0 and TIER 1 lookups)
+# ═══════════════════════════════════════════════════════════════════════════════
+
+Write-Host "`n════════════════════════════════════════════════════════════════" -ForegroundColor Magenta
+Write-Host "TIER 2: Processing Dependent Data (with TIER 0 and TIER 1 lookups)" -ForegroundColor Magenta
+Write-Host "════════════════════════════════════════════════════════════════`n" -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
+ # Link to specific product
+ "[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
+ # (Lookup is optional, so we can omit [email protected])
+ }
+)
+
+Write-Host "`nProcessing testimonials..." -ForegroundColor Cyan
+foreach ($testimonial in $testimonials) {
+ New-DataverseRecordIfNotExists -EntitySetName "cr_testimonials" -Data $testimonial -NameColumn "cr_name"
+}
+
+Write-Host "`n════════════════════════════════════════════════════════════════" -ForegroundColor Green
+Write-Host "Sample data processing complete!" -ForegroundColor Green
+Write-Host "════════════════════════════════════════════════════════════════" -ForegroundColor Green
+Write-Host "`nRecords processed (created or reused):" -ForegroundColor Yellow
+Write-Host " - Categories: $($categoryIds.Count)"
+Write-Host " - Statuses: $($statusIds.Count)"
+Write-Host " - Departments: $($departmentIds.Count)"
+Write-Host " - Products: $($productIds.Count)"
+Write-Host " - Team Members: $($teamMemberIds.Count)"
+Write-Host " - Contact Submissions: $($contacts.Count)"
+Write-Host " - Testimonials: $($testimonials.Count)"
+```
+
+### Verify Data and Relationships
+
+After inserting, verify the data and its 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"
+}
+```
+
+---
+
+## Next Steps
+
+After setting up Dataverse tables with sample data, the next step is to 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` with the Dataverse setup details including the data architecture and reuse decisions:
+
+```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 (skipped existing)
+
+## Data Architecture
+
+### Existing Table Analysis
+
+| Required Table | Decision | Existing Table | Action Taken |
+|----------------|----------|----------------|--------------|
+| cr_category | REUSE | cr_category | Used existing table |
+| cr_product | EXTEND | cr_product | Added cr_imageurl, cr_isactive columns |
+| cr_testimonial | CREATE | - | Created new table |
+| cr_contactsubmission | CREATE | - | Created new table |
+
+### Dependency Graph
+```text
+TIER 0 (Reference Tables):
+ cr_category, cr_status, cr_department
+
+TIER 1 (Primary Tables):
+ cr_product → cr_category
+ cr_teammember → cr_department
+
+TIER 2 (Dependent Tables):
+ cr_contactsubmission → cr_status
+ cr_testimonial → cr_product
+```
+
+### Tables by Tier
+
+#### TIER 0 - Reference/Lookup Tables
+
+| Table Name | Display Name | Purpose |
+|------------|--------------|---------|
+| cr_category | Category | Product/content categories |
+| cr_status | Status | Status values for submissions |
+| cr_department | Department | Team member departments |
+
+#### TIER 1 - Primary Entity Tables
+
+| Table Name | Display Name | Relationships |
+|------------|--------------|---------------|
+| cr_product | Product | → cr_category (lookup) |
+| cr_teammember | Team Member | → cr_department (lookup) |
+
+#### TIER 2 - Dependent Tables
+
+| Table Name | Display Name | Relationships |
+|------------|--------------|---------------|
+| cr_contactsubmission | Contact Submission | → cr_status (lookup) |
+| cr_testimonial | Testimonial | → cr_product (optional lookup) |
+
+### Relationships Created
+
+| Relationship Name | Type | Source Table | Target Table | Lookup Column |
+|-------------------|------|--------------|--------------|---------------|
+| cr_category_product | 1:N | cr_product | cr_category | cr_categoryid |
+| cr_department_teammember | 1:N | cr_teammember | cr_department | cr_departmentid |
+| cr_status_contactsubmission | 1:N | cr_contactsubmission | cr_status | cr_statusid |
+| cr_product_testimonial | 1:N | cr_testimonial | cr_product | cr_productid |
+
+### Sample Data Summary
+
+| Table | Records | Notes |
+|-------|---------|-------|
+| cr_category | 3 | Services, Packages, Products |
+| cr_status | 4 | New, Reviewed, Responded, Closed |
+| cr_department | 4 | Executive, Engineering, Customer Success, Sales |
+| cr_product | 3 | All linked to categories |
+| cr_teammember | 3 | All linked to departments |
+| cr_contactsubmission | 3 | All linked to statuses |
+| cr_testimonial | 3 | 2 linked to products, 1 general |
+
+### Technical Details
+- Data Integration: OData Web API
+- Environment URL: [URL from pac org who]
+- Creation Order: TIER 0 → TIER 1 → TIER 2
+- Data Insertion Order: Reference data first, then dependent data with valid FK references
+
+## Current Status
+
+**Last Action**: Dataverse tables and relationships created with sample data
+
+**Next Step**: Run `/setup-webapi` to configure table permissions and Web API access
+
+## Notes
+
+- [DATE]: Created data architecture with [N] tables and [M] relationships
+- All tables created in dependency order
+- Sample data inserted with valid foreign key references
+```
+
+---
+
+## Troubleshooting
+
+### Existing Table Detection Issues
+
+- **Tables not found**: Ensure the filter `IsCustomEntity eq true` is correct for your needs
+- **Wrong publisher prefix**: Tables may have different prefixes (e.g., `new_`, `contoso_` instead of `cr_`)
+- **System tables included**: Add additional filters to exclude system tables if needed
+- **Case sensitivity**: Table logical names are case-insensitive but schema names preserve case
+
+### Table Reuse Issues
+
+- **Existing table has different schema**: Consider creating a new table with a unique name instead
+- **Column type mismatch**: Cannot change column types; may need to create new column with different name
+- **Relationship conflicts**: Verify existing relationships don't prevent your intended lookups
+- **Missing required columns on reused table**: Use `Add-DataverseColumnIfNotExists` to add only missing columns
+
+### Dataverse Web API Errors
+
+- Verify Azure CLI is logged in: `az login`
+- Check access token is valid: `az account get-access-token --resource <env-url>`
+- Ensure you have appropriate Dataverse permissions (System Administrator or System Customizer)
+
+### Table Creation Fails
+
+- Verify schema name uses valid publisher prefix (e.g., `cr_`)
+- Check that the table doesn't already exist
+- Ensure all required metadata fields are included in the request
+- Review the error response for specific validation failures
+
+### Relationship/Lookup Creation Fails
+
+- **"Referenced entity not found"**: Ensure the target table exists BEFORE creating the lookup
+ - Check creation order: TIER 0 tables must exist before TIER 1, etc.
+- **"Duplicate relationship name"**: Relationship names must be unique across the environment
+ - Use a consistent naming pattern: `{publisher}_{targettable}_{sourcetable}`
+- **"Invalid target entity"**: The target table must have a primary key attribute
+- **Self-referential lookup fails**: Create the table first, then add the self-lookup as a separate step
+
+### Sample Data Insertion Fails
+
+- **"Foreign key violation"**: The referenced record doesn't exist
+ - Insert TIER 0 data first, then TIER 1, then TIER 2
+ - Verify the lookup ID is correct (GUIDs are case-insensitive)
+ - If reusing existing lookup tables, query for existing record IDs first
+- **"Invalid @odata.bind syntax"**: Format must be `/entitysetname(guid)`
+ - Example: `"[email protected]" = "/cr_categories(12345678-1234-1234-1234-123456789012)"`
+- **"Entity set not found"**: Use the plural entity set name, not the logical name
+ - Table `cr_product` has entity set `cr_products` (usually plural)
+- **Duplicate record errors**: If using `New-DataverseRecordIfNotExists`, records with the same name are skipped
+ - Check for unique constraints on other columns if inserts still fail
+
+### Existing Data Conflicts
+
+- **Stale record IDs**: If reusing tables, always query for current record IDs; don't use cached values
+- **Data format differences**: Existing records may have different formats (e.g., dates, currency)
+- **Orphaned lookups**: When reusing tables, verify that lookup values still exist in referenced tables
+
+### Verifying Relationships
+
+```powershell
+# Check if a relationship exists
+$relations = Invoke-RestMethod -Uri "$baseUrl/RelationshipDefinitions?`$filter=SchemaName eq 'cr_category_product'" -Headers $headers
+if ($relations.value.Count -gt 0) {
+ Write-Host "Relationship exists"
+} else {
+ Write-Host "Relationship not found"
+}
+
+# List all relationships for a table
+$tableRelations = Invoke-RestMethod -Uri "$baseUrl/EntityDefinitions(LogicalName='cr_product')/OneToManyRelationships" -Headers $headers
+$tableRelations.value | ForEach-Object { Write-Host $_.SchemaName }
+```
+
+---
+
+## Reference Documentation
+
+- [Dataverse Web API](https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/overview)
+- [Dataverse Entity Metadata](https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/create-update-entity-definitions-using-web-api)
+- [OData Query Options](https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/query-data-web-api)
diff --git a/plugins/skills/setup-webapi/SKILL.md b/plugins/skills/setup-webapi/SKILL.md
new file mode 100644
index 000000000..4936e23fc
--- /dev/null
+++ b/plugins/skills/setup-webapi/SKILL.md
@@ -0,0 +1,324 @@
+---
+description: Configure Web API access for your Power Pages site. Creates site settings to enable table access via /_api endpoint, sets up entity permissions, and updates frontend code to use Power Pages Web API.
+user-invocable: true
+allowed-tools: Bash(pac:*), Bash(az:*), Bash(dotnet:*)
+model: sonnet
+---
+
+# 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 |
+| [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 Table Permissions │
+│ ───────────────────────────────────────────────────────────────────────── │
+│ • Create entity permission records for Web API access │
+│ • Configure scope (Global/Parent/Self) based on requirements │
+│ • Set appropriate CRUD permissions │
+│ 📖 See: table-permissions-reference.md │
+└─────────────────────────────────────────────────────────────────────────────┘
+ ↓
+┌─────────────────────────────────────────────────────────────────────────────┐
+│ STEP 4: 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 5: 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:**
+
+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 |
+
+**If starting fresh (no prior context):**
+
+Ask the user for:
+
+1. Project path (where the Power Pages site is located)
+2. Tables to enable for Web API (if not in memory bank)
+
+---
+
+## 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:
+
+1. **Enable setting**: `Webapi-<table>-enabled.sitesetting.yml`
+2. **Fields setting**: `Webapi-<table>-fields.sitesetting.yml`
+
+### 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
+
+---
+
+## STEP 3: 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.
+
+### Key Points
+
+- Use **Global scope** for public data (products, FAQs)
+- Use **Self scope** for user-specific data
+- Link permissions to appropriate web roles:
+ - **Anonymous Users** for public access
+ - **Authenticated Users** for logged-in users
+
+### Common Patterns
+
+| Data Type | Scope | Permissions |
+|-----------|-------|-------------|
+| Public content | Global | Read only |
+| Form submissions | Global | Create only |
+| User profiles | Self | Read, Write |
+
+### Actions
+
+1. Get environment URL and token
+2. Get Website ID from memory bank or `pac pages list`
+3. Create permissions using `New-TablePermission` function
+4. Associate permissions with web roles
+
+---
+
+## STEP 4: 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.
+
+### Key Points
+
+- Create `dataverseApi.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
+
+### CSRF Token Requirement
+
+POST, PATCH, DELETE requests require `__RequestVerificationToken` header. The reference includes a complete token handling implementation.
+
+### Actions
+
+1. Create `src/services/dataverseApi.ts` (copy from reference)
+2. Create type definitions for your entities
+3. Create entity-specific API wrappers
+4. Optionally create `useDataverse` React hook
+5. Update each component to use Web API
+6. Search and remove all mock data
+
+### Mock Data Checklist
+
+Search these locations for mock data to replace:
+
+- [ ] `src/data/` or `src/mock/` folders
+- [ ] Constants files with hardcoded arrays
+- [ ] Component files with inline data
+- [ ] JSON files used as data sources
+
+---
+
+## STEP 5: Build and Upload
+
+### Build the Project
+
+```powershell
+cd <PROJECT_ROOT>
+npm install # if needed
+npm run build
+```
+
+### Upload to Power Pages
+
+```powershell
+pac 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:
+
+```javascript
+fetch('/_api/cr_products')
+ .then(r => r.json())
+ .then(data => console.log('Products:', data.value))
+ .catch(err => console.error('Error:', err));
+```
+
+### Troubleshooting
+
+**📖 If you encounter issues, see: [troubleshooting.md](./troubleshooting.md)**
+
+---
+
+## 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] 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
+
+### Site Settings
+
+| Setting | Value | File |
+|---------|-------|------|
+| Webapi/cr_product/enabled | true | Webapi-cr_product-enabled.sitesetting.yml |
+| [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/dataverseApi.ts | Created 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
+```
diff --git a/plugins/skills/setup-webapi/frontend-integration-reference.md b/plugins/skills/setup-webapi/frontend-integration-reference.md
new file mode 100644
index 000000000..c9e6b613d
--- /dev/null
+++ b/plugins/skills/setup-webapi/frontend-integration-reference.md
@@ -0,0 +1,531 @@
+# 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:
+
+```text
+Base 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
+```
+
+## CSRF Token Requirement
+
+**IMPORTANT**: Power Pages requires a CSRF (Cross-Site Request Forgery) anti-forgery token for all non-GET requests (POST, PATCH, DELETE).
+
+- The token must be fetched from `/_layout/tokenhtml`
+- Include the token in the `__RequestVerificationToken` header
+- GET requests do not require this token
+- The token may expire, so handle 403 errors by refreshing the token
+
+## Dataverse API Service (TypeScript)
+
+Create a reusable API service for Web API calls.
+
+**File: `src/services/dataverseApi.ts`**
+
+```typescript
+// Power Pages Web API Service
+const API_BASE = '/_api';
+
+interface QueryOptions {
+ select?: string[];
+ filter?: string;
+ orderBy?: string;
+ top?: number;
+ expand?: string;
+}
+
+// Cache for the anti-forgery token
+let cachedToken: string | null = null;
+
+/**
+ * Fetches the CSRF anti-forgery token required for non-GET requests.
+ * Power Pages requires this token in the __RequestVerificationToken header
+ * for POST, PATCH, and DELETE operations.
+ */
+async function fetchAntiForgeryToken(): Promise<string> {
+ // Return cached token if available
+ if (cachedToken) {
+ return cachedToken;
+ }
+
+ try {
+ const tokenEndpoint = '/_layout/tokenhtml';
+ const response = await fetch(tokenEndpoint, {});
+
+ if (response.status !== 200) {
+ throw new Error(`Failed to fetch token: ${response.status}`);
+ }
+
+ const tokenResponse = await response.text();
+ const valueString = 'value="';
+ const terminalString = '" />';
+ const valueIndex = tokenResponse.indexOf(valueString);
+
+ if (valueIndex === -1) {
+ throw new Error('Token not found in response');
+ }
+
+ const requestVerificationToken = tokenResponse.substring(
+ valueIndex + valueString.length,
+ tokenResponse.indexOf(terminalString, valueIndex)
+ );
+
+ cachedToken = requestVerificationToken || '';
+ return cachedToken;
+ } catch (error) {
+ console.warn('[Web API] Failed to fetch anti-forgery token:', error);
+ return '';
+ }
+}
+
+/**
+ * Clears the cached token. Call this if you receive a 403 error
+ * which may indicate the token has expired.
+ */
+function clearTokenCache(): void {
+ cachedToken = null;
+}
+
+async function fetchWithAuth(url: string, options: RequestInit = {}) {
+ const method = options.method?.toUpperCase() || 'GET';
+ const headers: Record<string, string> = {
+ 'Content-Type': 'application/json',
+ 'Accept': 'application/json',
+ ...options.headers as Record<string, string>,
+ };
+
+ // Add anti-forgery token for non-GET requests (POST, PATCH, DELETE)
+ if (method !== 'GET') {
+ const token = await fetchAntiForgeryToken();
+ if (token) {
+ headers['__RequestVerificationToken'] = token;
+ }
+ }
+
+ const response = await fetch(url, {
+ ...options,
+ headers,
+ credentials: 'include', // Important for authenticated requests
+ });
+
+ if (!response.ok) {
+ // If we get a 403, the token may have expired - clear the cache
+ if (response.status === 403) {
+ clearTokenCache();
+ }
+ const error = await response.json().catch(() => ({ message: response.statusText }));
+ throw new Error(error.message || `API Error: ${response.status}`);
+ }
+
+ return response.json();
+}
+
+function buildQueryString(options: QueryOptions): string {
+ const params = new URLSearchParams();
+
+ if (options.select?.length) {
+ params.append('$select', options.select.join(','));
+ }
+ if (options.filter) {
+ params.append('$filter', options.filter);
+ }
+ if (options.orderBy) {
+ params.append('$orderby', options.orderBy);
+ }
+ if (options.top) {
+ params.append('$top', options.top.toString());
+ }
+ if (options.expand) {
+ params.append('$expand', options.expand);
+ }
+
+ const queryString = params.toString();
+ return queryString ? `?${queryString}` : '';
+}
+
+// Generic CRUD operations
+export const dataverseApi = {
+ // GET all records
+ async getAll<T>(entitySet: string, options: QueryOptions = {}): Promise<T[]> {
+ const queryString = buildQueryString(options);
+ const response = await fetchWithAuth(`${API_BASE}/${entitySet}${queryString}`);
+ return response.value;
+ },
+
+ // GET single record by ID
+ async getById<T>(entitySet: string, id: string, options: Pick<QueryOptions, 'select' | 'expand'> = {}): Promise<T> {
+ const queryString = buildQueryString(options);
+ return fetchWithAuth(`${API_BASE}/${entitySet}(${id})${queryString}`);
+ },
+
+ // POST create new record
+ async create<T>(entitySet: string, data: Partial<T>): Promise<T> {
+ return fetchWithAuth(`${API_BASE}/${entitySet}`, {
+ method: 'POST',
+ body: JSON.stringify(data),
+ });
+ },
+
+ // PATCH update existing record
+ async update<T>(entitySet: string, id: string, data: Partial<T>): Promise<void> {
+ await fetchWithAuth(`${API_BASE}/${entitySet}(${id})`, {
+ method: 'PATCH',
+ body: JSON.stringify(data),
+ });
+ },
+
+ // DELETE record
+ async delete(entitySet: string, id: string): Promise<void> {
+ await fetchWithAuth(`${API_BASE}/${entitySet}(${id})`, {
+ method: 'DELETE',
+ });
+ },
+};
+```
+
+## Entity-Specific Services
+
+Create typed wrappers for each entity:
+
+```typescript
+// Entity-specific services
+export const productsApi = {
+ getAll: (options?: QueryOptions) =>
+ dataverseApi.getAll<Product>('cr_products', options),
+ getById: (id: string) =>
+ dataverseApi.getById<Product>('cr_products', id),
+ getActive: () =>
+ dataverseApi.getAll<Product>('cr_products', { filter: 'cr_isactive eq true', orderBy: 'cr_name' }),
+};
+
+export const teamMembersApi = {
+ getAll: () =>
+ dataverseApi.getAll<TeamMember>('cr_teammembers', { orderBy: 'cr_displayorder' }),
+};
+
+export const testimonialsApi = {
+ getActive: () =>
+ dataverseApi.getAll<Testimonial>('cr_testimonials', { filter: 'cr_isactive eq true' }),
+};
+
+export const faqsApi = {
+ getActive: () =>
+ dataverseApi.getAll<FAQ>('cr_faqs', { filter: 'cr_isactive eq true', orderBy: 'cr_displayorder' }),
+};
+
+export const contactApi = {
+ submit: (data: ContactSubmission) =>
+ dataverseApi.create<ContactSubmission>('cr_contactsubmissions', {
+ ...data,
+ cr_submissiondate: new Date().toISOString(),
+ cr_status: 1, // New
+ }),
+};
+```
+
+## Type Definitions
+
+```typescript
+export interface Product {
+ cr_productid: string;
+ cr_name: string;
+ cr_description: string;
+ cr_price: number;
+ cr_category: string;
+ cr_imageurl: string;
+ cr_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;
+}
+
+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;
+}
+
+export interface FAQ {
+ cr_faqid: string;
+ cr_question: string;
+ cr_answer: string;
+ cr_category: string;
+ cr_displayorder: number;
+ cr_isactive: boolean;
+}
+
+export interface ContactSubmission {
+ cr_name: string;
+ cr_email: string;
+ cr_message: string;
+ cr_submissiondate?: string;
+ cr_status?: number;
+}
+```
+
+## React Hook for Data Fetching
+
+**File: `src/hooks/useDataverse.ts`**
+
+```typescript
+import { useState, useEffect, useCallback } from 'react';
+import { dataverseApi, QueryOptions } from '../services/dataverseApi';
+
+interface UseDataverseResult<T> {
+ data: T[];
+ loading: boolean;
+ error: string | null;
+ refetch: () => Promise<void>;
+}
+
+export function useDataverse<T>(
+ entitySet: string,
+ options: QueryOptions = {},
+ deps: any[] = []
+): UseDataverseResult<T> {
+ const [data, setData] = useState<T[]>([]);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState<string | null>(null);
+
+ const fetchData = useCallback(async () => {
+ setLoading(true);
+ setError(null);
+ try {
+ const result = await dataverseApi.getAll<T>(entitySet, options);
+ setData(result);
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Failed to fetch data');
+ } finally {
+ setLoading(false);
+ }
+ }, [entitySet, JSON.stringify(options)]);
+
+ useEffect(() => {
+ fetchData();
+ }, [fetchData, ...deps]);
+
+ return { data, loading, error, refetch: fetchData };
+}
+
+// Usage example:
+// const { data: products, loading, error } = useDataverse<Product>('cr_products', { filter: 'cr_isactive eq true' });
+```
+
+## Component Examples
+
+### Data Display Component
+
+**Before (static data):**
+
+```tsx
+const products = [
+ { id: 1, name: 'Product 1', price: 99.99 },
+ { id: 2, name: 'Product 2', price: 149.99 },
+];
+
+function ProductList() {
+ return (
+ <div>
+ {products.map(product => (
+ <ProductCard key={product.id} product={product} />
+ ))}
+ </div>
+ );
+}
+```
+
+**After (Web API):**
+
+```tsx
+import { useState, useEffect } from 'react';
+import { productsApi, Product } from '../services/dataverseApi';
+
+function ProductList() {
+ const [products, setProducts] = useState<Product[]>([]);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState<string | null>(null);
+
+ useEffect(() => {
+ async function loadProducts() {
+ try {
+ const data = await productsApi.getActive();
+ setProducts(data);
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Failed to load products');
+ } finally {
+ setLoading(false);
+ }
+ }
+ loadProducts();
+ }, []);
+
+ if (loading) return <div className="loading">Loading products...</div>;
+ if (error) return <div className="error">{error}</div>;
+
+ return (
+ <div className="products-grid">
+ {products.map(product => (
+ <ProductCard key={product.cr_productid} product={product} />
+ ))}
+ </div>
+ );
+}
+```
+
+### Form Submission Component
+
+```tsx
+import { useState } from 'react';
+import { contactApi, ContactSubmission } from '../services/dataverseApi';
+
+function ContactForm() {
+ const [formData, setFormData] = useState<ContactSubmission>({
+ cr_name: '',
+ cr_email: '',
+ cr_message: '',
+ });
+ const [submitting, setSubmitting] = useState(false);
+ const [submitted, setSubmitted] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ const handleSubmit = async (e: React.FormEvent) => {
+ e.preventDefault();
+ setSubmitting(true);
+ setError(null);
+
+ try {
+ await contactApi.submit(formData);
+ setSubmitted(true);
+ setFormData({ cr_name: '', cr_email: '', cr_message: '' });
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Failed to submit form');
+ } finally {
+ setSubmitting(false);
+ }
+ };
+
+ if (submitted) {
+ return (
+ <div className="success-message">
+ <h3>Thank you!</h3>
+ <p>Your message has been sent. We'll get back to you soon.</p>
+ <button onClick={() => setSubmitted(false)}>Send another message</button>
+ </div>
+ );
+ }
+
+ return (
+ <form onSubmit={handleSubmit} className="contact-form">
+ {error && <div className="error-message">{error}</div>}
+
+ <div className="form-group">
+ <label htmlFor="name">Name</label>
+ <input
+ id="name"
+ type="text"
+ value={formData.cr_name}
+ onChange={e => setFormData({ ...formData, cr_name: e.target.value })}
+ required
+ />
+ </div>
+
+ <div className="form-group">
+ <label htmlFor="email">Email</label>
+ <input
+ id="email"
+ type="email"
+ value={formData.cr_email}
+ onChange={e => setFormData({ ...formData, cr_email: e.target.value })}
+ required
+ />
+ </div>
+
+ <div className="form-group">
+ <label htmlFor="message">Message</label>
+ <textarea
+ id="message"
+ value={formData.cr_message}
+ onChange={e => setFormData({ ...formData, cr_message: e.target.value })}
+ required
+ rows={5}
+ />
+ </div>
+
+ <button type="submit" disabled={submitting}>
+ {submitting ? 'Sending...' : 'Send Message'}
+ </button>
+ </form>
+ );
+}
+```
+
+## Mock Data Replacement Checklist
+
+When integrating Web APIs, you must replace **all** mock/static data:
+
+1. **Search the codebase** for hardcoded arrays, objects, or static data files
+2. **Identify all components** that display data from configured tables
+3. **Replace each instance** with the appropriate Web API call
+4. **Remove or comment out** old mock data
+5. **Verify no static data remains**
+
+### Common Locations for Mock Data
+
+- `src/data/` or `src/mock/` folders
+- Constants files with hardcoded arrays
+- Component files with inline data definitions
+- JSON files used as data sources
+
+## OData Query Reference
+
+| 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` |
+| Top N | `$top=N` | `$top=10` |
+| Skip | `$skip=N` | `$skip=20` |
+| Expand | `$expand=relationship` | `$expand=cr_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')` |
diff --git a/plugins/skills/setup-webapi/site-settings-reference.md b/plugins/skills/setup-webapi/site-settings-reference.md
new file mode 100644
index 000000000..58abf242c
--- /dev/null
+++ b/plugins/skills/setup-webapi/site-settings-reference.md
@@ -0,0 +1,209 @@
+# Site Settings Reference
+
+This document describes how to create and configure site settings for Power Pages Web API access.
+
+## Folder Structure
+
+Site settings in Power Pages are stored in the `.powerpages-site/site-settings` folder. Each setting is a separate YAML file with a unique ID.
+
+```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
+│ │ └── ...
+│ └── ...
+```
+
+## Site Setting File Format
+
+Each site setting file follows this YAML format:
+
+```yaml
+id: <UUID>
+name: <SETTING_NAME>
+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`
+
+## Required Site Settings for Each Table
+
+For each table that needs Web API access, create these settings:
+
+### 1. Enable Web API for Table
+
+```yaml
+# File: <PROJECT_ROOT>/.powerpages-site/site-settings/Webapi-<TABLE_LOGICAL_NAME>-enabled.sitesetting.yml
+id: <GENERATE_UUID>
+name: Webapi/<TABLE_LOGICAL_NAME>/enabled
+value: true # Boolean, not string
+```
+
+**Example** for `cr_product` table:
+
+```yaml
+# File: Webapi-cr_product-enabled.sitesetting.yml
+id: a1b2c3d4-e5f6-7890-abcd-ef1234567890
+name: Webapi/cr_product/enabled
+value: true
+```
+
+### 2. Configure Allowed Fields
+
+**SECURITY REQUIREMENT**: Always specify explicit field names. Never use `*` as it exposes all fields including sensitive system columns. Only include fields that are needed by the frontend.
+
+```yaml
+# File: <PROJECT_ROOT>/.powerpages-site/site-settings/Webapi-<TABLE_LOGICAL_NAME>-fields.sitesetting.yml
+id: <GENERATE_UUID>
+name: Webapi/<TABLE_LOGICAL_NAME>/fields
+value: cr_name,cr_description,cr_price,cr_imageurl,cr_isactive
+```
+
+Specify comma-separated field logical names that your frontend actually needs.
+
+### 3. Enable Error Details (Development Only)
+
+For debugging purposes, enable detailed error messages:
+
+```yaml
+# File: Webapi-error-innererror.sitesetting.yml
+id: <GENERATE_UUID>
+name: Webapi/error/innererror
+value: true # Boolean, not string
+```
+
+**IMPORTANT**: Disable this in production by setting value to `false` or removing the setting.
+
+## PowerShell Helper Scripts
+
+### Create Site Settings for a Table
+
+```powershell
+function New-WebApiSiteSettings {
+ param(
+ [Parameter(Mandatory=$true)]
+ [string]$ProjectRoot,
+ [Parameter(Mandatory=$true)]
+ [string]$TableLogicalName,
+ [Parameter(Mandatory=$true)]
+ [string]$Fields # REQUIRED: Explicit field list (never use *)
+ )
+
+ # Security check: Never allow wildcard
+ if ($Fields -eq "*") {
+ throw "Security Error: Wildcard (*) is not allowed for fields. Specify explicit field names."
+ }
+
+ $siteSettingsPath = Join-Path $ProjectRoot ".powerpages-site\site-settings"
+
+ # Create directory if it doesn't exist
+ if (-not (Test-Path $siteSettingsPath)) {
+ New-Item -ItemType Directory -Path $siteSettingsPath -Force | Out-Null
+ }
+
+ # Generate UUIDs
+ $enabledUuid = [guid]::NewGuid().ToString()
+ $fieldsUuid = [guid]::NewGuid().ToString()
+
+ # Create enabled setting (value is boolean true, not string "true")
+ $enabledContent = @"
+id: $enabledUuid
+name: Webapi/$TableLogicalName/enabled
+value: true
+"@
+ $enabledFileName = "Webapi-$TableLogicalName-enabled.sitesetting.yml"
+ $enabledPath = Join-Path $siteSettingsPath $enabledFileName
+ Set-Content -Path $enabledPath -Value $enabledContent -Encoding UTF8
+ Write-Host "Created: $enabledPath"
+
+ # Create fields setting
+ $fieldsContent = @"
+id: $fieldsUuid
+name: Webapi/$TableLogicalName/fields
+value: $Fields
+"@
+ $fieldsFileName = "Webapi-$TableLogicalName-fields.sitesetting.yml"
+ $fieldsPath = Join-Path $siteSettingsPath $fieldsFileName
+ Set-Content -Path $fieldsPath -Value $fieldsContent -Encoding UTF8
+ Write-Host "Created: $fieldsPath"
+
+ return @{
+ TableName = $TableLogicalName
+ EnabledFile = $enabledFileName
+ FieldsFile = $fieldsFileName
+ }
+}
+```
+
+### Example Usage
+
+```powershell
+$projectRoot = "<PROJECT_ROOT>" # Replace with actual path
+
+# 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"
+
+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 "cr_testimonial" `
+ -Fields "cr_name,cr_quote,cr_company,cr_role,cr_rating,cr_photourl,cr_isactive"
+
+New-WebApiSiteSettings -ProjectRoot $projectRoot -TableLogicalName "cr_faq" `
+ -Fields "cr_question,cr_answer,cr_category,cr_displayorder,cr_isactive"
+
+New-WebApiSiteSettings -ProjectRoot $projectRoot -TableLogicalName "cr_contactsubmission" `
+ -Fields "cr_name,cr_email,cr_message,cr_submissiondate,cr_status"
+```
+
+### Create Error Setting
+
+```powershell
+function New-WebApiErrorSetting {
+ param(
+ [string]$ProjectRoot,
+ [bool]$Enabled = $true
+ )
+
+ $siteSettingsPath = Join-Path $ProjectRoot ".powerpages-site\site-settings"
+ $errorUuid = [guid]::NewGuid().ToString()
+
+ # Value is boolean true/false, not string
+ $errorContent = @"
+id: $errorUuid
+name: Webapi/error/innererror
+value: $($Enabled.ToString().ToLower())
+"@
+ $errorFileName = "Webapi-error-innererror.sitesetting.yml"
+ $errorPath = Join-Path $siteSettingsPath $errorFileName
+ Set-Content -Path $errorPath -Value $errorContent -Encoding UTF8
+ Write-Host "Created error setting: $errorPath"
+}
+
+# Enable detailed errors for development
+New-WebApiErrorSetting -ProjectRoot $projectRoot -Enabled $true
+```
+
+## Site Settings Quick Reference
+
+| 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/error/innererror` | Show detailed errors (dev only) | `true` |
+
+## Validation Checklist
+
+Before uploading:
+
+- [ ] All YAML files have valid syntax
+- [ ] Each file has a unique UUID for the `id` field
+- [ ] File extensions are `.yml` (not `.yaml`)
+- [ ] Field lists use explicit names (no wildcards)
+- [ ] Error setting is disabled for production
diff --git a/plugins/skills/setup-webapi/table-permissions-reference.md b/plugins/skills/setup-webapi/table-permissions-reference.md
new file mode 100644
index 000000000..9985927bd
--- /dev/null
+++ b/plugins/skills/setup-webapi/table-permissions-reference.md
@@ -0,0 +1,415 @@
+# 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
+ )
+
+ $permission = @{
+ "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"
+ return $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 Anonymous Users Role
+
+```powershell
+# Get the Anonymous Users web role ID
+$anonymousRole = Invoke-RestMethod `
+ -Uri "$baseUrl/adx_webroles?`$filter=adx_name eq 'Anonymous Users' and _adx_websiteid_value eq $websiteId&`$select=adx_webroleid" `
+ -Headers $headers
+
+if ($anonymousRole.value.Count -gt 0) {
+ $roleId = $anonymousRole.value[0].adx_webroleid
+ Write-Host "Anonymous Users Role ID: $roleId"
+}
+```
+
+### Associate Permission with Role
+
+```powershell
+function Add-PermissionToRole {
+ param(
+ [string]$PermissionId,
+ [string]$RoleId
+ )
+
+ $association = @{
+ "@odata.id" = "$baseUrl/adx_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"
+ }
+ catch {
+ Write-Host "Error associating permission: $_"
+ }
+}
+```
+
+### 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)"
+}
+```
+
+## PAC CLI Table Permission Files
+
+When working with Power Platform CLI (`pac paportal download`), table permissions are stored as YAML files.
+
+### File Naming Convention
+
+```
+<Permission-Name>.tablepermission.yml
+```
+
+Example: `Product-Read-Permission.tablepermission.yml`
+
+### YAML File Structure
+
+```yaml
+append: false
+appendto: false
+create: false
+delete: false
+entitylogicalname: cr_product
+entityname: Product Read Permission
+entitypermission_webrole:
+- 18c1fdce-684b-f011-877a-7c1e520c8613
+id: 71ecf203-dfe2-4c1e-9db2-112ed3925a52
+parententitypermission:
+read: true
+scope: 756150000
+write: false
+```
+
+### YAML Field Reference
+
+| Field | Type | Description |
+|-------|------|-------------|
+| `entitylogicalname` | string | Dataverse table logical name (e.g., `cr_product`) |
+| `entityname` | string | Display name for the permission |
+| `id` | GUID | Unique identifier for this permission |
+| `scope` | int | Permission scope (see values below) |
+| `read` | bool | Can retrieve/query records |
+| `create` | bool | Can create new records |
+| `write` | bool | Can update existing records |
+| `delete` | bool | Can delete records |
+| `append` | bool | Can associate records to this entity |
+| `appendto` | bool | Can associate this entity to other records |
+| `entitypermission_webrole` | list | GUIDs of web roles with this permission |
+| `parententitypermission` | GUID | Parent permission ID for hierarchical access |
+
+### 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 |
+
+### Example: Read-Only Public Permission
+
+```yaml
+append: false
+appendto: false
+create: false
+delete: false
+entitylogicalname: cr_product
+entityname: Product - Anonymous Read
+entitypermission_webrole:
+- <anonymous-users-webrole-guid>
+id: <new-guid>
+parententitypermission:
+read: true
+scope: 756150000
+write: false
+```
+
+### Example: User Self-Access Permission
+
+```yaml
+append: false
+appendto: false
+create: true
+delete: false
+entitylogicalname: cr_userprofile
+entityname: User Profile - Self Access
+entitypermission_webrole:
+- <authenticated-users-webrole-guid>
+id: <new-guid>
+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)
+
+#### Example: Parent Permission (Order)
+
+```yaml
+append: true
+appendto: false
+create: true
+delete: false
+entitylogicalname: cr_order
+entityname: Order - User Access
+entitypermission_webrole:
+- <authenticated-users-webrole-guid>
+id: a1b2c3d4-e5f6-7890-abcd-ef1234567890
+parententitypermission:
+read: true
+scope: 756150001
+write: true
+```
+
+#### Example: Child Permission (Order Items)
+
+```yaml
+append: false
+appendto: true
+create: true
+delete: true
+entitylogicalname: cr_orderitem
+entityname: Order Item - Parent Access
+entitypermission_webrole:
+- <authenticated-users-webrole-guid>
+id: <new-guid>
+parententitypermission: a1b2c3d4-e5f6-7890-abcd-ef1234567890
+read: true
+scope: 756150003
+write: true
+```
+
+In this example, users can only access order items that belong to orders they have access to.
+
+## 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/skills/setup-webapi/troubleshooting.md b/plugins/skills/setup-webapi/troubleshooting.md
new file mode 100644
index 000000000..50c5e7cc7
--- /dev/null
+++ b/plugins/skills/setup-webapi/troubleshooting.md
@@ -0,0 +1,318 @@
+# Troubleshooting Guide
+
+This document covers common issues when setting up Power Pages Web API and their solutions.
+
+## Quick Reference
+
+| Issue | Solution |
+|-------|----------|
+| `403 Forbidden` | Table permission not configured, not linked to web role, or missing/expired CSRF token |
+| `404 Not Found` | Web API not enabled for table (check site setting) |
+| `400 Bad Request` | Invalid OData query syntax or field not in allowed fields |
+| `500 Server Error` | Enable `Webapi/error/innererror` to see details |
+| `CSRF Token Error` | Ensure `__RequestVerificationToken` header is included for POST/PATCH/DELETE requests |
+
+## Site Settings Not Being Applied
+
+### Symptoms
+
+- Web API returns 404 even though settings exist
+- Settings don't appear in Power Pages Studio
+
+### Solutions
+
+1. **Validate YAML syntax**
+
+ ```yaml
+ # Correct
+ id: a1b2c3d4-e5f6-7890-abcd-ef1234567890
+ name: Webapi/cr_product/enabled
+ value: true
+
+ # Incorrect (missing quotes can cause issues in some cases)
+ id: a1b2c3d4e5f6-7890-abcd-ef1234567890 # Invalid UUID format
+ ```
+
+2. **Verify file extension is `.yml`** (not `.yaml`)
+
+3. **Check that `id` is a valid UUID**
+
+ ```powershell
+ # Generate a valid UUID
+ [guid]::NewGuid().ToString()
+ ```
+
+4. **Re-upload the site after adding settings**
+
+ ```powershell
+ pac pages upload-code-site --rootPath "<PROJECT_ROOT>"
+ ```
+
+## Web API Returns 403 Forbidden
+
+### Symptoms
+
+- GET requests return 403
+- POST/PATCH/DELETE requests fail with 403
+
+### For GET Requests
+
+1. **Verify table permission exists**
+
+ ```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
+ ```
+
+2. **Check permission is linked to correct web role**
+ - For public access: Link to "Anonymous Users"
+ - For authenticated access: Link to "Authenticated Users"
+
+3. **Verify permission has Read enabled**
+
+ ```powershell
+ # Permission should have adx_read = true
+ ```
+
+4. **Verify permission scope**
+ - Global (756150000) for public data
+ - Self (756150004) for user-specific data
+
+### For POST/PATCH/DELETE Requests
+
+1. **Ensure CSRF token is included**
+
+ ```javascript
+ // Fetch token
+ const response = await fetch('/_layout/tokenhtml');
+ const html = await response.text();
+ const match = html.match(/value="([^"]+)"/);
+ const token = match ? match[1] : null;
+
+ // Include in request
+ fetch('/_api/cr_products', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ '__RequestVerificationToken': token
+ },
+ body: JSON.stringify(data)
+ });
+ ```
+
+2. **Check if token expired**
+ - Clear cached token and fetch a new one
+ - Tokens can expire after extended inactivity
+
+3. **Verify Create/Write/Delete permissions**
+ - POST requires `adx_create = true`
+ - PATCH requires `adx_write = true`
+ - DELETE requires `adx_delete = true`
+
+## CSRF Token Issues
+
+### Test Token Fetch Manually
+
+```javascript
+// In browser console
+fetch('/_layout/tokenhtml')
+ .then(r => r.text())
+ .then(html => {
+ const match = html.match(/value="([^"]+)"/);
+ console.log('Token:', match ? match[1] : 'Not found');
+ });
+```
+
+### Common Token Problems
+
+| Problem | Solution |
+|---------|----------|
+| Token not found | Ensure `/_layout/tokenhtml` is accessible |
+| Token expired | Clear cache and fetch new token |
+| Token not sent | Check header name is `__RequestVerificationToken` |
+| Wrong token format | Parse HTML correctly to extract value |
+
+## Web API Returns 404 Not Found
+
+### Solutions
+
+1. **Verify site setting exists and is enabled**
+
+ ```yaml
+ name: Webapi/cr_product/enabled
+ value: 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
+
+3. **Ensure table exists in Dataverse**
+
+ ```powershell
+ # List tables
+ pac table list
+ ```
+
+4. **Re-upload site settings**
+
+ ```powershell
+ pac pages upload-code-site --rootPath "<PROJECT_ROOT>"
+ ```
+
+## Web API Returns 400 Bad Request
+
+### Common Causes
+
+1. **Invalid OData query syntax**
+
+ ```text
+ # Incorrect
+ /_api/cr_products?filter=cr_isactive eq true
+
+ # Correct ($ prefix required)
+ /_api/cr_products?$filter=cr_isactive eq true
+ ```
+
+2. **Field not in allowed fields list**
+ - Check `Webapi/<table>/fields` setting
+ - Add missing fields to the comma-separated list
+
+3. **Invalid filter value**
+
+ ```text
+ # Incorrect (string needs quotes)
+ $filter=cr_category eq Electronics
+
+ # Correct
+ $filter=cr_category eq 'Electronics'
+ ```
+
+4. **Invalid data type in request body**
+
+ ```javascript
+ // Incorrect
+ { "cr_price": "99.99" } // String instead of number
+
+ // Correct
+ { "cr_price": 99.99 }
+ ```
+
+## Web API Returns 500 Server Error
+
+### Enable Detailed Error Messages
+
+1. **Create error setting**
+
+ ```yaml
+ # File: Webapi-error-innererror.sitesetting.yml
+ id: <uuid>
+ name: Webapi/error/innererror
+ value: true
+ ```
+
+2. **Upload and test again**
+
+ ```powershell
+ pac pages upload-code-site --rootPath "<PROJECT_ROOT>"
+ ```
+
+3. **Check browser Network tab for detailed error response**
+
+### Common Server Errors
+
+| Error Message | Solution |
+|---------------|----------|
+| "Entity not found" | Check table logical name |
+| "Invalid field" | Field doesn't exist or not in allowed list |
+| "Permission denied" | Check table permissions and web role |
+
+## CORS Errors in Browser
+
+Power Pages Web API should not have CORS issues when called from the same origin.
+
+### If CORS Errors Occur
+
+1. **Use relative URLs**
+
+ ```javascript
+ // Correct
+ fetch('/_api/cr_products')
+
+ // Incorrect (may cause CORS issues)
+ fetch('https://site.powerappsportals.com/_api/cr_products')
+ ```
+
+2. **Check HTTP vs HTTPS**
+ - Ensure site URL and API URL use same protocol
+
+3. **Verify origin matches**
+ - Request must come from same domain as the site
+
+## Data Not Displaying
+
+### Debugging Steps
+
+1. **Check browser console for JavaScript errors**
+
+2. **Verify API response in Network tab**
+ - Look for the `/_api/...` request
+ - Check response status and body
+
+3. **Test API directly in browser**
+
+ ```text
+ https://<site-url>/_api/cr_products
+ ```
+
+4. **Check field name mapping**
+ - Ensure frontend uses Dataverse column logical names
+ - Example: `cr_productid` not `id`
+
+5. **Verify data exists in Dataverse**
+
+ ```powershell
+ # Query via Dataverse API
+ Invoke-RestMethod -Uri "$baseUrl/cr_products" -Headers $headers
+ ```
+
+## Debug Checklist
+
+Use this checklist to systematically debug Web API issues:
+
+- [ ] Site settings uploaded? (`pac pages upload-code-site`)
+- [ ] Site setting syntax valid? (YAML format, boolean values)
+- [ ] Table permission created? (check in Power Pages Studio)
+- [ ] Permission linked to web role? (Anonymous Users for public)
+- [ ] Permission has correct CRUD flags?
+- [ ] CSRF token included for write operations?
+- [ ] OData query syntax correct? (`$filter`, `$select`, etc.)
+- [ ] Fields in allowed fields list?
+- [ ] Entity set name correct? (pluralized)
+- [ ] Data exists in Dataverse?
+- [ ] Error details enabled for debugging?
+
+## Verify in Power Pages Studio
+
+### Check Site Settings
+
+1. Go to Power Pages Studio
+2. Navigate to **Setup > Site Settings**
+3. Search for "Webapi"
+4. Verify settings are present
+
+### Check Table Permissions
+
+1. Go to Power Pages Studio
+2. Navigate to **Security > Table Permissions**
+3. Verify permissions exist
+4. Check they're linked to appropriate web roles
+
+## Reference Documentation
+
+- [Power Pages Web API Overview](https://learn.microsoft.com/en-us/power-pages/configure/web-api-overview)
+- [Web API Operations](https://learn.microsoft.com/en-us/power-pages/configure/write-update-delete-operations)
+- [Site Settings Reference](https://learn.microsoft.com/en-us/power-pages/configure/configure-site-settings)
+- [Table Permissions](https://learn.microsoft.com/en-us/power-pages/security/table-permissions)
+- [OData Query Options](https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/query-data-web-api)
diff --git a/skills/create-site/SKILL.md b/skills/create-site/SKILL.md
deleted file mode 100644
index 270c0cf61..000000000
--- a/skills/create-site/SKILL.md
+++ /dev/null
@@ -1,402 +0,0 @@
----
-description: Create a Power Pages code site (SPA) using modern frontend frameworks like React, Angular, Vue, or Astro. Guides through design, build, upload, and activation.
-user-invocable: true
-allowed-tools: Bash(pac:*), Bash(az:*)
-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.
-
-## 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 │
-│ • 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 Manually │
-│ ───────────────────────────────────────────────────────────────────────── │
-│ • Go to Power Pages home page → Inactive sites │
-│ • Click Reactivate on your site │
-│ • Configure name and web address → Done │
-└─────────────────────────────────────────────────────────────────────────────┘
-```
-
----
-
-## STEP 1: Gather Requirements
-
-**IMPORTANT**: Before creating anything, you MUST ask the maker the following questions using the AskUserQuestion tool.
-
-### 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
-
-Based on what they want to build, 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. |
-
-### Question 3: Site Features
-
-Ask what features the maker wants in their site. Common options:
-
-- Landing page / Hero section
-- Navigation menu
-- Contact form
-- About page
-- Services/Products showcase
-- Image gallery
-- Blog/News section
-- User authentication (Microsoft Entra ID)
-- Data display from Dataverse (Web API)
-
-### Question 4: Design Preferences
-
-Ask about design preferences:
-
-- **Style**: Modern/Minimalist, Corporate/Professional, Creative/Bold, Elegant/Luxury
-- **Color scheme**: Let them specify or suggest based on their brand
-- **Special requirements**: Accessibility, mobile-first, specific branding guidelines
-
----
-
-## STEP 2: Create the Site
-
-After gathering requirements, use the **frontend-design skill** to create the site.
-
-### Instructions for Site Creation
-
-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
-
-### 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
-```
-
-### Create powerpages.config.json
-
-After the site is created, add this configuration file:
-
-```json
-{
- "siteName": "<SITE_NAME>",
- "defaultLandingPage": "index.html",
- "compiledPath": "./build"
-}
-```
-
-For Vue/Astro projects, change `compiledPath` to `"./dist"`.
-
-### Build the Project
-
-Run the appropriate build command:
-
-```bash
-# React (Create React App or Vite)
-npm run build
-
-# Angular
-ng build --configuration production
-
-# Vue
-npm run build
-
-# Astro
-npm run build
-```
-
----
-
-## STEP 3: Check Prerequisites
-
-**IMPORTANT**: Before uploading, verify that all required CLI tools are installed on the user's machine.
-
-### Check PAC CLI
-
-Run the following command to check if PAC CLI is installed:
-
-```powershell
-pac help
-```
-
-**If the command fails or PAC CLI is not found**, install it using .NET tool:
-
-```powershell
-dotnet tool install --global Microsoft.PowerApps.CLI.Tool
-```
-
-If installation fails, guide the user based on the error.
-
-After installation, verify it works:
-
-```powershell
-pac help
-```
-
-### Check Azure CLI
-
-Run the following command to check if Azure CLI is installed:
-
-```powershell
-az --version
-```
-
-**If the command fails or Azure CLI is not found**, install it using winget:
-
-```powershell
-winget install -e --id Microsoft.AzureCLI
-```
-
-After installation, the user may need to restart their terminal. Then verify it works:
-
-```powershell
-az --version
-```
-
-### Verify Authentication
-
-Once both CLIs are installed, ensure the user is authenticated:
-
-```powershell
-# Check PAC CLI authentication
-pac auth list
-
-# If not authenticated, prompt user to authenticate
-pac auth create
-
-# Check Azure CLI authentication
-az account show
-
-# If not authenticated, prompt user to login
-az login
-```
-
-### Verify Environment Connection
-
-```powershell
-pac org who
-```
-
----
-
-## STEP 4: Upload to Power Pages (Inactive)
-
-### Upload Command
-
-```powershell
-pac pages upload-code-site `
- --rootPath "<PROJECT_ROOT_PATH>" `
-```
-
-**Example:**
-
-```powershell
-pac pages upload-code-site `
- --rootPath "C:\repos\my-power-pages-site" `
-```
-
-### Get Website Record ID
-
-After upload, list sites to get the websiteRecordId:
-
-```powershell
-pac pages list --verbose
-```
-
-Note the **Website ID** (GUID) - this is needed for activation.
-
----
-
-## STEP 5: Preview Locally
-
-Before activating the site, run it locally to verify everything works correctly.
-
-### Run the Development Server
-
-```powershell
-# React (Vite)
-npm run dev
-
-# React (Create React App)
-npm start
-
-# Angular
-ng serve
-
-# Vue
-npm run dev
-
-# Astro
-npm run dev
-```
-
-### Verify the Site
-
-1. Open the local URL (usually `http://localhost:5173` or `http://localhost:3000`)
-2. Test all pages and navigation
-3. Verify forms and interactive elements work
-4. Check responsive design on different screen sizes
-
-Once you're satisfied with the local preview, proceed to activate the site.
-
----
-
-## STEP 6: Activate Website Manually
-
-After uploading, your site appears as **Inactive** in Power Pages. Follow these steps to activate it manually.
-
-### Steps to Activate
-
-1. **Go to Power Pages home page**
- - Navigate to [make.powerpages.microsoft.com](https://make.powerpages.microsoft.com)
- - Select your environment
-
-2. **Find your inactive site**
- - Click on **Inactive sites** in the left navigation
- - Your uploaded site will appear in the list
-
-3. **Reactivate the site**
- - Click the **Reactivate** button next to your site
-
-4. **Configure site details**
- - **Website name**: Enter or confirm the display name
- - **Web address**: Choose a subdomain (e.g., `my-site` → `my-site.powerappsportals.com`)
- - Click **Done**
-
-5. **Wait for provisioning**
- - The site will take a few minutes to provision
- - Once complete, it will appear in **Active sites**
-
-### Verify Activation
-
-```powershell
-pac pages list --verbose
-```
-
-Your site should now show as **Active** with a URL.
-
-**Reference**: [Reactivate a website - Microsoft Learn](https://learn.microsoft.com/en-us/power-pages/admin/reactivate-website)
-
----
-
-## Next Steps
-
-After the site is active, suggest the maker proceed with:
-
-### Web API Integration
-
-> **Recommended Next Step**: Implement Web API to connect your site to Dataverse data.
->
-> This will allow your site to:
->
-> - Read and display data from Dataverse tables
-> - Create, update, and delete records
-> - Implement user-specific data views
->
-> Use the **configure-web-api** skill to set this up.
-
-### Additional Enhancements
-
-- **Authentication**: Set up Microsoft Entra ID for user sign-in
-- **Table Permissions**: Configure entity permissions for data access
-- **Custom styling**: Further refine the design
-- **Performance optimization**: Enable caching and CDN
-
----
-
-## Troubleshooting
-
-### Upload Fails with JavaScript Error
-
-Enable JavaScript file uploads:
-
-1. Go to Power Platform admin center
-2. Navigate to Environments → [Your Environment] → Settings
-3. Go to Product → Privacy + Security
-4. In "Blocked Attachments", remove `js` from the list
-5. Save changes
-
-### Site Shows as Inactive After Upload
-
-This is expected. The upload creates an INACTIVE record. Follow STEP 6 to manually activate it via the Power Pages home page.
-
-### Site Not Appearing in Inactive Sites
-
-- Verify the upload completed successfully
-- Check you're in the correct environment
-- Run `pac pages list --verbose` to confirm the site exists
-
-### Reactivation Fails
-
-Ensure your user has appropriate permissions:
-
-- System Administrator or System Customizer role in the environment
-- Power Pages administrator access
-
----
-
-## Reference Documentation
-
-- [Create Code Sites in Power Pages](https://learn.microsoft.com/en-us/power-pages/configure/create-code-sites)
-- [Reactivate a Website](https://learn.microsoft.com/en-us/power-pages/admin/reactivate-website)
-- [PAC CLI Reference](https://learn.microsoft.com/en-us/power-platform/developer/cli/reference/pages)