upskill-event-manager/docs/API-REFERENCE.md
bengizmo 34f06709f0 feat: Implement comprehensive manual geocoding trigger system with 85% coverage
HVAC trainer profile geocoding system with outstanding results:
- 45 out of 53 trainer profiles successfully geocoded (85% coverage)
- Coverage spans 15+ US states and 3 Canadian provinces
- Google Maps API integration with intelligent rate limiting
- Real-time statistics and comprehensive error handling

Core Implementation:
- HVAC_Geocoding_Ajax class with three AJAX endpoints:
  * hvac_trigger_geocoding: Manual geocoding operations
  * hvac_run_enhanced_import: CSV location data population
  * hvac_get_geocoding_stats: Coverage monitoring and statistics
- Enhanced CSV import with corrected email field mapping
- Proper field priority mapping for location data extraction
- Automatic scheduling of geocoding operations after data import

Technical Features:
- Singleton pattern for proper class initialization
- WordPress AJAX security with nonce verification
- Role-based access control for master trainers
- Comprehensive error logging and status tracking
- API rate limiting (0.5s delays) to respect Google quotas
- Multiple address format support (US/International)

User Experience:
- Master trainer controls for manual geocoding triggers
- Real-time progress monitoring and statistics
- Detailed error reporting for failed geocoding attempts
- Production-ready interface for location data management

Documentation:
- Complete API reference with endpoint specifications
- Comprehensive manual geocoding system documentation
- Usage examples and troubleshooting guidelines
- Error codes and integration patterns

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-08-01 23:49:27 -03:00

17 KiB

HVAC Plugin API Reference

Table of Contents

PHP Classes

HVAC_Plugin

Main plugin initialization class.

class HVAC_Plugin {
    /**
     * Get plugin instance (Singleton)
     * @return HVAC_Plugin
     */
    public static function instance()
    
    /**
     * Initialize plugin components
     * @return void
     */
    public function init()
}

HVAC_Event_Manager

Manages event creation and manipulation.

class HVAC_Event_Manager {
    /**
     * Create a new event
     * @param array $event_data Event information
     * @return int|WP_Error Event ID or error
     */
    public static function create_event($event_data)
    
    /**
     * Get trainer events
     * @param int $trainer_id Trainer user ID
     * @param array $args Query arguments
     * @return array Array of event objects
     */
    public static function get_trainer_events($trainer_id, $args = array())
    
    /**
     * Update event
     * @param int $event_id Event ID
     * @param array $data Event data to update
     * @return bool Success status
     */
    public static function update_event($event_id, $data)
}

HVAC_Certificate_Generator

Handles PDF certificate generation.

class HVAC_Certificate_Generator {
    /**
     * Generate certificate for attendee
     * @param int $event_id Event ID
     * @param array $attendee Attendee data
     * @return string|WP_Error PDF file path or error
     */
    public function generate_certificate($event_id, $attendee)
    
    /**
     * Generate bulk certificates
     * @param int $event_id Event ID
     * @param array $attendees Array of attendee data
     * @return array Results array with successes and failures
     */
    public function generate_bulk_certificates($event_id, $attendees)
}

HVAC_Trainer_Profile

Manages trainer profile functionality.

class HVAC_Trainer_Profile {
    /**
     * Get trainer profile data
     * @param int $trainer_id User ID
     * @return array Profile data
     */
    public static function get_profile($trainer_id)
    
    /**
     * Update trainer profile
     * @param int $trainer_id User ID
     * @param array $data Profile data
     * @return bool Success status
     */
    public static function update_profile($trainer_id, $data)
    
    /**
     * Get trainer statistics
     * @param int $trainer_id User ID
     * @return array Statistics data
     */
    public static function get_statistics($trainer_id)
}

HVAC_Menu_System

Handles navigation menu rendering.

class HVAC_Menu_System {
    /**
     * Render trainer navigation menu
     * @return void Outputs HTML
     */
    public function render_trainer_menu()
    
    /**
     * Get menu structure for current user
     * @return array Menu items array
     */
    private function get_menu_structure()
}

JavaScript APIs

Global Objects

// Main HVAC object
window.HVAC = {
    // Initialize components
    init: function() {},
    
    // Event management
    events: {
        create: function(data) {},
        update: function(eventId, data) {},
        delete: function(eventId) {}
    },
    
    // Profile management
    profile: {
        load: function(userId) {},
        save: function(data) {},
        uploadPhoto: function(file) {}
    },
    
    // Utilities
    utils: {
        showMessage: function(message, type) {},
        confirm: function(message, callback) {},
        formatDate: function(date) {}
    }
};

