FUture Dev guides final - added

This commit is contained in:
IGNY8 VPS (Salman)
2026-03-08 02:36:44 +00:00
parent 35d60247ad
commit 2a9aac9119
4 changed files with 5122 additions and 0 deletions

View File

@@ -0,0 +1,820 @@
# Doc C — WordPress Ecosystem: Development Guide for Claude Code
**Version:** 1.0
**Date:** March 2026
**For:** Claude Code (Opus 4.6) in VSCode
**Purpose:** Step-by-step implementation guide for the IGNY8 WordPress Plugin (free + connected), Companion Theme, and Toolkit Plugin — where every file goes, what it does, build sequence, and how it connects to the IGNY8 SaaS platform
**Scope:** Plugin (14 modules, 10 build phases), Theme (7 CPTs, 9 taxonomies, 15 landing sections, 50+ block patterns, 5 starters, WooCommerce), Toolkit Plugin (5 modules)
**Rule:** Plugin works with ANY theme. Theme works WITHOUT the plugin. Both work WITHOUT the IGNY8 SaaS platform. Connected mode enhances both but is never required.
**Dependency:** Doc A (SAG Architecture) defines the blueprint/cluster data the plugin receives in connected mode. Doc B (Platform Modules) defines the IGNY8 SaaS features that push content/schemas/links to the plugin.
---
## Table of Contents
1. [Architecture Overview — Three Deliverables](#1-architecture-overview)
2. [Build Sequence — What Comes First](#2-build-sequence)
3. [IGNY8 Plugin — Foundation & Infrastructure](#3-plugin-foundation)
4. [IGNY8 Plugin — Module 1: SEO Core](#4-seo-core)
5. [IGNY8 Plugin — Module 2: Schema](#5-schema)
6. [IGNY8 Plugin — Module 3: Sitemap](#6-sitemap)
7. [IGNY8 Plugin — Module 4: Redirects](#7-redirects)
8. [IGNY8 Plugin — Module 5: Site Intelligence](#8-site-intelligence)
9. [IGNY8 Plugin — Module 6: Internal Linking](#9-internal-linking)
10. [IGNY8 Plugin — Module 7: GSC](#10-gsc)
11. [IGNY8 Plugin — Module 8: Socializer](#11-socializer)
12. [IGNY8 Plugin — Module 9: Analytics + SMTP](#12-analytics-smtp)
13. [IGNY8 Plugin — Module 10: Content Sync (Connected)](#13-content-sync)
14. [IGNY8 Plugin — Module 11: SAG Structure (Connected)](#14-sag-structure)
15. [IGNY8 Plugin — Setup Wizard & Import](#15-setup-wizard)
16. [IGNY8 Plugin — Data Architecture](#16-data-architecture)
17. [IGNY8 Plugin — REST API Endpoints](#17-rest-api)
18. [IGNY8 Plugin — Performance Rules](#18-performance)
19. [Theme — CPTs, Taxonomies, Meta Fields](#19-theme-structure)
20. [Theme — Term Landing Pages & SAG Templates](#20-term-templates)
21. [Theme — Landing Page Builder](#21-landing-pages)
22. [Theme — Block Patterns & Starter Templates](#22-patterns-starters)
23. [Theme — Interlinking Display Components](#23-interlinking-display)
24. [Theme — WooCommerce Integration](#24-woocommerce)
25. [Theme — Design System & Build Plan](#25-design-build)
26. [Toolkit Plugin — All 5 Modules](#26-toolkit)
27. [Free vs Premium Split](#27-free-premium)
28. [Theme ↔ Plugin Contract](#28-theme-plugin-contract)
29. [Plugin ↔ IGNY8 SaaS Communication](#29-saas-communication)
---
## 1. Architecture Overview — Three Deliverables {#1-architecture-overview}
```
┌────────────────────────────────────────────────────────────┐
│ IGNY8 PLUGIN │
│ SEO Core, Schema, Sitemap, Redirects, Analytics, GSC, │
│ Site Intelligence, Internal Linking, Socializer, SMTP │
│ + Connected: Content Sync, SAG Structure │
│ │
│ Distribution: Free on WordPress.org │
│ Connected premium features via IGNY8 SaaS subscription │
│ Works with ANY theme │
└──────────────────────┬─────────────────────────────────────┘
│ reads plugin data via igny8() API
┌──────────────────────┴─────────────────────────────────────┐
│ COMPANION THEME │
│ 7 CPTs, 9 custom taxonomies, meta fields, SAG templates, │
│ term landing pages, landing page builder, 50+ patterns, │
│ 5 site-type starters, WooCommerce templates, design system │
│ │
│ Distribution: Free on WordPress.org (limited), Premium │
│ Works WITHOUT the plugin (graceful degradation) │
└──────────────────────┬─────────────────────────────────────┘
│ extends theme with infrastructure
┌──────────────────────┴─────────────────────────────────────┐
│ TOOLKIT PLUGIN │
│ Performance/Caching, Forms, Security, SMTP, WooCommerce │
│ │
│ Distribution: Free on WordPress.org (limited), Premium │
│ Works with ANY theme │
└────────────────────────────────────────────────────────────┘
```
**Key principle:** Each piece works independently. Together they create the full SAG-optimized WordPress experience.
---
## 2. Build Sequence — What Comes First {#2-build-sequence}
```
PHASE 1 (Days 1-3) ─── Plugin Foundation
│ Skeleton, module manager, admin menu, REST API base,
│ setup wizard, database installer, compatibility layer
PHASE 2 (Days 4-7) ─── SEO Core Module
│ Meta box, title tags, meta description, content analysis,
│ OG tags, breadcrumbs, robots.txt, verification codes
PHASE 3 (Days 8-10) ─── Schema + Sitemap + Redirects
│ JSON-LD schemas, XML sitemap, redirect manager, 404 monitor
PHASE 4 (Days 11-13) ── Site Intelligence
│ Site audit, orphan detection, thin content, cannibalization,
│ cluster detection, intelligence dashboard
PHASE 5 (Days 14-15) ── Internal Linking
│ Link crawl, link audit, suggestions, link graph
PHASE 6 (Days 16-18) ── Socializer + Analytics + SMTP
│ Share buttons, social profiles, GA/GTM connector,
│ pixel manager, SMTP override, GSC OAuth + dashboard
PHASE 7 (Days 19-20) ── SEO Import
│ Yoast, RankMath, AIOSEO importers
PHASE 8 (Days 21-23) ── Connected Mode — Content Sync
│ API client, content puller, mapper, sync queue, scheduler
PHASE 9 (Days 24-27) ── Connected Mode — SAG Structure
│ Blueprint sync, taxonomy builder, term builder,
│ cluster manager, structure visualizer
PHASE 10 (Days 28-30) ─ Polish + Package
Cross-module testing, performance audit, WP.org compliance
--- THEME BUILD (30 days, can overlap with plugin Phases 6+) ---
THEME PHASE 1 (Days 1-3) Foundation (templates, design system, CSS)
THEME PHASE 2 (Days 4-6) CPTs + Taxonomies + Meta Boxes
THEME PHASE 3 (Days 7-9) Term Landing Page Templates
THEME PHASE 4 (Days 10-11) Interlinking Display Components
THEME PHASE 5 (Days 12-14) Landing Page Builder
THEME PHASE 6 (Days 15-16) Single Templates (service, portfolio, docs)
THEME PHASE 7 (Days 17-19) Custom Blocks + 50+ Patterns
THEME PHASE 8 (Days 20-22) Site-Type Starters + WooCommerce
THEME PHASE 9 (Days 23-27) Toolkit Plugin (all 5 modules)
THEME PHASE 10 (Days 28-30) Setup Wizard + Polish
--- THEME CAN START after Plugin Phase 5 (interlinking data contract defined) ---
```
---
## 3. IGNY8 Plugin — Foundation & Infrastructure {#3-plugin-foundation}
### 3.1 Complete File Structure
```
igny8/
├── igny8.php # Plugin header, bootstrap, constants
├── readme.txt # WordPress.org readme
├── uninstall.php # Full cleanup on uninstall
├── includes/
│ ├── class-igny8.php # Main singleton class
│ ├── class-module-manager.php # Register, activate, deactivate modules
│ ├── class-api-client.php # IGNY8 SaaS API client (connected mode)
│ ├── class-connection.php # API key validation, connection status
│ ├── class-utils.php # Shared utilities
│ ├── class-ajax.php # Shared AJAX handler
│ ├── class-rest-api.php # Plugin REST endpoints (for theme + external)
│ ├── class-compatibility.php # Detect conflicting plugins, show notices
│ │
│ ├── modules/ # 14 modules (see sections 4-14)
│ │ ├── seo/ # SEO Core (Phase 2)
│ │ ├── schema/ # Schema (Phase 3)
│ │ ├── sitemap/ # Sitemap (Phase 3)
│ │ ├── redirects/ # Redirects (Phase 3)
│ │ ├── analytics/ # Analytics (Phase 6)
│ │ ├── site-intelligence/ # Site Intelligence (Phase 4)
│ │ ├── linking/ # Internal Linking (Phase 5)
│ │ ├── gsc/ # Google Search Console (Phase 6)
│ │ ├── socializer/ # Social sharing + posting (Phase 6)
│ │ ├── smtp/ # Email delivery (Phase 6)
│ │ ├── content-sync/ # [Connected] Content from IGNY8 (Phase 8)
│ │ └── sag/ # [Connected] SAG structure (Phase 9)
│ │
│ ├── admin/ # Admin UI infrastructure
│ │ ├── class-admin-menu.php # Menu registration (top-level "IGNY8" menu)
│ │ ├── class-dashboard.php # Main plugin dashboard page
│ │ ├── class-setup-wizard.php # First-run wizard (6 steps)
│ │ ├── class-compatibility-notice.php # Admin notices for conflicts
│ │ ├── views/ # PHP templates for admin pages
│ │ │ ├── dashboard.php
│ │ │ ├── wizard/step-1 through step-6.php
│ │ │ └── connect-prompt.php
│ │ └── assets/
│ │ ├── admin.css, admin.js
│ │ └── meta-box.css, meta-box.js
│ │
│ ├── frontend/
│ │ ├── class-head-output.php # ALL <head> output (meta, schema, OG) in single hook
│ │ ├── class-share-output.php # Share button HTML/CSS/JS (conditional)
│ │ └── assets/
│ │ ├── share-buttons.css # <3KB, loaded only if share enabled
│ │ └── share-buttons.js # <2KB, loaded only if share enabled
│ │
│ ├── data/
│ │ ├── class-installer.php # Create all custom DB tables on activation
│ │ ├── class-migrator.php # Version-based migration handler
│ │ └── class-importer.php # Import from Yoast/RankMath/AIOSEO
│ │
│ └── integrations/
│ ├── class-woocommerce.php # WooCommerce-specific SEO/schema
│ └── class-theme-bridge.php # Data passing to companion theme
└── languages/
└── igny8.pot # Translation template
```
### 3.2 Module Manager Pattern
Every module follows the same lifecycle:
```php
// class-module-manager.php pattern
class ModuleManager {
private $modules = [];
public function register($slug, $class, $options = []) {
// Register module with slug, class path, free/connected flag
}
public function activate($slug) {
// Enable module, call module's activate() method
}
public function deactivate($slug) {
// Disable module, call module's deactivate() method
}
public function is_active($slug) {
// Check igny8_active_modules option
}
public function boot_active_modules() {
// Called on plugins_loaded — instantiate all active modules
}
}
// Each module extends:
abstract class IGNY8_Module {
abstract public function get_slug();
abstract public function get_name();
abstract public function init(); // Hook registration
public function activate() {} // On module enable
public function deactivate() {} // On module disable
public function is_connected_only() { return false; }
}
```
### 3.3 Admin Menu Structure
```
IGNY8 (top-level menu, dashicons-chart-area)
├── Dashboard # Plugin overview + connect prompt
├── SEO # SEO settings page
├── Schema # Schema settings
├── Sitemaps # Sitemap configuration
├── Redirects # Redirect manager + 404 log
├── Site Intelligence # Audit dashboard
├── Internal Links # Link audit + suggestions
├── Search Console # GSC connection + metrics
├── Socializer # Share buttons + accounts
├── Analytics # GA/GTM/pixel settings
├── SMTP # Mail settings
├── Settings # Global plugin settings
└── (Connected only, appear after connection):
├── Content Sync # Sync dashboard
└── SAG Structure # Blueprint + structure visualizer
```
### 3.4 Public API Class
The plugin exposes a global function for themes and other plugins:
```php
function igny8() {
return IGNY8::instance();
}
// Usage by theme:
if (function_exists('igny8')) {
$title = igny8()->seo->get_title($post_id);
$schema = igny8()->schema->get_json_ld($post_id);
$breadcrumbs = igny8()->seo->get_breadcrumbs();
$related = igny8()->linking->get_related_links($post_id);
$cluster_nav = igny8()->linking->get_cluster_navigation($post_id);
$term_content = igny8()->seo->get_term_content($term_id);
$share = igny8()->socializer->render_share_buttons($post_id);
}
```
---
## 4-12. Plugin Modules — Build Reference {#4-seo-core}
Each module section below specifies: files to create, what each file does, which hooks it uses, what data it reads/writes, and how it connects to the IGNY8 SaaS platform in connected mode.
### Module 1: SEO Core (Phase 2, Days 4-7)
**Files:** `modules/seo/` — 9 PHP files + 2 view templates (see file structure above)
**What it does:**
- `class-meta-box.php` — Adds SEO meta box below editor on all post types. Fields: focus keyword, SEO title (with SERP preview), meta description (with character counter), canonical URL, robots index/follow toggles. Saves to `_igny8_*` post meta keys. Connected enhancement: multi-keyword fields, cluster-aware scoring.
- `class-title-tag.php` — Manages `<title>` tag output. Template system: `{site_title} {separator} {page_title}`. Customizable per post type. Filters: `igny8_title_parts`, `igny8_title_separator`.
- `class-meta-tags.php` — Outputs `<meta name="description">`, `<meta name="robots">`, `<link rel="canonical">` in `<head>`. Single `wp_head` hook at priority 1.
- `class-content-analysis.php` — Real-time JavaScript analysis in editor: keyword density, heading check (H1 count, H2 usage), readability score (Flesch), internal link count, image alt text check, meta length check. Outputs score 0-100 stored in `_igny8_seo_score`.
- `class-breadcrumbs.php` — Generates breadcrumb HTML. Shortcode `[igny8_breadcrumbs]`. Also outputs BreadcrumbList schema. SAG-aware: when connected, breadcrumbs follow dimensional path (Home → Attribute → Term → Post).
- `class-opengraph.php` — OG title, description, image, type, URL. Twitter Card meta. Per-post overrides via meta box.
- `class-robots-txt.php` — Virtual robots.txt manager. Adds sitemap URL, custom rules.
- `class-verification.php` — Google, Bing, Pinterest, Yandex verification meta tags.
**WP Hooks used:** `wp_head` (priority 1), `add_meta_boxes`, `save_post`, `wp_title`, `document_title_parts`, `the_content` (for breadcrumb auto-insertion option).
### Module 2: Schema (Phase 3, Days 8-9)
**Files:** `modules/schema/` — 12 PHP files
**What it does:** Generates JSON-LD for all schema types and outputs as a single `<script type="application/ld+json">` block in `wp_head`. Schema types: Article/BlogPosting, Organization/Person, WebPage/CollectionPage, BreadcrumbList, FAQPage, HowTo, LocalBusiness, Service, Product (WooCommerce), WebSite+SearchAction, custom field for advanced users.
**Schema selection logic:** Content type → schema type mapping. Blog posts get Article. Service CPT gets Service. Products get Product. FAQ CPT gets FAQPage. Hub pages get WebPage. Users can override via `_igny8_schema_type` meta.
**Connected enhancement:** IGNY8 SaaS pushes pre-generated schemas (FAQ pairs, HowTo steps, Pros/Cons) via bulk endpoint. Plugin stores in post meta and renders alongside auto-generated schemas.
### Module 3: Sitemap (Phase 3, Day 9)
**Files:** `modules/sitemap/` — 5 PHP files
**What it does:** XML sitemap index at `/sitemap_index.xml`. Sub-sitemaps per post type, per taxonomy, image sitemap. XSL stylesheet for browser viewing. Respects noindex settings. Includes `<lastmod>`, `<image:image>`. WooCommerce: includes price, availability in product sitemap entries.
### Module 4: Redirects (Phase 3, Day 10)
**Files:** `modules/redirects/` — 4 PHP files + 1 view
**What it does:** CRUD for 301/302/307 redirects in custom DB table. 404 monitoring with hit count. Auto-redirect when post slug changes. CSV import/export. Admin page with sortable/filterable table.
### Module 5: Site Intelligence (Phase 4, Days 11-13)
**Files:** `modules/site-intelligence/` — 10 PHP files + 2 views
**What it does (Free):** Site audit runner (WP Cron scheduled, weekly). Orphan page detection (pages with 0 internal links pointing to them). Thin content scanner (below word count threshold, configurable). Empty taxonomy terms. Duplicate title/meta detection. Keyword cannibalization (multiple pages targeting same keyword). Basic cluster detection (auto-group content by topic similarity).
**What it does (Connected):** Full SAG gap analysis: missing clusters, missing term pages, missing attribute values. Cluster health scores: content coverage, link density per cluster. Architecture blueprint showing recommended new pages. Priority queue: which gaps to fill first. Topical authority scoring per cluster.
**Dashboard:** Admin page showing audit results. Severity color coding (critical/warning/info). Per-issue action buttons. Re-run audit button. Connected: SAG gap analysis section with "Connect to IGNY8 to fix these gaps" CTA.
### Module 6: Internal Linking (Phase 5, Days 14-15)
**Files:** `modules/linking/` — 7 PHP files + 2 views
**What it does (Free):** Link crawl: scans all content, builds `{prefix}igny8_link_map` table. Link audit page: per-post inbound/outbound link counts, broken links, orphan pages. Link suggestions: "This post could link to these 5 related posts" based on shared categories/tags/keywords. Link equity distribution overview.
**What it does (Connected):** SAG-aware automatic link suggestions based on cluster relationships (data from Doc A Linker module). Bulk link insertion tool. Link template rules (keyword → URL mapping). Contextual link placement (AI-determined anchor text and position). Link priority scoring based on cluster importance.
### Module 7: GSC (Phase 6, Day 18)
**Files:** `modules/gsc/` — 6 PHP files + 2 views
**What it does (Free):** Google OAuth connection. Search performance dashboard: clicks, impressions, CTR, position. Keyword position tracking. Date range filtering.
**What it does (Connected):** URL Inspection API: inspect any URL's index status. Auto-indexing: content published via IGNY8 gets auto-inspected and index-requested (driven by IGNY8 SaaS, plugin receives status updates). Status display: index status column in content list, metabox on edit screen.
### Module 8: Socializer (Phase 6, Days 16-17)
**Files:** `modules/socializer/` — 8 PHP files + 2 views
**What it does (Free):** Pure CSS/JS share buttons (zero external dependencies, <5KB total). Position options: floating, above/below content, inline. Networks: Facebook, X, LinkedIn, Pinterest, WhatsApp, Telegram, Email, Copy Link. Social profile links management (site-wide, used in schema).
**What it does (Connected):** Auto-post to social platforms on WordPress publish (content adapted by IGNY8 SaaS Socializer module). Per-platform message templates. Scheduling. Platform API connections: X, Facebook Pages, LinkedIn, Instagram. Dynamic OG image generation. Social post performance tracking.
### Module 9: Analytics + SMTP (Phase 6, Days 17-18)
**Analytics files:** `modules/analytics/` — 4 PHP files
**SMTP files:** `modules/smtp/` — 3 PHP files
**Analytics:** GA4 connector (tracking code injection), GTM connector, Facebook/TikTok/Pinterest pixel manager, custom header/footer scripts manager.
**SMTP:** Override `wp_mail()` with SMTP credentials. Email delivery log in custom DB table. Test email utility.
---
## 13. IGNY8 Plugin — Content Sync (Connected Mode) {#13-content-sync}
### Files
```
modules/content-sync/
├── class-sync-module.php # Module entry, WP Cron scheduling
├── class-content-puller.php # Fetch content from IGNY8 SaaS API
├── class-content-mapper.php # Map IGNY8 content_type → WP post type
├── class-image-downloader.php # Download AI images → attach to posts
├── class-sync-queue.php # {prefix}igny8_sync_queue table management
├── class-publish-scheduler.php # Review queue, scheduled publishing
└── views/
├── sync-dashboard.php # Status, controls, history
└── content-review.php # Review queue before publish
```
### Content Type Mapping
| IGNY8 content_type | WP post_type | WP template | Notes |
|-------------------|-------------|-------------|-------|
| post | post | Standard | Default |
| page | page | Default page | — |
| product | product | WooCommerce product | Requires WooCommerce |
| service | service | single-service template | Requires theme CPT |
| company_page | page | page-company template | — |
| taxonomy_landing | — | — | Written to term description, not a post |
| cluster_hub | page | page-hub template | Landing page preset applied |
| comparison | post | Standard | — |
| brand_page | post or page | Standard | — |
### Sync Flow
```
IGNY8 SaaS publishes content
→ Webhook to plugin: POST /wp-json/igny8/v1/sync/push
→ Plugin creates sync queue entry (status: pending)
→ WP Cron processes queue:
1. Download images → attach to media library
2. Map content_type → WP post_type
3. Create/update WP post with content, meta, featured image
4. Assign taxonomies from IGNY8 cluster/attribute data
5. If taxonomy_landing: write to term description instead
6. Status: 'review' (manual review required) or 'synced' (auto-publish)
→ Plugin POSTs confirmation back to IGNY8 SaaS
```
---
## 14. IGNY8 Plugin — SAG Structure (Connected Mode) {#14-sag-structure}
### Files
```
modules/sag/
├── class-sag-module.php # Module entry
├── class-blueprint-sync.php # Receive SAG blueprint JSON from IGNY8
├── class-taxonomy-builder.php # register_taxonomy() from SAG attributes
├── class-term-builder.php # wp_insert_term() from attribute values
├── class-cluster-manager.php # Map clusters → hub pages/terms
├── class-structure-visualizer.php # Visual map of site structure
└── views/
├── sag-dashboard.php # SAG structure overview
├── blueprint-review.php # Review proposed taxonomies before applying
└── structure-map.php # Visual cluster/taxonomy/content map
```
### Blueprint Sync Flow
```
IGNY8 SaaS confirms blueprint
→ POST to plugin: /wp-json/igny8/v1/sag/sync-blueprint
→ Plugin stores blueprint in igny8_sag_blueprint option
→ Blueprint review UI shows proposed changes:
- New taxonomies to create
- New terms to create
- Existing taxonomies to map
→ User approves → Taxonomy Builder executes:
1. register_taxonomy() for each SAG attribute
(stored in option for persistence across requests)
2. wp_insert_term() for each attribute value
3. Set term meta: _igny8_term_sag_attribute, _igny8_term_sag_level
4. Map clusters to existing hub pages or create placeholders
→ Plugin POSTs success + term IDs back to IGNY8 SaaS
→ IGNY8 SaaS updates SAGAttribute.wp_taxonomy_slug and wp_sync_status
```
### Structure Visualizer
Admin page showing:
- Tree view: Taxonomies → Terms → assigned posts/products
- Cluster map: clusters as cards with hub page status, supporting content count
- Gap indicators: terms without content, clusters without hubs
- Connected to IGNY8: "Generate content for this term" links to IGNY8 app
---
## 15. Setup Wizard & SEO Import {#15-setup-wizard}
### Wizard Steps
| Step | Title | What It Does |
|------|-------|-------------|
| 1 | Site Type | Blog, Business, eCommerce, Local Business, SaaS, Portfolio — sets schema defaults |
| 2 | SEO Import | Detects Yoast/RankMath/AIOSEO → one-click import via WP Cron |
| 3 | Site Basics | Site name, Organization/Person, logo, title separator |
| 4 | Social Profiles | All social URLs + default sharing image |
| 5 | Connect to IGNY8 | API key input, connection test, site pairing. Clear skip option. |
| 6 | Done | Summary, "Run first site audit" CTA, key settings links |
### SEO Import Data Mapping
| Source | Source Meta Key | IGNY8 Meta Key |
|--------|----------------|---------------|
| Yoast | `_yoast_wpseo_focuskw` | `_igny8_focus_keyword` |
| Yoast | `_yoast_wpseo_title` | `_igny8_seo_title` |
| Yoast | `_yoast_wpseo_metadesc` | `_igny8_meta_description` |
| Yoast | `_yoast_wpseo_canonical` | `_igny8_canonical_url` |
| Yoast | `_yoast_wpseo_meta-robots-noindex` | `_igny8_robots_index` |
| RankMath | `rank_math_focus_keyword` | `_igny8_focus_keyword` |
| RankMath | `rank_math_title` | `_igny8_seo_title` |
| RankMath | `rank_math_description` | `_igny8_meta_description` |
| RankMath | `rank_math_canonical_url` | `_igny8_canonical_url` |
| RankMath | `rank_math_robots` | `_igny8_robots_index` + `_igny8_robots_follow` |
| AIOSEO | `_aioseo_title` | `_igny8_seo_title` |
| AIOSEO | `_aioseo_description` | `_igny8_meta_description` |
Import runs as background WP Cron task with progress tracking. Completion report shows counts per data type.
---
## 16. Data Architecture {#16-data-architecture}
### Custom Database Tables
| Table | Purpose | Created In |
|-------|---------|-----------|
| `{prefix}igny8_redirects` | Redirect rules (source, target, type, hits) | Phase 3 |
| `{prefix}igny8_404_log` | 404 hit log (URL, referrer, hits, resolved) | Phase 3 |
| `{prefix}igny8_link_map` | Internal link graph (source→target, anchor, position) | Phase 5 |
| `{prefix}igny8_audit_results` | Site audit findings (type, severity, message, data) | Phase 4 |
| `{prefix}igny8_email_log` | SMTP delivery log (to, subject, status, error) | Phase 6 |
| `{prefix}igny8_sync_queue` | Content sync queue (IGNY8 ID, status, WP post/term ID) | Phase 8 |
### Post Meta Keys (all prefixed `_igny8_`)
SEO: `focus_keyword`, `secondary_keywords`, `seo_title`, `meta_description`, `canonical_url`, `robots_index`, `robots_follow`, `og_title`, `og_description`, `og_image`, `twitter_title`, `twitter_description`, `schema_type`, `schema_custom`, `seo_score`, `content_score`, `readability_score`
Connected: `cluster_id`, `related_links`, `link_suggestions`, `last_analysis`, `igny8_content_id`, `sync_status`, `schema_faq`, `schema_howto`, `schema_article`, `schema_review`
### Term Meta Keys (all prefixed `_igny8_term_`)
`seo_title`, `meta_description`, `robots_index`, `og_image`, `content`, `cluster_id`, `sag_attribute`, `sag_level`, `faq`, `related_terms`, `igny8_id`
### Options Keys (all prefixed `igny8_`)
Global: `version`, `active_modules`, `seo_settings`, `schema_settings`, `sitemap_settings`, `social_profiles`, `analytics_settings`, `redirect_settings`, `smtp_settings`, `share_settings`, `linking_settings`, `intelligence_settings`
Connected: `api_key`, `api_connected`, `site_id`, `last_sync`, `sag_blueprint`, `gsc_token`, `gsc_property`
---
## 17. REST API Endpoints {#17-rest-api}
### Plugin-Provided Endpoints (for theme + external consumers)
```
GET /wp-json/igny8/v1/related/{post_id} # Related content links
GET /wp-json/igny8/v1/cluster/{cluster_id} # All content in cluster
GET /wp-json/igny8/v1/term/{term_id}/content # Term landing page data
GET /wp-json/igny8/v1/structure/overview # Site structure summary
GET /wp-json/igny8/v1/audit/summary # Site audit summary
```
### Plugin-Received Endpoints (from IGNY8 SaaS platform)
```
POST /wp-json/igny8/v1/sync/push # Push content from IGNY8
POST /wp-json/igny8/v1/sag/sync-blueprint # Push SAG blueprint
POST /wp-json/igny8/v1/sag/create-taxonomies # Create taxonomies from blueprint
POST /wp-json/igny8/v1/terms/{term_id}/content # Push term content
POST /wp-json/igny8/v1/schema/bulk-update # Push schemas for multiple posts
POST /wp-json/igny8/v1/gsc/status-sync # Push GSC index statuses
POST /wp-json/igny8/v1/event # Webhooks (task ready, etc.)
```
All endpoints validate `X-IGNY8-API-KEY` header against `Site.wp_api_key`.
---
## 18. Performance Rules {#18-performance}
| Rule | How |
|------|-----|
| Zero frontend CSS unless share buttons enabled | `wp_enqueue_scripts` with conditional check |
| Zero frontend JS unless share buttons or dynamic features active | Same conditional |
| ALL `<head>` output in single `wp_head` hook at priority 1 | `class-head-output.php` consolidates everything |
| Schema as single JSON-LD block, not multiple `<script>` tags | `class-schema-generator.php` merges all schemas |
| Admin assets only on IGNY8 admin pages | `admin_enqueue_scripts` with screen check |
| Meta box assets only on editor screens | Screen check before enqueue |
| Site audit runs via WP Cron, never on page load | `wp_schedule_event` weekly |
| Link crawl is background process | WP Cron, batch processing |
| Connected mode API calls are async | WP Cron queue, never blocks |
| Option reads use object cache | `wp_cache_get/set` wrapping |
---
## 19-25. Theme Build Reference {#19-theme-structure}
### 19. CPTs, Taxonomies, Meta Fields
**7 CPTs:** service, landing_page, portfolio, team_member, testimonial, faq, documentation
**9 Custom Taxonomies:** service_category, service_area, service_attribute, cluster, portfolio_category, portfolio_tag, faq_category, doc_category, topic_tag
**WooCommerce:** Theme does NOT register Woo taxonomies. Provides rich templates for product_cat, product_tag, pa_* archives. Registers `cluster` taxonomy for `product` post type.
**Meta fields per CPT:** Service (10 fields: price, duration, process steps, outcomes, FAQs, CTA, areas, gallery, related). Portfolio (8 fields: client, date, URL, results, tech, testimonial, gallery, before/after). Team (6 fields: position, email, phone, social, order, department). Testimonial (8 fields: author name/title, company, rating, image, featured, linked service/product). FAQ (2 fields: order, schema enabled). Documentation (4 fields: sidebar, TOC, last reviewed, related docs).
All theme meta keys use `_theme_` prefix. Theme reads `_igny8_` prefix for plugin data.
### 20. Term Landing Pages & SAG Templates
Every taxonomy term archive renders as a rich landing page with 7 sections:
1. **Term Hero** — H1 from term name, description, breadcrumbs, post count
2. **Rich Content** — From IGNY8 `_igny8_term_content` or WP term description
3. **Child Terms** — Grid of child term cards (if hierarchical)
4. **Posts Grid** — All posts in this term, paginated
5. **Related Clusters** — Other clusters sharing attribute values
6. **FAQ** — From `_igny8_term_faq` or `_theme_*` meta
7. **CTA** — Configurable call to action
Template files: `taxonomy-service_category.html`, `taxonomy-service_area.html`, `taxonomy-service_attribute.html`, `taxonomy-cluster.html`, `taxonomy-faq_category.html`, `taxonomy-product_cat.html`, `taxonomy-product_tag.html`
### 21. Landing Page Builder
**CPT:** `landing_page` with section repeater meta box (`_theme_landing_sections`)
**15 section types:** hero, features-grid, how-it-works, social-proof, pricing, faq, cta-band, content-block, stats-counter, team, portfolio-grid, contact-form, video-embed, logo-bar, comparison-table
**8 presets:** SaaS Product, Service Business, Product Launch, Lead Generation, Portfolio/Agency, Event/Webinar, Cluster Hub, Term Landing
Admin JS: drag-to-reorder sections, add/remove/duplicate, per-section field configuration. Frontend renderer: loops through sections, renders each with its template.
### 22. Block Patterns & Starter Templates
**50+ block patterns** organized by category: Heroes (4), Content (4), Social Proof (4), Conversion (4), Services (3), Portfolio (3), Footers (3), plus additional patterns.
**5 site-type starters** (importable demo content): Blog, SaaS, Corporate, eCommerce, Portfolio. Each includes: front-page, core pages, sample CPT entries, sample taxonomy terms.
### 23. Interlinking Display Components
6 template parts that read IGNY8 plugin data with graceful fallbacks:
| Component | Template Part | Data Source | Fallback |
|-----------|-------------|-------------|----------|
| Related Content | `parts/related-content.html` | `_igny8_related_links` post meta | WordPress related by category |
| Cluster Navigation | `parts/cluster-navigation.html` | `igny8()->linking->get_cluster_navigation()` | Posts in same cluster term |
| Attribute Browse | `parts/attribute-browse.html` | Custom taxonomy terms for context | — |
| Breadcrumb Trail | `parts/breadcrumbs.html` | `igny8()->seo->get_breadcrumbs()` | Theme simple breadcrumbs |
| Term Quick Links | `parts/term-quick-links.html` | All terms assigned to current post | — |
| Child Term Grid | `parts/child-term-grid.html` | `get_term_children()` + term meta | — |
### 24. WooCommerce Integration
When WooCommerce active, theme provides:
- `woocommerce/archive-product.php` — SAG-structured shop page
- `woocommerce/single-product.php` — Enhanced product page
- `woocommerce/taxonomy-product_cat.php` — Rich category landing page
- `woocommerce/content-product.php` — Product card in archives
- Cart, checkout, account template overrides
### 25. Design System & Build Execution
**theme.json:** Complete design token system — colors (primary palette + extended), typography (heading + body from curated list), spacing scale, shadows, border radius, transitions. Custom tokens for term pages and interlinking components.
**CSS:** BEM naming `.tn-block__element--modifier`. Total CSS budget <35KB gzipped.
**JS:** ES6+, vanilla JS, no jQuery on frontend. Each feature in own file, conditionally loaded. Total JS budget <15KB gzipped.
**Performance targets:** FCP <1.0s, LCP <1.5s, TBT <50ms, CLS <0.05, PageSpeed 95+ mobile.
---
## 26. Toolkit Plugin — All 5 Modules {#26-toolkit}
### File Structure
```
theme-name-toolkit/
├── theme-name-toolkit.php # Plugin header, module loader
├── readme.txt
├── includes/
│ ├── class-toolkit.php # Main class
│ ├── class-module-manager.php # Module toggle system
│ ├── modules/
│ │ ├── performance/ # Page cache, asset optimizer, image optimizer,
│ │ │ # critical CSS, HTML minifier, browser cache, preload
│ │ ├── forms/ # Form builder, renderer, processor, notifications,
│ │ │ # entries admin, anti-spam
│ │ ├── security/ # Login protection, firewall, hardening, headers, audit log
│ │ ├── smtp/ # SMTP mailer, email log, test email
│ │ └── woocommerce/ # Quick view, wishlist, AJAX cart, product filters, gallery
│ └── admin/
│ ├── class-dashboard.php # Module toggle dashboard
│ └── views/dashboard.php
└── languages/
```
Each module: independent enable/disable toggle from toolkit dashboard. Zero frontend impact when disabled.
---
## 27. Free vs Premium Split {#27-free-premium}
### Theme
| Feature | Free (WordPress.org) | Premium |
|---------|---------------------|---------|
| All 7 CPTs + taxonomies | ✅ | ✅ |
| All term landing page templates | ✅ | ✅ |
| Basic interlinking components | ✅ | ✅ |
| Landing page sections | 3 (hero, content-block, cta-band) | All 15 |
| Landing page presets | 2 (generic, service) | All 8 |
| Block patterns | 10 (2 per category) | All 50+ |
| Starter templates | 2 (blog, corporate) | All 5 |
| WooCommerce templates | ❌ | ✅ |
| Setup wizard + demo import | ❌ | ✅ |
| IGNY8 plugin bridge | ✅ Full | ✅ Full |
### Toolkit Plugin
| Feature | Free | Premium |
|---------|------|---------|
| Performance: page cache + HTML minification | ✅ | ✅ |
| Performance: full suite (critical CSS, image opt, WebP, assets) | ❌ | ✅ |
| Security: basic hardening + login protection | ✅ | ✅ |
| Security: full suite (firewall, audit log, 2FA) | ❌ | ✅ |
| Forms: basic (5 field types) | ✅ | ✅ |
| Forms: full suite (conditional logic, multi-step, file upload) | ❌ | ✅ |
| SMTP: basic mail override | ✅ | ✅ |
| SMTP: full suite (email log, templates) | ❌ | ✅ |
| WooCommerce enhancements | ❌ | ✅ |
---
## 28. Theme ↔ Plugin Contract {#28-theme-plugin-contract}
### What Theme Reads from Plugin
| Data | Source | Used For |
|------|--------|---------|
| SEO title | `igny8()->seo->get_title()` | `<title>` tag (theme defers to plugin) |
| Breadcrumbs | `igny8()->seo->get_breadcrumbs()` | Breadcrumb display |
| Related links | `_igny8_related_links` post meta | Related Articles section |
| Cluster navigation | `igny8()->linking->get_cluster_navigation()` | "More in this topic" section |
| Term landing content | `_igny8_term_content` term meta | Term archive hero section |
| Term FAQs | `_igny8_term_faq` term meta | FAQ accordion on term pages |
| Related terms | `_igny8_term_related_terms` term meta | "Related topics" block |
| SAG attribute label | `_igny8_term_sag_attribute` term meta | Attribute navigation sections |
| Share buttons | `igny8()->socializer->render_share_buttons()` | Social sharing section |
| Schema | `igny8()->schema->get_json_ld()` | Theme does NOT render schema (plugin owns `<head>`) |
### Graceful Degradation
```php
// Theme pattern for ALL plugin data reads:
if (function_exists('igny8')) {
$data = igny8()->module->get_data($id);
} else {
$data = theme_fallback_function($id);
}
```
When plugin is NOT installed: breadcrumbs use theme's simple implementation, related content uses category-based matching, term pages show standard WP description, share buttons don't render, schema doesn't output.
---
## 29. Plugin ↔ IGNY8 SaaS Communication {#29-saas-communication}
### Authentication
- Plugin stores `igny8_api_key` (from setup wizard Step 5)
- All requests to IGNY8 SaaS include `Authorization: Bearer {api_key}`
- All requests FROM IGNY8 SaaS to plugin include `X-IGNY8-API-KEY` header
- Plugin validates against `igny8_api_key` option
### Outbound (Plugin → SaaS)
| Event | Endpoint on SaaS | Payload |
|-------|------------------|---------|
| Site structure sync (daily) | `POST /v1/integration/integrations/{id}/update-structure/` | Post types, taxonomies, counts |
| Incremental data sync | `POST /v1/integration/integrations/{id}/sync-data/` | Modified posts since last sync |
| Full site scan (weekly) | `POST /v1/integration/integrations/{id}/full-scan/` | All posts, products, taxonomies |
| Content publish confirmation | `POST /v1/integration/integrations/{id}/publish-confirm/` | WP post ID, URL, status |
| Taxonomy creation report | `POST /v1/integration/integrations/{id}/taxonomy-report/` | Created taxonomy slugs + term IDs |
### Inbound (SaaS → Plugin)
| Event | Plugin Endpoint | Payload |
|-------|----------------|---------|
| Push content | `POST /wp-json/igny8/v1/sync/push` | Content HTML, meta, images, content_type |
| Push blueprint | `POST /wp-json/igny8/v1/sag/sync-blueprint` | Full SAG blueprint JSON |
| Create taxonomies | `POST /wp-json/igny8/v1/sag/create-taxonomies` | Taxonomy definitions + terms |
| Push term content | `POST /wp-json/igny8/v1/terms/{id}/content` | HTML content + meta for term |
| Push schemas | `POST /wp-json/igny8/v1/schema/bulk-update` | Schema JSON-LD per post |
| Push GSC statuses | `POST /wp-json/igny8/v1/gsc/status-sync` | URL index statuses |
| Push events | `POST /wp-json/igny8/v1/event` | task_ready, link_suggestion, etc. |
### Sync Architecture
```
IGNY8 SaaS (api.igny8.com)
│ Outbound webhooks (push content, blueprints, schemas, statuses)
WordPress Plugin (site.com/wp-json/igny8/v1/*)
│ Periodic sync (structure, data, confirmations)
IGNY8 SaaS (api.igny8.com/v1/integration/*)
```
All communication is HTTPS. Plugin-side: async via WP Cron (never blocks page load). SaaS-side: async via Celery tasks (never blocks API response).
---
## Reference Documents
| Document | Purpose |
|----------|---------|
| **IGNY8-Plugin-Build-Plan.md** | Complete plugin plan — modules, features, phases, file structure |
| **Theme-Build-Plan.md** | Complete theme plan — CPTs, taxonomies, templates, patterns, toolkit |
| **IGNY8-Current-State.md** | Current IGNY8 SaaS state — integration layer, plugin distribution, sync architecture |
| **Doc A — SAG Architecture Dev Guide** | SAG models, blueprints — what the plugin receives in connected mode |
| **Doc B — Platform Modules Dev Guide** | SaaS modules — what generates content/schemas/links pushed to plugin |
---
*End of Doc C — WordPress Ecosystem Development Guide*

View File

@@ -0,0 +1,813 @@
# Doc D — Business & Services: Development Guide for Claude Code
**Version:** 1.0
**Date:** March 2026
**For:** Claude Code (Opus 4.6) in VSCode on IGNY8 repo
**Purpose:** Implementation guide for the business/revenue layer — Managed Services Add-On, Backlink Service Tiers, client onboarding workflows, white-label reporting, and billing integration for services
**Scope:** Managed Add-On tiers (Lite $100, Pro $399/site/month), Backlink service packaging (self-service + managed), Alorig client portfolio servicing, billing models and margin tracking
**Rule:** Core IGNY8 SaaS subscription plans (Free/Starter/Growth/Scale) are unchanged. Managed services are add-ons purchased per site, layered on top of existing plans. All service delivery uses existing IGNY8 platform features — no separate tool stack.
**Dependency:** Doc A (SAG Architecture) provides blueprints and campaign generation. Doc B (Platform Modules) provides content pipeline, GSC, Socializer. Doc C (WordPress Ecosystem) provides plugin infrastructure for delivery.
---
## Table of Contents
1. [Business Context — Current Revenue Model](#1-business-context)
2. [Managed Services Add-On — Product Definition](#2-managed-addon)
3. [Backlink Services — Product Definition](#3-backlink-services)
4. [Implementation: Backend Models & Billing](#4-backend-models)
5. [Implementation: Frontend — Service Management UI](#5-frontend-ui)
6. [Implementation: Service Delivery Workflow](#6-delivery-workflow)
7. [Implementation: Client Onboarding Automation](#7-onboarding)
8. [Implementation: Reporting & White-Label](#8-reporting)
9. [Implementation: Alorig Client Portfolio Servicing](#9-alorig-portfolio)
10. [API Endpoints](#10-api-endpoints)
11. [Celery Tasks](#11-celery-tasks)
12. [Feature Flags](#12-feature-flags)
13. [Margin Tracking & Business Intelligence](#13-margin-tracking)
---
## 1. Business Context — Current Revenue Model {#1-business-context}
### 1.1 Existing Subscription Plans
| Plan | Price | Sites | Users | Credits/Month |
|------|-------|-------|-------|---------------|
| Free | $0 | 1 | 1 | 100 |
| Starter | $49 | 3 | 3 | 1,000 |
| Growth | $149 | 10 | 10 | 5,000 |
| Scale | $349 | Unlimited | Unlimited | 25,000 |
**Payment:** Stripe and PayPal integrated (pending production credentials). Manual payment methods available.
**Billing models:** `modules/billing/` (API layer), `business/billing/` (services). `CreditService` manages all credit operations. `Plan` model in `auth/models.py`.
### 1.2 Revenue Expansion Opportunities
The current model is pure SaaS subscription + credits. Two service layers add high-margin revenue without changing the core platform:
1. **Managed Services Add-On** — Alorig team operates the IGNY8 platform on behalf of clients. Client pays subscription + managed fee. Alorig does the work.
2. **Backlink Services** — Link building packages using FatGrid/PR distribution. Self-service (client buys intelligence, executes themselves) or managed (Alorig team executes).
Both use the existing platform. No separate tools needed. The "service" is human expertise + platform operation — not new software features.
### 1.3 Existing Infrastructure to Leverage
| What Exists | How Services Use It |
|-------------|-------------------|
| SAG Site Builder (Doc A Phase 4) | Managed: Alorig runs wizard for client. Self-service: client runs it themselves. |
| Content Pipeline (Doc B Modules 1-2) | Managed: Alorig configures and runs automation. Client gets published content. |
| Backlink Campaign Generator (Doc A Phase 10) | Both: Platform generates campaign plan. Managed: Alorig executes. Self-service: client executes. |
| GSC Integration (Doc B Module 4) | Managed: Alorig monitors indexing, submits URLs. Reports to client. |
| Socializer (Doc B Module 6) | Managed Pro: Alorig configures social posting for client. |
| Rich Schema (Doc B Module 5) | Managed: Alorig runs retroactive enhancement on client sites. |
| WordPress Plugin (Doc C) | Both: Plugin installed on client site. Managed: Alorig configures connected mode. |
---
## 2. Managed Services Add-On — Product Definition {#2-managed-addon}
### 2.1 Tiers
| Tier | Price | What Client Gets | What Alorig Does |
|------|-------|------------------|-----------------|
| **Managed Lite** | $100/site/month | 10 articles/month, basic SEO setup, monthly report | Run SAG wizard, configure automation for 10 articles, publish to WordPress, basic optimization, email monthly report |
| **Managed Pro** | $399/site/month | 30 articles/month, full SAG architecture, backlink campaign management, social posting, weekly report, dedicated account manager | Full SAG build, configure all automation stages, manage backlink campaign execution, configure socializer, run retroactive schema enhancement, weekly report with KPIs |
### 2.2 What's Included in Each Tier
**Managed Lite ($100/site/month):**
- Initial SAG blueprint generation (one-time, first month)
- 10 articles/month through the content pipeline
- Basic WordPress taxonomy setup from blueprint
- Content published to WordPress (auto or scheduled)
- Monthly PDF report: articles published, keywords tracked, basic traffic metrics
- Email support (48hr response)
**Managed Pro ($399/site/month):**
- Everything in Lite, plus:
- Full SAG architecture with detailed mode (not quick mode)
- 30 articles/month (hub pages + supporting content per blueprint execution priority)
- Taxonomy term content generation (term landing pages)
- Backlink campaign management: plan generation, link sourcing via FatGrid, quality verification, anchor text management
- Monthly backlink budget: separate from service fee, passed through at cost + 20% markup
- Social media content generation + scheduling across configured platforms
- Retroactive schema enhancement on existing site pages
- GSC monitoring: auto-indexing, re-inspection, issue alerts
- Weekly PDF report: content published, backlinks built, indexing status, keyword rankings, traffic, DR progress
- Dedicated Slack channel or email thread (24hr response)
### 2.3 Client Requirements
The client must provide or enable:
- WordPress admin access (or install IGNY8 plugin themselves)
- Domain/hosting (Alorig does not host client sites)
- Business data for SAG wizard (products/services, brands, locations, problems solved — per Doc A Section 9.3)
- Approval on SAG blueprint before execution (Alorig presents, client approves)
- Social media account access (for Managed Pro social posting)
- Backlink budget approval (for Managed Pro, separate from service fee)
### 2.4 Margin Analysis
| Component | Managed Lite | Managed Pro |
|-----------|-------------|-------------|
| Service fee | $100/month | $399/month |
| IGNY8 platform cost (credits) | ~$15-25/month (10 articles, basic images) | ~$50-80/month (30 articles, quality images, social, schema) |
| Human time (Alorig team) | ~2-3 hrs/month | ~8-12 hrs/month |
| Effective hourly rate | $25-40/hr | $25-35/hr |
| Gross margin | ~75% | ~70-80% (excluding backlink pass-through) |
Backlink costs are pass-through with 20% markup — not included in the service fee.
---
## 3. Backlink Services — Product Definition {#3-backlink-services}
### 3.1 Two Modes
**Self-Service Mode:**
Client uses IGNY8's backlink campaign module (Doc A Phase 10) to generate campaign plans, browse FatGrid publishers, and track links. IGNY8 provides the intelligence. Client executes link building themselves.
No additional subscription needed — included with Scale plan or as a credit-based add-on.
**Managed Mode:**
Client submits campaign to Alorig team. Alorig sources links, manages quality, tracks progress, generates white-label reports. Client pays per-link or monthly retainer.
### 3.2 Service Tiers (Managed Mode)
| Tier | Service | IGNY8/Alorig Cost | Client Price | Margin |
|------|---------|-------------------|-------------|--------|
| **Basic Guest Post** | DR 30-50 via FatGrid | $30-80 | $150-300 | 3-5x |
| **Standard Guest Post** | DR 50-70 via FatGrid | $100-300 | $400-800 | 2-3x |
| **Premium Guest Post** | DR 70+ via FatGrid | $500-2,000 | $1,500-5,000 | 2-3x |
| **PR Basic** | 300+ outlets via EIN Presswire | $99-499 | $500-1,500 | 3-5x |
| **PR Premium** | Yahoo/Bloomberg/Fox via PRNews.io/Linking News | $500-5,000 | $2,000-15,000 | 3-4x |
### 3.3 Monthly Packages (Managed Mode)
| Package | Links/Month | DR Range | Monthly Cost | Typical Site Size |
|---------|------------|----------|-------------|------------------|
| **Starter** | 5-8 links | DR 30-50 | $800-1,500 | Small sites, PK market |
| **Growth** | 10-15 links | DR 30-70 mix | $2,000-4,000 | Medium sites, UK/CA market |
| **Authority** | 15-25 links | DR 40-70+ mix + PR | $4,000-8,000 | Large sites, USA market |
| **Enterprise** | Custom | Custom | Custom | Multi-site, agency clients |
### 3.4 Niche Surcharges
| Niche | Multiplier | Reason |
|-------|-----------|--------|
| Crypto/Casino | 2-3x | Limited publishers, high competition |
| Finance/Insurance | 1.5-2x | YMYL, stricter publisher requirements |
| Health/Medical | 1.5-2x | YMYL, content quality requirements |
| Tech/SaaS | 1.2-1.5x | Moderate competition |
| General | 1x (baseline) | Standard pricing |
---
## 4. Implementation: Backend Models & Billing {#4-backend-models}
### 4.1 New Models
Add to existing billing module or create new services module:
```python
# modules/billing/models.py or new modules/services/models.py
class ManagedServiceSubscription(AccountBaseModel):
"""Managed service add-on subscription per site."""
id = models.UUIDField(primary_key=True, default=uuid4)
site = models.ForeignKey('auth.Site', on_delete=models.CASCADE, related_name='managed_subscriptions')
tier = models.CharField(max_length=20, choices=[
('lite', 'Managed Lite'),
('pro', 'Managed Pro'),
])
status = models.CharField(max_length=20, choices=[
('pending', 'Pending Setup'),
('active', 'Active'),
('paused', 'Paused'),
('cancelled', 'Cancelled'),
], default='pending')
monthly_price = models.DecimalField(max_digits=8, decimal_places=2)
articles_per_month = models.IntegerField()
# Assigned team member
account_manager = models.ForeignKey('auth.User', null=True, blank=True, on_delete=models.SET_NULL,
related_name='managed_clients')
# Tracking
current_month_articles_published = models.IntegerField(default=0)
current_month_start = models.DateField(null=True, blank=True)
# Service config
service_config = models.JSONField(default=dict, help_text='Per-site service configuration: automation settings, social platforms, backlink budget, report schedule')
started_at = models.DateTimeField(null=True, blank=True)
cancelled_at = models.DateTimeField(null=True, blank=True)
next_billing_date = models.DateField(null=True, blank=True)
class BacklinkServiceOrder(AccountBaseModel):
"""Individual backlink service order or monthly retainer."""
id = models.UUIDField(primary_key=True, default=uuid4)
site = models.ForeignKey('auth.Site', on_delete=models.CASCADE)
campaign = models.ForeignKey('sag.SAGCampaign', null=True, blank=True, on_delete=models.SET_NULL)
order_type = models.CharField(max_length=20, choices=[
('one_time', 'One-Time Order'),
('monthly', 'Monthly Retainer'),
])
package = models.CharField(max_length=30, choices=[
('starter', 'Starter (5-8 links)'),
('growth', 'Growth (10-15 links)'),
('authority', 'Authority (15-25 links)'),
('enterprise', 'Enterprise (custom)'),
('custom', 'Custom Order'),
], blank=True)
# Financial
client_price = models.DecimalField(max_digits=10, decimal_places=2)
actual_cost = models.DecimalField(max_digits=10, decimal_places=2, default=0)
margin = models.DecimalField(max_digits=10, decimal_places=2, default=0)
niche_surcharge = models.FloatField(default=1.0, help_text='Multiplier: 1.0 = baseline')
# Delivery
links_ordered = models.IntegerField(default=0)
links_delivered = models.IntegerField(default=0)
links_live = models.IntegerField(default=0)
status = models.CharField(max_length=20, choices=[
('draft', 'Draft'),
('approved', 'Approved'),
('in_progress', 'In Progress'),
('delivered', 'Delivered'),
('completed', 'Completed'),
], default='draft')
# Tracking
ordered_at = models.DateTimeField(null=True, blank=True)
delivered_at = models.DateTimeField(null=True, blank=True)
notes = models.TextField(blank=True)
class ServiceReport(AccountBaseModel):
"""Generated report for a managed service client."""
id = models.UUIDField(primary_key=True, default=uuid4)
site = models.ForeignKey('auth.Site', on_delete=models.CASCADE)
managed_subscription = models.ForeignKey(ManagedServiceSubscription, null=True, blank=True, on_delete=models.SET_NULL)
report_type = models.CharField(max_length=20, choices=[
('weekly', 'Weekly Report'),
('monthly', 'Monthly Report'),
('quarterly', 'Quarterly Review'),
])
period_start = models.DateField()
period_end = models.DateField()
# Report data
report_data = models.JSONField(default=dict, help_text='All metrics for this period')
report_pdf_url = models.URLField(blank=True, help_text='Generated PDF stored in S3')
# White-label
is_white_label = models.BooleanField(default=False)
brand_name = models.CharField(max_length=200, blank=True, help_text='Client-facing brand name (if white-label)')
brand_logo_url = models.URLField(blank=True)
generated_at = models.DateTimeField(auto_now_add=True)
sent_at = models.DateTimeField(null=True, blank=True)
```
### 4.2 Billing Integration
Managed services integrate with the existing billing system:
```python
# business/billing/managed_billing_service.py # NEW
class ManagedBillingService:
def create_managed_subscription(self, site, tier, payment_method):
"""Create managed service subscription + first invoice."""
# 1. Create ManagedServiceSubscription record
# 2. Create Stripe/PayPal subscription or manual invoice
# 3. Deduct from account credit balance OR charge directly
# 4. Set next_billing_date
pass
def process_monthly_billing(self):
"""Celery task: process all active managed subscriptions monthly."""
# For each active subscription:
# 1. Generate invoice
# 2. Charge payment method
# 3. Reset current_month_articles_published
# 4. Update current_month_start
pass
def process_backlink_order(self, order):
"""Process payment for a backlink service order."""
# 1. Calculate total: client_price × niche_surcharge
# 2. Charge payment method
# 3. Update order status to 'approved'
pass
def calculate_margin(self, order):
"""Calculate and store margin on a completed backlink order."""
order.margin = order.client_price - order.actual_cost
order.save()
```
### 4.3 Service Configuration Storage
The `service_config` JSON field on ManagedServiceSubscription stores per-client settings:
```json
{
"automation": {
"schedule": "weekly",
"articles_per_run": 3,
"content_types": ["post", "cluster_hub", "taxonomy_landing"],
"auto_publish": false,
"review_required": true
},
"backlinks": {
"monthly_budget": 2000,
"target_country": "US",
"package": "growth",
"auto_approve_under": 200
},
"social": {
"platforms": ["linkedin", "twitter"],
"auto_post_on_publish": true,
"posting_schedule": "best_time"
},
"reporting": {
"frequency": "weekly",
"format": "pdf",
"white_label": false,
"recipients": ["client@example.com"],
"include_backlinks": true,
"include_rankings": true,
"include_traffic": true
}
}
```
---
## 5. Implementation: Frontend — Service Management UI {#5-frontend-ui}
### 5.1 Admin-Only Service Dashboard
This is an internal Alorig team interface, not client-facing.
```
frontend/src/pages/
└── Services/ # NEW page (admin only)
├── ServicesDashboard.tsx # Overview: all managed clients, revenue summary
│ ├── ClientList.tsx # All managed subscriptions with status
│ ├── RevenueSummary.tsx # MRR, active clients, margin totals
│ └── UpcomingActions.tsx # Tasks due: reports, renewals, content due
├── ClientDetail.tsx # Single client management view
│ ├── ClientConfig.tsx # Service config editor (automation, social, backlinks)
│ ├── ContentTracker.tsx # Articles published this month vs target
│ ├── BacklinkTracker.tsx # Links ordered vs delivered vs live
│ ├── ReportHistory.tsx # Generated reports with resend option
│ └── BillingHistory.tsx # Invoices, payments, margin
├── BacklinkOrders.tsx # All backlink orders across clients
│ ├── OrderList.tsx # Filterable by client, status, package
│ └── OrderDetail.tsx # Individual order with link-by-link tracking
└── ReportGenerator.tsx # Generate reports for any client/period
```
**Sidebar addition (admin only):**
```
ADMIN
├── Sector Templates
└── Managed Services (NEW — admin only)
```
### 5.2 Client-Facing View (Optional)
Managed clients who also have IGNY8 app access see a simplified view:
```
frontend/src/pages/
└── ManagedService/ # NEW page (for managed clients)
├── ServiceOverview.tsx # What's included, current month progress
├── ReportViewer.tsx # View past reports
└── ApprovalQueue.tsx # Approve blueprint, content (if review_required)
```
This page appears in the client's sidebar only if they have an active `ManagedServiceSubscription`:
```
ACCOUNT
├── Account Settings
├── Plans & Billing
├── Managed Service (NEW — if managed subscription active)
├── Usage
└── AI Models
```
---
## 6. Implementation: Service Delivery Workflow {#6-delivery-workflow}
### 6.1 Managed Lite — Monthly Workflow
```
Month Start
├── Check: blueprint exists? If not → run SAG wizard for client (first month)
├── Run automation pipeline (10 articles):
│ 1. Blueprint check → load unfulfilled content needs
│ 2. Generate ideas from blueprint (execution priority order)
│ 3. Create tasks (content_type based on blueprint)
│ 4. Generate content (type-specific prompts)
│ 5. Generate images
│ 6. → Review queue
├── Alorig team reviews content (manual quality check)
│ - Approve or edit in Writer → Review tab
│ - Publish approved content to WordPress
├── Update ManagedServiceSubscription.current_month_articles_published
└── Month End:
├── Generate monthly report (ServiceReport)
├── Send to client via email
└── Process next month billing
```
### 6.2 Managed Pro — Monthly Workflow
```
Month Start
├── Everything from Lite, PLUS:
├── Run automation for 30 articles (hub pages prioritized in early months)
├── Backlink campaign management:
│ 1. Load this month's plan from SAGCampaign
│ 2. Browse FatGrid for publishers matching plan criteria
│ 3. Place orders on FatGrid/PR platforms
│ 4. Track delivery: ordered → pending → live
│ 5. Quality check each delivered link
│ 6. Log in SAGBacklink records
│ 7. Run dead link check on previous links
├── Social media:
│ 1. Generate social posts for published content
│ 2. Schedule across configured platforms
│ 3. Monitor engagement metrics
├── Schema enhancement:
│ 1. Run retroactive schema scan on any new/updated pages
│ 2. Generate and push schemas to WordPress
├── GSC monitoring:
│ 1. Check indexing status of all published content
│ 2. Re-request indexing for pending items
│ 3. Flag issues to client if needed
└── Week End (weekly report):
├── Generate weekly report (ServiceReport)
├── Include: articles published, backlinks built, indexing status, ranking changes
└── Send to client
```
### 6.3 Backlink Order Workflow (Managed Mode)
```
Client approves monthly backlink budget
├── Alorig loads this month's campaign plan from IGNY8
│ - Target pages, DR ranges, anchor text mix, link count
├── Browse FatGrid publishers:
│ - Filter by: country, niche, DR range, budget
│ - Compare prices across marketplaces
│ - Select best-value publishers
├── Place orders:
│ - Guest post orders on FatGrid
│ - PR distribution on EIN Presswire / PRNews.io
│ - Create BacklinkServiceOrder record
├── Track delivery:
│ - Monitor publisher for content creation
│ - Verify link is live (HTTP check)
│ - Quality check: DR, traffic, niche relevance, outbound links
│ - Log each link as SAGBacklink
├── Quality scoring:
│ - Auto-score where possible (Ahrefs/FatGrid data)
│ - Manual checks: content quality, relevance, link placement
│ - Flag issues if quality below threshold
└── Update campaign:
- BacklinkServiceOrder.links_delivered++
- SAGCampaign KPI update
- Calculate margin: client_price - actual_cost
```
---
## 7. Implementation: Client Onboarding Automation {#7-onboarding}
### 7.1 Managed Client Onboarding Flow
When a managed service subscription is created:
```python
# business/services/onboarding_service.py # NEW
class ManagedOnboardingService:
def onboard_client(self, subscription):
"""Automated onboarding for new managed client."""
site = subscription.site
# Step 1: Ensure IGNY8 plugin is installed and connected
# Check site.wp_api_key exists → if not, send installation guide email
# Step 2: Run SAG Site Builder if no blueprint exists
if not site.sag_blueprint_id:
# Queue Celery task to generate blueprint
# Notification to account manager: "Blueprint ready for review"
pass
# Step 3: Configure automation based on service_config
# Set AutomationConfig schedule, stages, content types
# Step 4: Send welcome email to client
# Include: what to expect, how to approve content, contact info
# Step 5: Create first month tasks in internal queue
# Notification to account manager: "New client onboarded, first content due"
# Step 6: Update subscription status: pending → active
```
### 7.2 Client Intake Form
For collecting business data (feeds into SAG wizard):
```
frontend/src/pages/Services/
└── components/
└── ClientIntakeForm.tsx # NEW — admin fills this during client onboarding
```
Collects per Doc A Section 9.3:
- Site URL, industry, sectors
- Products/services list
- Problems solved
- Brands (if e-commerce)
- Locations (if service-based)
- Competitors
- Target countries (for backlink campaigns)
- Social media accounts
- Current SEO status (any existing plugins, backlink profile)
This data feeds directly into the SAG wizard's business data inputs.
---
## 8. Implementation: Reporting & White-Label {#8-reporting}
### 8.1 Report Generation Service
```python
# business/services/report_service.py # NEW
class ReportService:
def generate_report(self, site, period_start, period_end, report_type, white_label=False):
"""Generate a service report for a managed client."""
report_data = {
'content': self._get_content_metrics(site, period_start, period_end),
'backlinks': self._get_backlink_metrics(site, period_start, period_end),
'indexing': self._get_indexing_metrics(site, period_start, period_end),
'rankings': self._get_ranking_metrics(site, period_start, period_end),
'traffic': self._get_traffic_metrics(site, period_start, period_end),
'social': self._get_social_metrics(site, period_start, period_end),
'health': self._get_sag_health(site),
}
# Generate PDF
pdf_url = self._render_pdf(report_data, white_label, site)
# Create ServiceReport record
report = ServiceReport.objects.create(
site=site, report_type=report_type,
period_start=period_start, period_end=period_end,
report_data=report_data, report_pdf_url=pdf_url,
is_white_label=white_label,
)
return report
def _get_content_metrics(self, site, start, end):
"""Articles published, content types breakdown, word count total."""
pass
def _get_backlink_metrics(self, site, start, end):
"""Links built, DR distribution, cost, quality scores."""
pass
def _get_indexing_metrics(self, site, start, end):
"""Pages indexed, pending, errors (from GSC module)."""
pass
def _get_ranking_metrics(self, site, start, end):
"""Keywords in top 10/20/50, position changes (from GSC module)."""
pass
def _get_traffic_metrics(self, site, start, end):
"""Organic traffic, impressions, CTR (from GSC module)."""
pass
def _get_social_metrics(self, site, start, end):
"""Posts published, engagement, clicks (from Socializer module)."""
pass
def _get_sag_health(self, site):
"""SAG health score, cluster completion (from SAG module)."""
pass
```
### 8.2 PDF Report Template
Reports generated as PDF using a template system. Stored in S3/media storage.
**Report sections (configurable per client):**
1. Executive Summary — key wins this period
2. Content Performance — articles published, type breakdown
3. Indexing Status — indexed/pending/error counts with trend
4. Keyword Rankings — top movers, new entries, lost positions
5. Organic Traffic — clicks, impressions, CTR with month-over-month
6. Backlink Campaign (if active) — links built, DR distribution, budget spent, quality
7. Social Media (if active) — posts, engagement, top performers
8. SAG Health — overall score, cluster completion, recommendations
9. Next Month Plan — what's coming, what client needs to approve
### 8.3 White-Label Support
For agency clients reselling IGNY8 services:
- `ServiceReport.brand_name` replaces "IGNY8" / "Alorig" throughout PDF
- `ServiceReport.brand_logo_url` replaces logo in PDF header
- Report footer shows agency contact info, not Alorig
- White-label reports generated via Linking News API for backlink reporting
---
## 9. Implementation: Alorig Client Portfolio Servicing {#9-alorig-portfolio}
### 9.1 Current Alorig Clients (from Rich Schema doc)
| Client | Type | Site | Priority Services |
|--------|------|------|------------------|
| Banner Printing (UK) | Service/eCommerce | ~50 pages | FAQ Schema, Breadcrumbs, Local Business Schema, Review markup |
| Aterna Advisors (CA) | Finance content | ~135 pages | Article + Author Schema (YMYL), FAQ, TL;DR, Definition blocks |
| Seva Mattress | WooCommerce | Product catalog | Product Schema, AggregateRating, FAQ, Pros & Cons |
| VAINO | WooCommerce + brand | Product + brand pages | Product Schema, Breadcrumbs, FAQ, Review markup |
| African Fair Trade Society | Nonprofit content | Content + service pages | Article Schema, FAQ, Organization Schema, Breadcrumbs |
| Halal VPN | Blog + product | Blog + product pages | Article, HowTo, FAQ, Comparison Tables, Pros & Cons |
### 9.2 Per-Client Service Plan
Each Alorig client can be onboarded as a Managed Service subscriber:
```
For each client:
1. Create ManagedServiceSubscription (Lite or Pro based on scope)
2. Run client intake → collect business data
3. Run SAG Site Builder → generate blueprint
4. Install/update IGNY8 plugin on client site
5. Run retroactive schema enhancement (Rich Schema module)
6. Configure content pipeline based on gaps
7. Set up reporting schedule
8. (Pro clients) Generate backlink campaign, begin execution
```
### 9.3 Internal Service Tracking
The admin Services Dashboard provides at-a-glance view of all Alorig clients:
- Client name, site, tier, status
- This month: articles target vs published, backlinks target vs delivered
- Overdue items: reports not sent, content not published, links behind schedule
- Revenue: MRR from managed services, backlink revenue, total margin
---
## 10. API Endpoints {#10-api-endpoints}
### Managed Services
```
GET /api/v1/services/subscriptions/ # List managed subscriptions (admin)
POST /api/v1/services/subscriptions/ # Create subscription
GET /api/v1/services/subscriptions/{id}/ # Subscription detail
PATCH /api/v1/services/subscriptions/{id}/ # Update config, status
POST /api/v1/services/subscriptions/{id}/onboard/ # Trigger onboarding workflow
POST /api/v1/services/subscriptions/{id}/pause/ # Pause subscription
POST /api/v1/services/subscriptions/{id}/cancel/ # Cancel subscription
```
### Backlink Orders
```
GET /api/v1/services/backlink-orders/ # List orders (admin)
POST /api/v1/services/backlink-orders/ # Create order
GET /api/v1/services/backlink-orders/{id}/ # Order detail
PATCH /api/v1/services/backlink-orders/{id}/ # Update status, delivery
GET /api/v1/services/backlink-orders/{id}/links/ # Links in this order
```
### Reports
```
GET /api/v1/services/reports/ # List reports (admin + client)
POST /api/v1/services/reports/generate/ # Generate report
GET /api/v1/services/reports/{id}/ # Report detail + PDF URL
POST /api/v1/services/reports/{id}/send/ # Email report to client
```
### Dashboard (Admin)
```
GET /api/v1/services/dashboard/ # Revenue summary, client overview
GET /api/v1/services/dashboard/overdue/ # Overdue tasks across clients
GET /api/v1/services/dashboard/margin/ # Margin tracking summary
```
---
## 11. Celery Tasks {#11-celery-tasks}
| Task | Schedule | Purpose |
|------|----------|---------|
| `process_managed_billing` | Monthly (1st of month) | Invoice all active managed subscriptions |
| `generate_weekly_reports` | Weekly (Monday 6am) | Generate reports for all Pro clients |
| `generate_monthly_reports` | Monthly (1st of month) | Generate reports for all Lite + Pro clients |
| `send_pending_reports` | Daily | Email any generated but unsent reports |
| `check_overdue_deliverables` | Daily | Flag any managed clients behind on content/links |
| `reset_monthly_counters` | Monthly (1st of month) | Reset current_month_articles_published |
| `check_backlink_delivery` | Daily | Check FatGrid/publisher status on open orders |
---
## 12. Feature Flags {#12-feature-flags}
| Flag | Controls | Default |
|------|---------|---------|
| `managed_services_enabled` | Services admin page, subscription management, onboarding | `False` |
| `backlink_orders_enabled` | Backlink order management (independent of campaign module) | `False` |
| `white_label_reports` | White-label branding on reports | `False` |
---
## 13. Margin Tracking & Business Intelligence {#13-margin-tracking}
### 13.1 What to Track
| Metric | Source | Aggregation |
|--------|--------|-------------|
| Managed Services MRR | Sum of active ManagedServiceSubscription.monthly_price | Monthly |
| Backlink Revenue | Sum of BacklinkServiceOrder.client_price (completed orders) | Monthly |
| Backlink Cost | Sum of BacklinkServiceOrder.actual_cost | Monthly |
| Backlink Margin | Revenue - Cost per order, aggregated | Monthly |
| Blended Margin % | (Total Revenue - Total Cost) / Total Revenue | Monthly |
| Cost Per Article | Platform credits used / articles published per client | Monthly |
| Team Hours (manual tracking) | Time spent per client | Monthly |
| Effective Hourly Rate | (Revenue - Platform Costs) / Hours | Monthly |
| Client Retention | Active subscriptions / Total ever created | Lifetime |
| Average Revenue Per Client | Total revenue / Active clients | Monthly |
### 13.2 Admin Dashboard Metrics
The Services Dashboard (admin-only) shows:
- Total MRR from managed services
- Total backlink revenue (monthly)
- Blended margin percentage
- Client count by tier (Lite vs Pro)
- Top 5 clients by revenue
- Clients behind on deliverables
- Month-over-month growth
### 13.3 Future: Automated Margin Calculation
When FatGrid API integration is complete (Doc A Phase 10), backlink order costs can be auto-populated from actual FatGrid transaction data, making margin tracking fully automated instead of manually entered.
---
## Reference Documents
| Document | Purpose |
|----------|---------|
| **IGNY8-Current-State.md** | Billing system, credit costs, subscription plans |
| **SAG-Doc4-External-Backlink-Campaign-PLAN.md** | Campaign generation, FatGrid tiers, service pricing |
| **IGNY8-Rich-Schema-SERP-Enhancement-Module.docx** | Client portfolio with retroactive enhancement opportunities |
| **Doc A — SAG Architecture Dev Guide** | Campaign module (Phase 10), SAG Site Builder (Phase 4) |
| **Doc B — Platform Modules Dev Guide** | GSC, Socializer, Rich Schema — features delivered to managed clients |
| **Doc C — WordPress Ecosystem Dev Guide** | Plugin installation and configuration for managed sites |
---
*End of Doc D — Business & Services Development Guide*