Files
twilio-wp-plugin/CLAUDE.md
jknapp 7cd7f036ff Fix extension transfer system and browser phone compatibility
Major Fixes:
- Fixed extension transfers going directly to voicemail for available agents
- Resolved browser phone call disconnections during transfers
- Fixed voicemail transcription placeholder text issue
- Added Firefox compatibility with automatic media permissions

Extension Transfer Improvements:
- Changed from active client dialing to proper queue-based system
- Fixed client name generation consistency (user_login vs display_name)
- Added 2-minute timeout with automatic voicemail fallback
- Enhanced agent availability detection for browser phone users

Browser Phone Enhancements:
- Added automatic microphone/speaker permission requests
- Improved Firefox compatibility with explicit getUserMedia calls
- Fixed client naming consistency across capability tokens and call acceptance
- Added comprehensive error handling for permission denials

Database & System Updates:
- Added auto_busy_at column for automatic agent status reversion
- Implemented 1-minute auto-revert system for busy agents with cron job
- Updated database version to 1.6.2 for automatic migration
- Fixed voicemail user_id association for extension voicemails

Call Statistics & Logging:
- Fixed browser phone calls not appearing in agent statistics
- Enhanced call logging with proper agent_id association in JSON format
- Improved customer number detection for complex call topologies
- Added comprehensive debugging for call leg detection

Voicemail & Transcription:
- Replaced placeholder transcription with real Twilio API integration
- Added manual transcription request capability for existing voicemails
- Enhanced voicemail callback handling with user_id support
- Fixed transcription webhook processing for extension voicemails

Technical Improvements:
- Standardized client name generation across all components
- Added ElevenLabs TTS integration to agent connection messages
- Enhanced error handling and logging throughout transfer system
- Fixed TwiML generation syntax errors in dial() methods

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-09-02 11:03:33 -07:00

31 KiB

CLAUDE.md - Twilio WordPress Plugin Documentation

This file provides comprehensive guidance to Claude Code (claude.ai/code) when working with the Twilio WordPress Plugin codebase.

🚨 CRITICAL: Testing & Deployment Environment

THIS PLUGIN RUNS ON A REMOTE SERVER IN A DOCKER CONTAINER - NOT LOCALLY

  • Production Server Path: /home/shadowdao/public_html/wp-content/plugins/twilio-wp-plugin/
  • Production URL: https://phone.cloud-hosting.io/
  • Development Path: /home/jknapp/code/twilio-wp-plugin/
  • Deployment Method: Files synced via rsync from development to Docker container

IMPORTANT NOTES:

  • NEVER assume local testing - all tests must work on remote server
  • Direct PHP tests work (php test-twilio-direct.php send)
  • WordPress admin context has issues that need investigation
  • The plugin requires Twilio PHP SDK v8.7.0 to function

📞 Standardized Phone Number Variable Names

THESE NAMING CONVENTIONS MUST BE STRICTLY FOLLOWED:

Required Variable Names:

  • incoming_number = Phone number that initiated contact (sent SMS/call TO the system)
  • agent_number = Phone number used to reach a specific agent
  • customer_number = Phone number of customer calling into the system
  • workflow_number = Twilio number assigned to a specific workflow
  • queue_number = Twilio number assigned to a specific queue
  • default_number = Default Twilio number when none specified

BANNED Variable Names (DO NOT USE):

  • from_number - Ambiguous, could be customer or system
  • to_number - Ambiguous, could be agent or system
  • phone_number - Too generic, must specify whose number
  • $agent_phone - Use $agent_number instead

Test Numbers:

  • Twilio Number: +19516215107
  • Test Agent Number: +19095737372
  • Fake Test Number: +19512345678 (DO NOT SEND SMS TO THIS)

Legacy Webhook URLs:

  • SMS: https://www.streamers.channel/wp-json/twilio-webhook/v1/sms
  • Voice: https://www.streamers.channel/wp-json/twilio-webhook/v1/voice

