upskill-event-manager/docs/CLAUDE-CODE-DEVELOPMENT-BEST-PRACTICES.md
Ben c3e7fe9140 feat: comprehensive HVAC plugin development framework and modernization
## Major Enhancements

### 🏗️ Architecture & Infrastructure
- Implement comprehensive Docker testing infrastructure with hermetic environment
- Add Forgejo Actions CI/CD pipeline for automated deployments
- Create Page Object Model (POM) testing architecture reducing test duplication by 90%
- Establish security-first development patterns with input validation and output escaping

### 🧪 Testing Framework Modernization
- Migrate 146+ tests from 80 duplicate files to centralized architecture
- Add comprehensive E2E test suites for all user roles and workflows
- Implement WordPress error detection with automatic site health monitoring
- Create robust browser lifecycle management with proper cleanup

### 📚 Documentation & Guides
- Add comprehensive development best practices guide
- Create detailed administrator setup documentation
- Establish user guides for trainers and master trainers
- Document security incident reports and migration guides

### 🔧 Core Plugin Features
- Enhance trainer profile management with certification system
- Improve find trainer functionality with advanced filtering
- Strengthen master trainer area with content management
- Add comprehensive venue and organizer management

### 🛡️ Security & Reliability
- Implement security-first patterns throughout codebase
- Add comprehensive input validation and output escaping
- Create secure credential management system
- Establish proper WordPress role-based access control

### 🎯 WordPress Integration
- Strengthen singleton pattern implementation across all classes
- Enhance template hierarchy with proper WordPress integration
- Improve page manager with hierarchical URL structure
- Add comprehensive shortcode and menu system

### 🔍 Developer Experience
- Add extensive debugging and troubleshooting tools
- Create comprehensive test data seeding scripts
- Implement proper error handling and logging
- Establish consistent code patterns and standards

### 📊 Performance & Optimization
- Optimize database queries and caching strategies
- Improve asset loading and script management
- Enhance template rendering performance
- Streamline user experience across all interfaces

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

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

435 lines
No EOL
13 KiB
Markdown

