Architecture Overview

This document provides a comprehensive technical overview of the WooAI Chatbot Pro WordPress plugin architecture for senior developers. It covers the plugin structure, design patterns, data flows, and integration points.

1. High-Level Architecture

WooAI Chatbot Pro follows a modular, component-based architecture that integrates deeply with WordPress and WooCommerce while maintaining clean separation of concerns.

+------------------------------------------------------------------+
|                        WordPress Environment                       |
+------------------------------------------------------------------+
|                                                                    |
|  +------------------------+    +-----------------------------+     |
|  |    Admin Dashboard     |    |      Frontend Widget        |     |
|  |  (React + Tailwind)    |    |   (React + TypeScript)      |     |
|  +----------+-------------+    +-------------+---------------+     |
|             |                                |                     |
|             v                                v                     |
|  +----------------------------------------------------------+     |
|  |                    REST API Layer                         |     |
|  |     /woo-ai/v1/chat | /woo-ai/v1/playbooks | /cart       |     |
|  +---------------------------+------------------------------+     |
|                              |                                     |
|  +---------------------------v------------------------------+     |
|  |                     Plugin Core                           |     |
|  |  +-------------+  +---------------+  +----------------+   |     |
|  |  |   Plugin    |  |     Core      |  |    Admin       |   |     |
|  |  |  (Singleton)|  |   (Loader)    |  |   (Settings)   |   |     |
|  |  +------+------+  +-------+-------+  +--------+-------+   |     |
|  |         |                 |                   |           |     |
|  +---------|-----------------|-------------------|-----------+     |
|            |                 |                   |                 |
|  +---------v-----------------v-------------------v-----------+     |
|  |                   Business Logic Layer                     |    |
|  |  +---------------+  +--------------+  +----------------+   |    |
|  |  | AIOrchestrator|  |   Playbook   |  |    Analytics   |   |    |
|  |  |  (Singleton)  |  |    Engine    |  |    Manager     |   |    |
|  |  +-------+-------+  +------+-------+  +--------+-------+   |    |
|  |          |                 |                   |           |    |
|  +----------|-----------------|-------------------|-----------+    |
|             |                 |                   |                |
|  +----------v-----------------v-------------------v----------+     |
|  |                    Data Access Layer                       |    |
|  |  +---------------+  +--------------+  +----------------+   |    |
|  |  |   Supabase    |  |  WordPress   |  |  WooCommerce   |   |    |
|  |  |    Client     |  |    DB/CPT    |  |   Integration  |   |    |
|  |  +---------------+  +--------------+  +----------------+   |    |
|  +------------------------------------------------------------+    |
|                                                                    |
+------------------------------------------------------------------+
|                     External Services                              |
|  +---------------+  +--------------+  +----------------+           |
|  |    OpenAI     |  |    Gemini    |  |    Claude      |           |
|  |     API       |  |     API      |  |     API        |           |
|  +---------------+  +--------------+  +----------------+           |
+------------------------------------------------------------------+

Main Components

Component Responsibility
Plugin Bootstrap, hook registration, dependency initialization
AIOrchestrator Multi-provider AI management with fallback logic
MessageHandler Chat message processing, tool execution
PlaybookEngine Conversational flow automation
Widget Frontend chat interface rendering
RestChat REST API endpoints for chat operations

2. Directory Structure

