סקירת ארכיטקטורה

⚠️ תת-מערכת Playbooks רדומה בגרסה המופצת

קוד ה-M3 Playbook נכלל בתוסף אך אינו מאותחל: המתודה Plugin::init_m3_system() ריקה ופריט התפריט הוסר. נתיבי ה-REST, ה-CPT, טבלאות waa_playbook* וה-hooks אינם קיימים בזמן ריצה בהתקנה רגילה. הרכיב מתואר כאן לצורכי עיון; בגרסה הנוכחית השתמשו ב-Custom Rules, Topics, Context ו-Promotions.

סקירת ארכיטקטורה

מסמך זה מספק סקירה טכנית מקיפה של ארכיטקטורת תוסף WordPress WooAI Chatbot Pro למפתחים בכירים. הוא מכסה את מבנה התוסף, תבניות עיצוב, זרימות נתונים ונקודות אינטגרציה.

1. ארכיטקטורה ברמה גבוהה

WooAI Chatbot Pro עוקב אחר ארכיטקטורה מודולרית מבוססת רכיבים שמשתלבת עמוק עם WordPress ו-WooCommerce תוך שמירה על הפרדת אחריות נקייה.

+------------------------------------------------------------------+
|                        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        |           |
|  +---------------+  +--------------+  +----------------+           |
+------------------------------------------------------------------+

רכיבים עיקריים

רכיבאחריות
PluginBootstrap, רישום hooks, אתחול תלויות
AIOrchestratorניהול AI רב-ספקי עם לוגיקת fallback
MessageHandlerעיבוד הודעות צ'אט, הרצת כלים
PlaybookEngineאוטומציה של זרימות שיחה
Widgetעיבוד ממשק צ'אט frontend
RestChatנקודות קצה REST API לפעולות צ'אט

2. מבנה תיקיות

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. רכיבי ליבה

תהליך Bootstrap של התוסף

אתחול התוסף עוקב אחר רצף מחמיר:

// 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
WooAIChatbotAutoloader::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
WooAIChatbotCoreLogger::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 = WooAIChatbotPlugin::instance();
    $plugin->run();
}

יישום תבנית Singleton

גם Plugin וגם AIOrchestrator משתמשים בתבנית Singleton כדי להבטיח מופעים יחידים:

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

התוסף תומך ב-namespaces כפולים:

Namespaceמיפוי תיקיותמוסכמת שמות קבצים
WooAIChatbotincludes/סגנון WordPress: class-foo-bar.php
WooAIincludes/ (מערכת M3)סגנון PSR-4: 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. תבניות עיצוב בשימוש

תבנית Singleton

שימוש: Plugin, AIOrchestrator, LicenseManager, ToolRegistry

מבטיחה מופע יחיד לאורך מחזור חיי היישום. קריטית לניהול מצב משותף כמו ספקי AI, sessions פעילים וסטטוס רישיון.

תבנית Repository

יישום: PlaybookRepository

מפשטת אחסון נתונים באמצעות Custom Post Types של WordPress:

namespace WooAIPlaybook;

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

יישום: AIProviderInterface

מגדירה חוזה משותף לכל ספקי AI, מאפשרת שימוש חליפי:

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

יישום: מבצעי Steps ו-Actions

יוצרת באופן דינמי את המבצע המתאים לפי סוג השלב:

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

יישום: CoreLoader

מרכזת רישום hooks של WordPress, מפרידה הגדרות hook מביצוע:

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. מחזור חיי בקשה

אתחול Widget Frontend

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

זרימת עיבוד הודעות צ'אט

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

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

כל נקודות הקצה REST עוקבות אחר תבנית זו:

  1. אימות Nonce: אימות header של X-WP-Nonce
  2. בדיקת הרשאות: בקרת גישה מבוססת capabilities
  3. הגבלת קצב: חסימת בקשות מבוססת transients
  4. סניטציית קלט: פונקציות סניטציה של WordPress
  5. לוגיקה עסקית: הרצת handler
  6. עיצוב תגובה: WP_REST_Response עם קודי סטטוס מתאימים

6. תלויות

תלויות PHP (Composer)

חבילהגרסהמטרה
guzzlehttp/guzzle^7.8לקוח HTTP לקריאות API
openai-php/client^0.8OpenAI API SDK
vlucas/phpdotenv^5.5טעינת משתני סביבה
monolog/monolog^2.9לוגינג מובנה

תלויות JavaScript (NPM)

חבילהמטרה
react, react-dom^18.3מסגרת UI
@radix-ui/*primitives UI נגישים
tailwind-merge, clsxניהול מחלקות CSS
lucide-reactספריית אייקונים
rechartsגרפי analytics
motionאנימציות
react-hook-formניהול טפסים

כלי בנייה

כלימטרה
webpackאיגוד מודולים
typescriptבדיקת טיפוסים
tailwindcssCSS utility
babeltranspilation של JS
postcss-rtlcssתמיכה RTL

שירותים חיצוניים

שירותנקודת אינטגרציה
OpenAI APIOpenAIProvider למודלי GPT ו-embeddings
Google GeminiGeminiProvider למודלי Gemini
Anthropic ClaudeClaudeProvider למודלי Claude
Supabaseמסד נתונים וקטורי לחיפוש סמנטי RAG

7. הגדרות

משתני סביבה (.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

מפתח אפשרותתיאור
woo_ai_chatbot_settingsמערך הגדרות ראשי
woo_ai_chat_enabledtoggle נראות widget
woo_ai_chat_positionמיקום widget (bottom-right, bottom-left)
woo_ai_chat_welcome_messageברכה ראשונית
woo_ai_chatbot_analytics_configהגדרות GA4, Meta Pixel, Mixpanel

מבנה הגדרות התוסף

$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,
];

טבלאות מסד נתונים מותאמות אישית

טבלהמטרה
{prefix}_waa_sessionsשמירת sessions של צ'אט
{prefix}_waa_eventsמעקב אירועי analytics
{prefix}_waa_playbook_statesמצב ביצוע playbook

8. נקודות אינטגרציה מרכזיות

Hooks של WooCommerce

// 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();

תמיכה רב-לשונית

סדר זיהוי אוטומטי: 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);
}

משימות מתוזמנות (WP-Cron)

אירועלוח זמניםמטרה
woo_ai_chatbot_daily_indexיומיאינדוקס מחדש מלא של מוצרים
woo_ai_chatbot_cleanupשבועיניקוי sessions/events
waa_cleanup_playbook_sessionsשעתיפקיעת sessions ישנים של playbook
woo_ai_supabase_keepaliveיומימניעת השהיית free tier של Supabase

השלבים הבאים