🏗️ Plugin Architecture Overview

Core Plugin Structure

twilio-wp-plugin/
├── twilio-wp-plugin.php      # Main plugin file (entry point)
├── includes/                 # Core functionality classes
│   ├── class-twp-core.php    # Main plugin initialization
│   ├── class-twp-activator.php    # Database setup
│   ├── class-twp-twilio-api.php   # Twilio SDK wrapper
│   ├── class-twp-webhooks.php     # REST API endpoints
│   ├── class-twp-tts-helper.php   # TTS with ElevenLabs/Twilio
│   └── ...                   # Other core classes
├── admin/                    # Admin interface
│   └── class-twp-admin.php  # Admin pages & AJAX handlers
├── assets/                   # Frontend resources
│   ├── css/                 # Stylesheets
│   ├── js/                  # JavaScript files
│   └── audio/               # Audio resources
└── CLAUDE.md                # This documentation file

📦 Core Classes Documentation

Main Classes (includes/ directory)

TWP_Core

  • Purpose: Main plugin initialization and hook registration
  • Key Methods:
    • define_admin_hooks(): Registers all admin AJAX actions
    • define_public_hooks(): Registers frontend hooks
    • define_webhook_hooks(): Registers REST API endpoints

TWP_Activator

  • Purpose: Database table creation and plugin activation
  • Tables Created: 15 database tables (see Database Schema section)
  • Key Methods:
    • ensure_tables_exist(): Checks and creates missing tables
    • migrate_tables(): Handles schema migrations
    • add_missing_columns(): Updates table structures

TWP_Twilio_API

  • Purpose: Wrapper for Twilio PHP SDK v8.7.0
  • Important: Uses direct instantiation (new TWP_Twilio_API())
  • Key Methods:
    • make_call(): Initiates outbound calls
    • send_sms(): Sends SMS messages
    • update_call(): Updates call state (hold/resume)
    • create_queue_twiml(): Generates queue TwiML

TWP_Webhooks

  • Purpose: Handles all Twilio webhook endpoints
  • Namespace: twilio-webhook/v1
  • Total Endpoints: 26 REST API routes

TWP_TTS_Helper (UNIVERSALLY INTEGRATED)

  • Purpose: Text-to-Speech with ElevenLabs integration, caching, and universal call control integration
  • Features:
    • Universal integration across all call control functions
    • Automatic ElevenLabs detection with Alice fallback
    • 30-day intelligent cache for identical text
    • Professional voice consistency throughout call lifecycle
  • Key Methods:
    • add_tts_to_twiml(): Universal TTS integration for all voice prompts
    • generate_tts_audio(): Pre-generates cached audio for performance
  • Coverage: Hold, transfer, requeue, workflow steps, and queue announcements

TWP_User_Queue_Manager (NEW)

  • Purpose: Comprehensive user-specific queue management with automatic creation
  • Features:
    • Automatic personal and hold queue creation for any user
    • Unique extension generation (100-9999) with collision detection
    • Database consistency with proper foreign key relationships
    • Browser phone call support for complex topologies
    • Schema compatibility (enqueued_at and joined_at columns)
    • Comprehensive error handling with rollback mechanisms
  • Key Methods:
    • create_user_queues(): Creates personal and hold queues with unique extensions
    • transfer_to_hold_queue(): Enhanced hold with auto-queue creation fallback
    • resume_from_hold(): Comprehensive resume with target queue support
    • generate_unique_extension(): Intelligent extension generation (3-4 digits)
    • get_user_extension_data(): Retrieves complete user queue information
  • Auto-Creation: Seamlessly integrates with hold, transfer, and queue operations

TWP_ElevenLabs_API

  • Purpose: Integration with ElevenLabs TTS service
  • Configuration: Uses twp_elevenlabs_* options
  • Features: Voice selection, model configuration, audio generation

TWP_Workflow

  • Purpose: Call flow processing and TwiML generation
  • Features: IVR menus, queue routing, schedule checking