woo-ai-chatbot-pro/
├── woo-ai-chatbot-pro.php      # Plugin entry point, constants, bootstrap
├── composer.json               # PHP dependencies (Guzzle, Monolog, OpenAI)
├── package.json                # JS dependencies (React, Radix, Tailwind)
├── webpack.config.js           # Build configuration
├── tailwind.config.js          # Tailwind CSS configuration
│
├── includes/                   # PHP source code
│   ├── class-plugin.php        # Main Plugin singleton
│   ├── class-autoloader.php    # PSR-4 autoloader for dual namespaces
│   ├── class-activator.php     # Activation hooks
│   ├── class-deactivator.php   # Deactivation hooks
│   │
│   ├── Core/                   # Core infrastructure
│   │   ├── class-loader.php    # WordPress hook management (Observer pattern)
│   │   ├── class-logger.php    # Centralized logging
│   │   ├── class-database.php  # Database operations
│   │   ├── class-i18n.php      # Internationalization
│   │   └── class-frontend-translations.php
│   │
│   ├── AI/                     # AI provider layer
│   │   ├── AIProviderInterface.php       # Provider contract
│   │   ├── class-ai-orchestrator.php     # Provider fallback (Singleton)
│   │   ├── class-prompt-builder.php      # System prompt construction
│   │   ├── class-tool-registry.php       # Tool function registration
│   │   ├── Providers/
│   │   │   ├── class-openai-provider.php
│   │   │   ├── class-claude-provider.php
│   │   │   └── GeminiProvider.php
│   │   └── Tools/                        # AI tool implementations
│   │       ├── class-tool-interface.php
│   │       ├── class-search-products-tool.php
│   │       ├── class-add-to-cart-tool.php
│   │       └── class-create-checkout-tool.php
│   │
│   ├── chat/                   # Chat subsystem
│   │   ├── class-widget.php              # Frontend widget
│   │   ├── class-rest-chat.php           # REST API controller
│   │   ├── class-message-handler.php     # Message processing
│   │   └── class-session-manager.php     # Session persistence
│   │
│   ├── playbook/               # M3 Playbook system (WooAI namespace)
│   │   ├── PlaybookEngine.php            # Execution engine
│   │   ├── PlaybookRepository.php        # CPT data access (Repository pattern)
│   │   ├── PlaybookStateManager.php      # Session state
│   │   ├── PlaybookCPT.php               # Custom Post Type registration
│   │   ├── PlaybookSchema.php            # JSON schema validation
│   │   ├── PlaybookAIBridge.php          # AI-Playbook integration
│   │   ├── RestPlaybook.php              # REST API
│   │   ├── StepExecutors/                # Step type handlers (Factory)
│   │   │   ├── StepExecutorInterface.php
│   │   │   ├── MessageStep.php
│   │   │   ├── QuestionStep.php
│   │   │   ├── OptionsStep.php
│   │   │   ├── ProductListStep.php
│   │   │   ├── CouponStep.php
│   │   │   └── LinkStep.php
│   │   └── ActionExecutors/              # Action handlers
│   │       ├── ActionExecutorInterface.php
│   │       ├── AddToCartAction.php
│   │       ├── ApplyCouponAction.php
│   │       ├── OpenUrlAction.php
│   │       └── SendMessageAction.php
│   │
│   ├── promotion/              # Promotion system
│   │   ├── PromotionManager.php
│   │   └── RestPromotion.php
│   │
│   ├── search/                 # RAG search layer
│   │   ├── class-semantic-search.php     # Vector similarity search
│   │   ├── class-simple-product-search.php
│   │   ├── class-product-indexer.php
│   │   ├── class-embedding-generator.php
│   │   └── class-supabase-client.php
│   │
│   ├── admin/                  # Admin interfaces
│   │   ├── class-admin.php               # Menu, enqueue scripts
│   │   ├── class-settings.php            # Settings registration
│   │   ├── class-rest-analytics.php
│   │   ├── class-rest-playbooks.php
│   │   └── class-rest-topics.php
│   │
│   ├── analytics/              # Analytics subsystem
│   │   ├── class-analytics-manager.php
│   │   ├── class-analytics-query.php
│   │   ├── class-tracker.php
│   │   └── class-kpi-calculator.php
│   │
│   ├── integration/            # WooCommerce integration
│   │   ├── class-woo-commerce.php
│   │   └── class-woocommerce-actions.php
│   │
│   ├── topic/                  # Topic detection
│   │   ├── class-topic-detector.php
│   │   ├── class-topic-router.php
│   │   └── class-rest-topics-public.php
│   │
│   └── License/                # License management
│       ├── class-license-manager.php
│       └── class-hashed-keys.php
│
├── assets/                     # Frontend assets
│   ├── src/                    # TypeScript/React source
│   │   ├── admin/              # Admin dashboard
│   │   └── chat/               # Chat widget
│   ├── admin/js/               # Compiled admin bundle
│   └── chat/                   # Compiled chat bundle
│       ├── js/
│       └── css/
│
├── languages/                  # Translation files
│   ├── woo-ai-chatbot-pro.pot
│   ├── woo-ai-chatbot-pro-he_IL.po
│   └── ...
│
├── tests/                      # PHPUnit tests
│   ├── bootstrap.php
│   ├── AI/
│   ├── Chat/
│   └── Integration/
│
└── docs/                       # Documentation