// AJAX helper
window.hvacAjax = {
    post: function(action, data, success, error) {},
    get: function(action, data, success, error) {}
};

jQuery Plugins

// Dashboard initialization
jQuery(document).ready(function($) {
    // Initialize date pickers
    $('.hvac-datepicker').datepicker({
        dateFormat: 'yy-mm-dd'
    });
    
    // Initialize form validation
    $('.hvac-form').validate({
        rules: {
            event_title: 'required',
            event_date: 'required'
        }
    });
});

WordPress Hooks

Actions

// Plugin lifecycle
do_action('hvac_plugin_activated');
do_action('hvac_plugin_deactivated');
do_action('hvac_plugin_updated', $old_version, $new_version);

// Page creation
do_action('hvac_before_create_pages');
do_action('hvac_after_create_pages', $page_ids);

// Event management
do_action('hvac_before_event_save', $event_data);
do_action('hvac_after_event_save', $event_id, $event_data);
do_action('hvac_event_deleted', $event_id);

// Certificate generation
do_action('hvac_before_certificate_generate', $event_id, $attendee);
do_action('hvac_after_certificate_generate', $certificate_path);

// User profile
do_action('hvac_profile_updated', $user_id, $profile_data);
do_action('hvac_trainer_registered', $user_id);

Filters

// Capability checks
apply_filters('hvac_user_can_manage_event', $can_manage, $user_id, $event_id);
apply_filters('hvac_user_can_generate_certificates', $can_generate, $user_id);

// Data manipulation
apply_filters('hvac_event_data', $event_data, $event_id);
apply_filters('hvac_certificate_data', $certificate_data, $event_id, $attendee);
apply_filters('hvac_profile_fields', $fields, $user_id);

// Display filters
apply_filters('hvac_menu_items', $menu_items, $user_role);
apply_filters('hvac_dashboard_widgets', $widgets, $user_id);
apply_filters('hvac_date_format', $format);

// Query filters
apply_filters('hvac_events_query_args', $args, $context);
apply_filters('hvac_trainers_query_args', $args);

Template System

HVAC_Community_Events Template Loading

The plugin uses a custom template loading system via the template_include filter.

class HVAC_Community_Events {
    /**
     * Load custom templates for HVAC pages
     * @param string $template Current template path
     * @return string Modified template path
     */
    public function load_custom_templates($template)
}

Template Mappings:

// Certificate pages use full page templates
'trainer/certificate-reports' => 'templates/page-certificate-reports.php'
'trainer/generate-certificates' => 'templates/page-generate-certificates.php'

// Dashboard pages
'trainer/dashboard' => 'templates/template-hvac-dashboard.php'
'master-trainer/master-dashboard' => 'templates/template-hvac-master-dashboard.php'

// Other pages
'trainer/event/manage' => 'templates/page-manage-event.php'
'trainer/profile' => 'templates/page-trainer-profile.php'

Template Structure Requirements: All HVAC page templates must include:

// Define constant to indicate page template context
define('HVAC_IN_PAGE_TEMPLATE', true);

get_header(); // Required: WordPress header
?>
<div class="hvac-page-wrapper">
    <?php
    // Navigation menu
    if (class_exists('HVAC_Menu_System')) {
        HVAC_Menu_System::instance()->render_trainer_menu();
    }
    
    // Breadcrumbs
    if (class_exists('HVAC_Breadcrumbs')) {
        echo HVAC_Breadcrumbs::instance()->render_breadcrumbs();
    }
    ?>
    
    <div class="container">
        <?php echo do_shortcode('[hvac_shortcode_name]'); ?>
    </div>
</div>
<?php
get_footer(); // Required: WordPress footer

Astra Theme Integration

class HVAC_Astra_Integration {
    /**
     * Disable Astra breadcrumbs for HVAC pages
     */
    public function disable_astra_breadcrumbs($enabled)
    public function disable_breadcrumb_option($option)
    public function disable_breadcrumb_position($position)
    
    /**
     * Force full-width layout for HVAC pages
     */
    public function force_hvac_page_layout($layout)
    public function force_hvac_content_layout($layout)
}

Common Template Issues & Solutions:

  1. Pages showing only shortcode content:

    • Ensure load_custom_templates() uses page templates, not content templates
    • Verify get_header() and get_footer() are called
  2. Duplicate breadcrumbs:

    • Add Astra breadcrumb disable filters
    • Check theme breadcrumb settings
  3. Missing navigation:

    • Remove HVAC_NAV_RENDERED constant checks
    • Ensure Menu System is properly initialized

