upskill-event-manager/docs/TROUBLESHOOTING.md
bengizmo 40274d98ad feat: Implement comprehensive user role field and certification tracking system
• Add user role field to registration, profile display, and profile edit
  - 10 role options: technician, installer, supervisor, manager, trainer, consultant, sales rep, engineer, business owner, other
  - Required field with server-side validation
  - Radio buttons in registration, dropdown in profile edit
  - Displays in profile with proper capitalization

• Implement advanced certification tracking system
  - Date Certified: HTML5 date picker with validation (no future dates)
  - Certification Type: dropdown with "Certified measureQuick Trainer" and "Certified measureQuick Champion"
  - Certification Status: color-coded status badges (Active/Expired/Pending/Disabled)

• Add sophisticated role-based access control
  - Regular trainers: read-only access to certification fields
  - Administrators & master trainers: full edit access to certification fields
  - Visual indicators for read-only fields
  - Server-side permission validation

• Enhance plugin activation system
  - Initialize all 36 user meta fields for existing users
  - Smart default assignment based on user capabilities
  - Backward compatibility maintained

• Add professional UI styling
  - Blue-bordered certification section with trophy icon
  - Color-coded status badges with proper contrast
  - Read-only field styling with visual indicators
  - Enhanced form controls with focus states

• Comprehensive testing and documentation
  - E2E test coverage with visual verification
  - Updated API reference with new meta fields
  - Access control patterns documented
  - 100% test pass rate on staging environment

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-08-01 10:52:11 -03:00

12 KiB

HVAC Plugin Troubleshooting Guide

Table of Contents

Common Issues

1. Pages Not Found (404 Errors)

Symptoms:

  • Trainer pages return 404
  • Certificate reports page not accessible
  • Profile page missing

Solutions:

# Flush rewrite rules
wp rewrite flush

# Recreate pages
wp eval 'do_action("hvac_create_pages");'

# Verify page exists
wp post list --post_type=page --name=trainer

Code Fix:

// Force page creation in plugin
HVAC_Page_Manager::create_required_pages();
flush_rewrite_rules();

2. Duplicate Navigation Menus

Symptoms:

  • Two navigation bars showing
  • Both trainer and master menus visible

Root Cause:

  • User has both trainer and master trainer roles
  • Navigation system rendering both menus

Solution: Already fixed in HVAC_Menu_System:

// Check get_menu_structure() method
// Master trainers always see master menu only

3. Missing CSS/Styling

Symptoms:

  • Pages appear unstyled
  • Broken layouts
  • Missing theme integration

Diagnosis:

// Check if CSS is loading
add_action('wp_head', function() {
    global $wp_styles;
    echo "<!-- Loaded styles:\n";
    foreach($wp_styles->queue as $style) {
        echo $style . "\n";
    }
    echo "-->";
});

Solutions:

  1. Verify HVAC_Scripts_Styles is loading
  2. Check is_plugin_page() detection
  3. Ensure template has HVAC_IN_PAGE_TEMPLATE constant

4. Sidebar Still Showing

Symptoms:

  • 2-column layout persists
  • Sidebar visible on trainer pages

Solutions:

  1. Check Astra integration is active:
// In theme's functions.php temporarily
add_action('init', function() {
    if (class_exists('HVAC_Astra_Integration')) {
        error_log('Astra integration loaded');
    }
});
  1. Force no-sidebar via database:
wp eval '
$pages = get_posts(array(
    "post_type" => "page",
    "meta_key" => "_wp_page_template",
    "meta_value" => "trainer",
    "meta_compare" => "LIKE"
));
foreach($pages as $page) {
    update_post_meta($page->ID, "site-sidebar-layout", "no-sidebar");
    update_post_meta($page->ID, "ast-site-sidebar-layout", "no-sidebar");
}'

5. Profile Page Using Wrong Template

Symptoms:

  • Old navigation showing
  • Missing fields
  • Wrong layout

Quick Fix:

# Find profile page
wp post list --post_type=page --name=profile --fields=ID,post_title

# Update template
wp post meta update [PAGE_ID] _wp_page_template templates/page-trainer-profile.php

Debugging Techniques

1. Enable WordPress Debug Mode

wp-config.php:

define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true);
define('WP_DEBUG_DISPLAY', false);
define('SCRIPT_DEBUG', true);

2. Plugin-Specific Debug

Add to plugin file:

// Debug page detection
add_action('wp', function() {
    if (defined('HVAC_DEBUG') && HVAC_DEBUG) {
        error_log('Current page: ' . $_SERVER['REQUEST_URI']);
        error_log('Is plugin page: ' . (HVAC_Scripts_Styles::is_plugin_page() ? 'yes' : 'no'));
        error_log('Template: ' . get_page_template());
    }
});

3. JavaScript Debugging

// Add debug logging
if (window.hvac_debug) {
    console.log('HVAC Debug:', {
        page: window.location.pathname,
        user: hvac_ajax.user_id,
        role: hvac_ajax.user_role
    });
}

4. Database Query Monitoring

// Log all queries for a page load
define('SAVEQUERIES', true);

add_action('shutdown', function() {
    global $wpdb;
    error_log('Total queries: ' . count($wpdb->queries));
    foreach($wpdb->queries as $query) {
        if ($query[1] > 0.05) { // Queries taking > 50ms
            error_log('Slow query: ' . $query[0] . ' (' . $query[1] . 's)');
        }
    }
});

Error Messages

"There has been a critical error on this website"

Common Causes:

  1. PHP syntax error
  2. Missing required file
  3. Fatal error in hook

Debugging Steps:

# Check PHP error log
tail -f wp-content/debug.log

# Check syntax
php -l includes/class-name.php

# Enable recovery mode
wp config set WP_DISABLE_FATAL_ERROR_HANDLER true

"Headers already sent"

Cause: Output before WordPress headers

Fix:

// Remove any whitespace before <?php
// Check for BOM in files
// Use ob_start() if necessary

AJAX Errors

Debug AJAX:

jQuery.ajax({
    // ... options
    error: function(xhr, status, error) {
        console.error('AJAX Error:', {
            status: status,
            error: error,
            response: xhr.responseText
        });
    }
});

Performance Issues

1. Slow Page Loads

Diagnosis:

// Add to theme's functions.php
add_action('wp_footer', function() {
    echo "<!-- Page generated in " . timer_stop(0) . " seconds -->";
    echo "<!-- Queries: " . get_num_queries() . " -->";
});

Common Fixes:

  1. Enable object caching
  2. Optimize database queries
  3. Use transients for expensive operations

2. High Database Query Count

Identify Problem Queries:

// Find duplicate queries
add_filter('posts_request', function($query) {
    error_log('Query: ' . $query);
    return $query;
});

Optimization:

// Cache user queries
$cache_key = 'hvac_trainer_' . $user_id;
$trainer_data = wp_cache_get($cache_key);
if (false === $trainer_data) {
    $trainer_data = get_user_meta($user_id);
    wp_cache_set($cache_key, $trainer_data, '', 3600);
}

3. Memory Issues

Symptoms:

  • "Allowed memory size exhausted"
  • White screen of death

Solutions:

// Increase memory limit
define('WP_MEMORY_LIMIT', '256M');
define('WP_MAX_MEMORY_LIMIT', '512M');

// Find memory usage
error_log('Memory: ' . memory_get_usage() / 1024 / 1024 . 'MB');
error_log('Peak: ' . memory_get_peak_usage() / 1024 / 1024 . 'MB');

Deployment Problems

1. Plugin Not Activating

Check Requirements:

# PHP version
php -v

# Required extensions
php -m | grep -E "(mysqli|curl|gd|mbstring)"

# WordPress version
wp core version

2. Files Not Updating

Clear All Caches:

# WordPress cache
wp cache flush

# Opcache
wp eval 'if (function_exists("opcache_reset")) opcache_reset();'

# Breeze cache
wp breeze purge --all

# CloudFlare (if applicable)
# Use CloudFlare dashboard or API

3. Database Changes Not Applying

Force Update:

# Deactivate and reactivate
wp plugin deactivate hvac-community-events
wp plugin activate hvac-community-events

# Run activation hook manually
wp eval 'do_action("activate_hvac-community-events/hvac-community-events.php");'

Theme Conflicts

1. Astra Theme Issues

Check Theme Version:

wp theme list --fields=name,version,status

Force Compatibility:

// Add to theme's functions.php
add_action('after_setup_theme', function() {
    // Force load Astra integration
    if (!class_exists('HVAC_Astra_Integration')) {
        require_once WP_PLUGIN_DIR . '/hvac-community-events/includes/class-hvac-astra-integration.php';
        HVAC_Astra_Integration::instance();
    }
}, 5);

2. Other Theme Conflicts

Identify Conflicts:

// Switch to default theme temporarily
wp theme activate twentytwentyone