3. Core Components

Plugin Bootstrap Process

The plugin initialization follows a strict sequence:

// 1. woo-ai-chatbot-pro.php - Entry point
define('WOO_AI_CHATBOT_VERSION', '0.2.1');
define('WOO_AI_CHATBOT_PLUGIN_DIR', plugin_dir_path(__FILE__));

// 2. Load Composer autoloader (dependencies)
require_once WOO_AI_CHATBOT_PLUGIN_DIR . 'vendor/autoload.php';

// 3. Register PSR-4 autoloader for plugin classes
WooAIChatbot\Autoloader::register();

// 4. Manually load core classes (WordPress compatibility)
$core_classes = ['Core/class-logger.php', ...];
foreach ($core_classes as $class_file) {
    require_once WOO_AI_CHATBOT_PLUGIN_DIR . 'includes/' . $class_file;
}

// 5. Initialize Logger singleton
WooAIChatbot\Core\Logger::init();

// 6. Hook into plugins_loaded
add_action('plugins_loaded', 'woo_ai_chatbot_init');

function woo_ai_chatbot_init() {
    if (!woo_ai_chatbot_check_woocommerce()) return;

    $plugin = WooAIChatbot\Plugin::instance();
    $plugin->run();
}

Singleton Pattern Implementation

Both Plugin and AIOrchestrator use the Singleton pattern to ensure single instances:

namespace WooAIChatbot;

class Plugin {
    private static $instance = null;

    public static function instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    private function __construct() {
        $this->load_dependencies();
        $this->set_locale();
        $this->define_admin_hooks();
        $this->define_public_hooks();
        $this->define_rest_api();
        $this->init_ai_providers();
        $this->init_rag_system();
        $this->init_m3_system();
        $this->schedule_cron_jobs();
    }
}

PSR-4 Autoloading Structure

The plugin supports dual namespaces:

Namespace Directory Mapping File Naming Convention
WooAIChatbot\ includes/ WordPress style: class-foo-bar.php
WooAI\ includes/ (M3 system) PSR-4 style: FooBar.php
// Autoloader supports both conventions
class Autoloader {
    public static function autoload($class) {
        $prefixes = [
            'WooAIChatbot\\' => 'class-',  // Legacy: class-foo-bar.php
            'WooAI\\'        => '',         // M3: FooBar.php
        ];
        // ... resolution logic
    }
}

4. Design Patterns Used

Singleton Pattern

Usage: Plugin, AIOrchestrator, LicenseManager, ToolRegistry

Ensures single instance across the application lifecycle. Critical for managing shared state like AI providers, active sessions, and license status.

Repository Pattern

Implementation: PlaybookRepository

Abstracts data persistence using WordPress Custom Post Types:

namespace WooAI\Playbook;

class PlaybookRepository {
    private const POST_TYPE = 'waa_playbook';

    public function create(array $data): int { ... }
    public function update(int $id, array $data): bool { ... }
    public function delete(int $id): bool { ... }
    public function get(int $id): ?array { ... }
    public function list(array $args = []): array { ... }
    public function find_by_intent(string $intent): ?array { ... }
}

Strategy Pattern

Implementation: AIProviderInterface

Defines a common contract for all AI providers, allowing interchangeable usage:

