סקירת ארכיטקטורה
קוד ה-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 | |
| +---------------+ +--------------+ +----------------+ |
+------------------------------------------------------------------+
רכיבים עיקריים
| רכיב | אחריות |
|---|---|
| Plugin | Bootstrap, רישום 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 | מיפוי תיקיות | מוסכמת שמות קבצים |
|---|---|---|
WooAIChatbot | includes/ | סגנון WordPress: class-foo-bar.php |
WooAI | includes/ (מערכת 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 עוקבות אחר תבנית זו:
- אימות Nonce: אימות header של
X-WP-Nonce - בדיקת הרשאות: בקרת גישה מבוססת capabilities
- הגבלת קצב: חסימת בקשות מבוססת transients
- סניטציית קלט: פונקציות סניטציה של WordPress
- לוגיקה עסקית: הרצת handler
- עיצוב תגובה:
WP_REST_Responseעם קודי סטטוס מתאימים
6. תלויות
תלויות PHP (Composer)
| חבילה | גרסה | מטרה |
|---|---|---|
guzzlehttp/guzzle | ^7.8 | לקוח HTTP לקריאות API |
openai-php/client | ^0.8 | OpenAI 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 | בדיקת טיפוסים |
tailwindcss | CSS utility |
babel | transpilation של JS |
postcss-rtlcss | תמיכה RTL |
שירותים חיצוניים
| שירות | נקודת אינטגרציה |
|---|---|
| OpenAI API | OpenAIProvider למודלי GPT ו-embeddings |
| Google Gemini | GeminiProvider למודלי Gemini |
| Anthropic Claude | ClaudeProvider למודלי 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_enabled | toggle נראות 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 |
השלבים הבאים
- מדריך REST API – כל ה-endpoints, אימות וסכמות בקשה ותגובה
- אינטגרציית AI – הגדרת ספקים והתאמה אישית
- Hooks ו-Filters – נקודות הרחבה לפיתוח מותאם אישית
- סכמת מסד הנתונים – טבלאות, אינדקסים וזרימת נתונים