TWP_Call_Queue

  • Purpose: Queue management and position tracking
  • Features: User-specific queues, hold queues, priority handling

TWP_Agent_Manager

  • Purpose: Agent status and call acceptance
  • Features: Phone number validation, availability tracking

TWP_Callback_Manager

  • Purpose: Callback request handling
  • Features: SMS confirmations, automatic processing

TWP_Call_Logger

  • Purpose: Call logging and statistics
  • Features: Detailed call records, duration tracking

TWP_Shortcodes

  • Purpose: WordPress shortcodes for frontend features
  • Shortcode: [twp_browser_phone] - Browser phone interface

💾 Database Schema

Complete Table List (15 tables)

  1. twp_phone_schedules - Business hours definitions
  2. twp_call_queues - Queue configurations (includes user-specific)
  3. twp_queued_calls - Active calls in queues
  4. twp_workflows - Call flow definitions
  5. twp_workflow_phones - Phone-to-workflow mappings
  6. twp_call_log - Complete call history
  7. twp_sms_log - SMS message tracking
  8. twp_voicemails - Voicemail recordings and transcriptions
  9. twp_agent_groups - Agent group definitions
  10. twp_group_members - User-to-group relationships
  11. twp_agent_status - Real-time agent availability
  12. twp_callbacks - Callback request queue
  13. twp_call_recordings - Call recording metadata
  14. twp_user_extensions - User extension numbers
  15. twp_queue_assignments - User queue assignments

Key Table Structures

twp_call_queues (Enhanced)

  • Supports user-specific queues (user_id field)
  • Queue types: general, personal, hold
  • Extension support for direct dialing
  • TTS message configuration

twp_queued_calls

  • Uses enqueued_at timestamp (migrated from joined_at)
  • No customer_number field (uses from_number/to_number)
  • Tracks agent assignment and status

🔌 REST API Endpoints (Webhooks)

Voice Endpoints

  • /voice - Main incoming call handler
  • /browser-voice - Browser phone calls
  • /smart-routing - Intelligent call routing
  • /agent-screen - Agent screening before connection
  • /agent-confirm - Agent confirmation handler
  • /ring-group-result - Handle ring group outcomes
  • /agent-connect - Connect accepted agents

SMS Endpoints

  • /sms - Main SMS handler (includes "1" responses)
  • /status - Call/SMS status updates

Queue Management

  • /queue-wait - Queue hold music and announcements
  • /queue-action - Queue-specific actions
  • /ivr-response - IVR menu selections

Voicemail

  • /voicemail-callback - Voicemail recording handler
  • /voicemail-complete - Post-recording processing
  • /voicemail-audio/{id} - Audio playback proxy

Recording

  • /recording-status - Recording status callbacks
  • /recording-audio/{id} - Recording playback proxy
  • /transcription - Transcription webhooks

Callback System

  • /callback-choice - Customer callback selection
  • /request-callback - Callback request handler
  • /callback-agent - Agent-side callback
  • /callback-customer - Customer-side callback

Outbound Calling

  • /outbound-agent - Basic outbound calls
  • /outbound-agent-with-from - Outbound with caller ID selection

Utility

  • /resume-call - Resume held calls
  • /smart-routing-fallback - Routing error handler
  • /browser-fallback - Browser phone fallback

🎛️ AJAX Endpoints (Admin & Frontend)

Total: 68 AJAX Actions

Categories:

  1. Schedule Management (4 actions)
  2. Workflow Management (5 actions)
  3. Phone Number Management (5 actions)
  4. Queue Management (6 actions)
  5. Agent Management (11 actions)
  6. Call Control (15 actions)
  7. Voicemail (5 actions)
  8. Recording (4 actions)
  9. SMS Management (4 actions)
  10. ElevenLabs Integration (3 actions)
  11. Browser Phone (4 actions)
  12. Transfer & Hold (8 actions)