interface AIProviderInterface {
    public function generate_response($messages, $context = []);
    public function format_messages($messages);
    public function validate_api_key();
    public function get_models();
    public function get_provider_name();
    public function is_available();
}

// Implementations
class OpenAIProvider implements AIProviderInterface { ... }
class ClaudeProvider implements AIProviderInterface { ... }
class GeminiProvider implements AIProviderInterface { ... }

Factory Pattern

Implementation: Step and Action Executors

Dynamically instantiates the appropriate executor based on step type:

interface StepExecutorInterface {
    public function execute(array $step, array $context): array;
    public function get_type(): string;
}

// Step type executors
class MessageStep implements StepExecutorInterface { ... }
class QuestionStep implements StepExecutorInterface { ... }
class OptionsStep implements StepExecutorInterface { ... }
class ProductListStep implements StepExecutorInterface { ... }

Observer Pattern

Implementation: Core\Loader

Centralizes WordPress hook registration, decoupling hook definitions from execution:

class Loader {
    protected $actions = [];
    protected $filters = [];

    public function add_action($hook, $component, $callback, $priority = 10, $accepted_args = 1) {
        $this->actions[] = [
            'hook' => $hook,
            'component' => $component,
            'callback' => $callback,
            'priority' => $priority,
            'accepted_args' => $accepted_args,
        ];
    }

    public function run() {
        foreach ($this->actions as $hook) {
            add_action(
                $hook['hook'],
                [$hook['component'], $hook['callback']],
                $hook['priority'],
                $hook['accepted_args']
            );
        }
    }
}

5. Request Lifecycle

Frontend Widget Initialization

sequenceDiagram
    participant Browser
    participant WordPress
    participant Widget
    participant React

    Browser->>WordPress: Page Request
    WordPress->>Widget: wp_enqueue_scripts hook
    Widget->>Widget: should_display() check
    Widget->>WordPress: Enqueue chat-widget.bundle.js
    Widget->>WordPress: wp_localize_script (config)
    WordPress->>Browser: HTML + Scripts
    Browser->>React: Initialize widget
    React->>React: Mount to #woo-ai-chatbot-widget-root
    React->>Browser: Render chat interface

Chat Message Processing Flow

sequenceDiagram
    participant Widget
    participant RestChat
    participant MessageHandler
    participant AIOrchestrator
    participant Provider
    participant ToolRegistry

    Widget->>RestChat: POST /woo-ai/v1/chat/message
    RestChat->>RestChat: Rate limit check
    RestChat->>RestChat: Session validation
    RestChat->>MessageHandler: process_message()
    MessageHandler->>MessageHandler: Build context
    MessageHandler->>AIOrchestrator: generate_response()
    AIOrchestrator->>Provider: Try primary provider
    Provider-->>AIOrchestrator: Response or error
    alt Provider failed
        AIOrchestrator->>Provider: Try fallback provider
    end
    AIOrchestrator-->>MessageHandler: AI response
    MessageHandler->>ToolRegistry: Execute tool calls
    ToolRegistry-->>MessageHandler: Tool results
    MessageHandler-->>RestChat: Formatted response
    RestChat-->>Widget: JSON response

Admin Panel Request Handling

sequenceDiagram
    participant Browser
    participant Admin
    participant RestAPI
    participant Repository

    Browser->>Admin: Load admin page
    Admin->>Browser: Enqueue admin.bundle.js
    Browser->>RestAPI: GET /woo-ai/v1/settings
    RestAPI->>RestAPI: Capability check
    RestAPI->>Repository: Fetch data
    Repository-->>RestAPI: Settings/Playbooks
    RestAPI-->>Browser: JSON response
    Browser->>Browser: React renders UI

REST API Request Flow

All REST endpoints follow this pattern:

  1. Nonce Verification: X-WP-Nonce header validation
  2. Permission Check: Capability-based access control
  3. Rate Limiting: Transient-based request throttling
  4. Input Sanitization: WordPress sanitization functions
  5. Business Logic: Handler execution
  6. Response Formatting: WP_REST_Response with proper status codes

