A plugin marketplace for GitHub Copilot and other AI agents that provides Power Platform development plugins, including reusable skills, agents, and commands for building and deploying solutions.
JavaScript claude-code-pluginclaude-code-skillscode-appsgithub-copilot-pluginpower-appspower-pagespower-platform
Modular skill references (#3)
Priyanshu Agrawala9dcae558192
diff --git a/AGENTS.md b/AGENTS.mdindex 667e3710c..93a089b5a 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -79,6 +79,35 @@ Use these in skills, hooks, and scripts:- `${CLAUDE_SESSION_ID}` - Current session ID- `$ARGUMENTS` - Arguments passed to skill+## DRY Principle (Don't Repeat Yourself)++**Always follow the DRY principle when creating or modifying plugin content.**++### Guidelines++1. **Use shared reference files** for common instructions, documentation, or code that multiple skills need+2. **Create files in `shared/` folder** for content used across multiple skills+3. **Reference shared files** using `${CLAUDE_PLUGIN_ROOT}/shared/<filename>` instead of duplicating content+4. **Never copy-paste** the same instructions into multiple skill files++### Example++Instead of duplicating cleanup instructions in each skill:++```markdown+## Cleanup Helper Files++**π See: [cleanup-reference.md](${CLAUDE_PLUGIN_ROOT}/shared/cleanup-reference.md)**++Remove any temporary helper files created during this skill's execution.+```++### Shared Resources Location++Common resources should be placed in:+- `plugins/<plugin-name>/shared/` - Plugin-specific shared files+- Reference using `${CLAUDE_PLUGIN_ROOT}/shared/<filename>`+## Memory Bank SystemPlugins use a memory bank (`memory-bank.md`) to persist state across sessions.diff --git a/README.md b/README.mdindex f8747ccbb..396e12686 100644--- a/README.md+++ b/README.md@@ -33,36 +33,49 @@ Create and deploy Power Pages sites using modern development approaches.**Currently supported**: Code Sites (SPAs) with React, Angular, Vue, or Astro-| Skill | Description |-|-------|-------------|-| `/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-## Installation-To use a plugin from this marketplace, reference it in your Claude Code configuration:+### Add from GitHub Marketplace-```json-{- "plugins": ["./plugins/power-pages"]-}-```+To use a plugin from this marketplace:-## Workflow Example (Power Pages)+1. Add the marketplace to your Claude Code instance-```-βββββββββββββββ βββββββββββββββ βββββββββββββββ βββββββββββββββ-β 1. Design β βββΆ β 2. Build β βββΆ β 3. Upload β βββΆ β 4. Activate β-β & Create β β Project β β (Inactive) β β (Go Live) β-βββββββββββββββ βββββββββββββββ βββββββββββββββ βββββββββββββββ-```+ ```bash+ /plugin marketplace add microsoft/power-platform-claude-plugin+ ```++2. Install the desired plugin++ ```bash+ /plugin install power-pages@power-platform-claude-plugin+ ```++### Add from local path++1. Clone this repository+1. Add the marketplace to your Claude Code instance++ ```bash+ /plugin marketplace add /path/to/power-platform-claude-plugin+ ```++1. Install the desired plugin (installs to user scope by default)++ ```bash+ /plugin install power-pages@power-platform-claude-plugin+ ```++## Local Development++To develop and test plugins locally, follow these steps:++1. Clone this repository+1. Launch Claude Code with plugin path:++ ```bash+ claude --plugin-dir /path/to/power-platform-claude-plugin/plugins/power-pages+ ```## Documentation@@ -92,4 +105,3 @@ trademarks or logos is subject to and must follow[Microsoft's Trademark & Brand Guidelines](https://www.microsoft.com/legal/intellectualproperty/trademarks/usage/general).Use of Microsoft trademarks or logos in modified versions of this project must not cause confusion or imply Microsoft sponsorship.Any use of third-party trademarks or logos are subject to those third-party's policies.-diff --git a/plugins/.claude-plugin/plugin.json b/plugins/power-pages/.claude-plugin/plugin.jsonsimilarity index 100%rename from plugins/.claude-plugin/plugin.jsonrename to plugins/power-pages/.claude-plugin/plugin.jsondiff --git a/plugins/.mcp.json b/plugins/power-pages/.mcp.jsonsimilarity index 100%rename from plugins/.mcp.jsonrename to plugins/power-pages/.mcp.jsondiff --git a/plugins/agents/code-site-architect.md b/plugins/power-pages/agents/code-site-architect.mdsimilarity index 100%rename from plugins/agents/code-site-architect.mdrename to plugins/power-pages/agents/code-site-architect.mddiff --git a/plugins/commands/create-site.md b/plugins/power-pages/commands/create-site.mdsimilarity index 100%rename from plugins/commands/create-site.mdrename to plugins/power-pages/commands/create-site.mddiff --git a/plugins/power-pages/commands/setup-auth.md b/plugins/power-pages/commands/setup-auth.mdnew file mode 100644index 000000000..be8ce205b--- /dev/null+++ b/plugins/power-pages/commands/setup-auth.md@@ -0,0 +1,5 @@+# Setup Authentication & Authorization++Read and follow the instructions in `${CLAUDE_PLUGIN_ROOT}/skills/setup-auth/SKILL.md` to guide the user through implementing authentication (login/logout) and role-based authorization for their Power Pages site.++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-dataverse.md b/plugins/power-pages/commands/setup-dataverse.mdsimilarity index 100%rename from plugins/commands/setup-dataverse.mdrename to plugins/power-pages/commands/setup-dataverse.mddiff --git a/plugins/commands/setup-webapi.md b/plugins/power-pages/commands/setup-webapi.mdsimilarity index 100%rename from plugins/commands/setup-webapi.mdrename to plugins/power-pages/commands/setup-webapi.mddiff --git a/plugins/power-pages/shared/cleanup-reference.md b/plugins/power-pages/shared/cleanup-reference.mdnew file mode 100644index 000000000..b984bfba6--- /dev/null+++ b/plugins/power-pages/shared/cleanup-reference.md@@ -0,0 +1,19 @@+# Cleanup Helper Files++After successfully completing a skill, remove any temporary helper scripts or files that were created in the project root during execution.++## What to Remove++Any temporary scripts or helper files created during the skill that are not part of the final site structure.++## What NOT to Remove++- `memory-bank.md` (needed for session continuity)+- `.powerpages-site/` folder and all its contents+- `src/` folder and source files+- Configuration files (`package.json`, `powerpages.config.json`, `tsconfig.json`, etc.)+- Any files that existed before running the skill++## When to Cleanup++Only clean up helper files after confirming the skill completed successfully and the setup is working correctly.diff --git a/plugins/shared/memory-bank.md b/plugins/power-pages/shared/memory-bank.mdsimilarity index 100%rename from plugins/shared/memory-bank.mdrename to plugins/power-pages/shared/memory-bank.mddiff --git a/plugins/power-pages/skills/create-site/SKILL.md b/plugins/power-pages/skills/create-site/SKILL.mdnew file mode 100644index 000000000..946d6b8c0--- /dev/null+++ b/plugins/power-pages/skills/create-site/SKILL.md@@ -0,0 +1,268 @@+---+description: Create a Power Pages code site, website, portal, or SPA using modern frontend frameworks like React, Angular, Vue, or Astro. Use this skill when you need to create a new Power Pages site, build a website, set up a portal, scaffold a project, design pages, upload site to Power Pages, or activate a site for public access.+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.++## Reference Documentation++This skill uses modular reference files for detailed instructions:++| File | Purpose |+|------|---------|+| [requirements-reference.md](./requirements-reference.md) | Framework options, features, design preferences |+| [site-creation-reference.md](./site-creation-reference.md) | Project structure, powerpages.config.json, memory bank |+| [seo-reference.md](./seo-reference.md) | Meta tags, robots.txt, sitemap.xml, favicons |+| [testing-reference.md](./testing-reference.md) | Unit tests (Vitest) and E2E tests (Playwright) |+| [upload-activation-reference.md](./upload-activation-reference.md) | Prerequisites, PAC CLI upload, API activation |+| [troubleshooting.md](./troubleshooting.md) | Common issues and solutions |++## Memory Bank++This skill uses a **memory bank** (`memory-bank.md`) to persist context across sessions.++**Follow the instructions in `${CLAUDE_PLUGIN_ROOT}/shared/memory-bank.md`** for:+- Checking and reading the memory bank before starting+- Skipping completed steps and resuming progress+- Updating the memory bank after each major step++## Workflow Overview++```text+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+β STEP 1: Gather Requirements β+β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β+β β’ Frontend framework selection (React, Angular, Vue, Astro) β+β β’ Site features and functionality β+β β’ Design preferences and style β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+ β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+β STEP 2: Create the Site β+β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β+β β’ Use frontend-design skill to build production-grade UI β+β β’ Generate complete SPA with chosen framework β+β β’ Add SEO assets (meta tags, robots.txt, sitemap.xml, favicon) β+β β’ Write unit tests for components and utilities β+β β’ Write end-to-end tests with Playwright β+β β’ Build the project for production β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+ β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+β STEP 3: Check Prerequisites β+β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β+β β’ Verify PAC CLI is installed (install if missing) β+β β’ Verify Azure CLI is installed (install if missing) β+β β’ Ensure authentication is configured β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+ β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+β STEP 4: Upload to Power Pages (Inactive) β+β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β+β β’ Use PAC CLI: pac pages upload-code-site β+β β’ Site uploaded in INACTIVE mode β+β β’ Get websiteRecordId for activation β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+ β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+β STEP 5: Preview Locally β+β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β+β β’ Run the app locally to verify it works β+β β’ Test all features before activation β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+ β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+β STEP 6: Activate Website β+β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β+β β’ Ask user for subdomain preference β+β β’ Call Power Platform CreateWebsite API via az rest β+β β’ Monitor operation status until complete β+β β’ Fallback: Manual activation via Power Pages portal β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+```++---++## STEP 1: Gather Requirements++**π Detailed reference: [requirements-reference.md](./requirements-reference.md)**++**IMPORTANT**: Before creating anything, ask the maker the following questions using the AskUserQuestion tool.++### Questions to Ask++1. **What do you want to build?** - Site purpose, key functionality, target audience+2. **Frontend framework** - React (recommended), Angular, Vue, or Astro+3. **Site features** - Landing page, navigation, forms, authentication, data display+4. **Design preferences** - Style, color scheme, special requirements++### Key Points++- Only use frameworks that build to static HTML/CSS/JS files+- **NOT supported**: Next.js, Nuxt.js, Remix, SvelteKit, Liquid templates+- Power Pages code sites are static SPAs served from Azure CDN++---++## STEP 2: Create the Site++**π Detailed references:**+- [site-creation-reference.md](./site-creation-reference.md) - Project structure, config+- [seo-reference.md](./seo-reference.md) - Meta tags, robots.txt, sitemap.xml+- [testing-reference.md](./testing-reference.md) - Unit and E2E tests++### Quick Summary++1. **Invoke the frontend-design skill** with gathered requirements+2. **Create powerpages.config.json** in project root+3. **Add SEO assets** - meta tags, robots.txt, sitemap.xml, favicons+4. **Write unit tests** - components, utilities, hooks+5. **Write E2E tests** - Playwright for critical user journeys+6. **Build the project** - `npm run build`+7. **Initialize memory bank** - Create `memory-bank.md`++### Actions++1. Use frontend-design skill with explicit constraints (Vite, no SSR)+2. Create `powerpages.config.json` with correct `compiledPath`+3. Add meta tags to index.html (see seo-reference.md)+4. Create robots.txt and sitemap.xml in public folder+5. Set up Vitest and write unit tests+6. Set up Playwright and write E2E tests+7. Run all tests - **all must pass before proceeding**+8. Build the project+9. Create memory-bank.md++---++## STEP 3: Check Prerequisites++**π Detailed reference: [upload-activation-reference.md](./upload-activation-reference.md)**++### Quick Summary++Verify CLI tools are installed and authenticated before uploading.++### Actions++1. Check PAC CLI: `pac help`+ - If missing: `dotnet tool install --global Microsoft.PowerApps.CLI.Tool`++2. Check Azure CLI: `az --version`+ - If missing: `winget install -e --id Microsoft.AzureCLI`++3. Verify authentication:+ - `pac auth list` (create with `pac auth create` if needed)+ - `az account show` (login with `az login` if needed)++4. Verify environment: `pac org who`++---++## STEP 4: Upload to Power Pages (Inactive)++**π Detailed reference: [upload-activation-reference.md](./upload-activation-reference.md)**++### Quick Summary++Upload the built site to Power Pages as an inactive site.++### Actions++1. **Confirm account**: Run `pac auth list` and ask user to confirm+2. **Upload**: `pac pages upload-code-site --rootPath "<PROJECT_ROOT>"`+3. **Get Website ID**: `pac pages list --verbose`++---++## STEP 5: Preview Locally++**π Detailed reference: [upload-activation-reference.md](./upload-activation-reference.md)**++### Quick Summary++Run the site locally to verify everything works before activation.++### Actions++1. Run dev server: `npm run dev` (or framework-specific command)+2. Test all pages and navigation+3. Verify forms and interactive elements+4. Check responsive design++---++## STEP 6: Activate Website++**π Detailed reference: [upload-activation-reference.md](./upload-activation-reference.md)**++### Quick Summary++Activate the uploaded site using Power Platform API or manual activation.++### Actions++1. **Ask for subdomain** using AskUserQuestion tool+2. **Get IDs**: `pac org who` for environment and organization IDs+3. **Activate via API**: Use `az rest` to call CreateWebsite API+4. **Monitor status**: Poll operation URL until complete+5. **Verify**: `pac pages list --verbose` to confirm active status+6. **Fallback**: Manual activation via make.powerpages.microsoft.com if API fails++### Update Memory Bank++After activation, update memory-bank.md with:+- Website ID+- Site URL+- All completed steps marked `[x]`+- Next step: `/setup-dataverse`++### Cleanup Helper Files++**π See: [cleanup-reference.md](${CLAUDE_PLUGIN_ROOT}/shared/cleanup-reference.md)**++Remove any temporary helper files created during this skill's execution.++---++## 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++**π Detailed reference: [troubleshooting.md](./troubleshooting.md)**++Common issues covered:+- Upload fails with JavaScript error+- Site shows as inactive after upload+- Next.js or SSR framework used+- Liquid templates not working+- Unit tests failing+- E2E tests failing+- Authentication issues+- Build issuesdiff --git a/plugins/power-pages/skills/create-site/requirements-reference.md b/plugins/power-pages/skills/create-site/requirements-reference.mdnew file mode 100644index 000000000..32e44ff3b--- /dev/null+++ b/plugins/power-pages/skills/create-site/requirements-reference.md@@ -0,0 +1,91 @@+# Requirements Reference++This document describes the questions to ask users when gathering requirements for a Power Pages code site.++## Question 1: What Do You Want to Build?++If the user has not already specified what they want to build, ask them to describe their site:++- What is the purpose of the site? (e.g., company portal, customer self-service, employee directory, event registration)+- What key functionality do they need?+- Who is the target audience?++This helps inform framework selection and feature recommendations.++## Question 2: Frontend Framework++Ask the maker which frontend framework they want to use:++| Option | Description |+|--------|-------------|+| **React (Recommended)** | Most popular choice with excellent ecosystem. Best for complex interactive UIs. |+| **Angular** | Full-featured framework by Google. Great for enterprise applications with built-in state management. |+| **Vue** | Progressive framework, easy to learn. Good balance of simplicity and power. |+| **Astro** | Modern static site generator with partial hydration. Best for content-focused sites with minimal JS. |++### Unsupported Technologies++Power Pages code sites are **static SPAs** served from Azure CDN. The following technologies are **NOT supported**:++| Technology | Reason |+|------------|--------|+| **Next.js** | Requires Node.js server runtime (SSR/ISR not available) |+| **Nuxt.js** | Requires Node.js server runtime |+| **Remix** | Requires server-side rendering |+| **SvelteKit** | Server features not supported |+| **Liquid templates** | Power Pages code sites don't use Liquid (only classic Power Pages sites do) |+| **Server-side APIs** | No Node.js/Express backend; use Dataverse Web API instead |+| **Server components** | React Server Components not supported |++**Only use frameworks that can build to static HTML/CSS/JS files.**++## Question 3: Site Features++Ask what features the maker wants in their site. Common options:++### Content Features++- Landing page / Hero section+- Navigation menu+- About page+- Services/Products showcase+- Image gallery+- Blog/News section++### Interactive Features++- Contact form+- Search functionality+- Filtering and sorting++### Data Features++- User authentication (Microsoft Entra ID)+- Data display from Dataverse (Web API)+- Form submissions to Dataverse++## Question 4: Design Preferences++Ask about design preferences:++### Style Options++| Style | Description |+|-------|-------------|+| **Modern/Minimalist** | Clean lines, lots of whitespace, simple color palette |+| **Corporate/Professional** | Traditional business look, structured layouts |+| **Creative/Bold** | Vibrant colors, unique typography, dynamic layouts |+| **Elegant/Luxury** | Sophisticated, refined aesthetics with premium feel |++### Color Scheme++- Let the user specify brand colors+- Or suggest based on their industry/purpose+- Consider accessibility (WCAG 2.1 AA contrast requirements)++### Special Requirements++- Accessibility compliance (WCAG 2.1)+- Mobile-first design+- Specific branding guidelines+- RTL language supportdiff --git a/plugins/power-pages/skills/create-site/seo-reference.md b/plugins/power-pages/skills/create-site/seo-reference.mdnew file mode 100644index 000000000..7ab9aa2fd--- /dev/null+++ b/plugins/power-pages/skills/create-site/seo-reference.md@@ -0,0 +1,216 @@+# SEO Reference++This document describes how to add SEO assets to your Power Pages code site.++## Meta Tags Template++Ensure the `index.html` file includes comprehensive meta tags for SEO and social sharing:++```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>+```++## Framework-Specific Locations++| Framework | index.html Location |+|-----------|---------------------|+| React (Vite) | Project root `index.html` |+| React (CRA) | `public/index.html` |+| Vue | Project root `index.html` |+| Angular | `src/index.html` |+| Astro | `src/layouts/Layout.astro` or use `<head>` slot |++## Required SEO Assets++Place these assets 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 |++---++## robots.txt++Create `robots.txt` in the `public/` folder:++```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 Directives++| Directive | Purpose |+|-----------|---------|+| `User-agent: *` | Applies rules to all search engine bots |+| `Allow: /` | Permits crawling of all pages |+| `Disallow: /path/` | Blocks crawling of specific paths |+| `Sitemap:` | Points crawlers to your sitemap |++### Framework-Specific Location (robots.txt)++| Framework | robots.txt Location |+|-----------|---------------------|+| React (Vite) | `public/robots.txt` |+| React (CRA) | `public/robots.txt` |+| Vue | `public/robots.txt` |+| Angular | `src/robots.txt` (add to `angular.json` assets) |+| Astro | `public/robots.txt` |++---++## sitemap.xml++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++| 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 After Deployment++After the site is active, verify the sitemap is accessible:++```+https://[subdomain].powerappsportals.com/sitemap.xml+```++Update the sitemap whenever you add new pages to your site.diff --git a/plugins/power-pages/skills/create-site/site-creation-reference.md b/plugins/power-pages/skills/create-site/site-creation-reference.mdnew file mode 100644index 000000000..5a6bad1b8--- /dev/null+++ b/plugins/power-pages/skills/create-site/site-creation-reference.md@@ -0,0 +1,132 @@+# Site Creation Reference++This document describes how to create the site using the frontend-design skill and configure it for Power Pages.++## Using the Frontend-Design Skill++After gathering requirements, use the **frontend-design skill** to create the site.++### Instructions++1. **Invoke the frontend-design skill** with the gathered requirements+2. The skill will create a production-grade, distinctive UI+3. Ensure the project structure follows Power Pages code site requirements++### Critical Constraints++When invoking the frontend-design skill, explicitly specify:++- Use **Vite** as the build tool for React/Vue projects+- Use **Create React App** only if Vite is not preferred+- **DO NOT use Next.js, Nuxt.js, Remix, or any SSR framework**+- **DO NOT use Liquid templates** - they are not supported in code sites+- The output must be **purely static files** (HTML, CSS, JS) that can be served from a CDN++## Required Project Structure++```text+/site-project+βββ src/ # Source code+βββ public/ # Static assets+βββ build/ or dist/ # Compiled output (after build)+βββ package.json # Dependencies+βββ powerpages.config.json # Power Pages configuration (create this)+βββ README.md+```++## powerpages.config.json++Create this configuration file in the project root:++```json+{+ "siteName": "<SITE_NAME>",+ "defaultLandingPage": "index.html",+ "compiledPath": "./build"+}+```++### Framework-Specific compiledPath++| Framework | compiledPath |+|-----------|--------------|+| React (Vite) | `"./dist"` |+| React (CRA) | `"./build"` |+| Vue | `"./dist"` |+| Angular | `"./dist/<project-name>"` |+| Astro | `"./dist"` |++## Build Commands++Run the appropriate build command for your framework:++```powershell+# React (Create React App or Vite)+npm run build++# Angular+ng build --configuration production++# Vue+npm run build++# Astro+npm run build+```++## Memory Bank Initialization++After the site is created, create `memory-bank.md` in the project root:++```markdown+# Power Pages Project Memory Bank++> Last Updated: [CURRENT_TIMESTAMP]++## Project Overview++| Property | Value |+|----------|-------|+| Project Name | [SITE_NAME from powerpages.config.json] |+| Project Path | [FULL_PROJECT_PATH] |+| Framework | [CHOSEN_FRAMEWORK] |+| Created Date | [CURRENT_DATE] |+| Status | Site Created |++## User Preferences++### Design Preferences+- Style: [USER'S STYLE CHOICE]+- Color Scheme: [USER'S COLOR CHOICE]+- Special Requirements: [ANY SPECIAL REQUIREMENTS]++### Site Features+[LIST ALL FEATURES USER REQUESTED]++## Completed Steps++### /create-site+- [x] Requirements gathered+- [x] Framework selected: [FRAMEWORK]+- [x] Site created with features: [FEATURE_LIST]+- [x] powerpages.config.json created+- [x] SEO assets added (meta tags, favicon, robots.txt, sitemap.xml)+- [x] Unit tests written and passing+- [x] E2E tests written and passing (Playwright)+- [x] Project built successfully+- [ ] Prerequisites verified (PAC CLI, Azure CLI)+- [ ] Uploaded to Power Pages+- [ ] Site activated++## Current Status++**Last Action**: Site created, all tests passing, and built successfully++**Next Step**: Verify prerequisites (PAC CLI, Azure CLI) then upload to Power Pages++## Notes++- [CURRENT_DATE]: Project initialized with [FRAMEWORK] framework+```++**Update this file after each subsequent step is completed.**diff --git a/plugins/power-pages/skills/create-site/testing-reference.md b/plugins/power-pages/skills/create-site/testing-reference.mdnew file mode 100644index 000000000..d6e5c659c--- /dev/null+++ b/plugins/power-pages/skills/create-site/testing-reference.md@@ -0,0 +1,434 @@+# Testing Reference++This document describes how to set up and write unit tests and end-to-end tests for your Power Pages code site.++## Unit Tests++### Install Testing Dependencies++```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 Vitest (Vite 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++| Category | What to Test |+|----------|--------------|+| Components | Rendering, user interactions, props |+| Utility functions | Data transformations, validators, formatters |+| Custom hooks | State management, side effects |+| Form validation | Validation rules, error messages |+| API services | Dataverse Web API wrapper functions (mock the API) |++### Test File Structure++```text+/src+βββ components/+β βββ Header.tsx+β βββ Header.test.tsx # Component test+βββ utils/+β βββ formatters.ts+β βββ formatters.test.ts # Utility test+βββ hooks/+β βββ useDataverse.ts+β βββ useDataverse.test.ts # Hook test+βββ test/+ βββ setup.ts # Test setup file+```++### Example Component Test (React)++```typescript+// 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 Unit Tests++```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.**++---++## End-to-End Tests (Playwright)++### 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', // Adjust for your framework+ 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,+ },+})+```++### Framework-Specific URLs++| Framework | baseURL / webServer.url |+|-----------|-------------------------|+| 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++| Category | What to Test |+|----------|--------------|+| Page Navigation | All links work, routes load correctly |+| Form Submissions | Contact forms, search, filters work end-to-end |+| Responsive Design | Site works on mobile, tablet, and desktop |+| Interactive Elements | Modals, dropdowns, accordions function properly |+| Accessibility | Keyboard navigation, focus states |+| Error States | Error pages and validation messages |++### Example: Home Page Test++```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('/')++ await expect(page.getByRole('heading', { level: 1 })).toBeVisible()+ await expect(page.getByRole('banner')).toBeVisible()++ const ctaButton = page.getByRole('link', { name: /get started/i })+ await expect(ctaButton).toBeVisible()+ })++ test('should have valid meta tags', async ({ page }) => {+ await page.goto('/')++ await expect(page).toHaveTitle(/My Site/)++ const metaDescription = page.locator('meta[name="description"]')+ await expect(metaDescription).toHaveAttribute('content', /.+/)+ })+})+```++### Example: 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('/')++ await page.getByRole('link', { name: /about/i }).click()+ await expect(page).toHaveURL(/.*about/)+ await expect(page.getByRole('heading', { name: /about/i })).toBeVisible()++ await page.getByRole('link', { name: /contact/i }).click()+ await expect(page).toHaveURL(/.*contact/)+ await expect(page.getByRole('heading', { name: /contact/i })).toBeVisible()++ await page.getByRole('link', { name: /home/i }).click()+ await expect(page).toHaveURL('/')+ })++ test('should toggle mobile menu on small screens', async ({ page }) => {+ await page.setViewportSize({ width: 375, height: 667 })+ await page.goto('/')++ const nav = page.getByRole('navigation')+ await expect(nav).not.toBeVisible()++ await page.getByRole('button', { name: /menu/i }).click()+ await expect(nav).toBeVisible()+ })+})+```++### Example: 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 }) => {+ await page.getByRole('button', { name: /submit/i }).click()++ 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()++ await expect(page.getByText(/thank you|success/i)).toBeVisible()+ })+})+```++### Example: 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('/')++ await page.keyboard.press('Tab')+ const firstFocusable = page.locator(':focus')+ await expect(firstFocusable).toBeVisible()++ 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('/')++ const h1 = page.getByRole('heading', { level: 1 })+ await expect(h1).toHaveCount(1)++ 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.**diff --git a/plugins/power-pages/skills/create-site/troubleshooting.md b/plugins/power-pages/skills/create-site/troubleshooting.mdnew file mode 100644index 000000000..6b0eab253--- /dev/null+++ b/plugins/power-pages/skills/create-site/troubleshooting.md@@ -0,0 +1,185 @@+# Troubleshooting++This document covers common issues and solutions when creating Power Pages code sites.++## Upload Issues++### 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 the activation steps in [upload-activation-reference.md](./upload-activation-reference.md).++### 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++---++## Framework Issues++### Next.js or SSR Framework Used++Power Pages code sites **do not support** server-side rendering frameworks:++| Framework | Issue |+|-----------|-------|+| Next.js | Requires Node.js server runtime |+| Nuxt.js | Requires Node.js server runtime |+| Remix | Requires server-side rendering |+| SvelteKit | Server features not supported |++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 Test Issues++### Tests Failing++Investigate and fix before proceeding:++| Issue | Solution |+|-------|----------|+| 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 Test Issues (Playwright)++### Common E2E Failures++| Issue | Solution |+|-------|----------|+| Browser not installed | Run `npx playwright install` |+| Server not starting | Check that `webServer.command` matches your dev script |+| Wrong port | Ensure `baseURL` matches your dev server port |+| Element not found | Use Playwright UI mode to debug selectors |+| Timeout errors | Increase timeout: `await expect().toBeVisible({ timeout: 10000 })` |+| Flaky tests | Add `await page.waitForLoadState('networkidle')` before assertions |++### Debugging Commands++```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.++---++## Authentication Issues++### PAC CLI Not Authenticated++```powershell+# Check current auth+pac auth list++# Create new auth profile+pac auth create+```++### Azure CLI Not Authenticated++```powershell+# Check current auth+az account show++# Login+az login+```++### Wrong Environment++```powershell+# Check current environment+pac org who++# Switch environment+pac org select+```++---++## Build Issues++### Build Fails++| Issue | Solution |+|-------|----------|+| TypeScript errors | Fix type errors before building |+| Missing dependencies | Run `npm install` |+| Out of memory | Increase Node memory: `NODE_OPTIONS=--max_old_space_size=4096 npm run build` |+| Path issues | Use absolute paths or verify relative paths are correct |++### Build Output Missing++- Check `powerpages.config.json` has the correct `compiledPath`+- Verify the build command completed successfully+- Check the build/dist folder exists and contains files++---++## 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/power-pages/skills/create-site/upload-activation-reference.md b/plugins/power-pages/skills/create-site/upload-activation-reference.mdnew file mode 100644index 000000000..d5c3c1e1e--- /dev/null+++ b/plugins/power-pages/skills/create-site/upload-activation-reference.md@@ -0,0 +1,274 @@+# Upload and Activation Reference++This document describes how to verify prerequisites, upload your site to Power Pages, and activate it.++## Prerequisites++### Check PAC CLI++```powershell+pac help+```++**If not found**, install using .NET tool:++```powershell+dotnet tool install --global Microsoft.PowerApps.CLI.Tool+```++Verify after installation:++```powershell+pac help+```++### Check Azure CLI++```powershell+az --version+```++**If not found**, install using winget:++```powershell+winget install -e --id Microsoft.AzureCLI+```++Restart terminal after installation, then verify:++```powershell+az --version+```++### Verify Authentication++```powershell+# Check PAC CLI authentication+pac auth list++# If not authenticated+pac auth create++# Check Azure CLI authentication+az account show++# If not authenticated+az login+```++### Verify Environment Connection++```powershell+pac org who+```++---++## Upload to Power Pages++### Confirm Connected Account++**Before uploading**, confirm the connected account:++```powershell+pac auth list+```++Display the account information:+- Active profile (marked with `*`)+- Environment URL+- User email/account++Ask user to confirm before proceeding. If they need to switch accounts:++```powershell+pac auth create+```++### 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.++---++## Preview Locally++Before activating, run the site locally to verify everything works:++```powershell+# React (Vite)+npm run dev++# React (Create React App)+npm start++# Angular+ng serve++# Vue+npm run dev++# Astro+npm run dev+```++Verify:+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++---++## 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:+- 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++```powershell+pac org who+```++Note:+- **Environment ID** - The GUID of the environment+- **Organization ID** - The Dataverse organization ID++### Activate via API++```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)+$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`:++```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+```diff --git a/plugins/power-pages/skills/setup-auth/SKILL.md b/plugins/power-pages/skills/setup-auth/SKILL.mdnew file mode 100644index 000000000..9afab8fa6--- /dev/null+++ b/plugins/power-pages/skills/setup-auth/SKILL.md@@ -0,0 +1,414 @@+---+description: Configure authentication, login, logout, and role-based authorization for Power Pages. Use this skill when you need to set up user login, implement authentication, configure Azure AD/Entra ID login, add logout functionality, manage user sessions, implement role-based access control, protect routes, or add conditional UI rendering based on user roles and permissions.+user-invocable: true+allowed-tools: Bash(pac:*), Bash(az:*), Bash(dotnet:*)+model: sonnet+---++# Setup Authentication & Authorization++This skill guides makers through implementing authentication (user login/logout) and authorization (role-based access control) for their Power Pages site. It uses Power Pages' built-in server-side authentication with Azure Active Directory and role-based UI conditional rendering.++## Reference Documentation++This skill uses modular reference files for detailed instructions:++| File | Purpose |+|------|---------|+| [authentication-reference.md](./authentication-reference.md) | Auth service code, login/logout flow, user info retrieval |+| [authorization-reference.md](./authorization-reference.md) | Role-based access control, conditional rendering, route protection |++## Memory Bank++This skill uses a **memory bank** (`memory-bank.md`) to persist context across sessions.++**Follow the instructions in `${CLAUDE_PLUGIN_ROOT}/shared/memory-bank.md`** for:+- Checking and reading the memory bank before starting+- Skipping completed steps and resuming progress+- Updating the memory bank after each major step++## Workflow Overview++```text+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+β STEP 1: Resume or Start Fresh β+β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β+β β’ Check memory bank for project context β+β β’ Verify /setup-webapi was completed β+β β’ Identify authentication requirements β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+ β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+β STEP 2: Create Authentication Service β+β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β+β β’ Create auth service with login/logout methods β+β β’ Implement user info retrieval from Power Pages portal object β+β β’ Handle authentication state management β+β π See: authentication-reference.md β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+ β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+β STEP 3: Create Authorization Utilities β+β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β+β β’ Create role checking utilities β+β β’ Implement conditional rendering components β+β β’ Create route protection (if applicable) β+β π See: authorization-reference.md β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+ β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+β STEP 4: Create Auth UI Components β+β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β+β β’ Create login/logout button component β+β β’ Create user profile display component β+β β’ Integrate with site navigation β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+ β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+β STEP 5: Implement Role-Based UI β+β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β+β β’ Identify components needing role-based visibility β+β β’ Apply conditional rendering based on user roles β+β β’ Test with different user roles β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+ β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+β STEP 6: Build and Upload β+β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β+β β’ Build the project β+β β’ Upload to Power Pages β+β β’ Verify authentication is working β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+```++---++## STEP 1: Resume or Start Fresh++### Check Memory Bank First++**Before asking questions**, check if a memory bank exists:++1. If continuing from `/setup-webapi` in the same session, use the known project path+2. Otherwise, ask the user for the project path+3. Read `<PROJECT_PATH>/memory-bank.md` if it exists+4. Extract:+ - Project name and framework+ - Website ID and environment URL+ - Web roles configured (Anonymous Users, Authenticated Users)+ - Any previously configured authentication settings++If the memory bank shows `/setup-auth` steps already completed:++- Inform the user what was done+- Ask if they want to modify settings or add role-based features++### Check Prerequisites++**Verify Web API setup is complete:**++The authentication system depends on having:+- Site uploaded to Power Pages (required for `/_layout/tokenhtml` endpoint)+- Web roles created (Authenticated Users role must exist)++If `/setup-webapi` was not completed, suggest running it first:++> **Prerequisites Required**+>+> Authentication requires your site to be uploaded to Power Pages with Web API configured.+>+> Please run `/setup-webapi` first to complete the prerequisites.++### Gather Requirements++Use the `AskUserQuestion` tool to understand authentication needs:++| Question | Options |+|----------|---------|+| **Which features need authentication?** | Login/Logout only, User profile display, Role-based content, All of the above |+| **What roles need conditional UI?** | None, Admin only sections, Member-only content, Multiple role levels |++---++## STEP 2: Create Authentication Service++**π Detailed reference: [authentication-reference.md](./authentication-reference.md)**++### Quick Summary++Create an authentication service that handles:++1. **Login**: Server-side form submission to `/Account/Login/ExternalLogin`+2. **Logout**: Redirect to `/Account/Login/LogOff`+3. **User Info**: Retrieve from `window.Microsoft.Dynamic365.Portal.User`++### Key Points++- Power Pages uses **server-side authentication** (not client-side tokens)+- Anti-forgery token required from `/_layout/tokenhtml`+- User info is available in the global `window.Microsoft.Dynamic365.Portal` object+- Authentication state is session-based (cookies)++### Power Pages Portal Object++The portal object provides user information:++```typescript+window.Microsoft.Dynamic365.Portal.User = {+ userName: string; // Login username+ firstName: string; // First name+ lastName: string; // Last name+ email: string; // Email address+ contactId: string; // Dataverse contact ID+ userRoles: string[]; // Array of role names+}+```++### Actions++1. Create `src/services/authService.ts` (copy from reference)+2. Create `src/types/powerPages.d.ts` for TypeScript declarations+3. Test that user info is accessible when logged in++---++## STEP 3: Create Authorization Utilities++**π Detailed reference: [authorization-reference.md](./authorization-reference.md)**++### Quick Summary++Create utilities for role-based access control:++1. **Role Checking**: Functions to check if user has specific roles+2. **Conditional Rendering**: Components that show/hide based on roles+3. **Route Protection**: Guards for protected routes (if using client-side routing)++### Key Points++- User roles are in `window.Microsoft.Dynamic365.Portal.User.userRoles`+- Roles are returned as an array of role names (strings)+- Common roles: "Administrators", "Authenticated Users", custom roles+- Role checks should be case-insensitive++### Actions++1. Create `src/utils/authorization.ts` with role checking functions+2. Create wrapper components for conditional rendering+3. Create route guard component (if using React Router, Vue Router, etc.)++---++## STEP 4: Create Auth UI Components++### Login/Logout Button Component++Create a component that:++- Shows "Sign In" button when not authenticated+- Shows user name and "Sign Out" button when authenticated+- Handles the login/logout flow++The component should:++1. Check authentication state on mount+2. Display appropriate UI based on state+3. Handle login button click (redirect to AAD)+4. Handle logout button click (redirect to logout endpoint)++### User Profile Component (Optional)++If user profile display is needed:++- Show user avatar/initials+- Display user name and email+- Show user roles (for debugging/admin purposes)++### Navigation Integration++Integrate auth components into the site header/navigation:++1. Read current navigation component+2. Add auth button to appropriate location+3. Ensure responsive design (mobile menu handling)++---++## STEP 5: Implement Role-Based UI++### Identify Components Needing Role-Based Access++Work with the user to identify:++- Admin-only sections (dashboard, settings)+- Member-only content (premium features, downloads)+- Role-specific navigation items+- Edit/delete buttons for content owners++### Apply Conditional Rendering++For each identified component:++1. Import authorization utilities+2. Wrap content with role-checking component+3. Provide fallback UI if needed (login prompt, access denied)++### Example Pattern++```tsx+// Show only to users with "Administrators" role+<RequireRole roles={["Administrators"]}>+ <AdminDashboard />+</RequireRole>++// Show only to authenticated users+<RequireAuth>+ <MemberContent />+</RequireAuth>++// Show different content based on role+{hasRole("Administrators") ? (+ <EditButton onClick={handleEdit} />+) : null}+```++---++## STEP 6: Build and Upload++### Build the Project++```powershell+cd <PROJECT_ROOT>+npm install # if needed+npm run build+```++### Confirm Connected Account++**IMPORTANT**: Before uploading, you MUST confirm which account the user is connected with.++1. Run the following command to show the connected account:++```powershell+pac auth list+```++2. Display the connected account information to the user, including:+ - The active profile (marked with `*`)+ - The environment URL+ - The user email/account++3. Use the `AskUserQuestion` tool to confirm:++| Question | Options |+|----------|---------|+| **You are about to upload the site to the account shown above. Do you want to proceed?** | **Yes, upload to this account** - Proceed with the upload; **No, let me switch accounts** - User will run `pac auth create` to connect to a different account |++4. **Only proceed with upload after the user confirms.** If the user selects "No", guide them to authenticate to the correct account:++```powershell+# Create new authentication profile+pac auth create+```++Then run `pac auth list` again to verify and ask for confirmation again.++### Upload to Power Pages++```powershell+pac pages upload-code-site --rootPath "<PROJECT_ROOT>"+```++### Configure Site Settings++**IMPORTANT**: Configure the following site setting to ensure users are redirected to your app's home page after login (instead of Power Pages' default profile page):++| Setting | Value | Purpose |+|---------|-------|---------|+| `Authentication/Registration/ProfileRedirectEnabled` | `false` | Redirect to home page instead of profile page after login |++**π See [authentication-reference.md](./authentication-reference.md#site-settings)** for detailed instructions on how to configure this setting via Power Pages Admin Center, PAC CLI, or Dataverse Web API.++### Verify Authentication++1. Open the site in a browser+2. Click "Sign In" - should redirect to AAD login+3. After login, verify:+ - User name displays correctly+ - User roles are accessible+ - Role-based UI shows/hides correctly+4. Click "Sign Out" - should log out and redirect to home++### Test Role-Based Features++1. Log in with different users having different roles+2. Verify conditional UI works correctly:+ - Admin features visible only to admins+ - Member content visible only to members+ - Public content visible to all++### Troubleshooting++**Login button doesn't work:**+- Ensure site is uploaded to Power Pages (not local dev)+- Check browser console for errors+- Verify anti-forgery token endpoint is accessible++**User info not available:**+- User must be logged in for `window.Microsoft.Dynamic365.Portal.User` to be populated+- Check if user has a Contact record in Dataverse++**Roles not showing:**+- Verify user's Contact record is associated with web roles in Power Pages portal+- Check for typos in role names (case-insensitive comparison recommended)++---++## Cleanup Helper Files++**π See: [cleanup-reference.md](${CLAUDE_PLUGIN_ROOT}/shared/cleanup-reference.md)**++Remove any temporary helper files created during this skill's execution. Verify authentication is working correctly before cleanup.++---++## Update Memory Bank++After completing this skill, update `memory-bank.md`:++```markdown+### /setup-auth+- [x] Authentication service created+- [x] PowerPages type declarations added+- [x] Authorization utilities created+- [x] Auth UI components created (login/logout button)+- [x] Role-based conditional rendering implemented+- [x] Project built successfully+- [x] Uploaded to Power Pages+- [x] Authentication verified working++## Created Resources++### Auth Files++| File | Purpose |+|------|---------|+| src/services/authService.ts | Authentication service |+| src/types/powerPages.d.ts | TypeScript declarations |+| src/utils/authorization.ts | Role checking utilities |+| src/components/AuthButton.tsx | Login/logout component |++### Role-Based Components++| Component | Roles Required | Purpose |+|-----------|----------------|---------|+| AdminDashboard | Administrators | Admin-only section |+| [ADD MORE AS IMPLEMENTED] |++## Current Status++**Last Action**: Authentication and authorization configured++**Next Step**: Test with different user accounts and roles+```diff --git a/plugins/power-pages/skills/setup-auth/authentication-reference.md b/plugins/power-pages/skills/setup-auth/authentication-reference.mdnew file mode 100644index 000000000..6851dea27--- /dev/null+++ b/plugins/power-pages/skills/setup-auth/authentication-reference.md@@ -0,0 +1,913 @@+# Authentication Reference++This document provides code patterns for implementing server-side authentication in Power Pages sites.++## How Power Pages Authentication Works++Power Pages uses **server-side session-based authentication** with Azure Active Directory (AAD):++1. **Login Flow**: Form submission to `/Account/Login/ExternalLogin` with anti-forgery token+2. **Session Management**: Server maintains session via cookies+3. **User Info**: Available in `window.Microsoft.Dynamic365.Portal.User` after login+4. **Logout**: Redirect to `/Account/Login/LogOff`++```text+βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ+β User clicks βββββ>β Fetch token βββββ>β POST to login β+β "Sign In" β β /_layout/ β β /Account/Login β+β β β tokenhtml β β /ExternalLogin β+βββββββββββββββββββ βββββββββββββββββββ ββββββββββ¬βββββββββ+ β+ v+βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ+β User info β<βββββ Redirect to β<βββββ AAD Login β+β available in β β site with β β Page β+β Portal object β β session β β β+βββββββββββββββββββ βββββββββββββββββββ βββββββββββββββββββ+```++## TypeScript Declarations++**File: `src/types/powerPages.d.ts`**++```typescript+/**+ * Power Pages Portal User Interface+ * Available at window.Microsoft.Dynamic365.Portal.User when user is logged in+ */+export interface PowerPagesUser {+ /** Login username */+ userName: string;+ /** User's first name */+ firstName: string;+ /** User's last name */+ lastName: string;+ /** User's email address */+ email: string;+ /** Dataverse Contact ID (GUID) */+ contactId: string;+ /** Array of web role names assigned to the user */+ userRoles: string[];+}++/**+ * Power Pages Portal Configuration+ * Available at window.Microsoft.Dynamic365.Portal+ */+export interface PowerPagesPortal {+ /** Current user information (populated when logged in) */+ User: PowerPagesUser;+ /** Portal version */+ version: string;+ /** Portal type */+ type: string;+ /** Portal ID */+ id: string;+ /** Geographic region */+ geo: string;+ /** Azure AD Tenant ID */+ tenant: string;+ /** Correlation ID for debugging */+ correlationId: string;+ /** Organization environment ID */+ orgEnvironmentId: string;+ /** Organization ID */+ orgId: string;+ /** Production or Trial indicator */+ portalProductionOrTrialType: string;+ /** Telemetry enabled flag */+ isTelemetryEnabled: string;+ /** Instrumentation settings */+ InstrumentationSettings: {+ instrumentationKey: string;+ collectorEndpoint: string;+ };+ /** Timer profile for batching */+ timerProfileForBatching: string;+ /** Active languages */+ activeLanguages: string[];+ /** Client API enabled flag */+ isClientApiEnabled: string;+}++/**+ * Microsoft namespace on window object+ */+export interface MicrosoftNamespace {+ Dynamic365: {+ Portal: PowerPagesPortal;+ };+}++/**+ * Extend Window interface+ */+declare global {+ interface Window {+ Microsoft?: MicrosoftNamespace;+ }+}++export {};+```++## Authentication Service++**File: `src/services/authService.ts`**++```typescript+import type { PowerPagesUser } from '../types/powerPages';++/**+ * Authentication state+ */+export interface AuthState {+ isAuthenticated: boolean;+ user: PowerPagesUser | null;+ isLoading: boolean;+}++/**+ * Get the current Power Pages portal user+ * Returns null if not authenticated or portal object not available+ */+export function getCurrentUser(): PowerPagesUser | null {+ try {+ const portalUser = window.Microsoft?.Dynamic365?.Portal?.User;++ // Check if user is actually logged in (userName will be empty if not)+ if (portalUser && portalUser.userName) {+ return {+ userName: portalUser.userName || '',+ firstName: portalUser.firstName || '',+ lastName: portalUser.lastName || '',+ email: portalUser.email || '',+ contactId: portalUser.contactId || '',+ userRoles: portalUser.userRoles || [],+ };+ }++ return null;+ } catch (error) {+ console.warn('[Auth] Failed to get current user:', error);+ return null;+ }+}++/**+ * Check if user is currently authenticated+ */+export function isAuthenticated(): boolean {+ const user = getCurrentUser();+ return user !== null && user.userName !== '';+}++/**+ * Get the tenant ID from the portal configuration+ */+export function getTenantId(): string {+ try {+ return window.Microsoft?.Dynamic365?.Portal?.tenant || '';+ } catch {+ return '';+ }+}++/**+ * Fetch the anti-forgery token required for login+ * This token prevents CSRF attacks on the login form+ */+async function fetchAntiForgeryToken(): Promise<string> {+ try {+ const tokenEndpoint = '/_layout/tokenhtml';+ const response = await fetch(tokenEndpoint);++ if (!response.ok) {+ throw new Error(`Failed to fetch token: ${response.status}`);+ }++ const tokenResponse = await response.text();++ // Parse the token from the HTML response+ // Response format: <input name="__RequestVerificationToken" type="hidden" value="TOKEN_VALUE" />+ const valueString = 'value="';+ const terminalString = '" />';+ const valueIndex = tokenResponse.indexOf(valueString);++ if (valueIndex === -1) {+ throw new Error('Token not found in response');+ }++ const token = tokenResponse.substring(+ valueIndex + valueString.length,+ tokenResponse.indexOf(terminalString, valueIndex)+ );++ return token;+ } catch (error) {+ console.error('[Auth] Failed to fetch anti-forgery token:', error);+ throw error;+ }+}++/**+ * Initiate login flow+ * Creates a form submission to the Power Pages login endpoint+ * This will redirect to Azure AD for authentication+ *+ * @param returnUrl - URL to redirect to after successful login (default: current page)+ */+export async function login(returnUrl?: string): Promise<void> {+ try {+ // Get anti-forgery token+ const token = await fetchAntiForgeryToken();++ // Get tenant ID for AAD login+ const tenantId = getTenantId();++ if (!tenantId) {+ throw new Error('Tenant ID not available. Ensure site is loaded from Power Pages.');+ }++ // Create form for submission+ const form = document.createElement('form');+ form.method = 'POST';+ form.action = '/Account/Login/ExternalLogin';++ // Anti-forgery token+ const tokenInput = document.createElement('input');+ tokenInput.type = 'hidden';+ tokenInput.name = '__RequestVerificationToken';+ tokenInput.value = token;+ form.appendChild(tokenInput);++ // Provider (Azure AD)+ const providerInput = document.createElement('input');+ providerInput.type = 'hidden';+ providerInput.name = 'provider';+ providerInput.value = `https://login.windows.net/${tenantId}/`;+ form.appendChild(providerInput);++ // Return URL+ const returnUrlInput = document.createElement('input');+ returnUrlInput.type = 'hidden';+ returnUrlInput.name = 'returnUrl';+ returnUrlInput.value = returnUrl || window.location.pathname;+ form.appendChild(returnUrlInput);++ // Submit the form+ document.body.appendChild(form);+ form.submit();+ } catch (error) {+ console.error('[Auth] Login failed:', error);+ throw error;+ }+}++/**+ * Logout the current user+ * Redirects to the Power Pages logout endpoint+ *+ * @param returnUrl - URL to redirect to after logout (default: home page)+ */+export function logout(returnUrl: string = '/'): void {+ const encodedReturnUrl = encodeURIComponent(returnUrl);+ window.location.href = `/Account/Login/LogOff?returnUrl=${encodedReturnUrl}`;+}++/**+ * Get user's display name (full name or username)+ */+export function getUserDisplayName(): string {+ const user = getCurrentUser();++ if (!user) {+ return '';+ }++ // Prefer full name, fall back to username+ const fullName = [user.firstName, user.lastName].filter(Boolean).join(' ');+ return fullName || user.userName;+}++/**+ * Get user's initials for avatar display+ */+export function getUserInitials(): string {+ const user = getCurrentUser();++ if (!user) {+ return '';+ }++ const firstName = user.firstName || '';+ const lastName = user.lastName || '';++ if (firstName && lastName) {+ return `${firstName[0]}${lastName[0]}`.toUpperCase();+ }++ if (user.userName) {+ return user.userName.substring(0, 2).toUpperCase();+ }++ return '';+}+```++## React Components++### Auth Button Component++**File: `src/components/AuthButton.tsx`**++```tsx+import { useState, useEffect } from 'react';+import {+ getCurrentUser,+ login,+ logout,+ getUserDisplayName,+ getUserInitials,+ type PowerPagesUser+} from '../services/authService';++interface AuthButtonProps {+ /** CSS class name for styling */+ className?: string;+ /** Show user avatar/initials when logged in */+ showAvatar?: boolean;+ /** Text for sign in button */+ signInText?: string;+ /** Text for sign out button */+ signOutText?: string;+}++export function AuthButton({+ className = '',+ showAvatar = true,+ signInText = 'Sign In',+ signOutText = 'Sign Out'+}: AuthButtonProps) {+ const [user, setUser] = useState<PowerPagesUser | null>(null);+ const [isLoading, setIsLoading] = useState(true);++ useEffect(() => {+ // Check authentication state on mount+ const currentUser = getCurrentUser();+ setUser(currentUser);+ setIsLoading(false);+ }, []);++ const handleLogin = async () => {+ try {+ setIsLoading(true);+ await login();+ // Note: Page will redirect, so we don't need to handle success+ } catch (error) {+ console.error('Login error:', error);+ setIsLoading(false);+ }+ };++ const handleLogout = () => {+ logout();+ };++ if (isLoading) {+ return (+ <div className={`auth-button auth-button--loading ${className}`}>+ <span className="auth-button__spinner" />+ </div>+ );+ }++ if (user) {+ return (+ <div className={`auth-button auth-button--authenticated ${className}`}>+ {showAvatar && (+ <div className="auth-button__avatar" title={getUserDisplayName()}>+ {getUserInitials()}+ </div>+ )}+ <span className="auth-button__name">{getUserDisplayName()}</span>+ <button+ type="button"+ className="auth-button__logout"+ onClick={handleLogout}+ >+ {signOutText}+ </button>+ </div>+ );+ }++ return (+ <button+ type="button"+ className={`auth-button auth-button--login ${className}`}+ onClick={handleLogin}+ >+ {signInText}+ </button>+ );+}+```++### Auth Button Styles++**File: `src/components/AuthButton.css`**++```css+.auth-button {+ display: inline-flex;+ align-items: center;+ gap: 0.5rem;+}++.auth-button--loading {+ opacity: 0.7;+}++.auth-button__spinner {+ width: 1rem;+ height: 1rem;+ border: 2px solid currentColor;+ border-top-color: transparent;+ border-radius: 50%;+ animation: spin 0.6s linear infinite;+}++@keyframes spin {+ to { transform: rotate(360deg); }+}++.auth-button--authenticated {+ display: flex;+ align-items: center;+ gap: 0.75rem;+}++.auth-button__avatar {+ width: 2rem;+ height: 2rem;+ border-radius: 50%;+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);+ color: white;+ display: flex;+ align-items: center;+ justify-content: center;+ font-size: 0.75rem;+ font-weight: 600;+}++.auth-button__name {+ font-weight: 500;+}++.auth-button__logout,+.auth-button--login {+ padding: 0.5rem 1rem;+ border: 1px solid currentColor;+ border-radius: 0.25rem;+ background: transparent;+ cursor: pointer;+ font-size: 0.875rem;+ transition: all 0.2s;+}++.auth-button__logout:hover,+.auth-button--login:hover {+ background: rgba(0, 0, 0, 0.05);+}+```++## React Hook++**File: `src/hooks/useAuth.ts`**++```typescript+import { useState, useEffect, useCallback } from 'react';+import {+ getCurrentUser,+ isAuthenticated as checkIsAuthenticated,+ login as performLogin,+ logout as performLogout,+ getUserDisplayName,+ type PowerPagesUser+} from '../services/authService';++interface UseAuthReturn {+ /** Current user or null if not authenticated */+ user: PowerPagesUser | null;+ /** Whether user is authenticated */+ isAuthenticated: boolean;+ /** Whether auth state is still loading */+ isLoading: boolean;+ /** User's display name */+ displayName: string;+ /** Initiate login flow */+ login: (returnUrl?: string) => Promise<void>;+ /** Logout user */+ logout: (returnUrl?: string) => void;+ /** Refresh auth state */+ refresh: () => void;+}++export function useAuth(): UseAuthReturn {+ const [user, setUser] = useState<PowerPagesUser | null>(null);+ const [isLoading, setIsLoading] = useState(true);++ const refresh = useCallback(() => {+ const currentUser = getCurrentUser();+ setUser(currentUser);+ setIsLoading(false);+ }, []);++ useEffect(() => {+ refresh();+ }, [refresh]);++ const login = useCallback(async (returnUrl?: string) => {+ setIsLoading(true);+ await performLogin(returnUrl);+ }, []);++ const logout = useCallback((returnUrl?: string) => {+ performLogout(returnUrl);+ }, []);++ return {+ user,+ isAuthenticated: user !== null,+ isLoading,+ displayName: getUserDisplayName(),+ login,+ logout,+ refresh,+ };+}+```++## Vue 3 Composition API++**File: `src/composables/useAuth.ts`**++```typescript+import { ref, computed, onMounted } from 'vue';+import {+ getCurrentUser,+ login as performLogin,+ logout as performLogout,+ getUserDisplayName,+ getUserInitials,+ type PowerPagesUser+} from '../services/authService';++export function useAuth() {+ const user = ref<PowerPagesUser | null>(null);+ const isLoading = ref(true);++ const isAuthenticated = computed(() => user.value !== null);+ const displayName = computed(() => getUserDisplayName());+ const initials = computed(() => getUserInitials());++ function refresh() {+ user.value = getCurrentUser();+ isLoading.value = false;+ }++ async function login(returnUrl?: string) {+ isLoading.value = true;+ await performLogin(returnUrl);+ }++ function logout(returnUrl?: string) {+ performLogout(returnUrl);+ }++ onMounted(() => {+ refresh();+ });++ return {+ user,+ isAuthenticated,+ isLoading,+ displayName,+ initials,+ login,+ logout,+ refresh,+ };+}+```++## Angular Service++**File: `src/app/services/auth.service.ts`**++```typescript+import { Injectable } from '@angular/core';+import { BehaviorSubject, Observable } from 'rxjs';++interface PowerPagesUser {+ userName: string;+ firstName: string;+ lastName: string;+ email: string;+ contactId: string;+ userRoles: string[];+}++@Injectable({+ providedIn: 'root'+})+export class AuthService {+ private userSubject = new BehaviorSubject<PowerPagesUser | null>(null);+ private loadingSubject = new BehaviorSubject<boolean>(true);++ user$: Observable<PowerPagesUser | null> = this.userSubject.asObservable();+ isLoading$: Observable<boolean> = this.loadingSubject.asObservable();++ constructor() {+ this.refresh();+ }++ get currentUser(): PowerPagesUser | null {+ return this.userSubject.value;+ }++ get isAuthenticated(): boolean {+ return this.currentUser !== null;+ }++ refresh(): void {+ try {+ const portalUser = (window as any).Microsoft?.Dynamic365?.Portal?.User;++ if (portalUser && portalUser.userName) {+ this.userSubject.next({+ userName: portalUser.userName || '',+ firstName: portalUser.firstName || '',+ lastName: portalUser.lastName || '',+ email: portalUser.email || '',+ contactId: portalUser.contactId || '',+ userRoles: portalUser.userRoles || [],+ });+ } else {+ this.userSubject.next(null);+ }+ } catch {+ this.userSubject.next(null);+ }++ this.loadingSubject.next(false);+ }++ async login(returnUrl?: string): Promise<void> {+ this.loadingSubject.next(true);++ const token = await this.fetchAntiForgeryToken();+ const tenantId = (window as any).Microsoft?.Dynamic365?.Portal?.tenant || '';++ const form = document.createElement('form');+ form.method = 'POST';+ form.action = '/Account/Login/ExternalLogin';++ this.addHiddenField(form, '__RequestVerificationToken', token);+ this.addHiddenField(form, 'provider', `https://login.windows.net/${tenantId}/`);+ this.addHiddenField(form, 'returnUrl', returnUrl || window.location.pathname);++ document.body.appendChild(form);+ form.submit();+ }++ logout(returnUrl: string = '/'): void {+ window.location.href = `/Account/Login/LogOff?returnUrl=${encodeURIComponent(returnUrl)}`;+ }++ private async fetchAntiForgeryToken(): Promise<string> {+ const response = await fetch('/_layout/tokenhtml');+ const text = await response.text();++ const valueString = 'value="';+ const terminalString = '" />';+ const valueIndex = text.indexOf(valueString);++ return text.substring(+ valueIndex + valueString.length,+ text.indexOf(terminalString, valueIndex)+ );+ }++ private addHiddenField(form: HTMLFormElement, name: string, value: string): void {+ const input = document.createElement('input');+ input.type = 'hidden';+ input.name = name;+ input.value = value;+ form.appendChild(input);+ }+}+```++## Vanilla JavaScript++**File: `src/auth.js`**++```javascript+/**+ * Power Pages Authentication Module+ * Framework-agnostic authentication utilities+ */++/**+ * Get the current user from Power Pages portal object+ * @returns {Object|null} User object or null if not authenticated+ */+function getCurrentUser() {+ try {+ const portalUser = window.Microsoft?.Dynamic365?.Portal?.User;++ if (portalUser && portalUser.userName) {+ return {+ userName: portalUser.userName || '',+ firstName: portalUser.firstName || '',+ lastName: portalUser.lastName || '',+ email: portalUser.email || '',+ contactId: portalUser.contactId || '',+ userRoles: portalUser.userRoles || [],+ };+ }++ return null;+ } catch (error) {+ console.warn('[Auth] Failed to get current user:', error);+ return null;+ }+}++/**+ * Check if user is authenticated+ * @returns {boolean}+ */+function isAuthenticated() {+ const user = getCurrentUser();+ return user !== null && user.userName !== '';+}++/**+ * Fetch anti-forgery token+ * @returns {Promise<string>}+ */+async function fetchAntiForgeryToken() {+ const response = await fetch('/_layout/tokenhtml');+ const text = await response.text();++ const valueString = 'value="';+ const terminalString = '" />';+ const valueIndex = text.indexOf(valueString);++ return text.substring(+ valueIndex + valueString.length,+ text.indexOf(terminalString, valueIndex)+ );+}++/**+ * Initiate login flow+ * @param {string} [returnUrl] - URL to redirect to after login+ */+async function login(returnUrl) {+ const token = await fetchAntiForgeryToken();+ const tenantId = window.Microsoft?.Dynamic365?.Portal?.tenant || '';++ const form = document.createElement('form');+ form.method = 'POST';+ form.action = '/Account/Login/ExternalLogin';++ const fields = {+ '__RequestVerificationToken': token,+ 'provider': `https://login.windows.net/${tenantId}/`,+ 'returnUrl': returnUrl || window.location.pathname+ };++ Object.entries(fields).forEach(([name, value]) => {+ const input = document.createElement('input');+ input.type = 'hidden';+ input.name = name;+ input.value = value;+ form.appendChild(input);+ });++ document.body.appendChild(form);+ form.submit();+}++/**+ * Logout user+ * @param {string} [returnUrl='/'] - URL to redirect to after logout+ */+function logout(returnUrl = '/') {+ window.location.href = `/Account/Login/LogOff?returnUrl=${encodeURIComponent(returnUrl)}`;+}++// Export for module usage+export { getCurrentUser, isAuthenticated, login, logout };++// Also expose globally for non-module usage+window.PowerPagesAuth = { getCurrentUser, isAuthenticated, login, logout };+```++## Site Settings++When implementing authentication, configure these site settings in Power Pages to customize the login behavior.++### Disable Profile Page Redirect++**IMPORTANT**: By default, Power Pages redirects users to the built-in profile page (`/profile`) after login. For code sites (SPAs), you should disable this so users are redirected to your app's home page instead.++| Setting Name | Value | Description |+|--------------|-------|-------------|+| `Authentication/Registration/ProfileRedirectEnabled` | `false` | Disables redirect to profile page after login |++#### How to Configure++1. **Via Power Pages Admin Center**:+ - Go to **Set up** > **Site Settings**+ - Click **+ New setting**+ - Name: `Authentication/Registration/ProfileRedirectEnabled`+ - Value: `false`+ - Click **Save**++2. **Via PAC CLI**:+ ```powershell+ # Create site setting using PAC CLI+ pac paportal download --path ./portal-data --modelVersion 2+ # Add the setting to the site settings file and upload+ pac paportal upload --path ./portal-data+ ```++3. **Via Dataverse Web API**:+ ```typescript+ // Create site setting record+ await fetch(`${dataverseUrl}/api/data/v9.2/adx_sitesettings`, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ 'Authorization': `Bearer ${accessToken}`+ },+ body: JSON.stringify({+ 'adx_name': 'Authentication/Registration/ProfileRedirectEnabled',+ 'adx_value': 'false',+ '[email protected]': `/adx_websites(${websiteId})`+ })+ });+ ```++> **Note**: After setting this, users will be redirected to the `returnUrl` specified in the login form (see `login()` function in the Authentication Service section above), which defaults to the current page or home page.++### Other Useful Authentication Settings++| Setting Name | Value | Description |+|--------------|-------|-------------|+| `Authentication/Registration/Enabled` | `true` | Enable/disable registration |+| `Authentication/Registration/OpenRegistrationEnabled` | `true`/`false` | Allow open registration |+| `Authentication/Registration/InvitationEnabled` | `true`/`false` | Require invitation for registration |+| `Authentication/Registration/LocalLoginEnabled` | `true`/`false` | Enable local account login |++## Important Notes++### Local Development++- Authentication **only works** when the site is served from Power Pages+- During local development (`npm run dev`), the `window.Microsoft.Dynamic365.Portal` object will not be available+- Create mock data for local testing:++```typescript+// src/mocks/portalUser.ts (for development only)+if (import.meta.env.DEV) {+ (window as any).Microsoft = {+ Dynamic365: {+ Portal: {+ User: {+ userName: '[email protected]',+ firstName: 'Dev',+ lastName: 'User',+ email: '[email protected]',+ contactId: '00000000-0000-0000-0000-000000000000',+ userRoles: ['Authenticated Users', 'Administrators'],+ },+ tenant: 'your-tenant-id',+ },+ },+ };+}+```++### Security Considerations++1. **Server-side validation**: Always validate permissions on the server (via table permissions)+2. **Client-side is cosmetic**: Role checks in the UI are for UX only, not security+3. **Anti-forgery tokens**: Required for all POST operations to prevent CSRF attacks+4. **Session timeout**: Handle cases where session expires during usagediff --git a/plugins/power-pages/skills/setup-auth/authorization-reference.md b/plugins/power-pages/skills/setup-auth/authorization-reference.mdnew file mode 100644index 000000000..573f8ae1e--- /dev/null+++ b/plugins/power-pages/skills/setup-auth/authorization-reference.md@@ -0,0 +1,887 @@+# Authorization Reference++This document provides code patterns for implementing role-based access control in Power Pages sites.++## How Power Pages Authorization Works++Power Pages provides user roles through the portal object:++```javascript+window.Microsoft.Dynamic365.Portal.User.userRoles // Array of role names+```++Common built-in roles:+- **Anonymous Users** - Unauthenticated visitors+- **Authenticated Users** - Any logged-in user+- **Administrators** - Full admin access++Custom roles can be created in Power Pages Portal Management app.++```text+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+β User Roles in Power Pages β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€+β β+β window.Microsoft.Dynamic365.Portal.User.userRoles = [ β+β "Authenticated Users", β+β "Administrators", β+β "Premium Members" β+β ] β+β β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+```++## Authorization Utilities++**File: `src/utils/authorization.ts`**++```typescript+import { getCurrentUser } from '../services/authService';++/**+ * Get all roles for the current user+ * @returns Array of role names (empty if not authenticated)+ */+export function getUserRoles(): string[] {+ const user = getCurrentUser();+ return user?.userRoles || [];+}++/**+ * Check if user has a specific role+ * @param roleName - Role name to check (case-insensitive)+ */+export function hasRole(roleName: string): boolean {+ const roles = getUserRoles();+ const normalizedRole = roleName.toLowerCase();+ return roles.some(role => role.toLowerCase() === normalizedRole);+}++/**+ * Check if user has ANY of the specified roles+ * @param roleNames - Array of role names to check+ */+export function hasAnyRole(roleNames: string[]): boolean {+ return roleNames.some(role => hasRole(role));+}++/**+ * Check if user has ALL of the specified roles+ * @param roleNames - Array of role names to check+ */+export function hasAllRoles(roleNames: string[]): boolean {+ return roleNames.every(role => hasRole(role));+}++/**+ * Check if user is authenticated (has any role other than Anonymous)+ */+export function isAuthenticated(): boolean {+ const user = getCurrentUser();+ return user !== null && user.userName !== '';+}++/**+ * Check if user is an administrator+ */+export function isAdmin(): boolean {+ return hasRole('Administrators');+}++/**+ * Check if user has elevated permissions (admin or specific roles)+ * @param additionalRoles - Additional roles that grant elevated access+ */+export function hasElevatedAccess(additionalRoles: string[] = []): boolean {+ return hasAnyRole(['Administrators', ...additionalRoles]);+}+```++## React Components for Conditional Rendering++### RequireAuth Component++Show content only to authenticated users.++**File: `src/components/RequireAuth.tsx`**++```tsx+import { ReactNode } from 'react';+import { isAuthenticated } from '../utils/authorization';++interface RequireAuthProps {+ /** Content to show when authenticated */+ children: ReactNode;+ /** Content to show when not authenticated (optional) */+ fallback?: ReactNode;+ /** Whether to show a login prompt as fallback */+ showLoginPrompt?: boolean;+}++export function RequireAuth({+ children,+ fallback = null,+ showLoginPrompt = false+}: RequireAuthProps) {+ if (isAuthenticated()) {+ return <>{children}</>;+ }++ if (showLoginPrompt) {+ return (+ <div className="auth-required">+ <p>Please sign in to access this content.</p>+ <button onClick={() => import('../services/authService').then(m => m.login())}>+ Sign In+ </button>+ </div>+ );+ }++ return <>{fallback}</>;+}+```++### RequireRole Component++Show content only to users with specific roles.++**File: `src/components/RequireRole.tsx`**++```tsx+import { ReactNode } from 'react';+import { hasAnyRole, hasAllRoles, isAuthenticated } from '../utils/authorization';++interface RequireRoleProps {+ /** Content to show when user has required roles */+ children: ReactNode;+ /** Role(s) required to view content */+ roles: string | string[];+ /** Require ALL roles (true) or ANY role (false, default) */+ requireAll?: boolean;+ /** Content to show when user lacks required roles */+ fallback?: ReactNode;+ /** Show access denied message */+ showAccessDenied?: boolean;+}++export function RequireRole({+ children,+ roles,+ requireAll = false,+ fallback = null,+ showAccessDenied = false+}: RequireRoleProps) {+ const roleArray = Array.isArray(roles) ? roles : [roles];++ // Check authentication first+ if (!isAuthenticated()) {+ if (showAccessDenied) {+ return (+ <div className="access-denied">+ <p>Please sign in to access this content.</p>+ </div>+ );+ }+ return <>{fallback}</>;+ }++ // Check roles+ const hasAccess = requireAll+ ? hasAllRoles(roleArray)+ : hasAnyRole(roleArray);++ if (hasAccess) {+ return <>{children}</>;+ }++ if (showAccessDenied) {+ return (+ <div className="access-denied">+ <p>You don't have permission to access this content.</p>+ </div>+ );+ }++ return <>{fallback}</>;+}+```++### RoleSwitch Component++Show different content based on user roles.++**File: `src/components/RoleSwitch.tsx`**++```tsx+import { ReactNode } from 'react';+import { hasAnyRole, isAuthenticated } from '../utils/authorization';++interface RoleSwitchProps {+ children: ReactNode;+}++interface RoleCaseProps {+ /** Roles that can see this content */+ roles: string | string[];+ children: ReactNode;+}++interface RoleDefaultProps {+ children: ReactNode;+}++// Context to track if a case has matched+let matched = false;++export function RoleSwitch({ children }: RoleSwitchProps) {+ matched = false;+ return <>{children}</>;+}++export function RoleCase({ roles, children }: RoleCaseProps) {+ if (matched) return null;++ const roleArray = Array.isArray(roles) ? roles : [roles];++ if (hasAnyRole(roleArray)) {+ matched = true;+ return <>{children}</>;+ }++ return null;+}++export function AuthenticatedCase({ children }: RoleDefaultProps) {+ if (matched) return null;++ if (isAuthenticated()) {+ matched = true;+ return <>{children}</>;+ }++ return null;+}++export function AnonymousCase({ children }: RoleDefaultProps) {+ if (matched) return null;++ if (!isAuthenticated()) {+ matched = true;+ return <>{children}</>;+ }++ return null;+}++export function RoleDefault({ children }: RoleDefaultProps) {+ if (matched) return null;+ return <>{children}</>;+}++// Usage example:+// <RoleSwitch>+// <RoleCase roles="Administrators">+// <AdminDashboard />+// </RoleCase>+// <RoleCase roles={["Premium Members", "VIP"]}>+// <PremiumContent />+// </RoleCase>+// <AuthenticatedCase>+// <MemberContent />+// </AuthenticatedCase>+// <AnonymousCase>+// <PublicContent />+// </AnonymousCase>+// </RoleSwitch>+```++## React Hook for Authorization++**File: `src/hooks/useAuthorization.ts`**++```typescript+import { useMemo } from 'react';+import {+ getUserRoles,+ hasRole,+ hasAnyRole,+ hasAllRoles,+ isAuthenticated,+ isAdmin+} from '../utils/authorization';++interface UseAuthorizationReturn {+ /** All roles for current user */+ roles: string[];+ /** Check if user has specific role */+ hasRole: (role: string) => boolean;+ /** Check if user has any of the roles */+ hasAnyRole: (roles: string[]) => boolean;+ /** Check if user has all of the roles */+ hasAllRoles: (roles: string[]) => boolean;+ /** Whether user is authenticated */+ isAuthenticated: boolean;+ /** Whether user is an administrator */+ isAdmin: boolean;+}++export function useAuthorization(): UseAuthorizationReturn {+ const roles = useMemo(() => getUserRoles(), []);++ return {+ roles,+ hasRole,+ hasAnyRole,+ hasAllRoles,+ isAuthenticated: isAuthenticated(),+ isAdmin: isAdmin(),+ };+}++// Usage:+// const { hasRole, isAdmin } = useAuthorization();+// if (hasRole('Premium Members')) { ... }+```++## Route Protection (React Router)++**File: `src/components/ProtectedRoute.tsx`**++```tsx+import { ReactNode } from 'react';+import { Navigate, useLocation } from 'react-router-dom';+import { isAuthenticated, hasAnyRole } from '../utils/authorization';++interface ProtectedRouteProps {+ children: ReactNode;+ /** Roles required to access this route */+ roles?: string[];+ /** Redirect path when not authenticated */+ loginPath?: string;+ /** Redirect path when authenticated but lacking roles */+ unauthorizedPath?: string;+}++export function ProtectedRoute({+ children,+ roles,+ loginPath = '/login',+ unauthorizedPath = '/unauthorized'+}: ProtectedRouteProps) {+ const location = useLocation();++ // Check authentication+ if (!isAuthenticated()) {+ // Save intended destination for redirect after login+ return <Navigate to={loginPath} state={{ from: location }} replace />;+ }++ // Check roles if specified+ if (roles && roles.length > 0 && !hasAnyRole(roles)) {+ return <Navigate to={unauthorizedPath} replace />;+ }++ return <>{children}</>;+}++// Usage in router:+// <Route+// path="/admin"+// element={+// <ProtectedRoute roles={['Administrators']}>+// <AdminPage />+// </ProtectedRoute>+// }+// />+```++### Login Page with Redirect++**File: `src/pages/LoginPage.tsx`**++```tsx+import { useEffect } from 'react';+import { useLocation, useNavigate } from 'react-router-dom';+import { login } from '../services/authService';+import { isAuthenticated } from '../utils/authorization';++export function LoginPage() {+ const location = useLocation();+ const navigate = useNavigate();+ const from = (location.state as any)?.from?.pathname || '/';++ useEffect(() => {+ // If already authenticated, redirect to intended destination+ if (isAuthenticated()) {+ navigate(from, { replace: true });+ }+ }, [from, navigate]);++ const handleLogin = async () => {+ // Pass the intended destination as return URL+ await login(from);+ };++ return (+ <div className="login-page">+ <h1>Sign In Required</h1>+ <p>Please sign in to access this page.</p>+ <button onClick={handleLogin}>Sign In with Azure AD</button>+ </div>+ );+}+```++## Vue 3 Authorization Composable++**File: `src/composables/useAuthorization.ts`**++```typescript+import { computed } from 'vue';+import { getCurrentUser } from '../services/authService';++export function useAuthorization() {+ const roles = computed(() => {+ const user = getCurrentUser();+ return user?.userRoles || [];+ });++ const isAuthenticated = computed(() => {+ const user = getCurrentUser();+ return user !== null && user.userName !== '';+ });++ function hasRole(roleName: string): boolean {+ const normalizedRole = roleName.toLowerCase();+ return roles.value.some(role => role.toLowerCase() === normalizedRole);+ }++ function hasAnyRole(roleNames: string[]): boolean {+ return roleNames.some(role => hasRole(role));+ }++ function hasAllRoles(roleNames: string[]): boolean {+ return roleNames.every(role => hasRole(role));+ }++ const isAdmin = computed(() => hasRole('Administrators'));++ return {+ roles,+ isAuthenticated,+ isAdmin,+ hasRole,+ hasAnyRole,+ hasAllRoles,+ };+}+```++### Vue Directive for Role-Based Visibility++**File: `src/directives/vRole.ts`**++```typescript+import type { Directive } from 'vue';+import { getCurrentUser } from '../services/authService';++function hasRole(roleName: string): boolean {+ const user = getCurrentUser();+ const roles = user?.userRoles || [];+ return roles.some(role => role.toLowerCase() === roleName.toLowerCase());+}++function hasAnyRole(roleNames: string[]): boolean {+ return roleNames.some(role => hasRole(role));+}++/**+ * Vue directive for role-based visibility+ *+ * Usage:+ * v-role="'Administrators'"+ * v-role="['Administrators', 'Managers']"+ */+export const vRole: Directive<HTMLElement, string | string[]> = {+ mounted(el, binding) {+ const roles = Array.isArray(binding.value) ? binding.value : [binding.value];++ if (!hasAnyRole(roles)) {+ el.style.display = 'none';+ }+ },+ updated(el, binding) {+ const roles = Array.isArray(binding.value) ? binding.value : [binding.value];++ if (hasAnyRole(roles)) {+ el.style.display = '';+ } else {+ el.style.display = 'none';+ }+ },+};++// Register in main.ts:+// app.directive('role', vRole);+```++## Angular Authorization++### Auth Guard++**File: `src/app/guards/auth.guard.ts`**++```typescript+import { inject } from '@angular/core';+import { Router, CanActivateFn } from '@angular/router';+import { AuthService } from '../services/auth.service';++export const authGuard: CanActivateFn = (route, state) => {+ const authService = inject(AuthService);+ const router = inject(Router);++ if (!authService.isAuthenticated) {+ // Store intended URL for redirect after login+ sessionStorage.setItem('redirectUrl', state.url);+ router.navigate(['/login']);+ return false;+ }++ return true;+};++export const roleGuard: CanActivateFn = (route, state) => {+ const authService = inject(AuthService);+ const router = inject(Router);++ // First check authentication+ if (!authService.isAuthenticated) {+ sessionStorage.setItem('redirectUrl', state.url);+ router.navigate(['/login']);+ return false;+ }++ // Then check roles+ const requiredRoles = route.data['roles'] as string[];++ if (requiredRoles && requiredRoles.length > 0) {+ const userRoles = authService.currentUser?.userRoles || [];+ const hasRole = requiredRoles.some(role =>+ userRoles.some(ur => ur.toLowerCase() === role.toLowerCase())+ );++ if (!hasRole) {+ router.navigate(['/unauthorized']);+ return false;+ }+ }++ return true;+};++// Usage in routes:+// {+// path: 'admin',+// component: AdminComponent,+// canActivate: [roleGuard],+// data: { roles: ['Administrators'] }+// }+```++### Structural Directive for Role-Based Rendering++**File: `src/app/directives/has-role.directive.ts`**++```typescript+import { Directive, Input, TemplateRef, ViewContainerRef, OnInit } from '@angular/core';+import { AuthService } from '../services/auth.service';++@Directive({+ selector: '[appHasRole]',+ standalone: true+})+export class HasRoleDirective implements OnInit {+ @Input('appHasRole') roles: string | string[] = [];++ constructor(+ private templateRef: TemplateRef<any>,+ private viewContainer: ViewContainerRef,+ private authService: AuthService+ ) {}++ ngOnInit() {+ this.updateView();+ }++ private updateView() {+ const roleArray = Array.isArray(this.roles) ? this.roles : [this.roles];+ const userRoles = this.authService.currentUser?.userRoles || [];++ const hasRole = roleArray.some(role =>+ userRoles.some(ur => ur.toLowerCase() === role.toLowerCase())+ );++ this.viewContainer.clear();++ if (hasRole) {+ this.viewContainer.createEmbeddedView(this.templateRef);+ }+ }+}++// Usage in template:+// <button *appHasRole="'Administrators'">Admin Action</button>+// <div *appHasRole="['Administrators', 'Managers']">Management Section</div>+```++## Vanilla JavaScript++**File: `src/authorization.js`**++```javascript+/**+ * Power Pages Authorization Module+ * Framework-agnostic authorization utilities+ */++/**+ * Get user roles from portal object+ * @returns {string[]}+ */+function getUserRoles() {+ try {+ const user = window.Microsoft?.Dynamic365?.Portal?.User;+ return user?.userRoles || [];+ } catch {+ return [];+ }+}++/**+ * Check if user has a specific role+ * @param {string} roleName+ * @returns {boolean}+ */+function hasRole(roleName) {+ const roles = getUserRoles();+ const normalizedRole = roleName.toLowerCase();+ return roles.some(role => role.toLowerCase() === normalizedRole);+}++/**+ * Check if user has any of the specified roles+ * @param {string[]} roleNames+ * @returns {boolean}+ */+function hasAnyRole(roleNames) {+ return roleNames.some(role => hasRole(role));+}++/**+ * Check if user is authenticated+ * @returns {boolean}+ */+function isAuthenticated() {+ const user = window.Microsoft?.Dynamic365?.Portal?.User;+ return user && user.userName !== '';+}++/**+ * Show/hide element based on roles+ * @param {HTMLElement} element+ * @param {string|string[]} roles+ */+function showForRoles(element, roles) {+ const roleArray = Array.isArray(roles) ? roles : [roles];++ if (hasAnyRole(roleArray)) {+ element.style.display = '';+ } else {+ element.style.display = 'none';+ }+}++/**+ * Initialize role-based visibility for elements with data-require-role attribute+ * Usage: <div data-require-role="Administrators">Admin content</div>+ * <div data-require-role="Admin,Manager">Multi-role content</div>+ */+function initRoleBasedVisibility() {+ document.querySelectorAll('[data-require-role]').forEach(element => {+ const rolesAttr = element.getAttribute('data-require-role');+ const roles = rolesAttr.split(',').map(r => r.trim());+ showForRoles(element, roles);+ });++ // Handle authentication-required elements+ document.querySelectorAll('[data-require-auth]').forEach(element => {+ if (!isAuthenticated()) {+ element.style.display = 'none';+ }+ });+}++// Auto-initialize when DOM is ready+if (document.readyState === 'loading') {+ document.addEventListener('DOMContentLoaded', initRoleBasedVisibility);+} else {+ initRoleBasedVisibility();+}++// Export for module usage+export { getUserRoles, hasRole, hasAnyRole, isAuthenticated, showForRoles };++// Expose globally+window.PowerPagesAuth = {+ ...window.PowerPagesAuth,+ getUserRoles,+ hasRole,+ hasAnyRole,+ isAuthenticated,+ showForRoles,+};+```++## Common Usage Patterns++### Conditional Navigation Items++```tsx+// React example+function Navigation() {+ const { isAuthenticated, hasRole } = useAuthorization();++ return (+ <nav>+ <Link to="/">Home</Link>+ <Link to="/products">Products</Link>++ {/* Only for authenticated users */}+ {isAuthenticated && (+ <Link to="/account">My Account</Link>+ )}++ {/* Only for admins */}+ {hasRole('Administrators') && (+ <Link to="/admin">Admin Dashboard</Link>+ )}++ {/* Only for premium members */}+ {hasRole('Premium Members') && (+ <Link to="/premium">Premium Content</Link>+ )}+ </nav>+ );+}+```++### Conditional Action Buttons++```tsx+function ProductCard({ product, onEdit, onDelete }) {+ const { hasRole } = useAuthorization();++ return (+ <div className="product-card">+ <h3>{product.name}</h3>+ <p>{product.description}</p>++ {/* Edit/Delete only for admins or content managers */}+ {hasRole('Administrators') || hasRole('Content Managers') ? (+ <div className="product-actions">+ <button onClick={() => onEdit(product)}>Edit</button>+ <button onClick={() => onDelete(product)}>Delete</button>+ </div>+ ) : null}+ </div>+ );+}+```++### Content Sections by Role++```tsx+function Dashboard() {+ return (+ <div className="dashboard">+ <h1>Dashboard</h1>++ {/* Public section - everyone */}+ <section className="public-stats">+ <h2>Overview</h2>+ <PublicStats />+ </section>++ {/* Authenticated users section */}+ <RequireAuth>+ <section className="user-section">+ <h2>Your Activity</h2>+ <UserActivity />+ </section>+ </RequireAuth>++ {/* Admin-only section */}+ <RequireRole roles="Administrators">+ <section className="admin-section">+ <h2>Admin Controls</h2>+ <AdminControls />+ </section>+ </RequireRole>++ {/* Premium members section */}+ <RequireRole roles={['Premium Members', 'VIP']}>+ <section className="premium-section">+ <h2>Premium Features</h2>+ <PremiumFeatures />+ </section>+ </RequireRole>+ </div>+ );+}+```++## Security Considerations++### Client-Side Authorization is for UX Only++**IMPORTANT**: Client-side role checks are for **user experience** only, not security.++- They hide/show UI elements based on roles+- They do NOT prevent unauthorized access to data+- All data access must be protected by **table permissions** in Power Pages++### Always Enforce Server-Side++```text+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+β Security Layers β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€+β β+β CLIENT-SIDE (UX only) SERVER-SIDE (Security) β+β βββββββββββββββββββββ βββββββββββββββββββββ β+β β’ Hide admin buttons β’ Table permissions β+β β’ Show/hide nav items β’ Entity permissions β+β β’ Conditional rendering β’ Web roles in Power Pages β+β β’ Route guards (redirect) β’ Actual data access control β+β β+β If bypassed: Bad UX If bypassed: Security breach β+β β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+```++### Example: Proper Security Setup++1. **Client-side** (this reference): Hide edit button for non-admins+2. **Server-side** (via `/setup-webapi`): Table permission allows only Administrators to PATCH records++If someone bypasses the UI and sends a PATCH request directly:+- **Without server-side protection**: Data gets modified (VULNERABILITY!)+- **With server-side protection**: Returns 403 Forbidden (SECURE)++### Testing Authorization++1. Test with different user accounts having different roles+2. Use browser dev tools to verify hidden elements can't be accessed+3. Test API calls directly to ensure table permissions are enforced+4. Never rely solely on client-side authorizationdiff --git a/plugins/power-pages/skills/setup-dataverse/SKILL.md b/plugins/power-pages/skills/setup-dataverse/SKILL.mdnew file mode 100644index 000000000..fad4e3b3d--- /dev/null+++ b/plugins/power-pages/skills/setup-dataverse/SKILL.md@@ -0,0 +1,394 @@+---+description: Setup Dataverse tables, schema, entities, and data model for Power Pages. Use this skill when you need to create Dataverse tables, define table columns, set up entity relationships, create lookup fields, design database schema, add sample data, or configure table structure for your Power Pages site.+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.++## Reference Documentation++This skill uses modular reference files for detailed instructions:++| File | Purpose |+|------|---------|+| [data-architecture-reference.md](./data-architecture-reference.md) | Entity relationships, table tiers, dependency graphs |+| [api-authentication-reference.md](./api-authentication-reference.md) | OData Web API setup, Azure CLI authentication |+| [table-management-reference.md](./table-management-reference.md) | Table creation, columns, helper functions |+| [relationship-reference.md](./relationship-reference.md) | Lookups, 1:N and N:N relationships |+| [sample-data-reference.md](./sample-data-reference.md) | Data insertion with referential integrity |+| [troubleshooting.md](./troubleshooting.md) | Common issues and solutions |++## Memory Bank++This skill uses a **memory bank** (`memory-bank.md`) to persist context across sessions.++**Follow the instructions in `${CLAUDE_PLUGIN_ROOT}/shared/memory-bank.md`** for:+- Checking and reading the memory bank before starting+- Skipping completed steps and resuming progress+- Updating the memory bank after each major step++## Workflow Overview++```text++-----------------------------------------------------------------------------++| STEP 1: Resume or Start Fresh |+| - Check if continuing from /create-site |+| - Identify existing site project path |+| - Offer to proceed or show resume command |++-----------------------------------------------------------------------------++ |+ v++-----------------------------------------------------------------------------++| STEP 2: Analyze Site & Design Data Architecture |+| - Read site source code and configuration |+| - Identify data requirements from components |+| - Design entity-relationship model with proper normalization |+| - Document table relationships (1:N, N:N, self-referential) |+| See: data-architecture-reference.md |++-----------------------------------------------------------------------------++ |+ v++-----------------------------------------------------------------------------++| STEP 3: Build Dependency Graph & Determine Creation Order |+| - Analyze foreign key relationships |+| - Perform topological sort to determine creation order |+| - Identify reference/lookup tables (create first) |+| - Identify dependent tables (create after their references) |+| See: data-architecture-reference.md |++-----------------------------------------------------------------------------++ |+ v++-----------------------------------------------------------------------------++| STEP 4: Set Up OData Web API Authentication |+| - Configure Azure CLI authentication |+| - Get environment URL and access token |+| - Set up API headers for Dataverse calls |+| See: api-authentication-reference.md |++-----------------------------------------------------------------------------++ |+ v++-----------------------------------------------------------------------------++| STEP 5: Review Existing Tables & Identify Reusable Tables |+| - Query all existing custom tables in the environment |+| - Compare existing tables against recommended schema |+| - Identify tables that can be reused (matching or similar schema) |+| - Present options: reuse existing, extend existing, or create new |+| See: table-management-reference.md |++-----------------------------------------------------------------------------++ |+ v++-----------------------------------------------------------------------------++| STEP 6: Create/Extend Tables in Dependency Order |+| - Skip tables marked for reuse |+| - Extend existing tables with missing columns if needed |+| - Create only new tables that don't exist |+| - Add relationship columns (lookups) after both tables exist |+| See: table-management-reference.md, relationship-reference.md |++-----------------------------------------------------------------------------++ |+ v++-----------------------------------------------------------------------------++| STEP 7: Add Sample Data with Referential Integrity |+| - Check for existing data in reused tables |+| - Insert reference/lookup data first (skip if exists) |+| - Insert dependent records with valid foreign keys |+| - Verify relationships are correctly established |+| See: sample-data-reference.md |++-----------------------------------------------------------------------------++ |+ v+ Next: /setup-webapi skill+```++---++## STEP 1: Resume or Start Fresh++### Check Memory Bank First++**Before asking questions**, check if a memory bank exists:++1. If continuing from `/create-site` in the same session, use the known project path+2. Otherwise, ask the user for the project path+3. Read `<PROJECT_PATH>/memory-bank.md` if it exists+4. Extract:+ - Project name and framework+ - Site features (to recommend appropriate tables)+ - Any previously chosen preferences+ - Whether this skill was already partially completed++If the memory bank shows `/setup-dataverse` steps already completed:++- Inform the user what was done+- Ask if they want to add more tables, modify existing ones, or skip to next steps++### Check Context++**If continuing from create-site:**++Show this message:++> **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 |++---++## STEP 2: Analyze Site & Design Data Architecture++**See: [data-architecture-reference.md](./data-architecture-reference.md)**++### Quick Summary++1. **Read powerpages.config.json** to get site name and structure+2. **Scan component files** for data patterns:+ - Forms (contact forms, registration forms)+ - Lists/Tables (product listings, team members)+ - Cards (testimonials, portfolio items)++### Data Pattern Recognition++| Pattern | Recommended Table | Likely Relationships |+|---------|-------------------|---------------------|+| Contact form | `cr_contactsubmission` | -> `cr_contactstatus` (lookup) |+| Product/service cards | `cr_product` | -> `cr_category` (lookup) |+| Team member section | `cr_teammember` | -> `cr_department` (lookup) |+| Testimonials/Reviews | `cr_testimonial` | -> `cr_product` (optional) |+| Blog/News section | `cr_blogpost` | -> `cr_category`, -> `cr_author` |+| FAQ section | `cr_faq` | -> `cr_faqcategory` (lookup) |++### Actions++1. Design a complete ER model identifying all entities and relationships+2. Classify tables into tiers (TIER 0 reference tables, TIER 1 primary entities, etc.)+3. Present architecture recommendations using `AskUserQuestion`++---++## STEP 3: Build Dependency Graph & Validate Creation Order++**See: [data-architecture-reference.md](./data-architecture-reference.md)**++### Quick Summary++Before creating any tables, validate the creation order:++1. List all tables and their lookup columns+2. Build adjacency list: for each table, list tables it depends on+3. Perform topological sort to get valid creation order+4. Group tables by tier for parallel creation where possible++### Validation Rules++- **No circular dependencies** - A cannot depend on B if B depends on A+- **All referenced tables exist** - Either in schema or as system tables+- **Self-references are handled** - Table created first, then self-lookup added++---++## STEP 4: Set Up OData Web API Authentication++**See: [api-authentication-reference.md](./api-authentication-reference.md)**++### Quick Summary++```powershell+# Verify Azure CLI is logged in+az account show++# Get environment URL+pac org who++# Get access token+$envUrl = "https://<org>.crm.dynamics.com"+$token = (az account get-access-token --resource $envUrl --query accessToken -o tsv)++# Set up headers+$headers = @{+ "Authorization" = "Bearer $token"+ "Content-Type" = "application/json"+ "OData-MaxVersion" = "4.0"+ "OData-Version" = "4.0"+ "Prefer" = "return=representation"+}++$baseUrl = "$envUrl/api/data/v9.2"+```++---++## STEP 5: Review Existing Tables & Identify Reusable Tables++**See: [table-management-reference.md](./table-management-reference.md)**++### Quick Summary++**CRITICAL**: Before creating any tables, review existing tables in the environment to prevent duplicates and leverage existing schema.++### Actions++1. Query all existing custom tables using `EntityDefinitions` API+2. Compare existing tables against recommended schema+3. Present reuse options to user:+ - **Reuse as-is**: Table has all required columns+ - **Extend**: Table exists but needs additional columns+ - **Create new**: Table doesn't exist++### Present Options++Use `AskUserQuestion`:++| Option | Description |+|--------|-------------|+| **Use recommendations** | Reuse existing tables, extend where needed, create only new |+| **Create all new** | Create new tables with unique names |+| **Review each table** | Decide for each table individually |++---++## STEP 6: Create/Extend Tables in Dependency Order++**See: [table-management-reference.md](./table-management-reference.md) and [relationship-reference.md](./relationship-reference.md)**++### Quick Summary++Based on STEP 5 decisions, create only new tables and extend existing tables as needed.++### Protocol++1. **PHASE 1**: Process tables based on decisions (skip reusable, extend, create new)+2. **PHASE 2**: Add non-lookup columns to new and extended tables+3. **PHASE 3**: Create/verify relationships (lookup columns)++### Key Functions++- `New-DataverseTableIfNotExists` - Create table only if it doesn't exist+- `Add-DataverseColumnIfNotExists` - Add column only if it doesn't exist+- `Add-DataverseLookupIfNotExists` - Create relationship only if it doesn't exist++---++## STEP 7: Add Sample Data with Referential Integrity++**See: [sample-data-reference.md](./sample-data-reference.md)**++### Quick Summary++Insert data **in the correct order** to maintain referential integrity.++### Protocol++1. Check for existing data in reused tables+2. Insert TIER 0 data first (categories, statuses, departments)+3. Insert TIER 1 data with valid TIER 0 lookups (products, team members)+4. Insert TIER 2 data with valid lookups (testimonials, submissions)++### Foreign Key Syntax++```powershell+# Use @odata.bind to reference related records+$product = @{+ cr_name = "Professional Consultation"+ "[email protected]" = "/cr_categories($categoryId)"+}+```++### Verify Data++After inserting, verify relationships using `$expand`:++```powershell+$products = Invoke-RestMethod -Uri "$baseUrl/cr_products?`$expand=cr_categoryid(`$select=cr_name)" -Headers $headers+```++---++## STEP 8: Cleanup Helper Files++**π See: [cleanup-reference.md](${CLAUDE_PLUGIN_ROOT}/shared/cleanup-reference.md)**++Remove any temporary helper files created during this skill's execution. Verify tables are created and data is inserted correctly before cleanup.++---++## Next Steps++After setting up Dataverse tables with sample data, configure table permissions so Power Pages can access the data.++> **Next Skill**: Run `/setup-webapi` to configure table permissions and enable Web API access for your Power Pages site.++---++## Update Memory Bank++After completing this skill, update `memory-bank.md`:++```markdown+### /setup-dataverse+- [x] Site analyzed for data requirements+- [x] Data architecture designed with dependency graph+- [x] Existing tables reviewed and analyzed+- [x] Reuse decisions made (reuse/extend/create)+- [x] Tables created/extended in dependency order+- [x] Relationships (lookups) established+- [x] Sample data inserted with referential integrity++## Data Architecture++### Tables by Tier++| Tier | Tables |+|------|--------|+| TIER 0 | cr_category, cr_status, cr_department |+| TIER 1 | cr_product, cr_teammember |+| TIER 2 | cr_testimonial, cr_contactsubmission |++### Relationships++| Source | Target | Lookup Column |+|--------|--------|---------------|+| cr_product | cr_category | cr_categoryid |+| cr_teammember | cr_department | cr_departmentid |+| cr_testimonial | cr_product | cr_productid |++## Current Status++**Last Action**: Dataverse tables and relationships created with sample data++**Next Step**: Run `/setup-webapi` to configure table permissions+```++---++## Troubleshooting++**See: [troubleshooting.md](./troubleshooting.md)** for common issues and solutions.diff --git a/plugins/power-pages/skills/setup-dataverse/api-authentication-reference.md b/plugins/power-pages/skills/setup-dataverse/api-authentication-reference.mdnew file mode 100644index 000000000..d830be4e5--- /dev/null+++ b/plugins/power-pages/skills/setup-dataverse/api-authentication-reference.md@@ -0,0 +1,198 @@+# API Authentication Reference++This document covers setting up authentication for the Dataverse OData Web API.++## Overview++This skill uses the Dataverse OData Web API for all table and data operations:++1. **Dataverse Web API** for table creation, schema management, and data operations+2. **Azure CLI** for authentication (`az account get-access-token`)+3. **PowerShell** for scripting API calls+4. **Client-side `/_api/` calls** from the Power Pages site for runtime data access++## Prerequisites++Ensure Azure CLI is authenticated before proceeding:++```powershell+# Verify Azure CLI is logged in+az account show++# If not logged in, run:+az login+```++## Get Environment URL++Get your Dataverse environment URL:++```powershell+# Using PAC CLI+pac org who+```++This returns information including the environment URL (e.g., `https://orgname.crm.dynamics.com`).++## Get Access Token++```powershell+# 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 API Headers++```powershell+# 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"+```++## API Headers Reference++| Header | Value | Purpose |+|--------|-------|---------|+| `Authorization` | `Bearer <token>` | Authentication token |+| `Content-Type` | `application/json` | Request body format |+| `OData-MaxVersion` | `4.0` | Maximum OData version supported |+| `OData-Version` | `4.0` | OData version to use |+| `MSCRM.SolutionUniqueName` | Solution name | Add created items to a solution |+| `Prefer` | `return=representation` | Return created record with ID |++## Complete Setup Script++```powershell+# Complete API setup script+function Initialize-DataverseApi {+ param(+ [Parameter(Mandatory=$true)]+ [string]$EnvironmentUrl,++ [string]$SolutionName = $null+ )++ # Get access token+ $token = (az account get-access-token --resource $EnvironmentUrl --query accessToken -o tsv)++ if (-not $token) {+ throw "Failed to get access token. Make sure you're logged in with 'az login'"+ }++ # Set up headers+ $headers = @{+ "Authorization" = "Bearer $token"+ "Content-Type" = "application/json"+ "OData-MaxVersion" = "4.0"+ "OData-Version" = "4.0"+ "Prefer" = "return=representation"+ }++ if ($SolutionName) {+ $headers["MSCRM.SolutionUniqueName"] = $SolutionName+ }++ $baseUrl = "$EnvironmentUrl/api/data/v9.2"++ # Store in script-level variables for reuse+ $script:DataverseHeaders = $headers+ $script:DataverseBaseUrl = $baseUrl++ Write-Host "Dataverse API initialized successfully" -ForegroundColor Green+ Write-Host " Environment: $EnvironmentUrl" -ForegroundColor Cyan+ Write-Host " Base URL: $baseUrl" -ForegroundColor Cyan++ return @{+ Headers = $headers+ BaseUrl = $baseUrl+ }+}++# Usage example:+# $api = Initialize-DataverseApi -EnvironmentUrl "https://orgname.crm.dynamics.com"+# $headers = $api.Headers+# $baseUrl = $api.BaseUrl+```++## Token Refresh++Access tokens expire after approximately 1 hour. For long-running scripts, implement token refresh:++```powershell+function Get-FreshToken {+ param([string]$EnvironmentUrl)++ return (az account get-access-token --resource $EnvironmentUrl --query accessToken -o tsv)+}++function Invoke-DataverseApi {+ param(+ [string]$Uri,+ [string]$Method = "Get",+ [hashtable]$Headers,+ [string]$Body = $null,+ [string]$EnvironmentUrl+ )++ try {+ if ($Body) {+ return Invoke-RestMethod -Uri $Uri -Method $Method -Headers $Headers -Body $Body+ } else {+ return Invoke-RestMethod -Uri $Uri -Method $Method -Headers $Headers+ }+ } catch {+ if ($_.Exception.Response.StatusCode -eq 401) {+ # Token expired, refresh and retry+ Write-Host "Token expired, refreshing..." -ForegroundColor Yellow+ $newToken = Get-FreshToken -EnvironmentUrl $EnvironmentUrl+ $Headers["Authorization"] = "Bearer $newToken"++ if ($Body) {+ return Invoke-RestMethod -Uri $Uri -Method $Method -Headers $Headers -Body $Body+ } else {+ return Invoke-RestMethod -Uri $Uri -Method $Method -Headers $Headers+ }+ }+ throw+ }+}+```++## Verify Connection++Test the API connection:++```powershell+# Test API connection+try {+ $whoami = Invoke-RestMethod -Uri "$baseUrl/WhoAmI" -Headers $headers+ Write-Host "Connected as: $($whoami.UserId)" -ForegroundColor Green+} catch {+ Write-Host "Connection failed: $($_.Exception.Message)" -ForegroundColor Red+}+```++## Required Permissions++To create tables and manage schema, you need one of these Dataverse security roles:++- **System Administrator** - Full access+- **System Customizer** - Can create and modify tables++To verify your permissions:++```powershell+# Get current user's security roles+$userId = (Invoke-RestMethod -Uri "$baseUrl/WhoAmI" -Headers $headers).UserId+$roles = Invoke-RestMethod -Uri "$baseUrl/systemusers($userId)/systemuserroles_association?`$select=name" -Headers $headers+Write-Host "Your security roles:" -ForegroundColor Cyan+$roles.value | ForEach-Object { Write-Host " - $($_.name)" }+```diff --git a/plugins/power-pages/skills/setup-dataverse/data-architecture-reference.md b/plugins/power-pages/skills/setup-dataverse/data-architecture-reference.mdnew file mode 100644index 000000000..294d30e68--- /dev/null+++ b/plugins/power-pages/skills/setup-dataverse/data-architecture-reference.md@@ -0,0 +1,179 @@+# Data Architecture Reference++This document covers data architecture principles for designing Dataverse table schemas for Power Pages sites.++## Entity-Relationship Analysis++Identify all entities and their relationships before creating any tables:++```text+RELATIONSHIP TYPES IN DATAVERSE++1:N (One-to-Many) - Most common+ - Parent table referenced by child table via Lookup column+ - Example: Category (1) -> Products (N)+ - Parent must exist before child can reference it++N:N (Many-to-Many)+ - Junction/intersection table created automatically+ - Example: Products <-> Tags+ - Both tables must exist before creating the relationship++Self-Referential+ - Table references itself+ - Example: Employee -> Manager (also an Employee)+ - Table must exist before adding self-referential lookup++Polymorphic (Customer/Regarding)+ - Single column can reference multiple table types+ - Example: Activity regarding Contact OR Account OR Lead+ - All target tables must exist before creating polymorphic lookup+```++## Table Classification++Classify tables into tiers based on their dependencies:++```text+TABLE DEPENDENCY TIERS++TIER 0: Reference/Lookup Tables (Create FIRST)+ - No foreign keys to other custom tables+ - Examples: Category, Status, Country, Department, Tag+ - These are the "dictionaries" of your data model++TIER 1: Primary Entity Tables (Create SECOND)+ - Only reference Tier 0 tables or system tables+ - Examples: Product (->Category), Employee (->Department)+ - Core business entities++TIER 2: Dependent/Transaction Tables (Create THIRD)+ - Reference Tier 1 tables+ - Examples: Order (->Customer), OrderLine (->Order, ->Product)+ - Often transactional or junction tables++TIER 3: Deeply Nested Tables (Create LAST)+ - Reference Tier 2 tables+ - Examples: OrderLineDetail (->OrderLine), PaymentAllocation (->Payment)+ - Rare in typical Power Pages sites+```++## Dependency Graph Documentation++**Always document the dependency graph before creating tables:**++```text+Example: E-Commerce Site Data Architecture++ +-------------++ | Category | TIER 0+ | (lookup) |+ +------+------++ |+ +---------------+---------------++ v v v+ +--------------+ +--------------+ +--------------++ | Product | | Supplier | | Customer | TIER 1+ | (->Category) | | | | |+ +------+-------+ +------+-------+ +------+-------++ | | |+ +---------------+---------------++ v+ +--------------++ | Order | TIER 2+ | (->Customer) |+ +------+-------++ |+ v+ +--------------++ | OrderLine | TIER 3+ |(->Order, |+ | ->Product) |+ +--------------+++Creation Order: Category -> Product, Supplier, Customer -> Order -> OrderLine+```++## Common Relationship Patterns for Power Pages Sites++| Site Feature | Tables | Relationships |+|--------------|--------|---------------|+| **Blog** | Category, Author, BlogPost, Comment | Category(0) -> BlogPost(1) -> Comment(2); Author(0) -> BlogPost(1) |+| **E-commerce** | Category, Product, Customer, Order, OrderLine | Category(0) -> Product(1); Customer(1) -> Order(2) -> OrderLine(3) <- Product(1) |+| **Event Registration** | EventType, Event, Attendee, Registration | EventType(0) -> Event(1); Attendee(1) -> Registration(2) <- Event(1) |+| **Support Portal** | Category, Priority, Ticket, Comment | Category(0), Priority(0) -> Ticket(1) -> Comment(2) |+| **Directory/Listing** | Category, Location, Listing, Review | Category(0), Location(0) -> Listing(1) -> Review(2) |+| **Job Board** | Department, JobType, JobPosting, Application | Department(0), JobType(0) -> JobPosting(1) -> Application(2) |++## Dependency Analysis Algorithm++```text+1. List all tables and their lookup columns+2. Build adjacency list: for each table, list tables it depends on+3. Perform topological sort to get valid creation order+4. If cycle detected, report error (invalid schema design)+5. Group tables by tier for parallel creation where possible+```++### Example Dependency Resolution++```powershell+# Example: Building dependency graph in PowerShell+$tables = @{+ "cr_category" = @() # No dependencies - TIER 0+ "cr_status" = @() # No dependencies - TIER 0+ "cr_department" = @() # No dependencies - TIER 0+ "cr_product" = @("cr_category") # Depends on category - TIER 1+ "cr_teammember" = @("cr_department") # Depends on department - TIER 1+ "cr_testimonial" = @("cr_product") # Depends on product - TIER 2+ "cr_contactsubmission" = @("cr_status") # Depends on status - TIER 1+}++# Topological sort result (creation order):+# 1. cr_category, cr_status, cr_department (can be parallel)+# 2. cr_product, cr_teammember, cr_contactsubmission (after their deps)+# 3. cr_testimonial (after cr_product)+```++## Validation Rules++Before proceeding to table creation, validate:++1. **No circular dependencies** - A cannot depend on B if B depends on A+2. **All referenced tables exist** - Either in schema or as system tables+3. **Lookup targets are valid** - Table being referenced must have a primary key+4. **Self-references are handled** - Table created first, then self-lookup added++## Example Analysis Output Format++```text+DATA ARCHITECTURE FOR: [Site Name]++TIER 0 - Reference Tables (No Dependencies)+ 1. cr_category - Product/content categories+ 2. cr_status - Status values for various entities+ 3. cr_department - Team member departments++TIER 1 - Primary Entity Tables+ 4. cr_product - Products (-> cr_category)+ 5. cr_teammember - Team members (-> cr_department)+ 6. cr_blogpost - Blog posts (-> cr_category)++TIER 2 - Dependent Tables+ 7. cr_testimonial - Testimonials (-> cr_product, optional)+ 8. cr_contactsubmission - Contact submissions (-> cr_status)++RELATIONSHIP DIAGRAM++ cr_category --+---> cr_product ---> cr_testimonial+ +---> cr_blogpost++ cr_department ---> cr_teammember++ cr_status -------> cr_contactsubmission++CREATION ORDER+ 1. cr_category, cr_status, cr_department (parallel - no deps)+ 2. cr_product, cr_teammember, cr_blogpost (after tier 0)+ 3. cr_testimonial, cr_contactsubmission (after their references)+```diff --git a/plugins/power-pages/skills/setup-dataverse/relationship-reference.md b/plugins/power-pages/skills/setup-dataverse/relationship-reference.mdnew file mode 100644index 000000000..b8b029bcf--- /dev/null+++ b/plugins/power-pages/skills/setup-dataverse/relationship-reference.md@@ -0,0 +1,284 @@+# Relationship Reference++This document covers creating and managing relationships between Dataverse tables.++## Relationship Types++| Type | Description | Use Case |+|------|-------------|----------|+| **1:N (One-to-Many)** | One parent record can have many child records | Category -> Products |+| **N:N (Many-to-Many)** | Records can relate to multiple records in both tables | Products <-> Tags |+| **Self-Referential** | Table references itself | Employee -> Manager |++## Check If Relationship Exists++```powershell+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+ }+}+```++## Get Table Relationships++```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+ }+}+```++## Create Lookup (1:N Relationship)++```powershell+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+}+```++## Safe Lookup 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 " [SKIP] Relationship '$RelationshipName' already exists" -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 " [SKIP] Lookup column '$LookupSchemaName' already exists on '$SourceTable'" -ForegroundColor Yellow+ return @{ Skipped = $true; Reason = "Lookup column already exists" }+ }++ Write-Host " [CREATE] Creating relationship '$RelationshipName' ($SourceTable -> $TargetTable)..." -ForegroundColor Cyan+ $result = Add-DataverseLookup -SourceTable $SourceTable -TargetTable $TargetTable `+ -LookupSchemaName $LookupSchemaName -LookupDisplayName $LookupDisplayName `+ -RelationshipName $RelationshipName++ Write-Host " [OK] Relationship '$RelationshipName' created successfully" -ForegroundColor Green+ return @{ Skipped = $false; Result = $result }+}+```++## Create Many-to-Many Relationship++```powershell+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+}+```++## Cascade Configuration Options++When creating relationships, you can configure cascade behavior:++| Option | Description |+|--------|-------------|+| `NoCascade` | No action on related records |+| `Cascade` | Perform action on all related records |+| `Active` | Perform action on active related records |+| `UserOwned` | Perform action on records owned by same user |+| `RemoveLink` | Clear the lookup value (recommended for Delete) |+| `Restrict` | Prevent action if related records exist |++## Relationship Naming Conventions++Follow this naming pattern for consistency:++```text+{publisher}_{targetTable}_{sourceTable}++Examples:+- cr_category_product (Product -> Category)+- cr_department_teammember (TeamMember -> Department)+- cr_status_contactsubmission (ContactSubmission -> Status)+```++## Complete Example: Creating Relationships in Dependency Order++```powershell+# ============================================+# PHASE 3: Create Relationships+# ============================================++Write-Host "`n=== Processing Relationships ===" -ForegroundColor Magenta++# --- TIER 1 -> TIER 0 Relationships ---+Write-Host "Processing TIER 1 -> TIER 0 relationships..." -ForegroundColor Cyan++# Product -> Category+Add-DataverseLookupIfNotExists -SourceTable "cr_product" -TargetTable "cr_category" `+ -LookupSchemaName "cr_categoryid" -LookupDisplayName "Category" `+ -RelationshipName "cr_category_product"++# 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"++# --- TIER 2 -> TIER 1 Relationships ---+Write-Host "`nProcessing TIER 2 -> TIER 1 relationships..." -ForegroundColor Cyan++# Testimonial -> Product (optional relationship)+Add-DataverseLookupIfNotExists -SourceTable "cr_testimonial" -TargetTable "cr_product" `+ -LookupSchemaName "cr_productid" -LookupDisplayName "Related Product" `+ -RelationshipName "cr_product_testimonial"++Write-Host "`n=== Relationship processing complete ===" -ForegroundColor Green+```++## Self-Referential Lookups++For tables that reference themselves (e.g., Employee -> Manager):++```powershell+# First, create the table+New-DataverseTable -SchemaName "cr_employee" -DisplayName "Employee" -PluralDisplayName "Employees"++# Add regular columns+Add-DataverseColumn -TableName "cr_employee" -SchemaName "cr_title" -DisplayName "Job Title" -Type "String"++# Then add self-referential lookup (table must exist first!)+Add-DataverseLookup -SourceTable "cr_employee" -TargetTable "cr_employee" `+ -LookupSchemaName "cr_managerid" -LookupDisplayName "Manager" `+ -RelationshipName "cr_employee_manager"+```++## 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" -ForegroundColor Green+ Write-Host " Referenced Entity: $($relations.value[0].ReferencedEntity)"+ Write-Host " Referencing Entity: $($relations.value[0].ReferencingEntity)"+} else {+ Write-Host "Relationship not found" -ForegroundColor Yellow+}++# List all relationships for a table+$tableRelations = Invoke-RestMethod -Uri "$baseUrl/EntityDefinitions(LogicalName='cr_product')/ManyToOneRelationships" -Headers $headers+Write-Host "Lookups on cr_product:" -ForegroundColor Cyan+$tableRelations.value | ForEach-Object {+ Write-Host " $($_.SchemaName): -> $($_.ReferencedEntity)"+}+```diff --git a/plugins/power-pages/skills/setup-dataverse/sample-data-reference.md b/plugins/power-pages/skills/setup-dataverse/sample-data-reference.mdnew file mode 100644index 000000000..3355950f1--- /dev/null+++ b/plugins/power-pages/skills/setup-dataverse/sample-data-reference.md@@ -0,0 +1,426 @@+# Sample Data Reference++This document covers inserting sample data into Dataverse tables while maintaining referential integrity.++## Data Insertion Protocol++```text+SAMPLE DATA INSERTION ORDER (WITH EXISTING DATA CHECKS)++0. Check for existing data in reused tables+ - Query record counts in each table+ - If data exists, ask user: skip, add more, or replace+ - Collect existing record IDs for use as foreign keys++1. Insert TIER 0 data (reference/lookup tables)+ - Categories, Statuses, Departments, etc.+ - Skip if records with same name already exist+ - Store the returned/existing record IDs for use in foreign keys++2. Insert TIER 1 data with valid lookups+ - Products (with Category lookup)+ - Team Members (with Department lookup)+ - Use the IDs from step 1 for lookup values++3. Insert TIER 2 data with valid lookups+ - Testimonials (with Product lookup)+ - Contact Submissions (with Status lookup)+ - Use IDs from steps 1 and 2 for lookup values++IMPORTANT: Never insert records with invalid/non-existent lookup values!+```++## Check Existing Data++```powershell+function Get-ExistingRecordCount {+ param([string]$EntitySetName)++ $result = Invoke-RestMethod -Uri "$baseUrl/$EntitySetName/`$count" -Headers $headers+ return [int]$result+}++function Get-ExistingRecordByName {+ param(+ [string]$EntitySetName,+ [string]$NameColumn, # Usually "cr_name" or the primary name attribute+ [string]$NameValue+ )++ $filter = "$NameColumn eq '$NameValue'"+ $result = Invoke-RestMethod -Uri "$baseUrl/$EntitySetName`?`$filter=$filter&`$top=1" -Headers $headers++ if ($result.value.Count -gt 0) {+ return $result.value[0]+ }+ return $null+}++# Check existing data counts+Write-Host "`nChecking existing data in tables..." -ForegroundColor Cyan+$existingDataCounts = @{+ "cr_categories" = Get-ExistingRecordCount -EntitySetName "cr_categories"+ "cr_statuses" = Get-ExistingRecordCount -EntitySetName "cr_statuses"+ "cr_departments" = Get-ExistingRecordCount -EntitySetName "cr_departments"+ "cr_products" = Get-ExistingRecordCount -EntitySetName "cr_products"+ "cr_teammembers" = Get-ExistingRecordCount -EntitySetName "cr_teammembers"+ "cr_testimonials" = Get-ExistingRecordCount -EntitySetName "cr_testimonials"+ "cr_contactsubmissions" = Get-ExistingRecordCount -EntitySetName "cr_contactsubmissions"+}++Write-Host "`nExisting record counts:" -ForegroundColor Yellow+$existingDataCounts.GetEnumerator() | ForEach-Object {+ $status = if ($_.Value -gt 0) { "[!]" } else { "[OK]" }+ Write-Host " $status $($_.Key): $($_.Value) records"+}+```++## Create Record Helper Function++```powershell+function New-DataverseRecord {+ param(+ [string]$EntitySetName,+ [hashtable]$Data+ )++ $body = $Data | ConvertTo-Json -Depth 5+ $response = Invoke-RestMethod -Uri "$baseUrl/$EntitySetName" -Method Post -Headers $headers -Body $body+ return $response+}+```++## Safe Record Creation (Skip If Exists)++```powershell+function New-DataverseRecordIfNotExists {+ param(+ [string]$EntitySetName,+ [hashtable]$Data,+ [string]$NameColumn = "cr_name"+ )++ $nameValue = $Data[$NameColumn]+ $existing = Get-ExistingRecordByName -EntitySetName $EntitySetName -NameColumn $NameColumn -NameValue $nameValue++ if ($existing) {+ Write-Host " [SKIP] Record '$nameValue' already exists - using existing" -ForegroundColor Yellow+ return @{+ Skipped = $true+ Record = $existing+ }+ }++ Write-Host " [CREATE] Creating record '$nameValue'..." -ForegroundColor Cyan+ $body = $Data | ConvertTo-Json -Depth 5+ $response = Invoke-RestMethod -Uri "$baseUrl/$EntitySetName" -Method Post -Headers $headers -Body $body+ Write-Host " [OK] Record '$nameValue' created" -ForegroundColor Green++ return @{+ Skipped = $false+ Record = $response+ }+}+```++## Foreign Key Syntax++When inserting records with lookup values, use the `@odata.bind` syntax:++```powershell+# Format: "[email protected]" = "/entitysetname(guid)"++$product = @{+ cr_name = "Professional Consultation"+ cr_description = "One-on-one consultation with our expert team."+ cr_price = 299.99+ # Reference category by its ID+ "[email protected]" = "/cr_categories($categoryId)"+}+```++## Complete Sample Data Script++```powershell+# ============================================+# TIER 0: Insert Reference/Lookup Data FIRST+# ============================================++Write-Host "`n=== TIER 0: Processing Reference/Lookup Data ===" -ForegroundColor Magenta++# --- Categories ---+$categoryIds = @{}++$categories = @(+ @{ cr_name = "Services"; cr_description = "Professional services"; cr_displayorder = 1; cr_isactive = $true },+ @{ cr_name = "Packages"; cr_description = "Bundled offerings"; cr_displayorder = 2; cr_isactive = $true },+ @{ cr_name = "Products"; cr_description = "Physical and digital products"; cr_displayorder = 3; cr_isactive = $true }+)++Write-Host "Processing categories..." -ForegroundColor Cyan+foreach ($cat in $categories) {+ $result = New-DataverseRecordIfNotExists -EntitySetName "cr_categories" -Data $cat -NameColumn "cr_name"+ $categoryIds[$cat.cr_name] = $result.Record.cr_categoryid+}++# --- Statuses ---+$statusIds = @{}++$statuses = @(+ @{ cr_name = "New"; cr_displayorder = 1 },+ @{ cr_name = "Reviewed"; cr_displayorder = 2 },+ @{ cr_name = "Responded"; cr_displayorder = 3 },+ @{ cr_name = "Closed"; cr_displayorder = 4 }+)++Write-Host "`nProcessing statuses..." -ForegroundColor Cyan+foreach ($status in $statuses) {+ $result = New-DataverseRecordIfNotExists -EntitySetName "cr_statuses" -Data $status -NameColumn "cr_name"+ $statusIds[$status.cr_name] = $result.Record.cr_statusid+}++# --- Departments ---+$departmentIds = @{}++$departments = @(+ @{ cr_name = "Executive"; cr_code = "EXEC" },+ @{ cr_name = "Engineering"; cr_code = "ENG" },+ @{ cr_name = "Customer Success"; cr_code = "CS" },+ @{ cr_name = "Sales"; cr_code = "SALES" }+)++Write-Host "`nProcessing departments..." -ForegroundColor Cyan+foreach ($dept in $departments) {+ $result = New-DataverseRecordIfNotExists -EntitySetName "cr_departments" -Data $dept -NameColumn "cr_name"+ $departmentIds[$dept.cr_name] = $result.Record.cr_departmentid+}++# ============================================+# TIER 1: Insert Primary Entity Data+# ============================================++Write-Host "`n=== TIER 1: Processing Primary Entity Data ===" -ForegroundColor Magenta++# --- Products (with Category lookup) ---+$productIds = @{}++$products = @(+ @{+ cr_name = "Professional Consultation"+ cr_description = "One-on-one consultation with our expert team."+ cr_price = 299.99+ cr_imageurl = "https://images.unsplash.com/photo-1553877522-43269d4ea984?w=400"+ cr_isactive = $true+ "[email protected]" = "/cr_categories($($categoryIds['Services']))"+ },+ @{+ cr_name = "Enterprise Solution Package"+ cr_description = "Complete enterprise solution with 12 months support."+ cr_price = 4999.99+ cr_imageurl = "https://images.unsplash.com/photo-1460925895917-afdab827c52f?w=400"+ cr_isactive = $true+ "[email protected]" = "/cr_categories($($categoryIds['Packages']))"+ },+ @{+ cr_name = "Starter Kit"+ cr_description = "Perfect for small businesses getting started."+ cr_price = 99.99+ cr_imageurl = "https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=400"+ cr_isactive = $true+ "[email protected]" = "/cr_categories($($categoryIds['Packages']))"+ }+)++Write-Host "Processing products..." -ForegroundColor Cyan+foreach ($product in $products) {+ $result = New-DataverseRecordIfNotExists -EntitySetName "cr_products" -Data $product -NameColumn "cr_name"+ $productIds[$product.cr_name] = $result.Record.cr_productid+}++# --- Team Members (with Department lookup) ---+$teamMemberIds = @{}++$team = @(+ @{+ cr_name = "Emily Rodriguez"+ cr_title = "Chief Executive Officer"+ cr_email = "[email protected]"+ cr_bio = "Emily has over 15 years of experience in technology leadership."+ cr_photourl = "https://images.unsplash.com/photo-1573496359142-b8d87734a5a2?w=300"+ cr_linkedin = "https://linkedin.com/in/emilyrodriguez"+ cr_displayorder = 1+ "[email protected]" = "/cr_departments($($departmentIds['Executive']))"+ },+ @{+ cr_name = "David Kim"+ cr_title = "Chief Technology Officer"+ cr_email = "[email protected]"+ cr_bio = "David brings deep technical expertise from his decade at leading tech companies."+ cr_photourl = "https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=300"+ cr_linkedin = "https://linkedin.com/in/davidkim"+ cr_displayorder = 2+ "[email protected]" = "/cr_departments($($departmentIds['Engineering']))"+ },+ @{+ cr_name = "Lisa Thompson"+ cr_title = "Head of Customer Success"+ cr_email = "[email protected]"+ cr_bio = "Lisa ensures our customers achieve their goals."+ cr_photourl = "https://images.unsplash.com/photo-1580489944761-15a19d654956?w=300"+ cr_linkedin = "https://linkedin.com/in/lisathompson"+ cr_displayorder = 3+ "[email protected]" = "/cr_departments($($departmentIds['Customer Success']))"+ }+)++Write-Host "`nProcessing team members..." -ForegroundColor Cyan+foreach ($member in $team) {+ $result = New-DataverseRecordIfNotExists -EntitySetName "cr_teammembers" -Data $member -NameColumn "cr_name"+ $teamMemberIds[$member.cr_name] = $result.Record.cr_teammemberid+}++# ============================================+# TIER 2: Insert Dependent Data+# ============================================++Write-Host "`n=== TIER 2: Processing Dependent Data ===" -ForegroundColor Magenta++# --- Contact Submissions (with Status lookup) ---+$contacts = @(+ @{+ cr_name = "John Smith"+ cr_email = "[email protected]"+ cr_message = "I'm interested in learning more about your services."+ cr_submissiondate = (Get-Date).ToString("yyyy-MM-ddTHH:mm:ssZ")+ "[email protected]" = "/cr_statuses($($statusIds['New']))"+ },+ @{+ cr_name = "Sarah Johnson"+ cr_email = "[email protected]"+ cr_message = "Looking for a partner for our upcoming project."+ cr_submissiondate = (Get-Date).AddDays(-2).ToString("yyyy-MM-ddTHH:mm:ssZ")+ "[email protected]" = "/cr_statuses($($statusIds['Reviewed']))"+ },+ @{+ cr_name = "Michael Chen"+ cr_email = "[email protected]"+ cr_message = "Questions about pricing and availability."+ cr_submissiondate = (Get-Date).AddDays(-5).ToString("yyyy-MM-ddTHH:mm:ssZ")+ "[email protected]" = "/cr_statuses($($statusIds['Responded']))"+ }+)++Write-Host "Processing contact submissions..." -ForegroundColor Cyan+foreach ($contact in $contacts) {+ New-DataverseRecordIfNotExists -EntitySetName "cr_contactsubmissions" -Data $contact -NameColumn "cr_name"+}++# --- Testimonials (with optional Product lookup) ---+$testimonials = @(+ @{+ cr_name = "Amanda Foster"+ cr_quote = "Their solution increased our efficiency by 40%."+ cr_company = "TechStart Inc."+ cr_role = "Operations Director"+ cr_rating = 5+ cr_photourl = "https://images.unsplash.com/photo-1494790108377-be9c29b29330?w=200"+ cr_isactive = $true+ "[email protected]" = "/cr_products($($productIds['Enterprise Solution Package']))"+ },+ @{+ cr_name = "Robert Martinez"+ cr_quote = "The best investment we've made this year."+ cr_company = "Global Solutions Ltd"+ cr_role = "CEO"+ cr_rating = 5+ cr_photourl = "https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=200"+ cr_isactive = $true+ "[email protected]" = "/cr_products($($productIds['Professional Consultation']))"+ },+ @{+ cr_name = "Jennifer Wu"+ cr_quote = "Delivered beyond expectations. Highly recommend."+ cr_company = "Innovate Partners"+ cr_role = "Managing Partner"+ cr_rating = 5+ cr_photourl = "https://images.unsplash.com/photo-1438761681033-6461ffad8d80?w=200"+ cr_isactive = $true+ # General testimonial - no specific product linked+ }+)++Write-Host "`nProcessing testimonials..." -ForegroundColor Cyan+foreach ($testimonial in $testimonials) {+ New-DataverseRecordIfNotExists -EntitySetName "cr_testimonials" -Data $testimonial -NameColumn "cr_name"+}++Write-Host "`n=== Sample data processing complete ===" -ForegroundColor Green+```++## Verify Data and Relationships++```powershell+# Verify products with their categories (expanded relationship)+Write-Host "Products with Categories:" -ForegroundColor Cyan+$products = Invoke-RestMethod -Uri "$baseUrl/cr_products?`$select=cr_name,cr_price&`$expand=cr_categoryid(`$select=cr_name)" -Headers $headers+$products.value | ForEach-Object {+ Write-Host " $($_.cr_name) - `$$($_.cr_price) - Category: $($_.cr_categoryid.cr_name)"+}++# Verify team members with their departments+Write-Host "`nTeam Members with Departments:" -ForegroundColor Cyan+$members = Invoke-RestMethod -Uri "$baseUrl/cr_teammembers?`$select=cr_name,cr_title&`$expand=cr_departmentid(`$select=cr_name)" -Headers $headers+$members.value | ForEach-Object {+ Write-Host " $($_.cr_name) ($($_.cr_title)) - Dept: $($_.cr_departmentid.cr_name)"+}++# Verify contact submissions with their statuses+Write-Host "`nContact Submissions with Statuses:" -ForegroundColor Cyan+$submissions = Invoke-RestMethod -Uri "$baseUrl/cr_contactsubmissions?`$select=cr_name,cr_email&`$expand=cr_statusid(`$select=cr_name)" -Headers $headers+$submissions.value | ForEach-Object {+ Write-Host " $($_.cr_name) ($($_.cr_email)) - Status: $($_.cr_statusid.cr_name)"+}++# Verify testimonials with their linked products+Write-Host "`nTestimonials with Products:" -ForegroundColor Cyan+$testimonials = Invoke-RestMethod -Uri "$baseUrl/cr_testimonials?`$select=cr_name,cr_company&`$expand=cr_productid(`$select=cr_name)" -Headers $headers+$testimonials.value | ForEach-Object {+ $productName = if ($_.cr_productid) { $_.cr_productid.cr_name } else { "(General)" }+ Write-Host " $($_.cr_name) from $($_.cr_company) - Product: $productName"+}+```++## Update Records++```powershell+function Update-DataverseRecord {+ param(+ [string]$EntitySetName,+ [string]$RecordId,+ [hashtable]$Data+ )++ $body = $Data | ConvertTo-Json -Depth 5+ Invoke-RestMethod -Uri "$baseUrl/$EntitySetName($RecordId)" -Method Patch -Headers $headers -Body $body+}++# Example: Update a product's price+Update-DataverseRecord -EntitySetName "cr_products" -RecordId $productIds['Starter Kit'] -Data @{+ cr_price = 129.99+}+```++## Delete Records++```powershell+function Remove-DataverseRecord {+ param(+ [string]$EntitySetName,+ [string]$RecordId+ )++ Invoke-RestMethod -Uri "$baseUrl/$EntitySetName($RecordId)" -Method Delete -Headers $headers+}++# CAUTION: Delete records in reverse dependency order (TIER 2 -> TIER 1 -> TIER 0)+```diff --git a/plugins/power-pages/skills/setup-dataverse/table-management-reference.md b/plugins/power-pages/skills/setup-dataverse/table-management-reference.mdnew file mode 100644index 000000000..c4dc45434--- /dev/null+++ b/plugins/power-pages/skills/setup-dataverse/table-management-reference.md@@ -0,0 +1,429 @@+# Table Management Reference++This document covers querying, creating, and managing Dataverse tables via the OData Web API.++## Query Existing Custom Tables++Before creating tables, review existing custom tables in the environment:++```powershell+# Get all custom tables (entities) in the environment+$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 Schema Details++```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+}+```++## Compare Existing vs Required 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+}+```++## Find Similar Tables++Search for tables with similar purposes but different names:++```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+}+```++## Check If Table/Column 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+ }+}+```++## Create Table 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+}+```++## 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 " [SKIP] Table '$SchemaName' already exists" -ForegroundColor Yellow+ return @{ Skipped = $true; Reason = "Already exists" }+ }++ Write-Host " [CREATE] Creating table '$SchemaName'..." -ForegroundColor Cyan+ $result = New-DataverseTable -SchemaName $SchemaName -DisplayName $DisplayName `+ -PluralDisplayName $PluralDisplayName -Description $Description `+ -PrimaryColumnName $PrimaryColumnName -PrimaryColumnDisplayName $PrimaryColumnDisplayName++ Write-Host " [OK] Table '$SchemaName' created successfully" -ForegroundColor Green+ return @{ Skipped = $false; Result = $result }+}+```++## Add Column Helper Function++```powershell+function Add-DataverseColumn {+ param(+ [string]$TableName,+ [string]$SchemaName,+ [string]$DisplayName,+ [string]$Type, # String, Email, Url, Memo, Integer, Money, DateTime, Boolean+ [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)+}+```++## 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 " [SKIP] Column '$SchemaName' already exists on '$TableName'" -ForegroundColor Yellow+ return @{ Skipped = $true; Reason = "Already exists" }+ }++ Write-Host " [CREATE] Adding column '$SchemaName' to '$TableName'..." -ForegroundColor Cyan+ $result = Add-DataverseColumn -TableName $TableName -SchemaName $SchemaName `+ -DisplayName $DisplayName -Type $Type -MaxLength $MaxLength++ Write-Host " [OK] Column '$SchemaName' added successfully" -ForegroundColor Green+ return @{ Skipped = $false; Result = $result }+}+```++## Add Choice/Picklist Column++```powershell+function Add-DataversePicklist {+ param(+ [string]$TableName,+ [string]$SchemaName,+ [string]$DisplayName,+ [hashtable[]]$Options # Array of @{ Value = 1; Label = "Option 1" }+ )++ $optionMetadata = $Options | ForEach-Object {+ @{+ "Value" = $_.Value+ "Label" = @{+ "@odata.type" = "Microsoft.Dynamics.CRM.Label"+ "LocalizedLabels" = @(@{+ "@odata.type" = "Microsoft.Dynamics.CRM.LocalizedLabel"+ "Label" = $_.Label+ "LanguageCode" = 1033+ })+ }+ }+ }++ $column = @{+ "@odata.type" = "Microsoft.Dynamics.CRM.PicklistAttributeMetadata"+ "SchemaName" = $SchemaName+ "AttributeType" = "Picklist"+ "DisplayName" = @{+ "@odata.type" = "Microsoft.Dynamics.CRM.Label"+ "LocalizedLabels" = @(@{ "@odata.type" = "Microsoft.Dynamics.CRM.LocalizedLabel"; "Label" = $DisplayName; "LanguageCode" = 1033 })+ }+ "OptionSet" = @{+ "@odata.type" = "Microsoft.Dynamics.CRM.OptionSetMetadata"+ "IsGlobal" = $false+ "OptionSetType" = "Picklist"+ "Options" = $optionMetadata+ }+ }++ Invoke-RestMethod -Uri "$baseUrl/EntityDefinitions(LogicalName='$TableName')/Attributes" -Method Post -Headers $headers -Body ($column | ConvertTo-Json -Depth 10)+}++# Example usage:+# Add-DataversePicklist -TableName "cr_contactsubmission" -SchemaName "cr_status" -DisplayName "Status" -Options @(+# @{ Value = 1; Label = "New" },+# @{ Value = 2; Label = "Reviewed" },+# @{ Value = 3; Label = "Responded" },+# @{ Value = 4; Label = "Closed" }+# )+```++## Common Table Templates++### Product/Service Table++```powershell+New-DataverseTable -SchemaName "cr_product" -DisplayName "Product" -PluralDisplayName "Products" -Description "Products and services offered"++Add-DataverseColumn -TableName "cr_product" -SchemaName "cr_description" -DisplayName "Description" -Type "Memo" -MaxLength 4000+Add-DataverseColumn -TableName "cr_product" -SchemaName "cr_price" -DisplayName "Price" -Type "Money"+Add-DataverseColumn -TableName "cr_product" -SchemaName "cr_imageurl" -DisplayName "Image URL" -Type "Url"+Add-DataverseColumn -TableName "cr_product" -SchemaName "cr_isactive" -DisplayName "Is Active" -Type "Boolean"+```++### Team Member Table++```powershell+New-DataverseTable -SchemaName "cr_teammember" -DisplayName "Team Member" -PluralDisplayName "Team Members" -Description "Team members displayed on the website"++Add-DataverseColumn -TableName "cr_teammember" -SchemaName "cr_title" -DisplayName "Job Title" -Type "String"+Add-DataverseColumn -TableName "cr_teammember" -SchemaName "cr_email" -DisplayName "Email" -Type "Email"+Add-DataverseColumn -TableName "cr_teammember" -SchemaName "cr_bio" -DisplayName "Bio" -Type "Memo" -MaxLength 4000+Add-DataverseColumn -TableName "cr_teammember" -SchemaName "cr_photourl" -DisplayName "Photo URL" -Type "Url"+Add-DataverseColumn -TableName "cr_teammember" -SchemaName "cr_linkedin" -DisplayName "LinkedIn" -Type "Url"+Add-DataverseColumn -TableName "cr_teammember" -SchemaName "cr_displayorder" -DisplayName "Display Order" -Type "Integer"+```++### Testimonial Table++```powershell+New-DataverseTable -SchemaName "cr_testimonial" -DisplayName "Testimonial" -PluralDisplayName "Testimonials" -Description "Customer testimonials and reviews"++Add-DataverseColumn -TableName "cr_testimonial" -SchemaName "cr_quote" -DisplayName "Quote" -Type "Memo" -MaxLength 2000+Add-DataverseColumn -TableName "cr_testimonial" -SchemaName "cr_company" -DisplayName "Company" -Type "String"+Add-DataverseColumn -TableName "cr_testimonial" -SchemaName "cr_role" -DisplayName "Role" -Type "String"+Add-DataverseColumn -TableName "cr_testimonial" -SchemaName "cr_rating" -DisplayName "Rating" -Type "Integer"+Add-DataverseColumn -TableName "cr_testimonial" -SchemaName "cr_photourl" -DisplayName "Photo URL" -Type "Url"+Add-DataverseColumn -TableName "cr_testimonial" -SchemaName "cr_isactive" -DisplayName "Is Active" -Type "Boolean"+```++### Contact Submission Table++```powershell+New-DataverseTable -SchemaName "cr_contactsubmission" -DisplayName "Contact Submission" -PluralDisplayName "Contact Submissions" -Description "Contact form submissions from the website"++Add-DataverseColumn -TableName "cr_contactsubmission" -SchemaName "cr_email" -DisplayName "Email" -Type "Email"+Add-DataverseColumn -TableName "cr_contactsubmission" -SchemaName "cr_message" -DisplayName "Message" -Type "Memo" -MaxLength 4000+Add-DataverseColumn -TableName "cr_contactsubmission" -SchemaName "cr_submissiondate" -DisplayName "Submission Date" -Type "DateTime"+```++### FAQ Table++```powershell+New-DataverseTable -SchemaName "cr_faq" -DisplayName "FAQ" -PluralDisplayName "FAQs" -Description "Frequently asked questions" -PrimaryColumnName "cr_question" -PrimaryColumnDisplayName "Question"++Add-DataverseColumn -TableName "cr_faq" -SchemaName "cr_answer" -DisplayName "Answer" -Type "Memo" -MaxLength 4000+Add-DataverseColumn -TableName "cr_faq" -SchemaName "cr_category" -DisplayName "Category" -Type "String"+Add-DataverseColumn -TableName "cr_faq" -SchemaName "cr_displayorder" -DisplayName "Display Order" -Type "Integer"+Add-DataverseColumn -TableName "cr_faq" -SchemaName "cr_isactive" -DisplayName "Is Active" -Type "Boolean"+```diff --git a/plugins/power-pages/skills/setup-dataverse/troubleshooting.md b/plugins/power-pages/skills/setup-dataverse/troubleshooting.mdnew file mode 100644index 000000000..b811f1f80--- /dev/null+++ b/plugins/power-pages/skills/setup-dataverse/troubleshooting.md@@ -0,0 +1,337 @@+# Troubleshooting++This document covers common issues and solutions when setting up Dataverse tables.++## Existing Table Detection Issues++### Tables not found++- Ensure the filter `IsCustomEntity eq true` is correct for your needs+- Some tables may be managed or system tables that don't appear in custom entity queries++### Wrong publisher prefix++Tables may have different prefixes depending on the solution:++```powershell+# Search for tables with any custom prefix+$allCustomTables = Invoke-RestMethod -Uri "$baseUrl/EntityDefinitions?`$filter=IsCustomEntity eq true" -Headers $headers+$allCustomTables.value | ForEach-Object { Write-Host $_.SchemaName }+```++Common prefixes: `cr_`, `new_`, `contoso_`, `msft_`++### System tables included++Add additional filters to exclude system tables:++```powershell+$filter = "IsCustomEntity eq true and IsManaged eq false"+```++### Case sensitivity++Table logical names are case-insensitive but schema names preserve case. Always use lowercase for logical names in API calls.++## Table Reuse Issues++### Existing table has different schema++If the existing table's schema is too different:++- Consider creating a new table with a unique name (e.g., `cr_site_category` instead of `cr_category`)+- Or extend the existing table and use only the columns you need++### Column type mismatch++Cannot change column types after creation. Options:++- Create a new column with a different name+- Use the existing column type if compatible+- Create an entirely new table++### Relationship conflicts++Verify existing relationships don't prevent your intended lookups:++```powershell+Get-TableRelationships -TableLogicalName "cr_product"+```++### Missing required columns on reused table++Use `Add-DataverseColumnIfNotExists` to add only missing columns without errors.++## Dataverse Web API Errors++### Authentication errors++```text+Error: 401 Unauthorized+```++**Solutions:**++1. Verify Azure CLI is logged in: `az login`+2. Check access token is valid: `az account get-access-token --resource <env-url>`+3. Token may have expired (tokens last ~1 hour), get a fresh one+4. Ensure you're using the correct environment URL++### Permission errors++```text+Error: 403 Forbidden+```++**Solutions:**++Ensure you have appropriate Dataverse permissions:++- **System Administrator** - Full access+- **System Customizer** - Can create and modify tables++### Rate limiting++```text+Error: 429 Too Many Requests+```++**Solutions:**++- Add delays between API calls+- Batch operations where possible+- Retry with exponential backoff++```powershell+function Invoke-WithRetry {+ param(+ [scriptblock]$ScriptBlock,+ [int]$MaxRetries = 3+ )++ $retryCount = 0+ while ($retryCount -lt $MaxRetries) {+ try {+ return & $ScriptBlock+ } catch {+ if ($_.Exception.Response.StatusCode -eq 429) {+ $retryCount+++ $waitTime = [math]::Pow(2, $retryCount)+ Write-Host "Rate limited. Waiting $waitTime seconds..." -ForegroundColor Yellow+ Start-Sleep -Seconds $waitTime+ } else {+ throw+ }+ }+ }+ throw "Max retries exceeded"+}+```++## Table Creation Fails++### Invalid schema name++```text+Error: "The schema name is invalid"+```++**Solutions:**++- Verify schema name uses valid publisher prefix (e.g., `cr_`)+- Schema names must start with a letter+- Only alphanumeric characters and underscores allowed+- Maximum 128 characters++### Table already exists++```text+Error: "Entity with this name already exists"+```++**Solutions:**++- Use `Test-TableExists` before creating+- Use `New-DataverseTableIfNotExists` helper function+- Choose a unique schema name++### Missing required metadata++```text+Error: "Required field missing"+```++**Solutions:**++Ensure all required metadata fields are included:++- `SchemaName`+- `DisplayName` with `LocalizedLabels`+- `DisplayCollectionName` (plural name)+- `PrimaryNameAttribute`++## Relationship/Lookup Creation Fails++### Referenced entity not found++```text+Error: "Referenced entity 'cr_category' not found"+```++**Solutions:**++- Ensure the target table exists BEFORE creating the lookup+- Check creation order: TIER 0 tables must exist before TIER 1, etc.+- Verify the table logical name is correct (case-insensitive)++### Duplicate relationship name++```text+Error: "Relationship with this name already exists"+```++**Solutions:**++- Relationship names must be unique across the environment+- Use a consistent naming pattern: `{publisher}_{targettable}_{sourcetable}`+- Use `Test-RelationshipExists` before creating++### Invalid target entity++```text+Error: "Invalid target entity for relationship"+```++**Solutions:**++- The target table must have a primary key attribute+- Ensure the table is not a virtual entity or external data source++### Self-referential lookup fails++**Solution:** Create the table first, then add the self-lookup as a separate step:++```powershell+# Step 1: Create table+New-DataverseTable -SchemaName "cr_employee" ...++# Step 2: Add self-referential lookup (table now exists)+Add-DataverseLookup -SourceTable "cr_employee" -TargetTable "cr_employee" ...+```++## Sample Data Insertion Fails++### Foreign key violation++```text+Error: "The specified lookup reference does not exist"+```++**Solutions:**++- 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++```text+Error: "Invalid @odata.bind value"+```++**Solutions:**++Format must be exactly: `/entitysetname(guid)`++```powershell+# Correct+"[email protected]" = "/cr_categories(12345678-1234-1234-1234-123456789012)"++# Wrong - missing leading slash+"[email protected]" = "cr_categories(12345678-1234-1234-1234-123456789012)"++# Wrong - using logical name instead of entity set name+"[email protected]" = "/cr_category(12345678-1234-1234-1234-123456789012)"+```++### Entity set not found++```text+Error: "Resource not found for segment 'cr_product'"+```++**Solutions:**++Use the plural entity set name, not the logical name:++- Table `cr_product` has entity set `cr_products` (usually adds 's')+- Table `cr_category` has entity set `cr_categories` (adds 'ies')++Find the correct entity set name:++```powershell+$table = Invoke-RestMethod -Uri "$baseUrl/EntityDefinitions(LogicalName='cr_product')?`$select=EntitySetName" -Headers $headers+Write-Host "Entity set name: $($table.EntitySetName)"+```++### Duplicate record errors++If using `New-DataverseRecordIfNotExists`, records with the same name are skipped. If inserts still fail:++- Check for unique constraints on other columns+- Verify the name column matches your expectation++## Existing Data Conflicts++### Stale record IDs++If reusing tables, always query for current record IDs; don't use cached values:++```powershell+# Always get fresh IDs before inserting dependent records+$categories = Invoke-RestMethod -Uri "$baseUrl/cr_categories?`$select=cr_categoryid,cr_name" -Headers $headers+$categoryIds = @{}+$categories.value | ForEach-Object { $categoryIds[$_.cr_name] = $_.cr_categoryid }+```++### Data format differences++Existing records may have different formats:++- Dates: Use ISO 8601 format `yyyy-MM-ddTHH:mm:ssZ`+- Currency: Ensure correct decimal precision+- Text: Check MaxLength constraints++### Orphaned lookups++When reusing tables, verify that lookup values still exist:++```powershell+# Check for orphaned references+$products = Invoke-RestMethod -Uri "$baseUrl/cr_products?`$select=cr_name&`$expand=cr_categoryid(`$select=cr_name)" -Headers $headers+$products.value | Where-Object { $_.cr_categoryid -eq $null } | ForEach-Object {+ Write-Host "Orphaned product (no category): $($_.cr_name)" -ForegroundColor Yellow+}+```++## 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/power-pages/skills/setup-webapi/SKILL.mdsimilarity index 60%rename from plugins/skills/setup-webapi/SKILL.mdrename to plugins/power-pages/skills/setup-webapi/SKILL.mdindex 4936e23fc..5ca8b43e1 100644--- a/plugins/skills/setup-webapi/SKILL.md+++ b/plugins/power-pages/skills/setup-webapi/SKILL.md@@ -1,5 +1,5 @@----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.+description: Configure Web API access, table permissions, entity permissions, and web roles for Power Pages. Use this skill when you need to set up table permissions, create entity permissions, configure web roles, enable API access, set CRUD permissions (read/write/create/delete), create site settings for Web API, or update frontend code to fetch data from Dataverse tables.user-invocable: trueallowed-tools: Bash(pac:*), Bash(az:*), Bash(dotnet:*)model: sonnet@@ -16,6 +16,7 @@ This skill uses modular reference files for detailed instructions:| File | Purpose ||------|---------|| [site-settings-reference.md](./site-settings-reference.md) | YAML format, naming conventions, PowerShell scripts |+| [web-roles-reference.md](./web-roles-reference.md) | Web role selection, creation, and user assignment || [table-permissions-reference.md](./table-permissions-reference.md) | Dataverse API for entity permissions, scopes, web roles || [frontend-integration-reference.md](./frontend-integration-reference.md) | Web API service code, React hooks, component patterns || [troubleshooting.md](./troubleshooting.md) | Common issues and solutions |@@ -51,16 +52,26 @@ This skill uses a **memory bank** (`memory-bank.md`) to persist context across sβββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ-β STEP 3: Create Table Permissions β+β STEP 3: Create Web Roles β+β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β+β β’ Determine required web roles based on site features β+β β’ Verify default roles exist (Anonymous, Authenticated, Administrators) β+β β’ Create custom roles if needed (Customers, Partners, etc.) β+β π See: web-roles-reference.md β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+ β+βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+β STEP 4: Create Table Permissions ββ βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ ββ β’ Create entity permission records for Web API access ββ β’ Configure scope (Global/Parent/Self) based on requirements ββ β’ Set appropriate CRUD permissions β+β β’ Associate permissions with web roles from Step 3 ββ π See: table-permissions-reference.md ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ-β STEP 4: Update Frontend Code β+β STEP 5: Update Frontend Code ββ βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ ββ β’ Create API service/utility for /_api calls ββ β’ Update components to fetch data dynamically β@@ -70,7 +81,7 @@ This skill uses a **memory bank** (`memory-bank.md`) to persist context across sβββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ-β STEP 5: Build and Upload β+β STEP 6: Build and Upload ββ βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ ββ β’ Build the project ββ β’ Upload to Power Pages β@@ -158,40 +169,91 @@ For each table that needs Web API access, create two site setting files:----## STEP 3: Create Table Permissions+## STEP 3: Create Web Roles++**π Detailed reference: [web-roles-reference.md](./web-roles-reference.md)**++### Quick Summary++Web roles define user groups with specific access levels. They must be created **before** table permissions because permissions are linked to roles.++### Key Points++- **Anonymous Users**: Unauthenticated visitors (public content, read-only)+- **Authenticated Users**: Signed-in users (member features, form submissions)+- **Administrators**: Full site management access+- **Custom roles**: Create for specific user groups (Customers, Partners, Employees)++### Determine Required Roles++Use this decision matrix:++| Site Feature | Required Role |+|--------------|---------------|+| Public landing page, product catalog | Anonymous Users |+| Contact form submission | Anonymous Users (create-only) |+| User dashboard, profile | Authenticated Users |+| Order history, support tickets | Custom role (e.g., Customers) |+| Partner portal | Custom role (e.g., Partners) |+| Admin panel | Administrators |++### Actions++1. Get environment URL and token (same as Step 2)+2. Get Website ID from memory bank or `pac pages list`+3. Verify default roles exist using `Get-WebRoles` function+4. Create custom roles if needed using `New-WebRole` function+5. Record role IDs for use in Step 4 (table permissions)++### Example: Create Custom Roles++```powershell+# For a customer portal+$customerRoleId = New-WebRole -Name "Customers" -WebsiteId $websiteId -Description "Registered customers"++# For a partner portal+$partnerRoleId = New-WebRole -Name "Partners" -WebsiteId $websiteId -Description "Business partners"+```++---++## STEP 4: Create Table Permissions**π Detailed reference: [table-permissions-reference.md](./table-permissions-reference.md)**### Quick Summary-Table permissions control which users can access data. Create via Dataverse API.+Table permissions control which users can access data. Create via Dataverse API and link to web roles from Step 3.### Key Points- Use **Global scope** for public data (products, FAQs)- Use **Self scope** for user-specific data-- Link permissions to appropriate web roles:+- Link permissions to appropriate web roles created in Step 3:- **Anonymous Users** for public access- **Authenticated Users** for logged-in users+ - **Custom roles** for specific user groups### Common Patterns-| Data Type | Scope | Permissions |-|-----------|-------|-------------|-| Public content | Global | Read only |-| Form submissions | Global | Create only |-| User profiles | Self | Read, Write |+| Data Type | Scope | Permissions | Web Role |+|-----------|-------|-------------|----------|+| Public content | Global | Read only | Anonymous Users |+| Form submissions | Global | Create only | Anonymous Users |+| User profiles | Self | Read, Write | Authenticated Users |+| Orders | Contact | Read, Write | Customers (custom) |### Actions1. Get environment URL and token2. Get Website ID from memory bank or `pac pages list`-3. Create permissions using `New-TablePermission` function-4. Associate permissions with web roles+3. Get web role IDs from Step 3 or using `Get-WebRoleId` function+4. Create permissions using `New-TablePermission` function+5. Associate permissions with web roles----## STEP 4: Update Frontend Code+## STEP 5: Update Frontend Code**π Detailed reference: [frontend-integration-reference.md](./frontend-integration-reference.md)**@@ -199,12 +261,15 @@ Table permissions control which users can access data. Create via Dataverse API.Update the frontend to use Power Pages Web API instead of mock data.+**CRITICAL**: This step is NOT complete until ALL mock/static data has been replaced with Web API calls. Do not proceed to Step 6 until verification is complete.+### Key Points-- Create `dataverseApi.ts` service with CRUD operations+- Create `webApi.ts` service with CRUD operations- Implement CSRF token handling for write operations- Create typed wrappers for each entity- Replace **ALL** static/mock data with API calls+- **VERIFY** no hardcoded data remains### CSRF Token Requirement@@ -212,25 +277,61 @@ POST, PATCH, DELETE requests require `__RequestVerificationToken` header. The re### Actions-1. Create `src/services/dataverseApi.ts` (copy from reference)+1. Create `src/services/webApi.ts` (copy from reference)2. Create type definitions for your entities3. 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+4. Optionally create `useWebApi` React hook+5. **Systematically search for ALL mock data** (see below)+6. Update each component to use Web API+7. **Delete mock data files/folders** after replacement+8. **Run verification checks** before proceeding-### Mock Data Checklist+### Mock Data Search (REQUIRED)-Search these locations for mock data to replace:+You MUST search for and replace ALL mock data. Use these searches:-- [ ] `src/data/` or `src/mock/` folders-- [ ] Constants files with hardcoded arrays-- [ ] Component files with inline data-- [ ] JSON files used as data sources+```powershell+# 1. Find mock data folders+Get-ChildItem -Path ./src -Directory -Recurse | Where-Object { $_.Name -match "^(mock|data|fixtures|fake|dummy)$" }++# 2. Find data files+Get-ChildItem -Path ./src -Recurse -Include "*.data.ts","*.data.js","*mock*.ts","*mock*.js"++# 3. Find inline array declarations (review each match)+Select-String -Path "src\**\*.ts","src\**\*.tsx" -Pattern "const\s+\w+\s*=\s*\[" | Where-Object { $_.Line -match "\{" }++# 4. Find JSON imports+Select-String -Path "src\**\*.ts","src\**\*.tsx" -Pattern "from ['\"].*\.json['\"]"+```++### Mock Data Verification (REQUIRED)++Before proceeding to Step 6, verify:++- [ ] No `src/data/` or `src/mock/` folders exist (or are empty)+- [ ] No `*.data.ts` or `*mock*.ts` files remain with active exports+- [ ] No components have inline hardcoded arrays for configured tables+- [ ] No JSON files are imported as data sources for configured tables+- [ ] All components displaying data use the `webApi` service+- [ ] All form components use the `webApi` service for submissions++**If any mock data remains, replace it before continuing.**++### Entity-Specific Checklist++For each table configured for Web API, verify:++| Table | Mock Data Replaced | Component Updated | Verified Working |+|-------|-------------------|-------------------|------------------|+| Products | [ ] | [ ] | [ ] |+| Team Members | [ ] | [ ] | [ ] |+| Testimonials | [ ] | [ ] | [ ] |+| FAQs | [ ] | [ ] | [ ] |+| Contact Form | [ ] | [ ] | [ ] |----## STEP 5: Build and Upload+## STEP 6: Build and Upload### Build the Project@@ -240,6 +341,36 @@ npm install # if needednpm run build```+### Confirm Connected Account++**IMPORTANT**: Before uploading, you MUST confirm which account the user is connected with.++1. Run the following command to show the connected account:++```powershell+pac auth list+```++2. Display the connected account information to the user, including:+ - The active profile (marked with `*`)+ - The environment URL+ - The user email/account++3. Use the `AskUserQuestion` tool to confirm:++| Question | Options |+|----------|---------|+| **You are about to upload the site to the account shown above. Do you want to proceed?** | **Yes, upload to this account** - Proceed with the upload; **No, let me switch accounts** - User will run `pac auth create` to connect to a different account |++4. **Only proceed with upload after the user confirms.** If the user selects "No", guide them to authenticate to the correct account:++```powershell+# Create new authentication profile+pac auth create+```++Then run `pac auth list` again to verify and ask for confirmation again.+### Upload to Power Pages```powershell@@ -271,6 +402,14 @@ fetch('/_api/cr_products')---+## STEP 7: Cleanup Helper Files++**π See: [cleanup-reference.md](${CLAUDE_PLUGIN_ROOT}/shared/cleanup-reference.md)**++Remove any temporary helper files created during this skill's execution. Verify the setup is working before cleanup.++---+## Update Memory BankAfter completing this skill, update `memory-bank.md`:@@ -279,6 +418,7 @@ After completing this skill, update `memory-bank.md`:### /setup-webapi- [x] Site settings folder created- [x] Web API enabled for tables: [LIST]+- [x] Web roles verified/created- [x] Table permissions created- [x] Frontend code updated with Web API service- [x] All mock/static data replaced with Web API calls@@ -295,6 +435,15 @@ After completing this skill, update `memory-bank.md`:| Webapi/cr_product/enabled | true | Webapi-cr_product-enabled.sitesetting.yml || [ADD MORE AS CREATED] |+### Web Roles++| Role Name | Role ID | Type |+|-----------|---------|------|+| Anonymous Users | [GUID] | Default |+| Authenticated Users | [GUID] | Default |+| Customers | [GUID] | Custom |+| [ADD MORE AS CREATED] |+### Table Permissions| Table | Scope | Permissions | Web Role |@@ -306,7 +455,7 @@ After completing this skill, update `memory-bank.md`:| File | Changes ||------|---------|-| src/services/dataverseApi.ts | Created Web API service |+| src/services/webApi.ts | Created Power Pages Web API service || [ADD MORE AS MODIFIED] |### Removed/Replaced Mock Datadiff --git a/plugins/skills/setup-webapi/frontend-integration-reference.md b/plugins/power-pages/skills/setup-webapi/frontend-integration-reference.mdsimilarity index 61%rename from plugins/skills/setup-webapi/frontend-integration-reference.mdrename to plugins/power-pages/skills/setup-webapi/frontend-integration-reference.mdindex c9e6b613d..27e48285c 100644--- a/plugins/skills/setup-webapi/frontend-integration-reference.md+++ b/plugins/power-pages/skills/setup-webapi/frontend-integration-reference.md@@ -30,11 +30,11 @@ DELETE /_api/cr_products(<guid>) # Delete product- GET requests do not require this token- The token may expire, so handle 403 errors by refreshing the token-## Dataverse API Service (TypeScript)+## Power Pages Web API Service (TypeScript)Create a reusable API service for Web API calls.-**File: `src/services/dataverseApi.ts`**+**File: `src/services/webApi.ts`**```typescript// Power Pages Web API Service@@ -158,7 +158,7 @@ function buildQueryString(options: QueryOptions): string {}// Generic CRUD operations-export const dataverseApi = {+export const webApi = {// GET all recordsasync getAll<T>(entitySet: string, options: QueryOptions = {}): Promise<T[]> {const queryString = buildQueryString(options);@@ -199,37 +199,60 @@ export const dataverseApi = {## Entity-Specific Services-Create typed wrappers for each entity:+Create typed wrappers for each entity.++**IMPORTANT**: Always include `$select` with the fields configured in site settings. Power Pages Web API returns an error if you request fields not listed in the `Webapi/<table>/fields` site setting. Omitting `$select` attempts to fetch all fields, which fails.```typescript// Entity-specific services+// IMPORTANT: The 'select' array must match the fields in your Webapi/<table>/fields site setting+export const productsApi = {getAll: (options?: QueryOptions) =>- dataverseApi.getAll<Product>('cr_products', options),+ webApi.getAll<Product>('cr_products', {+ select: ['cr_productid', 'cr_name', 'cr_description', 'cr_price', 'cr_category', 'cr_imageurl', 'cr_isactive'],+ ...options,+ }),getById: (id: string) =>- dataverseApi.getById<Product>('cr_products', id),+ webApi.getById<Product>('cr_products', id, {+ select: ['cr_productid', 'cr_name', 'cr_description', 'cr_price', 'cr_category', 'cr_imageurl', 'cr_isactive'],+ }),getActive: () =>- dataverseApi.getAll<Product>('cr_products', { filter: 'cr_isactive eq true', orderBy: 'cr_name' }),+ webApi.getAll<Product>('cr_products', {+ select: ['cr_productid', 'cr_name', 'cr_description', 'cr_price', 'cr_category', 'cr_imageurl', 'cr_isactive'],+ filter: 'cr_isactive eq true',+ orderBy: 'cr_name',+ }),};export const teamMembersApi = {getAll: () =>- dataverseApi.getAll<TeamMember>('cr_teammembers', { orderBy: 'cr_displayorder' }),+ webApi.getAll<TeamMember>('cr_teammembers', {+ select: ['cr_teammemberid', 'cr_name', 'cr_title', 'cr_email', 'cr_bio', 'cr_photourl', 'cr_linkedin', 'cr_displayorder'],+ orderBy: 'cr_displayorder',+ }),};export const testimonialsApi = {getActive: () =>- dataverseApi.getAll<Testimonial>('cr_testimonials', { filter: 'cr_isactive eq true' }),+ webApi.getAll<Testimonial>('cr_testimonials', {+ select: ['cr_testimonialid', 'cr_name', 'cr_quote', 'cr_company', 'cr_role', 'cr_rating', 'cr_photourl', 'cr_isactive'],+ filter: 'cr_isactive eq true',+ }),};export const faqsApi = {getActive: () =>- dataverseApi.getAll<FAQ>('cr_faqs', { filter: 'cr_isactive eq true', orderBy: 'cr_displayorder' }),+ webApi.getAll<FAQ>('cr_faqs', {+ select: ['cr_faqid', 'cr_question', 'cr_answer', 'cr_category', 'cr_displayorder', 'cr_isactive'],+ filter: 'cr_isactive eq true',+ orderBy: 'cr_displayorder',+ }),};export const contactApi = {submit: (data: ContactSubmission) =>- dataverseApi.create<ContactSubmission>('cr_contactsubmissions', {+ webApi.create<ContactSubmission>('cr_contactsubmissions', {...data,cr_submissiondate: new Date().toISOString(),cr_status: 1, // New@@ -292,11 +315,11 @@ export interface ContactSubmission {## React Hook for Data Fetching-**File: `src/hooks/useDataverse.ts`**+**File: `src/hooks/useWebApi.ts`**```typescriptimport { useState, useEffect, useCallback } from 'react';-import { dataverseApi, QueryOptions } from '../services/dataverseApi';+import { webApi, QueryOptions } from '../services/webApi';interface UseDataverseResult<T> {data: T[];@@ -305,7 +328,7 @@ interface UseDataverseResult<T> {refetch: () => Promise<void>;}-export function useDataverse<T>(+export function useWebApi<T>(entitySet: string,options: QueryOptions = {},deps: any[] = []@@ -318,7 +341,7 @@ export function useDataverse<T>(setLoading(true);setError(null);try {- const result = await dataverseApi.getAll<T>(entitySet, options);+ const result = await webApi.getAll<T>(entitySet, options);setData(result);} catch (err) {setError(err instanceof Error ? err.message : 'Failed to fetch data');@@ -335,7 +358,7 @@ export function useDataverse<T>(}// Usage example:-// const { data: products, loading, error } = useDataverse<Product>('cr_products', { filter: 'cr_isactive eq true' });+// const { data: products, loading, error } = useWebApi<Product>('cr_products', { filter: 'cr_isactive eq true' });```## Component Examples@@ -365,7 +388,7 @@ function ProductList() {```tsximport { useState, useEffect } from 'react';-import { productsApi, Product } from '../services/dataverseApi';+import { productsApi, Product } from '../services/webApi';function ProductList() {const [products, setProducts] = useState<Product[]>([]);@@ -403,7 +426,7 @@ function ProductList() {```tsximport { useState } from 'react';-import { contactApi, ContactSubmission } from '../services/dataverseApi';+import { contactApi, ContactSubmission } from '../services/webApi';function ContactForm() {const [formData, setFormData] = useState<ContactSubmission>({@@ -486,22 +509,173 @@ function ContactForm() {}```-## Mock Data Replacement Checklist+## Mock Data Replacement Guide++**CRITICAL**: The Web API setup is NOT complete until ALL mock/static data has been replaced with Web API calls. This section provides systematic instructions to find and replace every instance.++### Step 1: Search for Mock Data Files++Search for dedicated mock data files and folders:++```bash+# Find common mock data folders+find . -type d -name "mock*" -o -name "data" -o -name "fixtures" -o -name "fake*" -o -name "dummy*" 2>/dev/null++# Find data files+find . -type f \( -name "*.data.ts" -o -name "*.data.js" -o -name "*mock*.ts" -o -name "*mock*.js" -o -name "*.json" \) -path "*/src/*" 2>/dev/null+```++**PowerShell equivalent:**+```powershell+# Find mock data folders+Get-ChildItem -Path . -Directory -Recurse | Where-Object { $_.Name -match "mock|data|fixtures|fake|dummy" }++# Find data files in src+Get-ChildItem -Path ./src -Recurse -Include "*.data.ts","*.data.js","*mock*.ts","*mock*.js","*.json"+```++### Step 2: Search for Inline Mock Data Patterns++Search for common patterns that indicate hardcoded data:++```bash+# Arrays of objects (common mock data pattern)+grep -rn "^\s*\[\s*{" --include="*.ts" --include="*.tsx" --include="*.js" --include="*.jsx" src/++# Const arrays with data+grep -rn "const.*=\s*\[" --include="*.ts" --include="*.tsx" src/++# Export const arrays+grep -rn "export const.*\[\|export default \[" --include="*.ts" --include="*.tsx" src/+```++**PowerShell equivalent:**+```powershell+# Search for array declarations that look like mock data+Select-String -Path "src\**\*.ts","src\**\*.tsx" -Pattern "const\s+\w+\s*=\s*\[" | Where-Object { $_.Line -notmatch "useState|useEffect" }++# Search for exported arrays+Select-String -Path "src\**\*.ts","src\**\*.tsx" -Pattern "export (const|default)\s+.*\["+```-When integrating Web APIs, you must replace **all** mock/static data:+### Step 3: Identify Data by Entity Type-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**+For each table configured for Web API, search for related mock data:++| Table | Search Patterns |+|-------|-----------------|+| Products | `product`, `products`, `item`, `items`, `catalog` |+| Team Members | `team`, `member`, `staff`, `employee`, `people` |+| Testimonials | `testimonial`, `review`, `feedback`, `quote` |+| FAQs | `faq`, `question`, `answer`, `help` |+| Contact | `contact`, `submission`, `inquiry`, `message` |++**Example search:**+```powershell+# Find all references to products data+Select-String -Path "src\**\*.ts","src\**\*.tsx" -Pattern "products?\s*[:=]?\s*\[" -CaseSensitive:$false+```++### Step 4: Replace Each Instance++For each mock data instance found:++**Before (mock data):**+```typescript+// src/data/products.ts+export const products = [+ { id: 1, name: 'Widget', price: 29.99 },+ { id: 2, name: 'Gadget', price: 49.99 },+];++// src/components/ProductList.tsx+import { products } from '../data/products';++function ProductList() {+ return products.map(p => <ProductCard key={p.id} product={p} />);+}+```++**After (Web API):**+```typescript+// src/components/ProductList.tsx+import { useState, useEffect } from 'react';+import { productsApi, Product } from '../services/webApi';++function ProductList() {+ const [products, setProducts] = useState<Product[]>([]);+ const [loading, setLoading] = useState(true);++ useEffect(() => {+ // productsApi.getActive() already includes $select with allowed fields+ productsApi.getActive().then(setProducts).finally(() => setLoading(false));+ }, []);++ if (loading) return <LoadingSpinner />;+ return products.map(p => <ProductCard key={p.cr_productid} product={p} />);+}+```++### Step 5: Delete or Archive Mock Data Files++After replacing all usages:++1. **Delete mock data files** that are no longer imported anywhere+2. **Remove mock data folders** if empty+3. **Update any barrel exports** (index.ts files) that re-exported mock data++```powershell+# Verify no imports remain for a mock file before deleting+Select-String -Path "src\**\*.ts","src\**\*.tsx" -Pattern "from ['\"].*products\.data"++# If no results, safe to delete+Remove-Item -Path "src\data\products.data.ts"+```++### Step 6: Verify Complete Replacement++**IMPORTANT**: Run these verification checks before marking the skill complete:++```powershell+# 1. Check for any remaining mock/data folders+Get-ChildItem -Path ./src -Directory -Recurse | Where-Object { $_.Name -match "^(mock|data|fixtures|fake|dummy)$" }++# 2. Check for suspicious const array declarations (review each match)+Select-String -Path "src\**\*.ts","src\**\*.tsx" -Pattern "const\s+\w+\s*:\s*\w+\[\]\s*=\s*\[" | Where-Object { $_.Line -match "\{" }++# 3. Check for JSON imports that might be mock data+Select-String -Path "src\**\*.ts","src\**\*.tsx" -Pattern "from ['\"].*\.json['\"]"++# 4. Verify all components use the webApi service+Select-String -Path "src\**\*.ts","src\**\*.tsx" -Pattern "webApi|productsApi|teamMembersApi|testimonialsApi|faqsApi|contactApi"+```### 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+| Location | Description | Action |+|----------|-------------|--------|+| `src/data/` | Dedicated data folder | Replace all, then delete folder |+| `src/mock/` | Mock data folder | Replace all, then delete folder |+| `src/constants/` | May contain data arrays | Review and replace data arrays |+| `src/fixtures/` | Test fixtures with data | Replace with API calls or test mocks |+| `*.json` in src | JSON data files | Replace imports with API calls |+| Component files | Inline const arrays | Move to useEffect with API calls |+| Context providers | Initial state with data | Initialize empty, fetch in useEffect |++### Mock Data Replacement Tracking++Track replacements in the memory bank:++```markdown+### Removed/Replaced Mock Data++| Location | Description | Replaced With | Verified |+|----------|-------------|---------------|----------|+| src/data/products.ts | Static product array | productsApi.getActive() | β |+| src/data/team.ts | Team member list | teamMembersApi.getAll() | β |+| src/components/FAQ.tsx | Inline FAQ array | faqsApi.getActive() | β |+| src/data/ folder | Mock data folder | DELETED | β |+```## OData Query Referencediff --git a/plugins/skills/setup-webapi/site-settings-reference.md b/plugins/power-pages/skills/setup-webapi/site-settings-reference.mdsimilarity index 73%rename from plugins/skills/setup-webapi/site-settings-reference.mdrename to plugins/power-pages/skills/setup-webapi/site-settings-reference.mdindex 58abf242c..438db370d 100644--- a/plugins/skills/setup-webapi/site-settings-reference.md+++ b/plugins/power-pages/skills/setup-webapi/site-settings-reference.md@@ -1,10 +1,10 @@# Site Settings Reference-This document describes how to create and configure site settings for Power Pages Web API access.+This document describes how to create and configure site settings for Power Pages code sites.## 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.+Site settings in Power Pages code sites are stored in the `.powerpages-site/site-settings` folder. Each setting is a separate YAML file with a unique ID.```text<PROJECT_ROOT>/@@ -22,32 +22,69 @@ Site settings in Power Pages are stored in the `.powerpages-site/site-settings`Each site setting file follows this YAML format:```yaml+description: <OPTIONAL_DESCRIPTION>id: <UUID>name: <SETTING_NAME>value: <SETTING_VALUE>```+**Important**: Field names do NOT include the `adx_` prefix (e.g., use `name` not `adx_name`).++### YAML Field Reference++| Field | Type | Required | Description |+|-------|------|----------|-------------|+| `id` | GUID | Yes | Unique identifier for this setting |+| `name` | string | Yes | Setting name (key) |+| `value` | string | Yes | Setting value |+| `description` | string | No | Optional description of the setting |+**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`+### Generating Unique IDs++Each site setting must have a unique `id` field (UUID/GUID format: `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx`).++**When creating YAML files directly**: Generate a valid UUID where each `x` is a hexadecimal character (0-9, a-f).++**PowerShell**:+```powershell+[guid]::NewGuid().ToString()+```++**Bash/Linux/Mac**:+```bash+uuidgen | tr '[:upper:]' '[:lower:]'+```++**Python**:+```python+import uuid+print(str(uuid.uuid4()))+```+## Required Site Settings for Each TableFor each table that needs Web API access, create these settings:### 1. Enable Web API for Table+**File**: `.powerpages-site/site-settings/Webapi-<TABLE_LOGICAL_NAME>-enabled.sitesetting.yml`+```yaml-# File: <PROJECT_ROOT>/.powerpages-site/site-settings/Webapi-<TABLE_LOGICAL_NAME>-enabled.sitesetting.yml+description: Enable Web API access for the tableid: <GENERATE_UUID>name: Webapi/<TABLE_LOGICAL_NAME>/enabled-value: true # Boolean, not string+value: true```**Example** for `cr_product` table:+**File**: `.powerpages-site/site-settings/Webapi-cr_product-enabled.sitesetting.yml````yaml-# File: Webapi-cr_product-enabled.sitesetting.yml+description: Enable Web API access for the cr_product tableid: a1b2c3d4-e5f6-7890-abcd-ef1234567890name: Webapi/cr_product/enabledvalue: true@@ -57,8 +94,10 @@ value: true**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.+**File**: `.powerpages-site/site-settings/Webapi-<TABLE_LOGICAL_NAME>-fields.sitesetting.yml`+```yaml-# File: <PROJECT_ROOT>/.powerpages-site/site-settings/Webapi-<TABLE_LOGICAL_NAME>-fields.sitesetting.yml+description: Allowed fields for Web API accessid: <GENERATE_UUID>name: Webapi/<TABLE_LOGICAL_NAME>/fieldsvalue: cr_name,cr_description,cr_price,cr_imageurl,cr_isactive@@ -70,11 +109,13 @@ Specify comma-separated field logical names that your frontend actually needs.For debugging purposes, enable detailed error messages:+**File**: `.powerpages-site/site-settings/Webapi-error-innererror.sitesetting.yml`+```yaml-# File: Webapi-error-innererror.sitesetting.yml+description: Enable detailed error messages for debuggingid: <GENERATE_UUID>name: Webapi/error/innererror-value: true # Boolean, not string+value: true```**IMPORTANT**: Disable this in production by setting value to `false` or removing the setting.@@ -110,8 +151,9 @@ function New-WebApiSiteSettings {$enabledUuid = [guid]::NewGuid().ToString()$fieldsUuid = [guid]::NewGuid().ToString()- # Create enabled setting (value is boolean true, not string "true")+ # Create enabled setting$enabledContent = @"+description: Enable Web API access for $TableLogicalName tableid: $enabledUuidname: Webapi/$TableLogicalName/enabledvalue: true@@ -123,6 +165,7 @@ value: true# Create fields setting$fieldsContent = @"+description: Allowed fields for $TableLogicalName Web API accessid: $fieldsUuidname: Webapi/$TableLogicalName/fieldsvalue: $Fields@@ -173,12 +216,13 @@ function New-WebApiErrorSetting {$siteSettingsPath = Join-Path $ProjectRoot ".powerpages-site\site-settings"$errorUuid = [guid]::NewGuid().ToString()+ $enabledValue = if ($Enabled) { "true" } else { "false" }- # Value is boolean true/false, not string$errorContent = @"+description: Enable detailed error messages for debuggingid: $errorUuidname: Webapi/error/innererror-value: $($Enabled.ToString().ToLower())+value: $enabledValue"@$errorFileName = "Webapi-error-innererror.sitesetting.yml"$errorPath = Join-Path $siteSettingsPath $errorFileName@@ -204,6 +248,9 @@ Before uploading:- [ ] All YAML files have valid syntax- [ ] Each file has a unique UUID for the `id` field+- [ ] Fields are alphabetically sorted in the YAML file- [ ] File extensions are `.yml` (not `.yaml`)+- [ ] Field names do NOT include `adx_` prefix+- [ ] Boolean values are unquoted (`true` not `"true"`)- [ ] Field lists use explicit names (no wildcards)- [ ] Error setting is disabled for productiondiff --git a/plugins/skills/setup-webapi/table-permissions-reference.md b/plugins/power-pages/skills/setup-webapi/table-permissions-reference.mdsimilarity index 58%rename from plugins/skills/setup-webapi/table-permissions-reference.mdrename to plugins/power-pages/skills/setup-webapi/table-permissions-reference.mdindex 9985927bd..9bd61a3d8 100644--- a/plugins/skills/setup-webapi/table-permissions-reference.md+++ b/plugins/power-pages/skills/setup-webapi/table-permissions-reference.md@@ -72,7 +72,11 @@ function New-TablePermission {[bool]$AppendTo = $false)+ # Generate unique ID for the permission+ $permissionId = [guid]::NewGuid().ToString()+$permission = @{+ "adx_entitypermissionid" = $permissionId"adx_entityname" = $TableLogicalName"adx_entitylogicalname" = $TableLogicalName"adx_scope" = $Scope@@ -89,8 +93,11 @@ function New-TablePermission {try {$result = Invoke-RestMethod -Uri "$baseUrl/adx_entitypermissions" -Method Post -Headers $headers -Body $body- Write-Host "Created table permission for: $TableLogicalName"- return $result+ Write-Host "Created table permission for: $TableLogicalName (ID: $permissionId)"+ return @{+ "Id" = $permissionId+ "Result" = $result+ }}catch {Write-Host "Error creating permission for $TableLogicalName : $_"@@ -159,31 +166,89 @@ New-TablePermission -Name "Admin Orders" `Table permissions must be linked to web roles to take effect.-### Get Anonymous Users Role+### Get or Create Web Role++**IMPORTANT**: Always use `mspp_webroles` (not `adx_webroles`) for fetching web role IDs. If the role doesn't exist, create it first before proceeding with table permissions.```powershell-# 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+function Get-OrCreateWebRole {+ param(+ [Parameter(Mandatory=$true)]+ [string]$RoleName,+ [Parameter(Mandatory=$true)]+ [string]$WebsiteId,+ [string]$Description = ""+ )++ # Try to get existing role using mspp_webroles+ try {+ $existingRole = Invoke-RestMethod `+ -Uri "$baseUrl/mspp_webroles?`$filter=mspp_name eq '$RoleName' and _mspp_websiteid_value eq $WebsiteId&`$select=mspp_webroleid" `+ -Headers $headers++ if ($existingRole.value.Count -gt 0) {+ $roleId = $existingRole.value[0].mspp_webroleid+ Write-Host "Found existing web role '$RoleName' with ID: $roleId"+ return $roleId+ }+ }+ catch {+ Write-Host "Error checking for existing role: $_"+ }++ # Role doesn't exist - create it+ Write-Host "Web role '$RoleName' not found. Creating..."++ $newRoleId = [guid]::NewGuid().ToString()+ $webRole = @{+ "mspp_webroleid" = $newRoleId+ "mspp_name" = $RoleName+ "mspp_description" = $Description+ "[email protected]" = "/mspp_websites($WebsiteId)"+ }-if ($anonymousRole.value.Count -gt 0) {- $roleId = $anonymousRole.value[0].adx_webroleid- Write-Host "Anonymous Users Role ID: $roleId"+ try {+ Invoke-RestMethod -Uri "$baseUrl/mspp_webroles" -Method Post -Headers $headers -Body ($webRole | ConvertTo-Json -Depth 5)+ Write-Host "Created web role '$RoleName' with ID: $newRoleId"+ return $newRoleId+ }+ catch {+ Write-Host "Error creating web role '$RoleName': $_"+ return $null+ }+}++# Example: Get or create Anonymous Users role+$roleId = Get-OrCreateWebRole -RoleName "Anonymous Users" -WebsiteId $websiteId -Description "Unauthenticated site visitors"++if (-not $roleId) {+ Write-Host "ERROR: Unable to get or create web role. Cannot proceed with table permission creation." -ForegroundColor Red+ return}++Write-Host "Web Role ID: $roleId"```### Associate Permission with Role+**IMPORTANT**: Only create table permissions if you have a valid web role ID. If role retrieval/creation fails, do NOT create the permission.+```powershellfunction Add-PermissionToRole {param(+ [Parameter(Mandatory=$true)][string]$PermissionId,+ [Parameter(Mandatory=$true)][string]$RoleId)+ if (-not $RoleId) {+ Write-Host "ERROR: No valid role ID provided. Cannot associate permission." -ForegroundColor Red+ return $false+ }+$association = @{- "@odata.id" = "$baseUrl/adx_webroles($RoleId)"+ "@odata.id" = "$baseUrl/mspp_webroles($RoleId)"}try {@@ -193,9 +258,11 @@ function Add-PermissionToRole {-Headers $headers `-Body ($association | ConvertTo-Json)Write-Host "Associated permission $PermissionId with role $RoleId"+ return $true}catch {Write-Host "Error associating permission: $_"+ return $false}}```@@ -253,9 +320,21 @@ $linkedRoles.value | ForEach-Object {}```-## PAC CLI Table Permission Files+## Code Site Table Permission Files++Table permissions for Power Pages code sites are stored as YAML files in the `.powerpages-site/table-permissions/` folder.-When working with Power Platform CLI (`pac paportal download`), table permissions are stored as YAML files.+### Folder Structure++```+<PROJECT_ROOT>/+βββ .powerpages-site/+β βββ table-permissions/+β β βββ Product-Read-Permission.tablepermission.yml+β β βββ Contact-Self-Access.tablepermission.yml+β β βββ ...+β βββ ...+```### File Naming Convention@@ -268,37 +347,45 @@ Example: `Product-Read-Permission.tablepermission.yml`### YAML File Structure```yaml+accountrelationship:+adx_entitypermission_webrole:+- f0323770-7314-4f33-b904-21523abfbcb7append: falseappendto: false+contactrelationship:create: falsedelete: falseentitylogicalname: cr_productentityname: Product Read Permission-entitypermission_webrole:-- 18c1fdce-684b-f011-877a-7c1e520c8613-id: 71ecf203-dfe2-4c1e-9db2-112ed3925a52+id: b5d8334f-45fa-464c-ac1d-f7088325f697parententitypermission:+parentrelationship:read: truescope: 756150000write: false```+**Important**: Field names do NOT include the `adx_` prefix (e.g., use `read` not `adx_read`), EXCEPT for many-to-many relationship fields like `adx_entitypermission_webrole` which retain the full name.+### YAML Field Reference-| Field | Type | 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 |+| Field | Type | Required | Description |+|-------|------|----------|-------------|+| `id` | GUID | Yes | Unique identifier for this permission |+| `entitylogicalname` | string | Yes | Dataverse table logical name (e.g., `cr_product`) |+| `entityname` | string | Yes | Display name for the permission |+| `scope` | int | Yes | Permission scope (see values below) |+| `read` | bool | No | Can retrieve/query records |+| `create` | bool | No | Can create new records |+| `write` | bool | No | Can update existing records |+| `delete` | bool | No | Can delete records |+| `append` | bool | No | Can associate records to this entity |+| `appendto` | bool | No | Can associate this entity to other records |+| `adx_entitypermission_webrole` | list | No | GUIDs of web roles with this permission |+| `parententitypermission` | GUID | No | Parent permission ID for hierarchical access |+| `parentrelationship` | string | No | Relationship name for parent scope |+| `accountrelationship` | string | No | Relationship name for account filtering |+| `contactrelationship` | string | No | Relationship name for contact filtering |### Scope Values for YAML@@ -310,18 +397,60 @@ write: false| Parent | 756150003 | Records linked via parent relationship || Self | 756150004 | Only records owned by current user |+### Generating Unique IDs++**IMPORTANT**: Every table permission YAML file must have a unique `id` field (UUID/GUID format).++**When creating YAML files directly**: Generate a valid UUID in the format `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx` where each `x` is a hexadecimal character (0-9, a-f). Each permission must have a different UUID.++**PowerShell** (if running scripts):+```powershell+[guid]::NewGuid().ToString()+```++**Bash/Linux/Mac**:+```bash+uuidgen | tr '[:upper:]' '[:lower:]'+# or+cat /proc/sys/kernel/random/uuid+```++**Python**:+```python+import uuid+print(str(uuid.uuid4()))+```++**Online**: Use any UUID generator website++**Example UUIDs** (do NOT reuse these - generate new ones):+- `71ecf203-dfe2-4c1e-9db2-112ed3925a52`+- `82fde314-eff3-5d2f-0ec3-223fe4036b63`+- `93gef425-fgg4-6e3g-1fd4-334gf5147c74`+### Example: Read-Only Public Permission+**Before creating**, get the web role GUID from the `.powerpages-site/web-roles/` folder. Each web role has a `.webrole.yml` file containing its `id`.++**Web Role File Format** (`.powerpages-site/web-roles/Anonymous-Users.webrole.yml`):```yaml+anonymoususersrole: true+authenticatedusersrole: false+id: f0323770-7314-4f33-b904-21523abfbcb7+name: Anonymous Users+```++**Table Permission File** (`.powerpages-site/table-permissions/Product-Anonymous-Read.tablepermission.yml`):+```yaml+adx_entitypermission_webrole:+- f0323770-7314-4f33-b904-21523abfbcb7append: falseappendto: falsecreate: falsedelete: falseentitylogicalname: cr_productentityname: Product - Anonymous Read-entitypermission_webrole:-- <anonymous-users-webrole-guid>-id: <new-guid>+id: 71ecf203-dfe2-4c1e-9db2-112ed3925a52parententitypermission:read: truescope: 756150000@@ -330,16 +459,25 @@ write: false### Example: User Self-Access Permission+**Web Role File** (`.powerpages-site/web-roles/Authenticated-Users.webrole.yml`):```yaml+anonymoususersrole: false+authenticatedusersrole: true+id: ecac9573-effb-4d63-9b27-15861f70f3de+name: Authenticated Users+```++**Table Permission File** (`.powerpages-site/table-permissions/User-Profile-Self-Access.tablepermission.yml`):+```yaml+adx_entitypermission_webrole:+- ecac9573-effb-4d63-9b27-15861f70f3deappend: falseappendto: falsecreate: truedelete: falseentitylogicalname: cr_userprofileentityname: User Profile - Self Access-entitypermission_webrole:-- <authenticated-users-webrole-guid>-id: <new-guid>+id: 82fde314-eff3-5d2f-0ec3-223fe4036b63parententitypermission:read: truescope: 756150004@@ -357,20 +495,23 @@ When tables have relationships (e.g., Order β Order Items), you can create hie2. Note the parent permission's `id` (GUID)3. Create child permission with `parententitypermission` set to parent's ID4. Set child's `scope` to `756150003` (Parent)+5. Set `parentrelationship` to the relationship name between child and parent tables#### Example: Parent Permission (Order)+**File**: `.powerpages-site/table-permissions/Order-User-Access.tablepermission.yml````yaml+adx_entitypermission_webrole:+- ecac9573-effb-4d63-9b27-15861f70f3deappend: trueappendto: falsecreate: truedelete: falseentitylogicalname: cr_orderentityname: Order - User Access-entitypermission_webrole:-- <authenticated-users-webrole-guid>id: a1b2c3d4-e5f6-7890-abcd-ef1234567890parententitypermission:+parentrelationship:read: truescope: 756150001write: true@@ -378,17 +519,19 @@ write: true#### Example: Child Permission (Order Items)+**File**: `.powerpages-site/table-permissions/Order-Item-Parent-Access.tablepermission.yml````yaml+adx_entitypermission_webrole:+- ecac9573-effb-4d63-9b27-15861f70f3deappend: falseappendto: truecreate: truedelete: trueentitylogicalname: cr_orderitementityname: Order Item - Parent Access-entitypermission_webrole:-- <authenticated-users-webrole-guid>-id: <new-guid>+id: b2c3d4e5-f6a7-8901-bcde-fa2345678901parententitypermission: a1b2c3d4-e5f6-7890-abcd-ef1234567890+parentrelationship: cr_order_orderitemsread: truescope: 756150003write: true@@ -396,6 +539,19 @@ write: trueIn this example, users can only access order items that belong to orders they have access to.+## Validation Checklist++Before uploading:++- [ ] All YAML files have valid syntax+- [ ] Each file has a unique UUID for the `id` field+- [ ] Fields are alphabetically sorted in the YAML file+- [ ] File extensions are `.yml` (not `.yaml`)+- [ ] Field names do NOT include `adx_` prefix (except `adx_entitypermission_webrole`)+- [ ] Boolean values are unquoted (`true` not `"true"`)+- [ ] All GUIDs are valid UUID format (lowercase with hyphens)+- [ ] Web role GUIDs exist in `.powerpages-site/web-roles/` folder+## Security Best Practices1. **Least Privilege**: Grant only the minimum permissions neededdiff --git a/plugins/skills/setup-webapi/troubleshooting.md b/plugins/power-pages/skills/setup-webapi/troubleshooting.mdsimilarity index 85%rename from plugins/skills/setup-webapi/troubleshooting.mdrename to plugins/power-pages/skills/setup-webapi/troubleshooting.mdindex 50c5e7cc7..3d3775f55 100644--- a/plugins/skills/setup-webapi/troubleshooting.md+++ b/plugins/power-pages/skills/setup-webapi/troubleshooting.md@@ -8,9 +8,10 @@ This document covers common issues when setting up Power Pages Web API and their|-------|----------|| `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 |+| `400 Bad Request` | Invalid OData query syntax, missing `$select`, or field not in allowed list || `500 Server Error` | Enable `Webapi/error/innererror` to see details || `CSRF Token Error` | Ensure `__RequestVerificationToken` header is included for POST/PATCH/DELETE requests |+| `Field not allowed` | Add `$select` param with only fields listed in `Webapi/<table>/fields` setting |## Site Settings Not Being Applied@@ -175,7 +176,35 @@ fetch('/_layout/tokenhtml')/_api/cr_products?$filter=cr_isactive eq true```-2. **Field not in allowed fields list**+2. **Missing $select when fields are restricted** (Most Common)++ When `Webapi/<table>/fields` site setting specifies allowed fields, you **must** use `$select` in your query. Without `$select`, the API tries to return all fields and fails because only configured fields are allowed.++ ```text+ # Site setting+ name: Webapi/cr_product/fields+ value: cr_name,cr_price,cr_isactive++ # Incorrect (no $select - tries to fetch all fields)+ /_api/cr_products+ /_api/cr_products?$filter=cr_isactive eq true++ # Correct (only requests allowed fields)+ /_api/cr_products?$select=cr_name,cr_price,cr_isactive+ /_api/cr_products?$select=cr_name,cr_price,cr_isactive&$filter=cr_isactive eq true+ ```++ **Solution**: Always include `$select` with fields that match your `Webapi/<table>/fields` site setting:++ ```typescript+ // Always specify select with allowed fields+ webApi.getAll<Product>('cr_products', {+ select: ['cr_name', 'cr_price', 'cr_isactive'],+ filter: 'cr_isactive eq true',+ });+ ```++3. **Field not in allowed fields list**- Check `Webapi/<table>/fields` setting- Add missing fields to the comma-separated list@@ -288,6 +317,7 @@ Use this checklist to systematically debug Web API issues:- [ ] Permission has correct CRUD flags?- [ ] CSRF token included for write operations?- [ ] OData query syntax correct? (`$filter`, `$select`, etc.)+- [ ] **`$select` included with allowed fields?** (Required when `Webapi/<table>/fields` is set)- [ ] Fields in allowed fields list?- [ ] Entity set name correct? (pluralized)- [ ] Data exists in Dataverse?diff --git a/plugins/skills/create-site/web-roles-reference.md b/plugins/power-pages/skills/setup-webapi/web-roles-reference.mdsimilarity index 85%rename from plugins/skills/create-site/web-roles-reference.mdrename to plugins/power-pages/skills/setup-webapi/web-roles-reference.mdindex ed1706077..c5e99d5b5 100644--- a/plugins/skills/create-site/web-roles-reference.md+++ b/plugins/power-pages/skills/setup-webapi/web-roles-reference.md@@ -124,6 +124,8 @@ Use this decision matrix to determine which web roles you need:## Create Web Role Function+**IMPORTANT**: Always use `mspp_webroles` (not `adx_webroles`) for creating and querying web roles.+```powershellfunction New-WebRole {param(@@ -135,23 +137,29 @@ function New-WebRole {[string]$Description = "",- [bool]$AuthenticatedUsersRole = $false+ [bool]$AuthenticatedUsersRole = $false,++ [bool]$AnonymousUsersRole = $false)+ # Generate unique ID for the web role (see alternatives below for non-PowerShell)+ $webRoleId = [guid]::NewGuid().ToString()+$webRole = @{- "adx_name" = $Name- "adx_description" = $Description- "adx_authenticatedusersrole" = $AuthenticatedUsersRole- "[email protected]" = "/adx_websites($WebsiteId)"+ "mspp_webroleid" = $webRoleId+ "mspp_name" = $Name+ "mspp_description" = $Description+ "mspp_authenticatedusersrole" = $AuthenticatedUsersRole+ "mspp_anonymoususersrole" = $AnonymousUsersRole+ "[email protected]" = "/mspp_websites($WebsiteId)"}$body = $webRole | ConvertTo-Json -Depth 5try {- $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+ Invoke-RestMethod -Uri "$baseUrl/mspp_webroles" -Method Post -Headers $headers -Body $body+ Write-Host "Created web role '$Name' with ID: $webRoleId"+ return $webRoleId}catch {Write-Host "Error creating web role '$Name': $_"@@ -160,6 +168,23 @@ function New-WebRole {}```+### Alternative UUID Generation Methods++If not using PowerShell, generate UUIDs using:++**Bash/Linux/Mac**:+```bash+uuidgen | tr '[:upper:]' '[:lower:]'+```++**Python**:+```python+import uuid+print(str(uuid.uuid4()))+```++**Online**: Use any UUID generator website+## Common Web Role Patterns### Pattern 1: Public Website (Anonymous + Admin)@@ -167,14 +192,14 @@ function New-WebRole {For simple public websites with admin management:```powershell-# Anonymous Users - already exists, just verify+# Anonymous Users - already exists, just verify (use mspp_webroles)$anonymousRole = Invoke-RestMethod `- -Uri "$baseUrl/adx_webroles?`$filter=adx_name eq 'Anonymous Users' and _adx_websiteid_value eq $websiteId" `+ -Uri "$baseUrl/mspp_webroles?`$filter=mspp_name eq 'Anonymous Users' and _mspp_websiteid_value eq $websiteId" `-Headers $headers# Administrators - already exists, just verify$adminRole = Invoke-RestMethod `- -Uri "$baseUrl/adx_webroles?`$filter=adx_name eq 'Administrators' and _adx_websiteid_value eq $websiteId" `+ -Uri "$baseUrl/mspp_webroles?`$filter=mspp_name eq 'Administrators' and _mspp_websiteid_value eq $websiteId" `-Headers $headersWrite-Host "Using existing roles: Anonymous Users, Administrators"@@ -185,9 +210,9 @@ Write-Host "Using existing roles: Anonymous Users, Administrators"For sites requiring user sign-in:```powershell-# Verify Authenticated Users role exists+# Verify Authenticated Users role exists (use mspp_webroles)$authRole = Invoke-RestMethod `- -Uri "$baseUrl/adx_webroles?`$filter=adx_name eq 'Authenticated Users' and _adx_websiteid_value eq $websiteId" `+ -Uri "$baseUrl/mspp_webroles?`$filter=mspp_name eq 'Authenticated Users' and _mspp_websiteid_value eq $websiteId" `-Headers $headersif ($authRole.value.Count -eq 0) {@@ -279,8 +304,9 @@ function Get-WebRoles {[string]$WebsiteId)+ # Use mspp_webroles (not adx_webroles)$roles = Invoke-RestMethod `- -Uri "$baseUrl/adx_webroles?`$filter=_adx_websiteid_value eq $WebsiteId&`$select=adx_webroleid,adx_name,adx_description,adx_authenticatedusersrole" `+ -Uri "$baseUrl/mspp_webroles?`$filter=_mspp_websiteid_value eq $WebsiteId&`$select=mspp_webroleid,mspp_name,mspp_description,mspp_authenticatedusersrole,mspp_anonymoususersrole" `-Headers $headersreturn $roles.value@@ -289,7 +315,7 @@ function Get-WebRoles {# 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)"+ Write-Host "Role: $($_.mspp_name) | ID: $($_.mspp_webroleid) | Auth Required: $($_.mspp_authenticatedusersrole) | Anonymous: $($_.mspp_anonymoususersrole)"}```@@ -305,12 +331,13 @@ function Get-WebRoleId {[string]$WebsiteId)+ # Use mspp_webroles (not adx_webroles)$role = Invoke-RestMethod `- -Uri "$baseUrl/adx_webroles?`$filter=adx_name eq '$RoleName' and _adx_websiteid_value eq $WebsiteId&`$select=adx_webroleid" `+ -Uri "$baseUrl/mspp_webroles?`$filter=mspp_name eq '$RoleName' and _mspp_websiteid_value eq $WebsiteId&`$select=mspp_webroleid" `-Headers $headersif ($role.value.Count -gt 0) {- return $role.value[0].adx_webroleid+ return $role.value[0].mspp_webroleid}return $null}@@ -340,8 +367,9 @@ function Add-ContactToWebRole {}try {+ # Use mspp_webroles (not adx_webroles)Invoke-RestMethod `- -Uri "$baseUrl/adx_webroles($WebRoleId)/adx_webrole_contact/`$ref" `+ -Uri "$baseUrl/mspp_webroles($WebRoleId)/mspp_webrole_contact/`$ref" `-Method Post `-Headers $headers `-Body ($association | ConvertTo-Json)@@ -371,8 +399,9 @@ function Remove-ContactFromWebRole {)try {+ # Use mspp_webroles (not adx_webroles)Invoke-RestMethod `- -Uri "$baseUrl/adx_webroles($WebRoleId)/adx_webrole_contact($ContactId)/`$ref" `+ -Uri "$baseUrl/mspp_webroles($WebRoleId)/mspp_webrole_contact($ContactId)/`$ref" `-Method Delete `-Headers $headersWrite-Host "Removed contact $ContactId from web role $WebRoleId"@@ -428,7 +457,7 @@ $headers = @{$baseUrl = "$envUrl/api/data/v9.2"-# Verify default roles exist+# Verify default roles exist (use mspp_webroles)Write-Host "`n=== Verifying Default Web Roles ===" -ForegroundColor Cyan$defaultRoles = @("Anonymous Users", "Authenticated Users", "Administrators")@@ -436,11 +465,11 @@ $roleIds = @{}foreach ($roleName in $defaultRoles) {$role = Invoke-RestMethod `- -Uri "$baseUrl/adx_webroles?`$filter=adx_name eq '$roleName' and _adx_websiteid_value eq $WebsiteId" `+ -Uri "$baseUrl/mspp_webroles?`$filter=mspp_name eq '$roleName' and _mspp_websiteid_value eq $WebsiteId" `-Headers $headersif ($role.value.Count -gt 0) {- $roleIds[$roleName] = $role.value[0].adx_webroleid+ $roleIds[$roleName] = $role.value[0].mspp_webroleidWrite-Host "β Found: $roleName (ID: $($roleIds[$roleName]))" -ForegroundColor Green} else {Write-Host "β Missing: $roleName" -ForegroundColor Yellow@@ -453,7 +482,7 @@ if ($CustomRoles.Count -gt 0) {foreach ($customRole in $CustomRoles) {$existingRole = Invoke-RestMethod `- -Uri "$baseUrl/adx_webroles?`$filter=adx_name eq '$customRole' and _adx_websiteid_value eq $WebsiteId" `+ -Uri "$baseUrl/mspp_webroles?`$filter=mspp_name eq '$customRole' and _mspp_websiteid_value eq $WebsiteId" `-Headers $headersif ($existingRole.value.Count -eq 0) {@@ -463,7 +492,7 @@ if ($CustomRoles.Count -gt 0) {Write-Host "β Created: $customRole" -ForegroundColor Green}} else {- $roleIds[$customRole] = $existingRole.value[0].adx_webroleid+ $roleIds[$customRole] = $existingRole.value[0].mspp_webroleidWrite-Host "β Already exists: $customRole" -ForegroundColor Yellow}}diff --git a/plugins/skills/create-site/SKILL.md b/plugins/skills/create-site/SKILL.mddeleted file mode 100644index 94bc69a77..000000000--- a/plugins/skills/create-site/SKILL.md+++ /dev/null@@ -1,1338 +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.--## 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/setup-dataverse/SKILL.md b/plugins/skills/setup-dataverse/SKILL.mddeleted file mode 100644index f87767fa3..000000000--- a/plugins/skills/setup-dataverse/SKILL.md+++ /dev/null@@ -1,2055 +0,0 @@-----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)