# CLAUDE.md This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. ## Project Overview This is a comprehensive WordPress plugin for Twilio voice and SMS integration, featuring: - **Call Center Functionality**: Agent groups, call queues, call distribution - **Business Hours Management**: Schedules for workflow routing - **Outbound Calling**: Click-to-call with proper caller ID - **SMS Notifications**: Agent notifications and callback management - **Workflow Builder**: Visual call flow creation - **Voicemail System**: Recording and transcription - **Real-time Dashboard**: Agent queue management ## Plugin Architecture ### Core Classes (`includes/` directory) - **TWP_Core**: Main plugin initialization and hook registration - **TWP_Activator**: Database table creation and plugin activation - **TWP_Twilio_API**: Official Twilio PHP SDK wrapper (requires SDK v8.7.0) - **TWP_Webhooks**: Handles all Twilio webhook endpoints - **TWP_Scheduler**: Business hours and schedule management - **TWP_Workflow**: Call flow processing and TwiML generation - **TWP_Call_Queue**: Queue management and position tracking - **TWP_Agent_Groups**: Group management for call distribution - **TWP_Agent_Manager**: Agent status and call acceptance - **TWP_Callback_Manager**: Callback requests and processing - **TWP_Call_Logger**: Call logging and statistics ### Database Tables Created by `TWP_Activator::create_tables()`: - `twp_phone_schedules` - Business hours definitions - `twp_call_queues` - Queue configurations - `twp_queued_calls` - Active calls in queues - `twp_workflows` - Call flow definitions - `twp_call_log` - Complete call history - `twp_sms_log` - SMS message tracking - `twp_voicemails` - Voicemail recordings and transcriptions - `twp_agent_groups` - Agent group definitions - `twp_group_members` - User-to-group relationships - `twp_agent_status` - Real-time agent availability - `twp_callbacks` - Callback request queue ### Admin Interface (`admin/` directory) - **TWP_Admin**: Complete admin interface with pages for: - Dashboard with real-time statistics - Business Hours Schedules management - Workflow Builder with drag-drop interface - Call Queues configuration - Phone Numbers management (purchase/configure) - Voicemail inbox with playback - Call Logs with filtering - Agent Groups management - Agent Queue dashboard - **Outbound Calls interface** (click-to-call) ### Webhook Endpoints All registered in `TWP_Webhooks::register_endpoints()`: - `/voice` - Main voice webhook for incoming calls - `/sms` - SMS webhook (handles agent "1" responses) - `/ivr-response` - IVR menu selections - `/queue-wait` - Queue hold music and position announcements - `/ring-group-result` - Handle no-answer scenarios and requeuing - `/agent-connect` - Connect SMS-responding agents to calls - `/callback-*` - Callback system webhooks - `/outbound-agent-with-from` - Outbound calling with from number ## Key Features Implementation ### Agent Group System - **Simultaneous Ring**: All group members called at once - **Priority Ordering**: Members have priority levels - **SMS Notifications**: Automatic alerts when no agents available - **One-Click Accept**: Agents can text "1" to receive calls - **Real-time Status**: Available/busy/offline tracking ### Call Queue Management - **Position Tracking**: Callers know their queue position - **Timeout Handling**: Offers callback instead of hanging up - **Auto-requeue**: Failed agent connections return to queue - **Real-time Dashboard**: Agents see waiting calls ### Callback System - **Smart Callbacks**: Replace timeout hangups - **SMS Confirmations**: Notify customers of callback requests - **Automatic Processing**: Cron-based callback execution - **Statistics Tracking**: Success rates and timing ### Outbound Calling - **From Number Selection**: Choose business line for caller ID - **Conference Routing**: Agent-to-customer connection - **Call Logging**: Track all outbound attempts - **Proper Caller ID**: Target sees business number ## WordPress Plugin Conventions ### File Structure ``` twilio-wp-plugin/ ├── twilio-wp-plugin.php (main plugin file) ├── includes/ (core functionality) ├── admin/ (admin interface) ├── assets/ (CSS/JS/images) ├── CLAUDE.md (this file) ``` ### Class Naming - Prefix: `TWP_` for all classes - Database tables: `twp_` prefix - Options: `twp_` prefix - AJAX actions: `twp_` prefix ### Database Operations - Use WordPress `$wpdb` global for all database operations - Always sanitize inputs with `sanitize_text_field()`, `intval()`, etc. - Use prepared statements with `$wpdb->prepare()` - Call `TWP_Activator::ensure_tables_exist()` before database operations ### AJAX Handling All AJAX endpoints registered in `TWP_Core::define_admin_hooks()`: ```php $this->loader->add_action('wp_ajax_twp_action_name', $plugin_admin, 'ajax_action_name'); ``` ### User Profile Integration Agent phone numbers stored as user meta: - Meta key: `twp_phone_number` - Validation: `TWP_Agent_Manager::validate_phone_number()` - Duplicate checking: `TWP_Agent_Manager::is_phone_number_duplicate()` ## Twilio Integration ### Current Implementation (SDK-Only) - **Official Twilio SDK**: Uses `twilio/sdk` v8.7.0 for all operations - **TwiML Generation**: Uses `\Twilio\TwiML\VoiceResponse` classes - **Response Handling**: Native Twilio SDK response objects - **Error Handling**: Proper `\Twilio\Exceptions\TwilioException` handling ### Installation Requirements **IMPORTANT**: The Twilio PHP SDK v8.7.0 is **REQUIRED** for this plugin to function. **Installation Methods**: 1. **Script Installation** (Recommended): ```bash chmod +x install-twilio-sdk.sh ./install-twilio-sdk.sh ``` 2. **Composer Installation**: ```bash composer install ``` **PHP Requirements**: PHP 8.0+ required for SDK compatibility ### API Response Structure Current Twilio API responses follow this pattern: ```php // Success response [ 'success' => true, 'data' => [...] // Twilio response data ] // Error response [ 'success' => false, 'error' => 'Error message', 'code' => 400 ] // Call SID location $call_sid = $response['data']['sid']; // NOT $response['call_sid'] ``` ### TwiML Best Practices Always include XML declaration: ```php $twiml = ''; $twiml .= ''; $twiml .= 'Message'; $twiml .= ''; ``` ## Development Commands ```bash # Install WordPress development dependencies composer install # Install JavaScript dependencies npm install # Run PHP CodeSniffer for WordPress coding standards vendor/bin/phpcs # Fix PHP coding standards automatically vendor/bin/phpcbf # Run PHPUnit tests vendor/bin/phpunit # Install Twilio SDK (recommended migration) composer require twilio/sdk ``` ## Testing Approach ### Unit Testing - Use PHPUnit for PHP code testing - Mock WordPress functions using Brain Monkey or WP_Mock - Mock Twilio API responses for reliable testing ### Integration Testing - Test webhook endpoints with Twilio webhook simulator - Test complete call flows end-to-end - Verify database operations and data integrity ### Manual Testing - Use Twilio Console to monitor webhook calls - Check WordPress error logs for debugging - Test with real phone numbers for user experience ## Common Issues & Solutions ### Database Issues - **Missing Tables**: Call `TWP_Activator::ensure_tables_exist()` - **White Admin Modals**: Check for PHP errors in workflow loading ### Webhook Issues - **500 Errors**: Check PHP error logs for fatal errors - **Missing Parameters**: Parameters must be in webhook URL, not just POST data - **TwiML Parse Errors**: Always include XML declaration ### API Issues - **Call SID Access**: Use `$response['data']['sid']` not `$response['call_sid']` - **Phone Number Format**: Store with + prefix (e.g., "+1234567890") - **From Number**: Must be a verified Twilio number ### Agent Management - **SMS Responses**: Agents text "1" to receive calls - **Phone Validation**: Auto-formats US numbers to +1 format - **Duplicate Prevention**: Checks phone numbers across all users This plugin provides a complete call center solution with professional-grade features suitable for business use.