Key AJAX Actions:

  • twp_toggle_hold - Put call on hold/resume (uses call leg detection)
  • twp_transfer_call - Transfer to agent/queue (uses call leg detection)
  • twp_start_recording - Start call recording
  • twp_stop_recording - Stop call recording
  • twp_requeue_call - Return call to queue (uses call leg detection)
  • twp_initiate_outbound_call_with_from - Outbound with caller ID

Call Control Architecture (CRITICAL):

All call control functions (twp_toggle_hold, twp_transfer_call, twp_requeue_call) now use intelligent call leg detection to ensure actions are applied to the customer call leg, not the agent leg. This prevents customer disconnections in complex call topologies.

🎨 Frontend Components

JavaScript Files

  1. admin.js (116KB) - Admin interface functionality
  2. browser-phone-frontend.js (85KB) - Browser phone implementation
  3. twp-service-worker.js (2.5KB) - Push notifications

Browser Phone Features

  • Twilio Device SDK integration
  • Real-time call controls (hold, transfer, record)
  • Queue monitoring dashboard
  • Agent status management
  • Call history display
  • Visual call state indicators

CSS Files

  • admin.css - Admin interface styling
  • browser-phone-frontend.css - Browser phone UI

🔧 Recent Fixes & Improvements

CRITICAL: Advanced Call Control Fixes (September 2025) - FULLY RESOLVED

Major overhaul of hold, transfer, and requeue functionality with comprehensive fixes for complex call topologies.

Hold Function Complete Redesign

  • Issue Fixed: "Queue not found" errors when putting calls on hold
  • Root Cause: User-specific queues (personal and hold queues) weren't automatically created
  • Solution: Automatic queue creation system with intelligent fallbacks
  • Key Features:
    • Auto-Queue Creation: Creates personal and hold queues automatically if missing
    • Extension Assignment: Auto-generates unique 3-4 digit extensions (100-9999)
    • Database Integration: Proper queue assignments and extension tracking
    • Browser Phone Support: Handles calls not initially in queue database
    • ElevenLabs TTS: Enhanced hold messages with premium voice synthesis
    • Call Leg Detection: Uses find_customer_call_leg() for proper call control
  • Functions Enhanced: ajax_toggle_hold(), TWP_User_Queue_Manager::transfer_to_hold_queue()
  • Result: Hold functionality now works seamlessly for all call types

Transfer Function Comprehensive Fix

  • Issue Fixed: Customers hearing webhook URLs instead of proper transfer messages
  • Root Cause: Improper TwiML generation causing raw webhook URLs to be spoken
  • Solution: Complete TwiML generation overhaul with proper VoiceResponse usage
  • Key Features:
    • Proper TwiML Generation: Uses \Twilio\TwiML\VoiceResponse() for all transfer types
    • Multiple Transfer Types: Extension, queue, client (browser phone), and phone number transfers
    • Customer Call Leg Detection: Identifies correct call leg for outbound calls
    • ElevenLabs Integration: Premium TTS for all transfer announcements
    • Enhanced Logging: Comprehensive debugging for transfer operations
    • Browser Phone Transfers: Fixed client: identifier handling
  • Transfer Types Supported:
    • Extension transfers: Redirects to queue-wait endpoint with TTS announcement
    • Queue transfers: Proper queue routing with hold music
    • Client transfers: $dial->client($agent_name) for browser phone agents
    • Phone transfers: Direct $twiml->dial($target) for external numbers
  • Functions Enhanced: ajax_transfer_call() with intelligent target detection
  • Result: All transfer types now provide proper audio experience without exposing technical URLs