AJAX Endpoints

Event Management

// Create event
{
    action: 'hvac_create_event',
    nonce: hvac_ajax.nonce,
    event_data: {
        title: 'Event Title',
        start_date: '2025-08-15',
        venue_id: 123,
        capacity: 50
    }
}

// Update event
{
    action: 'hvac_update_event',
    nonce: hvac_ajax.nonce,
    event_id: 456,
    event_data: {
        title: 'Updated Title'
    }
}

// Delete event
{
    action: 'hvac_delete_event',
    nonce: hvac_ajax.nonce,
    event_id: 456
}

Profile Management

// Get profile data
{
    action: 'hvac_get_profile',
    nonce: hvac_ajax.nonce,
    user_id: 789 // Optional, defaults to current user
}

// Update profile
{
    action: 'hvac_update_profile',
    nonce: hvac_ajax.nonce,
    profile_data: {
        bio: 'Updated bio',
        certifications: ['NATE', 'EPA'],
        website: 'https://example.com'
    }
}

// Upload profile photo
{
    action: 'hvac_upload_photo',
    nonce: hvac_ajax.nonce,
    photo: File // File object from input
}

Certificate Generation

// Generate single certificate
{
    action: 'hvac_generate_certificate',
    nonce: hvac_ajax.nonce,
    event_id: 456,
    attendee_id: 789
}

// Generate bulk certificates
{
    action: 'hvac_generate_bulk_certificates',
    nonce: hvac_ajax.nonce,
    event_id: 456,
    attendee_ids: [789, 790, 791]
}

Shortcodes

Display Shortcodes

// Trainer dashboard
[hvac_trainer_dashboard]

// Event list
[hvac_event_list trainer_id="123" limit="10" status="upcoming"]

// Profile view
[hvac_trainer_profile_view user_id="123"]

// Profile edit form
[hvac_trainer_profile_edit]

// Certificate reports
[hvac_certificate_reports]

// Event creation form
[hvac_event_form]

// Venue management
[hvac_venue_list]
[hvac_venue_form]

// Organizer management
[hvac_organizer_list]
[hvac_organizer_form]

Shortcode Parameters

// Event list parameters
[hvac_event_list 
    trainer_id=""      // Trainer ID (default: current user)
    limit="10"         // Number of events
    status="upcoming"  // upcoming|past|all
    orderby="date"     // date|title|capacity
    order="ASC"        // ASC|DESC
]

// Profile view parameters
[hvac_trainer_profile_view 
    user_id=""         // User ID (default: current user)
    show_stats="true"  // Show statistics
    show_events="true" // Show event list
]

Database Schema

Post Meta (Events)

-- Event-specific meta keys
_EventStartDate         -- Event start datetime
_EventEndDate          -- Event end datetime
_EventVenueID          -- Venue post ID
_EventOrganizerID      -- Organizer post ID
_EventTrainerID        -- Trainer user ID
_EventCapacity         -- Maximum attendees
_EventRegisteredCount  -- Current registration count
_EventCertificateTemplate -- Certificate template ID

User Meta (Trainers)

-- Profile information
role                   -- User's HVAC industry role (technician, installer, etc.)
hvac_bio               -- Trainer biography
hvac_certifications    -- Serialized array of certifications
hvac_trainer_photo     -- Attachment ID of profile photo
hvac_website           -- Trainer website URL
hvac_location          -- Trainer location
hvac_phone             -- Contact phone

-- Certification information (admin/master trainer editable only)
date_certified         -- Date when trainer was certified (YYYY-MM-DD)
certification_type     -- Type of certification ('Certified measureQuick Trainer', 'Certified measureQuick Champion')
certification_status   -- Current certification status ('Active', 'Expired', 'Pending', 'Disabled')

-- Training preferences
hvac_training_formats  -- Serialized array of formats
hvac_training_audience -- Target audience
hvac_training_topics   -- Specialized topics

-- Statistics (cached)
hvac_total_events      -- Total events created
hvac_total_students    -- Total students trained
hvac_total_revenue     -- Total revenue generated

Options Table

-- Plugin settings
hvac_plugin_version    -- Current plugin version
hvac_settings          -- Serialized settings array
hvac_email_templates   -- Email template configurations
hvac_certificate_settings -- Certificate generation settings

