# TEC Template Override - Backend Architecture Design ## Phase 2 Implementation Specification **Document Version**: 1.0 **Date**: August 12, 2025 **Status**: Ready for Implementation **Agent**: Backend Architect --- ## EXECUTIVE SUMMARY This document defines the backend architecture for Phase 2 of the TEC template override system. Building on the successful Phase 1 (excerpt field prototype), Phase 2 will implement a modular, extensible, and secure backend architecture to handle 8+ additional WordPress core fields. **Key Architecture Goals**: - **Modular Design**: Individual field processors for scalability - **Security First**: Comprehensive validation and sanitization - **Extensibility**: Hook-based system for future enhancements - **Transaction Safety**: Atomic operations with rollback capability - **WordPress Integration**: Native WordPress functions and standards --- ## CURRENT STATE ANALYSIS ### Phase 1 Foundation (COMPLETE ✅) - **Template Override**: Working at `/templates/community-edit-event-prototype.php` - **Basic Processing**: Single method `process_tec_excerpt_field($event_id)` - **Hook Integration**: `tribe_events_community_before_event_save` - **Security**: Basic nonce verification - **Status**: Deployed to staging, excerpt field functional ### Phase 1 Architecture Limitations 1. **Non-scalable**: Single processing method cannot handle 8+ fields 2. **Limited Security**: Basic nonce check insufficient for file uploads 3. **No Modularity**: Fields cannot be independently developed/maintained 4. **Error Handling**: No comprehensive error collection or rollback 5. **Validation**: No field-specific validation framework --- ## PROPOSED BACKEND ARCHITECTURE ### 1. MAIN FIELD PROCESSOR CONTROLLER ```php /** * HVAC_TEC_Field_Processor - Main orchestration controller * * Responsibilities: * - Coordinate all field processing operations * - Manage security validation layer * - Handle transaction integrity * - Collect and manage errors * - Provide rollback capability */ class HVAC_TEC_Field_Processor { private $processors = []; private $security_manager; private $validator; private $errors = []; private $processed_fields = []; // Core methods public function register_processor($field_type, $processor_instance) {} public function process_all_fields($event_id, $post_data) {} public function get_processing_errors() {} public function rollback_changes($event_id) {} // Transaction management private function begin_transaction() {} private function commit_transaction() {} private function rollback_on_error($event_id) {} } ``` ### 2. MODULAR FIELD PROCESSORS Each field type gets its own dedicated processor class implementing the `HVAC_TEC_Field_Processor_Interface`: ```php interface HVAC_TEC_Field_Processor_Interface { public function validate($data, $event_id); public function process($data, $event_id); public function rollback($event_id); public function get_field_name(); } ``` #### 2.1 Categories Processor ```php class HVAC_TEC_Categories_Processor implements HVAC_TEC_Field_Processor_Interface { public function validate($data, $event_id) { // Validate category IDs exist // Check user permissions for categories // Validate hierarchical category structure } public function process($data, $event_id) { // Use wp_set_post_categories($event_id, $category_ids, false) // Handle multiple category selection // Log category assignments } public function rollback($event_id) { // Restore previous category assignments } } ``` #### 2.2 Featured Image Processor ```php class HVAC_TEC_FeaturedImage_Processor implements HVAC_TEC_Field_Processor_Interface { public function validate($data, $event_id) { // File upload security validation // Image type/size/dimension checks // User upload permissions } public function process($data, $event_id) { // Handle file upload to WordPress media library // Use set_post_thumbnail($event_id, $attachment_id) // Generate multiple image sizes if needed } public function rollback($event_id) { // Remove uploaded image // Restore previous featured image } } ``` #### 2.3 Tags Processor ```php class HVAC_TEC_Tags_Processor implements HVAC_TEC_Field_Processor_Interface { public function validate($data, $event_id) { // Validate tag format and length // Check for restricted tags // Validate user permissions } public function process($data, $event_id) { // Use wp_set_post_tags($event_id, $tags, false) // Handle tag creation for new tags // Process comma-separated tag input } } ``` #### 2.4 Custom Fields Processor ```php class HVAC_TEC_CustomFields_Processor implements HVAC_TEC_Field_Processor_Interface { public function process($data, $event_id) { // Use update_post_meta($event_id, $key, $value) // Handle different meta field types // Serialize complex data structures } } ``` ### 3. SECURITY FRAMEWORK ```php class HVAC_TEC_Security_Manager { // Comprehensive security validation public function validate_nonce($nonce_action = 'ecp_event_submission') {} public function validate_user_capabilities($event_id, $required_caps = []) {} public function validate_file_upload($file_data) {} public function validate_csrf_token() {} // Input sanitization by field type public function sanitize_text_field($input) {} public function sanitize_textarea_field($input) {} public function sanitize_file_upload($file) {} public function sanitize_taxonomy_terms($terms) {} } ``` ### 4. VALIDATION FRAMEWORK ```php class HVAC_TEC_Field_Validator { private $validation_rules = []; // Rule registration public function add_validation_rule($field, $rule, $callback) {} // Validation execution public function validate_field($field_name, $data, $event_id) {} public function collect_validation_errors() {} // Built-in validation methods public function validate_required($value) {} public function validate_file_type($file, $allowed_types) {} public function validate_image_dimensions($file, $max_width, $max_height) {} public function validate_category_ids($category_ids) {} } ``` --- ## DATABASE OPERATIONS STRATEGY ### WordPress Core Function Usage | Field Type | WordPress Function | Additional Processing | |------------|-------------------|----------------------| | Categories | `wp_set_post_categories()` | Taxonomy validation | | Tags | `wp_set_post_tags()` | Tag creation handling | | Featured Image | `set_post_thumbnail()` | Media library upload | | Custom Fields | `update_post_meta()` | Data serialization | | Post Status | `wp_update_post()` | Status validation | | Author | `wp_update_post()` | Capability checks | ### Transaction-Style Processing ```php public function process_all_fields($event_id, $post_data) { $this->begin_transaction(); try { foreach ($this->processors as $processor) { $result = $processor->process($post_data, $event_id); if (is_wp_error($result)) { throw new Exception($result->get_error_message()); } $this->processed_fields[] = $processor->get_field_name(); } $this->commit_transaction(); return new WP_Success("All fields processed successfully"); } catch (Exception $e) { $this->rollback_changes($event_id); return new WP_Error('processing_failed', $e->getMessage()); } } ``` --- ## EXTENSIBLE HOOK SYSTEM ### Core Processing Hooks ```php // Before any field processing do_action('hvac_tec_before_field_processing', $event_id, $post_data); // Individual field processing do_action('hvac_tec_field_processing', $field_type, $event_id, $field_data); do_action('hvac_tec_field_processed', $field_type, $event_id, $result); // After all field processing do_action('hvac_tec_after_all_fields', $event_id, $results); // Error handling hooks do_action('hvac_tec_processing_error', $field_type, $event_id, $error); do_action('hvac_tec_rollback_initiated', $event_id, $failed_fields); ``` ### Field-Specific Filters ```php // Field validation filters apply_filters('hvac_tec_validate_categories', $validation_result, $data, $event_id); apply_filters('hvac_tec_validate_featured_image', $validation_result, $file_data, $event_id); apply_filters('hvac_tec_validate_tags', $validation_result, $tags, $event_id); // Field processing filters apply_filters('hvac_tec_process_categories', $category_ids, $event_id); apply_filters('hvac_tec_process_featured_image', $attachment_id, $event_id); apply_filters('hvac_tec_process_custom_fields', $meta_data, $event_id); ``` --- ## TEMPLATE INTEGRATION ARCHITECTURE ### Modular Template Structure ``` /templates/ ├── community-edit-event-enhanced.php # Main template (Phase 2) └── community/modules/ # Field modules ├── hvac-excerpt.php # ✅ Existing (Phase 1) ├── hvac-categories.php # NEW - Categories field ├── hvac-featured-image.php # NEW - Image upload ├── hvac-tags.php # NEW - Tags input ├── hvac-custom-fields.php # NEW - Custom meta fields ├── hvac-post-status.php # NEW - Status selection └── hvac-author-selection.php # NEW - Author assignment ``` ### Template Data Preparation ```php // Enhanced template preparation in main template $field_data = [ 'categories' => [ 'selected' => wp_get_post_categories($event_id, ['fields' => 'ids']), 'available' => get_categories(['taxonomy' => 'tribe_events_cat']) ], 'featured_image' => [ 'current' => get_post_thumbnail_id($event_id), 'upload_url' => admin_url('async-upload.php') ], 'tags' => [ 'current' => wp_get_post_tags($event_id, ['fields' => 'names']), 'suggestions' => $this->get_popular_event_tags() ], 'custom_fields' => [ 'meta_values' => get_post_meta($event_id), 'field_definitions' => $this->get_custom_field_definitions() ] ]; // Pass prepared data to individual field modules foreach ($field_modules as $module_name => $module_config) { $module_config['data'] = array_merge( $module_config['data'] ?? [], $field_data[$module_name] ?? [] ); } ``` --- ## SECURITY IMPLEMENTATION ### Multi-Layer Security Validation 1. **Nonce Verification** - WordPress nonce system 2. **User Capabilities** - Role-based permission checks 3. **File Upload Security** - Type validation, size limits, scan for malicious content 4. **Input Sanitization** - Field-specific sanitization 5. **CSRF Protection** - Cross-site request forgery prevention ### Security Implementation Example ```php public function validate_security($event_id, $post_data) { // Layer 1: Nonce verification if (!wp_verify_nonce($_POST['_wpnonce'], 'ecp_event_submission')) { return new WP_Error('nonce_failed', 'Security verification failed'); } // Layer 2: User capabilities if (!current_user_can('edit_tribe_events') || !current_user_can('edit_post', $event_id)) { return new WP_Error('capability_failed', 'Insufficient permissions'); } // Layer 3: File upload validation (if applicable) if (isset($_FILES) && !empty($_FILES)) { $file_validation = $this->validate_file_uploads($_FILES); if (is_wp_error($file_validation)) { return $file_validation; } } // Layer 4: CSRF token validation if (!$this->validate_csrf_token($_POST)) { return new WP_Error('csrf_failed', 'Request origin validation failed'); } return true; } ``` --- ## INTEGRATION WITH EXISTING HVAC SYSTEM ### Enhanced HVAC_Community_Events Class ```php class HVAC_Community_Events { private $field_processor; public function init_hooks() { // Replace simple excerpt processing with comprehensive system remove_action('tribe_events_community_before_event_save', array($this, 'process_tec_excerpt_field')); add_action('tribe_events_community_before_event_save', array($this, 'process_all_tec_fields')); } public function process_all_tec_fields($event_id) { if (!$this->field_processor) { $this->field_processor = new HVAC_TEC_Field_Processor(); $this->register_field_processors(); } $result = $this->field_processor->process_all_fields($event_id, $_POST); if (is_wp_error($result)) { HVAC_Logger::error("TEC field processing failed: " . $result->get_error_message(), 'TEC Template Override'); // Add user-facing error message add_filter('tribe_events_community_submission_errors', function($errors) use ($result) { $errors[] = $result->get_error_message(); return $errors; }); } } private function register_field_processors() { $this->field_processor->register_processor('categories', new HVAC_TEC_Categories_Processor()); $this->field_processor->register_processor('featured_image', new HVAC_TEC_FeaturedImage_Processor()); $this->field_processor->register_processor('tags', new HVAC_TEC_Tags_Processor()); $this->field_processor->register_processor('custom_fields', new HVAC_TEC_CustomFields_Processor()); // ... additional processors } } ``` ### JavaScript Integration Updates Update existing comprehensive field population to work with new template: ```javascript // Enhanced field selectors for Phase 2 template const fieldSelectors = { excerpt: ['#post_excerpt', 'textarea[name="post_excerpt"]'], categories: ['select[name="tax_input[tribe_events_cat][]"]', '.hvac-categories-field'], featured_image: ['#hvac_featured_image', 'input[name="_thumbnail_id"]'], tags: ['#hvac_event_tags', 'input[name="tax_input[post_tag]"]'], custom_fields: { event_level: ['select[name="meta[event_level]"]'], max_attendees: ['input[name="meta[max_attendees]"]'] } }; // Enhanced population functions function populateEnhancedFields(eventData) { populateField(fieldSelectors.excerpt, eventData.core.excerpt, 'Excerpt'); populateCategories(fieldSelectors.categories, eventData.taxonomies.categories); populateFeaturedImage(fieldSelectors.featured_image, eventData.featured_image); populateTags(fieldSelectors.tags, eventData.taxonomies.tags); populateCustomFields(fieldSelectors.custom_fields, eventData.meta_fields); } ``` --- ## ERROR HANDLING AND LOGGING ### Comprehensive Error Management ```php class HVAC_TEC_Error_Handler { private $errors = []; private $warnings = []; public function add_error($field, $message, $code = 'field_error') { $this->errors[$field][] = [ 'message' => $message, 'code' => $code, 'timestamp' => current_time('mysql') ]; } public function has_errors() { return !empty($this->errors); } public function get_formatted_errors() { $formatted = []; foreach ($this->errors as $field => $field_errors) { $formatted[$field] = array_column($field_errors, 'message'); } return $formatted; } public function log_errors($event_id) { foreach ($this->errors as $field => $field_errors) { foreach ($field_errors as $error) { HVAC_Logger::error( "Field processing error - {$field}: {$error['message']} (Event ID: {$event_id})", 'TEC Template Override' ); } } } } ``` --- ## PERFORMANCE CONSIDERATIONS ### Optimization Strategies 1. **Lazy Loading**: Initialize processors only when needed 2. **Caching**: Cache validation rules and field configurations 3. **Batch Operations**: Process related fields together 4. **Resource Management**: Limit file upload sizes and processing time 5. **Database Optimization**: Use WordPress object cache for repeated queries ### Performance Monitoring Hooks ```php // Performance monitoring add_action('hvac_tec_before_field_processing', function($event_id) { update_option('hvac_tec_processing_start_' . $event_id, microtime(true)); }); add_action('hvac_tec_after_all_fields', function($event_id, $results) { $start_time = get_option('hvac_tec_processing_start_' . $event_id); $end_time = microtime(true); $processing_time = $end_time - $start_time; HVAC_Logger::info("Field processing completed in {$processing_time}s for event {$event_id}", 'TEC Performance'); delete_option('hvac_tec_processing_start_' . $event_id); }); ``` --- ## TESTING STRATEGY ### Unit Testing Structure ```php // Test individual field processors class Test_HVAC_TEC_Categories_Processor extends WP_UnitTestCase { public function test_category_validation() {} public function test_category_processing() {} public function test_category_rollback() {} } // Integration testing class Test_HVAC_TEC_Field_Integration extends WP_UnitTestCase { public function test_complete_field_processing() {} public function test_error_rollback() {} public function test_security_validation() {} } ``` ### E2E Testing Enhancement Extend existing Playwright test suite: ```javascript // test-tec-template-enhanced.js async function testEnhancedFields() { const fields = [ { name: 'Categories', selector: 'select[name="tax_input[tribe_events_cat][]"]' }, { name: 'Featured Image', selector: '#hvac_featured_image' }, { name: 'Tags', selector: '#hvac_event_tags' }, { name: 'Custom Fields', selector: '.hvac-custom-fields' } ]; for (const field of fields) { await testFieldPopulation(field); await testFieldSubmission(field); await testFieldPersistence(field); } } ``` --- ## DEPLOYMENT STRATEGY ### Phase 2 Deployment Plan 1. **Development Environment**: - Create feature branch: `feature/tec-template-phase2` - Implement architecture components incrementally - Unit test each processor individually 2. **Staging Deployment**: - Deploy enhanced template alongside prototype - A/B test Phase 1 vs Phase 2 templates - Run comprehensive E2E test suite - Performance benchmarking 3. **Production Rollout**: - Blue-green deployment strategy - Monitor error logs and performance metrics - Gradual rollout with feature flags - Rollback plan ready ### File Structure After Implementation ``` /includes/ ├── class-hvac-community-events.php # Enhanced main class ├── tec-fields/ # NEW - Field processors directory │ ├── class-hvac-tec-field-processor.php # Main controller │ ├── class-hvac-tec-security-manager.php # Security framework │ ├── class-hvac-tec-field-validator.php # Validation framework │ ├── processors/ # Individual processors │ │ ├── class-hvac-tec-categories-processor.php │ │ ├── class-hvac-tec-featured-image-processor.php │ │ ├── class-hvac-tec-tags-processor.php │ │ ├── class-hvac-tec-custom-fields-processor.php │ │ └── interface-hvac-tec-field-processor.php │ └── class-hvac-tec-error-handler.php # Error management └── ...existing files... /templates/ ├── community-edit-event-enhanced.php # NEW - Phase 2 template ├── community-edit-event-prototype.php # Phase 1 backup └── community/modules/ # Enhanced modules ├── hvac-excerpt.php # ✅ Existing ├── hvac-categories.php # NEW ├── hvac-featured-image.php # NEW ├── hvac-tags.php # NEW ├── hvac-custom-fields.php # NEW └── ...additional modules... ``` --- ## CONCLUSION This backend architecture provides a robust, scalable foundation for Phase 2 implementation. Key benefits: - **Modular Design**: Each field type independently developed and maintained - **Security First**: Comprehensive multi-layer security validation - **WordPress Integration**: Uses native WordPress functions and patterns - **Extensibility**: Hook-based system allows future enhancements - **Error Recovery**: Transaction-style processing with rollback capability - **Performance**: Optimized for minimal overhead and resource usage **Next Steps**: Implementation teams can begin developing individual components using this architecture specification, starting with the core `HVAC_TEC_Field_Processor` controller and security framework. --- **Document Control**: - Author: Backend Architect Agent - Review Status: Ready for Implementation - Implementation Teams: Phase 2 Development Team - Last Updated: August 12, 2025