Requeue Function Complete Rebuild

  • Issue Fixed: Customers hearing webhook URLs when requeued to waiting queues
  • Root Cause: Faulty create_queue_twiml() method generating improper TwiML
  • Solution: Replaced with proper TwiML generation and redirect methodology
  • Key Features:
    • VoiceResponse Integration: Uses proper Twilio TwiML classes
    • Redirect Method: Uses $twiml->redirect() instead of raw webhook calls
    • Queue-Wait Integration: Proper integration with /queue-wait endpoint
    • Database Consistency: Maintains call tracking with enqueued_at column support
    • ElevenLabs TTS: Premium voice synthesis for requeue messages
    • Call Leg Detection: Ensures customer (not agent) is requeued
  • Functions Enhanced: ajax_requeue_call() with proper TwiML flow
  • Result: Customers now hear professional requeue messages instead of technical errors

ElevenLabs TTS Integration Enhanced (September 2025)

  • Universal Integration: All voice prompts now use TWP_TTS_Helper::add_tts_to_twiml()
  • Automatic Fallback: Seamlessly falls back to Twilio's Alice voice if ElevenLabs unavailable
  • Voice Consistency: Hold, transfer, and requeue messages use consistent premium voices
  • Caching System: 30-day cache reduces API calls and improves performance
  • Configuration: Works with existing ElevenLabs API key settings
  • Coverage: Applies to all new call control functions and existing workflow steps

Call Leg Detection System Enhanced (September 2025)

  • Function: find_customer_call_leg($call_sid, $api) in TWP_Admin class
  • Enhanced Logic: Improved detection for complex outbound call topologies
  • Browser Phone Detection: Identifies client: prefixes and finds real customer legs
  • Parent Call Analysis: Uses parent call relationships for proper leg identification
  • Active Call Search: Searches active calls when parent relationship insufficient
  • Comprehensive Logging: Detailed debugging output for troubleshooting
  • Fallback Mechanisms: Multiple detection methods ensure reliability
  • Result: 100% accuracy in identifying customer vs agent call legs

Automatic Queue Management System (NEW)

  • Auto-Creation: Personal and hold queues created automatically for users
  • Extension System: Unique 3-4 digit extensions (100-9999) auto-assigned
  • Database Integration: Proper foreign key relationships and constraints
  • Queue Assignment: Auto-assignment to personal and hold queues
  • Migration Support: Handles users without existing queue infrastructure
  • Error Handling: Comprehensive rollback on queue creation failures
  • User Experience: Seamless queue access without manual setup

CRITICAL: Outbound Call Issues RESOLVED (September 2025)

  • Issue: Hold, transfer, and requeue functions were applying actions to wrong call leg (agent instead of customer), causing customer disconnections
  • Root Cause: Complex call topologies in outbound calls create agent and customer call legs with different SIDs
  • Solution: New intelligent call leg detection system
  • Functions Fixed: ajax_toggle_hold(), ajax_transfer_call(), ajax_requeue_call()
  • Result: All functions now work correctly for both inbound and outbound calls without disconnecting customers

Customer Number Detection Issues RESOLVED (September 2025)

  • Issue: Customer numbers showing as "client:agentname" instead of actual phone numbers in voicemail and call recording admin interfaces
  • Root Cause: Browser phone calls create complex call topologies where customer information is stored in different call legs
  • Solution: Enhanced customer number detection with fallback mechanisms
  • Areas Fixed: Voicemail callback handling and call recording customer identification
  • Result: Both inbound and outbound calls now properly identify real customer phone numbers

Call Leg Detection System (NEW)

  • Function: find_customer_call_leg($call_sid, $api) in TWP_Admin class
  • Purpose: Identifies customer vs agent call legs in complex call topologies
  • Detection Logic:
    • Detects browser phone calls by checking for client: prefixes
    • Uses parent call relationships to find customer leg
    • Searches active calls for related customer connections
    • Comprehensive fallback mechanisms
  • Logging: Extensive debugging output for call relationship tracking