-- Feature flags
hvac_enable_zoho       -- Zoho CRM integration
hvac_enable_analytics  -- Analytics tracking
hvac_maintenance_mode  -- Maintenance mode flag

Manual Geocoding API Endpoints

Trigger Manual Geocoding

Endpoint: hvac_trigger_geocoding
Method: POST (AJAX)
Permissions: hvac_master_trainer or administrator

Manually triggers geocoding for all trainer profiles using Google Maps API.

Parameters: None (uses AJAX nonce for security)

Response:

{
  "success": true,
  "data": {
    "total_profiles": 53,
    "geocoded_count": 45,
    "skipped_count": 7,
    "error_count": 1,
    "api_key_valid": true,
    "start_time": "2025-08-01 20:34:36",
    "end_time": "2025-08-01 20:34:36",
    "duration": 21600,
    "details": [
      {
        "id": 5868,
        "title": "William Ramsey - Trainer Profile",
        "status": "already_geocoded",
        "coordinates": {"lat": 33.9532531, "lng": -84.5499358}
      }
    ]
  }
}

Status Values:

  • geocoded - Successfully geocoded in this operation
  • already_geocoded - Profile already has valid coordinates
  • no_address - Profile missing location data
  • error - Geocoding failed with error
  • failed - Google Maps API returned no results

Enhanced CSV Import

Endpoint: hvac_run_enhanced_import
Method: POST (AJAX)
Permissions: hvac_master_trainer or administrator

Imports trainer location data from embedded CSV data with field mapping.

Parameters: None (uses embedded CSV data)

Response:

{
  "success": true,
  "data": {
    "total_rows": 43,
    "users_created": 0,
    "users_updated": 43,
    "profiles_created": 0,
    "profiles_updated": 43,
    "errors": 0,
    "geocoding_scheduled": 43,
    "session_id": "enhanced_2025-08-02_02-33-53",
    "import_log_saved": true,
    "start_time": "2025-08-01 19:12:36",
    "end_time": "2025-08-01 19:12:36",
    "duration": 0
  }
}

Get Geocoding Statistics

Endpoint: hvac_get_geocoding_stats
Method: POST (AJAX)
Permissions: hvac_trainer, hvac_master_trainer, or administrator

Retrieves current geocoding coverage and statistics.

Parameters: None

Response:

{
  "success": true,
  "data": {
    "total_profiles": "53",
    "geocoded_profiles": "45",
    "public_profiles": "53",
    "sync_issues": 0
  }
}

Error Codes

Geocoding Errors

  • GEOCODING_INVALID_NONCE - Security nonce verification failed
  • GEOCODING_INSUFFICIENT_PERMISSIONS - User lacks required capabilities
  • GEOCODING_API_KEY_INVALID - Google Maps API key missing or invalid
  • GEOCODING_NO_PROFILES - No trainer profiles found to geocode
  • GEOCODING_ADDRESS_FAILED - Address could not be geocoded
  • GEOCODING_API_ERROR - Google Maps API returned an error

CSV Import Errors

  • IMPORT_INVALID_NONCE - Security nonce verification failed
  • IMPORT_INSUFFICIENT_PERMISSIONS - User lacks required capabilities
  • IMPORT_NO_DATA - No CSV data available to import
  • IMPORT_USER_NOT_FOUND - CSV email doesn't match any WordPress user
  • IMPORT_PROFILE_NOT_FOUND - User doesn't have a trainer profile
  • IMPORT_UPDATE_FAILED - Failed to update profile metadata

Event Errors

  • HVAC001 - Invalid event data
  • HVAC002 - Event not found
  • HVAC003 - Insufficient permissions to manage event
  • HVAC004 - Event capacity exceeded

User Errors

  • HVAC101 - User not found
  • HVAC102 - Invalid user role
  • HVAC103 - Insufficient permissions
  • HVAC104 - Profile update failed

Certificate Errors

  • HVAC201 - Certificate generation failed
  • HVAC202 - Invalid attendee data
  • HVAC203 - Template not found
  • HVAC204 - PDF library error

System Errors

  • HVAC901 - Database connection error
  • HVAC902 - File system error
  • HVAC903 - Third-party API error
  • HVAC904 - Unknown error

Response Formats

Success Response

{
    "success": true,
    "data": {
        "id": 123,
        "message": "Operation completed successfully",
        "additional_data": {}
    }
}

Error Response

{
    "success": false,
    "data": {
        "code": "HVAC001",
        "message": "Invalid event data",
        "details": {
            "field": "event_date",
            "error": "Date must be in the future"
        }
    }
}