// Test plugin functionality
// If it works, theme conflict confirmed

Common Fixes:

  1. Add theme-specific integration class
  2. Use more specific CSS selectors
  3. Adjust hook priorities

Database Issues

1. Missing Meta Keys

Audit Meta Keys:

# Check post meta
wp db query "SELECT DISTINCT meta_key FROM wp_postmeta WHERE meta_key LIKE '%hvac%'"

# Check user meta
wp db query "SELECT DISTINCT meta_key FROM wp_usermeta WHERE meta_key LIKE '%hvac%'"

2. Orphaned Data

Clean Orphaned Event Data:

-- Find events without trainers
SELECT ID, post_title 
FROM wp_posts p
WHERE post_type = 'tribe_events'
AND NOT EXISTS (
    SELECT 1 FROM wp_postmeta pm 
    WHERE pm.post_id = p.ID 
    AND pm.meta_key = '_EventTrainerID'
);

3. Data Migration

Migrate Legacy Roles:

// Run via WP-CLI
wp eval '
$users = get_users(array("role" => "event_trainer"));
foreach($users as $user) {
    $user->remove_role("event_trainer");
    $user->add_role("hvac_trainer");
    echo "Migrated user: " . $user->user_login . "\n";
}'

Recovery Procedures

1. Emergency Rollback

# SSH to server
ssh user@server

# Navigate to plugins
cd /path/to/wp-content/plugins

# Backup current version
mv hvac-community-events hvac-community-events-broken

# Restore previous version
cp -r hvac-backups/hvac-community-events-backup-[date] hvac-community-events

# Reactivate
wp plugin activate hvac-community-events

# Clear caches
wp cache flush

2. Database Recovery

# Export current state
wp db export backup-$(date +%Y%m%d-%H%M%S).sql

# If needed, restore from backup
wp db import backup-file.sql

# Verify data
wp db query "SELECT COUNT(*) FROM wp_posts WHERE post_type = 'tribe_events'"

3. Complete Reset

Nuclear Option - Full Reset:

# Backup everything first!
wp db export full-backup.sql

# Deactivate plugin
wp plugin deactivate hvac-community-events

# Remove all plugin data
wp eval '
// Delete all pages
$pages = get_posts(array(
    "post_type" => "page",
    "meta_key" => "_wp_page_template",
    "meta_value" => "hvac",
    "meta_compare" => "LIKE",
    "posts_per_page" => -1
));
foreach($pages as $page) {
    wp_delete_post($page->ID, true);
}

// Delete options
delete_option("hvac_plugin_version");
delete_option("hvac_settings");
'

# Reinstall
wp plugin activate hvac-community-events

Monitoring & Logging

1. Set Up Error Monitoring

// Add to plugin
class HVAC_Error_Handler {
    public static function log_error($message, $context = array()) {
        $log_entry = sprintf(
            '[%s] %s | Context: %s',
            current_time('mysql'),
            $message,
            json_encode($context)
        );
        
        error_log($log_entry, 3, WP_CONTENT_DIR . '/hvac-errors.log');
        
        // Also send to external service if configured
        if (defined('HVAC_ERROR_WEBHOOK')) {
            wp_remote_post(HVAC_ERROR_WEBHOOK, array(
                'body' => json_encode(array(
                    'message' => $message,
                    'context' => $context,
                    'site' => home_url()
                ))
            ));
        }
    }
}

2. Performance Monitoring

// Track slow operations
function hvac_track_performance($operation, $callback) {
    $start = microtime(true);
    $result = $callback();
    $duration = microtime(true) - $start;
    
    if ($duration > 1.0) { // Log operations taking > 1 second
        HVAC_Error_Handler::log_error(
            'Slow operation detected',
            array(
                'operation' => $operation,
                'duration' => $duration,
                'memory' => memory_get_peak_usage() / 1024 / 1024
            )
        );
    }
    
    return $result;
}

Quick Reference Commands

# Check plugin status
wp plugin list --name=hvac-community-events

# View recent errors
tail -f wp-content/debug.log | grep -i hvac

# Clear all caches
wp cache flush && wp rewrite flush && wp breeze purge --all

# Test page routing
wp eval 'print_r(get_page_by_path("trainer/dashboard"));'

# Force recreate pages
wp eval 'HVAC_Page_Manager::create_required_pages();'

# Check user roles
wp user list --role=hvac_trainer,hvac_master_trainer

# Database optimization
wp db optimize