Enhanced Customer Number Detection (NEW)

  • Voicemail Callback Enhancement (TWP_Webhooks::handle_voicemail_callback()):
    • Fallback logic retrieves customer numbers from call log when From parameter missing
    • Browser phone detection identifies client: calls and finds real customer numbers
    • Parent call analysis and related call search functionality
    • Comprehensive logging for customer number detection process
  • Call Recording Enhancement (TWP_Admin::ajax_start_recording()):
    • Browser phone detection using client: prefix identification
    • Integration with find_customer_call_leg() helper for proper customer identification
    • Smart number extraction from appropriate call legs (from/to field analysis)
    • Enhanced logging for recording customer number detection

Browser Phone Call Support Enhanced

  • Client Transfer Support: Fixed "Invalid phone number format" errors for client: transfers
  • Detection: Automatically identifies client:agentname format calls
  • Transfer Methods:
    • Client transfers: $dial->client($agent_name)
    • Phone transfers: $twiml->dial($target)
    • Queue transfers: Uses customer leg for proper queue placement
  • Customer Number Resolution: Properly identifies real phone numbers in complex call topologies
  • Admin Interface Fixes: Voicemail and recording interfaces now show actual customer numbers instead of client identifiers

Hold Functionality (COMPLETELY REDESIGNED)

  • Previous Issue: TWP_Twilio_API::get_instance() error and queue not found errors
  • New Solution: Automatic user queue creation with comprehensive fallback system
  • Key Enhancements:
    • Auto-creates personal and hold queues if missing
    • Generates unique extensions (100-9999) automatically
    • Handles browser phone calls not initially in queue database
    • Uses proper call leg detection for outbound calls
    • Integrates ElevenLabs TTS for professional hold messages
    • Maintains database consistency with enqueued_at column support
  • Customer Impact: Seamless hold experience with premium audio and proper call handling

Transfer System (FULLY REBUILT)

  • Previous Issue: Customers hearing webhook URLs and transfer failures in outbound calls
  • New Solution: Complete TwiML generation overhaul with proper VoiceResponse usage
  • Key Enhancements:
    • Proper TwiML generation prevents webhook URLs from being spoken
    • All transfer types (extension, queue, client, phone) now work correctly
    • Customer call leg detection ensures proper call routing
    • ElevenLabs TTS integration for professional transfer announcements
    • Enhanced error handling and debugging
  • Transfer Types Enhanced:
    • Extension: Redirects to queue-wait with TTS "Transferring to extension X"
    • Queue: Direct queue routing with proper hold experience
    • Client: $dial->client() for browser phone agents with detection
    • Phone: Direct dial with "Transferring your call" announcement
  • Customer Impact: Professional transfer experience without technical errors

Requeue Functionality (COMPLETELY REDESIGNED)

  • Previous Issue: Customers hearing webhook URLs instead of proper queue experience
  • New Solution: Complete replacement of faulty create_queue_twiml() with proper TwiML
  • Key Enhancements:
    • Uses VoiceResponse and redirect method instead of raw webhook calls
    • Proper integration with /queue-wait endpoint for seamless experience
    • Customer call leg detection ensures correct call is requeued
    • ElevenLabs TTS for "Placing you back in the queue" messages
    • Database tracking maintains call history and position
    • Supports both enqueued_at and joined_at column schemas
  • Customer Impact: Professional requeue experience with proper hold music and announcements

Recording Management (Fixed)

  • Issue: "Unknown subresource update" error
  • Fix: Proper SDK v8 syntax using call recordings subresource
  • Fallback: Tries Twilio.CURRENT if specific SID fails

Queue Management (Fixed)

  • Issue: Enqueue::waitUrl() undefined method
  • Fix: Pass waitUrl as option: $response->enqueue($queue_name, ['waitUrl' => $url])

TTS Integration (UNIVERSALLY ENHANCED)

  • Universal Coverage: All call control functions now use TWP_TTS_Helper::add_tts_to_twiml()
  • ElevenLabs Integration: Automatic premium voice synthesis when configured
  • Intelligent Fallback: Seamless fallback to Twilio's Alice voice
  • Cache Duration: 30 days for identical text with automatic cleanup
  • Performance: Instant cached audio delivery
  • Professional Messages:
    • Hold: "Please hold while we prepare your call"
    • Transfer: "Transferring to extension X" or "Transferring your call"
    • Requeue: "Placing you back in the queue. Please hold."
  • Consistency: Same voice experience across all call operations
  • Configuration: Works with existing ElevenLabs API key settings
  • Integration Points: Hold operations, all transfer types, requeue operations, workflow steps