# Claude Code Development Best Practices
**Target Audience**: Claude Code agents working on the HVAC Community Events WordPress plugin
**Last Updated**: August 24, 2025
**Purpose**: Ensure consistent, secure, and effective development practices
## 🎯 Core Principles for Claude Code Agents
### 1. Leverage MCP Services and Specialized Agents
**CRITICAL**: Always utilize available MCP services and specialized agents from the user's `.claude` directory.
#### MCP Services Integration
- **Sequential Thinking** (`mcp__sequential-thinking__sequentialthinking`): Use for complex planning and multi-step tasks
- **Code Review** (`mcp__zen-mcp__codereview`): Use with GPT-5 & Qwen Coder for validation
- **Consensus Building** (`mcp__zen-mcp__consensus`): Use for architectural decisions
- **Deep Investigation** (`mcp__zen-mcp__thinkdeep`): Use for complex problem analysis
- **WebSearch**: Always use for documentation and best practices research
#### Specialized Agent Usage
```
- backend-architect: For architectural analysis and system design
- incident-responder: For production issues and critical bugs
- debugger: For systematic debugging and root cause analysis
- security-auditor: For security reviews and vulnerability assessment
- code-reviewer: For comprehensive code quality assessment
```
### 2. WordPress Template Architecture Patterns
**CRITICAL PATTERN**: Always use proper WordPress class initialization patterns.
#### ✅ Correct Singleton Usage
```php
// ALWAYS use singleton pattern for WordPress classes
if (class_exists('HVAC_Breadcrumbs')) {
echo HVAC_Breadcrumbs::instance()->render_breadcrumbs();
}
// NEVER assume static methods exist
// ❌ WRONG: HVAC_Breadcrumbs::render();
```
#### Template Requirements (MANDATORY)
Every WordPress template MUST include:
```php
// Template header
define('HVAC_IN_PAGE_TEMPLATE', true);
get_header();
// Template content here
// Template footer
get_footer();
```
### 3. Systematic Debugging Methodology
When encountering issues, follow this systematic approach:
#### Step 1: Comprehensive Analysis
```
1. Use mcp__sequential-thinking to plan investigation
2. Create comprehensive test suite FIRST
3. Document symptoms vs root causes
4. Use specialized debugging agents systematically
```
#### Step 2: Agent Deployment Strategy
```
1. incident-responder: For immediate triage
2. debugger: For technical investigation
3. backend-architect: For architectural analysis
4. code-reviewer: For quality validation
```
#### Step 3: Pattern Recognition
```
1. Compare working vs broken components
2. Identify architectural inconsistencies
3. Apply consistent patterns across codebase
4. Verify fixes actually resolve root causes
```
### 4. Testing Best Practices
#### E2E Testing with Playwright
Always create comprehensive test suites:
```javascript
// Use both standard Playwright and MCP browser tools
test('Master Trainer pages functionality', async ({ page }) => {
// Test actual page content, not just loading
await page.goto('/master-trainer/announcements/');
await expect(page.locator('h1')).toContainText('Manage Announcements');
await expect(page.locator('.hvac-announcements-content')).toBeVisible();
});
```
#### Test Coverage Requirements
- ✅ Authentication and access control
- ✅ Page content verification (not just successful loading)
- ✅ Navigation and UI consistency
- ✅ Role-specific functionality
- ✅ Mobile responsiveness
#### MCP Browser Tools Usage
When standard Playwright fails (display issues), use MCP tools:
```
mcp__playwright__browser_navigate
mcp__playwright__browser_click
mcp__playwright__browser_type
mcp__playwright__browser_snapshot
```
### 5. Security-First Development
#### Always Apply Security Patterns
```php
// Input Sanitization
$trainer_id = absint($_POST['trainer_id']);
$search_term = sanitize_text_field($_POST['search']);
// Output Escaping
echo esc_html($trainer_name);
echo esc_url($profile_link);
echo esc_attr($css_class);
// Nonce Verification
if (!wp_verify_nonce($_POST['nonce'], 'hvac_action')) {
wp_die('Security check failed');
}
// Capability Checking
if (!current_user_can('manage_own_events')) {
wp_die('Insufficient permissions');
}
// Role Checking (roles are NOT capabilities)
$user = wp_get_current_user();
if (!in_array('hvac_trainer', $user->roles)) {
wp_die('Access denied');
}
```
### 6. Deployment and Verification Workflow
#### Pre-Deployment (MANDATORY)
```bash
# Always run pre-deployment validation
scripts/pre-deployment-check.sh
# Run comprehensive tests
npm test
```
#### Staging Deployment (ALWAYS FIRST)
```bash
# Deploy to staging first
scripts/deploy.sh staging
# Verify deployment
scripts/verify-plugin-fixes.sh
```
#### Production Deployment (USER REQUEST ONLY)
```bash
# ONLY when user explicitly requests production deployment
scripts/deploy.sh production
```
### 7. WordPress Coding Standards
#### PHP Standards
```php
// Function naming: prefix + descriptive
function hvac_get_trainer_events($trainer_id) {
// WordPress array syntax (not PHP 7.4+ syntax)
$args = array(
'post_type' => 'tribe_events',
'meta_query' => array(
array(
'key' => '_EventTrainerID',
'value' => $trainer_id,
'compare' => '='
)
)
);
return get_posts($args);
}
// Class naming: HVAC_ prefix
class HVAC_Event_Manager {
// Singleton pattern
private static $instance = null;
public static function instance() {
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
}
```
#### JavaScript Standards
```javascript
// Always use jQuery in no-conflict mode
jQuery(document).ready(function($) {
'use strict';
// Event handling
$('.hvac-button').on('click', function(e) {
e.preventDefault();
// AJAX with proper error handling
$.ajax({
url: hvac_ajax.ajax_url,
type: 'POST',
data: {
action: 'hvac_action',
nonce: hvac_ajax.nonce,
data: $(this).serialize()
},
success: function(response) {
if (response.success) {
// Handle success
} else {
console.error(response.data.message);
}
},
error: function(xhr, status, error) {
console.error('AJAX error:', error);
}
});
});
});
```
### 8. Performance and Asset Management
#### Conditional Loading
```php
// Only load assets on plugin pages
public function enqueue_scripts() {
if (!$this->is_plugin_page()) {
return;
}
wp_enqueue_script('hvac-dashboard',
HVAC_PLUGIN_URL . 'assets/js/hvac-dashboard.js',
array('jquery'),
HVAC_PLUGIN_VERSION,
true
);
}
```
#### Caching Strategy
```php
// Cache expensive database queries
$cache_key = 'hvac_trainer_stats_' . $trainer_id;
$stats = wp_cache_get($cache_key);
if (false === $stats) {
$stats = $this->calculate_trainer_stats($trainer_id);
wp_cache_set($cache_key, $stats, '', 3600); // 1 hour
}
```
### 9. Error Handling and Logging
#### Graceful Degradation
```php
// Handle missing data gracefully
$trainer_name = get_user_meta($user_id, 'display_name', true)
?: $user->display_name
?: 'Unknown Trainer';
// API failure handling
try {
$result = $this->call_external_api($data);
} catch (Exception $e) {
error_log('External API failed: ' . $e->getMessage());
// Continue with fallback behavior
$result = $this->get_cached_fallback();
}
```
#### AJAX Response Standards
```php
// Always use consistent AJAX responses
public function ajax_handler() {
// Verify nonce first
if (!wp_verify_nonce($_POST['nonce'], 'hvac_action')) {
wp_send_json_error('Security check failed');
return;
}
try {
$result = $this->process_request($_POST);
wp_send_json_success($result);
} catch (Exception $e) {
error_log('AJAX handler error: ' . $e->getMessage());
wp_send_json_error('Processing failed');
}
}
```
### 10. Architecture Consistency
#### Template Hierarchy
All plugin templates must follow consistent structure:
```
templates/
├── page-trainer-*.php # Trainer pages
├── page-master-*.php # Master trainer pages
└── single-*.php # Single post templates
```
#### Class Organization
```
includes/
├── class-hvac-plugin.php # Main plugin controller
├── class-hvac-shortcodes.php # Centralized shortcodes
├── class-hvac-scripts-styles.php # Asset management
├── class-hvac-route-manager.php # URL routing
└── class-hvac-*-manager.php # Feature managers
```
## 🚨 Critical Don'ts
### Never Do This
- ❌ Deploy to production without explicit user request
- ❌ Skip pre-deployment validation checks
- ❌ Use `echo` without escaping output
- ❌ Assume static methods exist without verification
- ❌ Create standalone fixes outside plugin deployment
- ❌ Skip comprehensive testing before fixes
- ❌ Use hardcoded paths or URLs
- ❌ Ignore WordPress coding standards
### Always Do This
- ✅ Use MCP services and specialized agents proactively
- ✅ Test on staging before production
- ✅ Escape all output with appropriate functions
- ✅ Sanitize all input data
- ✅ Verify user capabilities and roles properly
- ✅ Use singleton patterns for WordPress classes
- ✅ Create comprehensive test suites first
- ✅ Apply consistent architectural patterns
## 🔧 Common Patterns and Solutions
### Role-Based Access Control
```php
// Check custom roles properly (NOT capabilities)
$user = wp_get_current_user();
$is_master_trainer = in_array('hvac_master_trainer', $user->roles);
$is_regular_trainer = in_array('hvac_trainer', $user->roles) && !$is_master_trainer;
if ($is_master_trainer) {
// Show master trainer interface
} else if ($is_regular_trainer) {
// Show regular trainer interface
} else {
wp_die('Access denied');
}
```
### Template Debugging Pattern
```php
// Debug template loading issues
if (defined('WP_DEBUG') && WP_DEBUG) {
error_log('Loading template: ' . __FILE__);
error_log('Template constants: ' . (defined('HVAC_IN_PAGE_TEMPLATE') ? 'DEFINED' : 'NOT DEFINED'));
}
```
### AJAX Form Handling
```javascript
// Complete AJAX form submission pattern
$('.hvac-form').on('submit', function(e) {
e.preventDefault();
var $form = $(this);
var $submitBtn = $form.find('button[type="submit"]');
var originalBtnText = $submitBtn.text();
// Show loading state
$submitBtn.prop('disabled', true).text('Processing...');
$.ajax({
url: hvac_ajax.ajax_url,
type: 'POST',
data: $form.serialize() + '&action=hvac_form_submit&nonce=' + hvac_ajax.nonce,
success: function(response) {
if (response.success) {
// Handle success
$form.trigger('hvac:success', response.data);
} else {
// Handle error
$form.trigger('hvac:error', response.data);
}
},
error: function() {
$form.trigger('hvac:error', {message: 'Network error occurred'});
},
complete: function() {
// Reset button state
$submitBtn.prop('disabled', false).text(originalBtnText);
}
});
});
```
## 📚 Resources and References
### Documentation
- **Main Documentation**: [docs/README.md](README.md)
- **WordPress Coding Standards**: [https://developer.wordpress.org/coding-standards/](https://developer.wordpress.org/coding-standards/)
- **WordPress Plugin Handbook**: [https://developer.wordpress.org/plugins/](https://developer.wordpress.org/plugins/)
- **The Events Calendar API**: [docs/scraped/the-events-calendar/](scraped/the-events-calendar/)
### Testing and Quality
- **Playwright Documentation**: [https://playwright.dev/](https://playwright.dev/)
- **WordPress Unit Testing**: [https://make.wordpress.org/core/handbook/testing/automated-testing/phpunit/](https://make.wordpress.org/core/handbook/testing/automated-testing/phpunit/)
### Plugin-Specific Guides
- **Architecture Overview**: [docs/ARCHITECTURE.md](ARCHITECTURE.md)
- **Security Guidelines**: [docs/SECURITY-FIXES.md](SECURITY-FIXES.md)
- **Troubleshooting Guide**: [docs/TROUBLESHOOTING.md](TROUBLESHOOTING.md)
---
*This document provides essential development guidelines specifically for Claude Code agents working on the HVAC Community Events plugin. Always refer to this document before beginning development work, and use the MCP services and specialized agents proactively for best results.*