6. Dependencies

PHP Dependencies (Composer)

Package Version Purpose
guzzlehttp/guzzle ^7.8 HTTP client for API calls
openai-php/client ^0.8 OpenAI API SDK
vlucas/phpdotenv ^5.5 Environment variable loading
monolog/monolog ^2.9 Structured logging

JavaScript Dependencies (NPM)

Package Purpose
react, react-dom ^18.3
@radix-ui/* Accessible UI primitives
tailwind-merge, clsx CSS class management
lucide-react Icon library
recharts Analytics charts
motion Animations
react-hook-form Form management

Build Tools

Tool Purpose
webpack Module bundling
typescript Type checking
tailwindcss Utility CSS
babel JS transpilation
postcss-rtlcss RTL support

External Services

Service Integration Point
OpenAI API OpenAIProvider for GPT models and embeddings
Google Gemini GeminiProvider for Gemini models
Anthropic Claude ClaudeProvider for Claude models
Supabase Vector database for RAG semantic search

7. Configuration

Environment Variables (.env)

# AI Providers
OPENAI_API_KEY=sk-...
GEMINI_API_KEY=...
ANTHROPIC_API_KEY=...
AI_PROVIDER_PRIORITY=gemini,openai,claude

# Supabase (RAG)
SUPABASE_URL=https://xxx.supabase.co
SUPABASE_SERVICE_KEY=eyJ...

# Logging
LOG_LEVEL=info  # debug, info, warning, error

WordPress Options

Option Key Description
woo_ai_chatbot_settings Main settings array
woo_ai_chat_enabled Widget visibility toggle
woo_ai_chat_position Widget position (bottom-right, bottom-left)
woo_ai_chat_welcome_message Initial greeting
woo_ai_chatbot_analytics_config GA4, Meta Pixel, Mixpanel config

Plugin Settings Structure

$settings = [
    // AI Configuration
    'gemini_api_key' => '',
    'openai_api_key' => '',
    'claude_api_key' => '',

    // Appearance
    'widget_color' => '#6366F1',
    'secondary_color' => '#4F46E5',
    'accent_color' => '#10B981',
    'font_family' => 'Inter (Default)',
    'widget_width' => 380,
    'max_height' => 600,

    // Behavior
    'welcome_message' => 'Hello! How can I help you today?',
    'welcome_messages' => [  // Per-language
        'en' => 'Hello!',
        'he' => '!שלום',
    ],
    'bot_name' => 'AI Assistant',
    'bot_avatar' => 'robot',

    // Features
    'show_greeting' => true,
    'show_rating' => true,
];

Custom Database Tables

Table Purpose
{prefix}_waa_sessions Chat session persistence
{prefix}_waa_events Analytics event tracking
{prefix}_waa_playbook_states Playbook execution state

8. Key Integration Points

WooCommerce Hooks

// Product indexing on save
add_action('woocommerce_update_product', [$this, 'index_product_on_save']);
add_action('woocommerce_new_product', [$this, 'index_product_on_save']);

// Cart operations via WooCommerceActions class
$woo_actions->add_to_cart($product_id, $quantity);
$woo_actions->apply_coupon($coupon_code);
$woo_actions->get_checkout_url();

Multilingual Support

Automatic detection order: WPML > Polylang > TranslatePress > WordPress locale

private function get_current_language() {
    if (defined('ICL_LANGUAGE_CODE')) return ICL_LANGUAGE_CODE;
    if (function_exists('pll_current_language')) return pll_current_language();
    return substr(get_locale(), 0, 2);
}

Scheduled Tasks (WP-Cron)

Event Schedule Purpose
woo_ai_chatbot_daily_index Daily Full product reindexing
woo_ai_chatbot_cleanup Weekly Session/event cleanup
waa_cleanup_playbook_sessions Hourly Expire stale playbook sessions
woo_ai_supabase_keepalive Daily Prevent Supabase free tier pause

Next Steps