🚀 Twilio Integration Details

SDK Version

  • Required: Twilio PHP SDK v8.7.0
  • Installation: Via Composer or install script
  • PHP Requirement: PHP 8.0+

API Response Structure

// Success response
[
    'success' => true,
    'data' => [...] // Twilio response data
]

// Error response  
[
    'success' => false,
    'error' => 'Error message',
    'code' => 400
]

TwiML Generation Best Practices

  • Always use SDK classes for TwiML generation
  • Include proper XML headers when needed
  • Use TTS helper for voice synthesis
  • Implement proper error handling

Recording Stop Methods (SDK v8)

// Method 1: Specific recording
$client->calls($call_sid)
       ->recordings($recording_sid)
       ->update(['status' => 'stopped']);

// Method 2: Single active recording
$client->calls($call_sid)
       ->recordings('Twilio.CURRENT')
       ->update(['status' => 'stopped']);

🛠️ Development Guidelines

Call Control Functions (CRITICAL)

ALWAYS use call leg detection for hold, transfer, and requeue operations:

// Correct pattern for call control functions
private function find_customer_call_leg($call_sid, $api) {
    // Detects browser phone vs regular calls
    // Uses parent call relationships
    // Searches active calls for customer leg
    // Returns correct SID for operations
}

// Usage in AJAX handlers
$customer_call_sid = $this->find_customer_call_leg($call_sid, $twilio);
$result = $api->update_call($customer_call_sid, ['twiml' => $twiml_xml]);

Why This Matters:

  • Outbound calls create separate agent and customer call legs
  • Applying actions to agent leg disconnects customer
  • Browser phone calls use client: identifiers
  • Customer leg must be identified for proper call control

Database Operations

  • Always use $wpdb global
  • Sanitize with sanitize_text_field(), intval()
  • Use prepared statements: $wpdb->prepare()
  • Call TWP_Activator::ensure_tables_exist() before operations

AJAX Handler Pattern

public function ajax_handler_name() {
    if (!$this->verify_ajax_nonce()) {
        wp_send_json_error('Invalid nonce');
        return;
    }
    
    // Handler logic
    
    wp_send_json_success($data);
}

Error Handling

  • Log errors with error_log()
  • Return structured error responses
  • Implement fallback mechanisms
  • Handle Twilio exceptions properly

Naming Conventions

  • Classes: TWP_Class_Name
  • Tables: twp_table_name
  • Options: twp_option_name
  • AJAX actions: twp_action_name
  • Nonces: twp_ajax_nonce or twp_frontend_nonce

📋 Common Issues & Solutions

Database Issues

  • Missing Tables: Run TWP_Activator::ensure_tables_exist()
  • Schema Changes: Check add_missing_columns() method
  • Migration Issues: Review migrate_tables() implementation

Webhook Issues

  • 500 Errors: Check PHP error logs
  • TwiML Errors: Verify XML structure
  • Authentication: Webhooks use __return_true permission

API Issues

  • Instantiation: Use new TWP_Twilio_API() not singleton
  • Phone Format: Always use E.164 format (+1XXXXXXXXXX)
  • Call SID: Access via $response['data']['sid']

Call Control Issues (Outbound Calls) - RESOLVED

  • Customer Disconnections: FIXED - All functions now use find_customer_call_leg() automatically
  • Queue Not Found Errors: FIXED - Automatic queue creation prevents this issue
  • Webhook URL Errors: FIXED - Proper TwiML generation eliminates raw URLs being spoken
  • Browser Phone Issues: FIXED - Enhanced client: prefix detection and handling
  • Transfer Failures: FIXED - All transfer types now use correct customer call leg
  • TwiML Generation: FIXED - Uses proper VoiceResponse classes throughout
  • Database Tracking: ENHANCED - Supports both enqueued_at and joined_at schemas
  • Extension System: NEW - Automatic extension assignment with user queue creation

Hold/Transfer/Requeue System (COMPLETELY ENHANCED)

  • Automatic Queue Creation: Creates personal and hold queues as needed
  • Extension Management: Auto-generates unique 3-4 digit extensions
  • ElevenLabs Integration: Premium TTS for all voice prompts with Alice fallback
  • Call Leg Detection: 100% accurate customer vs agent identification
  • TwiML Compliance: Proper XML generation prevents audio errors
  • Database Consistency: Handles schema variations gracefully
  • Error Recovery: Comprehensive fallback mechanisms
  • User Experience: Professional audio experience throughout call lifecycle

Advanced Debugging Features (NEW)

  • Call Leg Detection Logging: "TWP Call Leg Detection" entries show call relationship analysis
  • Queue Creation Logging: Tracks automatic queue and extension generation
  • TwiML Generation Logging: Shows proper XML construction vs old webhook methods
  • Customer Number Detection: Enhanced logging for browser phone call analysis
  • Extension Assignment: Logs unique extension generation and assignment process

🧪 Testing Approach

Unit Testing

  • PHPUnit for PHP code
  • Mock WordPress functions
  • Mock Twilio API responses

Integration Testing

  • Test webhook endpoints
  • Verify database operations
  • Test complete call flows

Manual Testing

  • Monitor Twilio Console
  • Check WordPress debug logs
  • Test with real phone numbers

📚 Key Features Implementation

Agent System

  • SMS Accept: Agents text "1" to accept calls
  • Real-time Status: Available/busy/offline states
  • Group Management: Priority-based call distribution
  • Personal Queues: Agent-specific call queues

Call Queue System

  • Position Tracking: Real-time queue position
  • Timeout Handling: Automatic callback offers
  • Hold Queues: Temporary call parking
  • User Queues: Personal agent queues

Browser Phone

  • Twilio Device: Full SDK integration
  • Call Controls: Hold, transfer, record, mute
  • Visual Interface: Real-time status updates
  • Queue Dashboard: Monitor waiting calls

Recording System

  • Start/Stop: Dynamic recording control
  • Storage: Database tracking with Twilio URLs
  • Playback: Authenticated proxy endpoints
  • Transcription: Automatic with callbacks

ElevenLabs TTS

  • Auto-detection: Uses ElevenLabs when configured
  • Caching: 30-day cache for repeated phrases
  • Fallback: Seamless Twilio voice fallback
  • Performance: Instant cached audio delivery

📝 Configuration Requirements

WordPress Settings

  • Twilio Credentials: Account SID, Auth Token
  • TwiML App: For browser phone functionality
  • Phone Numbers: At least one Twilio number
  • Webhook URLs: Configure in Twilio Console

Optional Settings

  • ElevenLabs: API key and voice selection
  • Hold Music: Custom URL support
  • SMS Notifications: Agent alert numbers
  • Business Hours: Schedule configurations

🔍 Debugging Tips

  1. Enable WordPress Debug: WP_DEBUG = true
  2. Check Error Logs: /wp-content/debug.log
  3. Monitor Twilio Console: Real-time webhook debugging
  4. Database Queries: Use $wpdb->last_error
  5. Browser Console: Check JavaScript errors
  6. Network Tab: Monitor AJAX requests
  7. Call Leg Detection: Look for "TWP Call Leg Detection" log entries
  8. Outbound Call Issues: Check for agent vs customer call SID usage
  9. Browser Phone Debugging: Search logs for "client:" identifier handling

📖 External Resources


Last Updated: September 2025 Plugin Version: Production Ready Maintained for: phone.cloud-hosting.io