From 5b5f37de365ff84fc231e414a719d1b2ff4ceff6 Mon Sep 17 00:00:00 2001
From: Jake Vanderwerf <get@jakevanderwerf.ca>
Date: Thu, 01 Jan 2026 22:38:58 +0000
Subject: [PATCH] =further feed block testing

---
 inc/managers/OperationQueue.php |  201 ++++++++++++++++++++++++++++++--------------------
 1 files changed, 121 insertions(+), 80 deletions(-)

diff --git a/inc/managers/OperationQueue.php b/inc/managers/OperationQueue.php
index f10def6..182ca97 100644
--- a/inc/managers/OperationQueue.php
+++ b/inc/managers/OperationQueue.php
@@ -3,6 +3,7 @@
 
 use JVBase\managers\CacheManager;
 use Exception;
+use JVBase\utility\Features;
 use WP_Error;
 use WP_REST_Response;
 use WP_REST_Request;
@@ -79,7 +80,7 @@
     {
 		global $wpdb;
 		$this->wpdb = $wpdb;
-		$this->cache = new CacheManager('queue');
+		$this->cache = CacheManager::for('queue', DAY_IN_SECONDS);
         add_action('jvb_process_queue', [ $this, 'checkQueue' ]);
 		add_action('jvb_queue_maintenance', [$this, 'hourlyMaintenance']);
         add_action('jvbEmailDailyMetricsReport', [$this, 'emailDailyMetricsReport']);
@@ -579,7 +580,7 @@
 
 			$this->updateLastModified($user_id);
 			$this->invalidateQueueCache();
-			$this->cache->invalidate(self::CACHE_USER_QUEUE_PREFIX . $user_id);
+			$this->cache->delete(self::CACHE_USER_QUEUE_PREFIX . $user_id);
 			$this->runQueueOnShutdown();
 
 			return [
@@ -598,12 +599,18 @@
 	}
 
 	protected function updateLastModified(int $user_id) {
-		JVB()->routes('queue')->updateUserQueueTimestamp($user_id);
+		CacheManager::updateTimestamp("user_{$user_id}");
 	}
 
 	protected function deepMerge(array $existing, array $new): array
 	{
 		$merged = $existing;
+
+		if (!$this->isAssociativeArray($existing) && !$this->isAssociativeArray($new)) {
+			error_log('It is an associative array!');
+			return array_merge($existing, $new);
+		}
+		error_log('Not an associative array... moving on!');
 		foreach ($new as $key => $newValue) {
 			if (!array_key_exists($key, $existing)) {
 				$merged[$key] = $newValue;
@@ -614,8 +621,15 @@
 						// Recursive merge going deeper, if any of them are associative arrays
 						$merged[$key] = $this->deepMerge($existingValue, $newValue);
 					} else {
-						// Unique merge if indexed arrays
-						$merged[$key] = array_unique(array_merge($existingValue, $newValue), SORT_REGULAR);
+						$containsComplex = $this->containsComplexData($existingValue) || $this->containsComplexData($newValue);
+
+						if ($containsComplex) {
+							// Just merge and re-index - preserves all items from chunks
+							$merged[$key] = array_values(array_merge($existingValue, $newValue));
+						} else {
+							// Simple scalar arrays - use unique merge
+							$merged[$key] = array_unique(array_merge($existingValue, $newValue), SORT_REGULAR);
+						}
 					}
 				} elseif (is_array($existingValue) && !is_array($newValue)) {
 					// The existing value is an array, but the new one isn't
@@ -663,6 +677,21 @@
 		return array_keys($arr) !== range(0, count($arr) - 1);
 	}
 
+	/**
+	 * Check if an array contains complex data (arrays or objects)
+	 * @param array $arr
+	 * @return bool
+	 */
+	protected function containsComplexData(array $arr): bool
+	{
+		foreach ($arr as $item) {
+			if (is_array($item) || is_object($item)) {
+				return true;
+			}
+		}
+		return false;
+	}
+
 	protected function getEarliestScheduledTime(string $existing, string $new): string
 	{
 		$existing_time = strtotime($existing);
@@ -786,8 +815,8 @@
 				$this->processOperation($operation);
 
 				// Invalidate operation cache after processing
-				$this->cache->invalidate(self::CACHE_OPERATION_PREFIX . $operation->id);
-				$this->cache->invalidate(self::CACHE_USER_QUEUE_PREFIX . $operation->user_id);
+				$this->cache->delete(self::CACHE_OPERATION_PREFIX . $operation->id);
+				$this->cache->delete(self::CACHE_USER_QUEUE_PREFIX . $operation->user_id);
 			}
 
 			// Batch invalidate caches at the end
@@ -997,13 +1026,12 @@
 		$keys = $cacheKeys[$scope] ?? $cacheKeys['all'];
 
 		foreach ($keys as $key) {
-			$this->cache->invalidate($key);
+			$this->cache->delete($key);
 		}
 
 		if ($scope === 'all') {
 			// Clear entire group for complete refresh
-			$this->cache->invalidateGroup($this->cacheGroup);
-			jvbUpdateCacheTimestamp('queue');
+			$this->cache->invalidate();
 			delete_transient('jvb_queue_status_counts');
 		}
 	}
@@ -1152,7 +1180,7 @@
 
         $message .= "Please check the error logs for more details.";
 
-        return jvbMail($admin_email, $subject, $message);
+        return JVB()->email()->sendEmail($admin_email, $subject, $message);
     }
 
     /**
@@ -1264,8 +1292,11 @@
 					$filterResult['result'] = [$filterResult['result']];
 				}
 				// Store the result data
+				error_log('Merging Old Result: '. print_r($oldResult, true));
+				error_log('With Newer Result: '. print_r($filterResult['result'], true));
 				$resultToStore = $this->deepMerge($oldResult, $filterResult['result']);
 
+				error_log('Merged Result: '.print_r($resultToStore, true));
 
 				$resultToStore['processed_at'] = current_time('mysql');
 
@@ -1375,7 +1406,7 @@
 				}
 			}
 			// Clear operation cache after any update
-			$this->cache->invalidate(self::CACHE_OPERATION_PREFIX . $operation->id);
+			$this->cache->delete(self::CACHE_OPERATION_PREFIX . $operation->id);
 			$this->updateLastModified($operation->user_id);
 			return $filterResult;
 
@@ -1526,8 +1557,8 @@
 
     protected function updateUserQueueTimestamp(int $user_id)
     {
-        $key = "{$user_id}_queue_timestamp";
-		$this->cache->set($key, time());
+
+		CacheManager::updateTimestamp("user_{$user_id}");
     }
 
 	/**
@@ -1653,91 +1684,101 @@
      * Send daily metrics report to admin
      * @return void
      */
-    public function emailDailyMetricsReport():void
-    {
+	public function emailDailyMetricsReport():void
+	{
+		$metrics_table = $this->wpdb->prefix . $this->metricsTable;
+		$yesterday = date('Y-m-d', strtotime('-1 day'));
 
-        $metrics_table = $this->wpdb->prefix . $this->metricsTable;
-        $yesterday     = date('Y-m-d', strtotime('-1 day'));
+		$metrics = $this->wpdb->get_results($this->wpdb->prepare(
+			"SELECT * FROM $metrics_table WHERE date = %s",
+			$yesterday
+		));
 
-        // Get yesterday's metrics
-        $metrics = $this->wpdb->get_results($this->wpdb->prepare(
-            "SELECT * FROM $metrics_table WHERE date = %s",
-            $yesterday
-        ));
+		if (empty($metrics)) {
+			return;
+		}
 
-        if (empty($metrics)) {
-            return; // No metrics to report
-        }
+		$admin_email = get_option('admin_email');
+		$site_name = get_bloginfo('name');
+		$subject = "[$site_name] Daily Queue Performance - " . $yesterday;
 
-        $admin_email = get_option('admin_email');
-        $site_name   = get_bloginfo('name');
+		// Calculate totals
+		$total_ops = 0;
+		$total_success = 0;
+		$total_failed = 0;
+		$total_items = 0;
 
-        $subject = "[$site_name] Daily Queue Performance Report - " . date('Y-m-d', strtotime('-1 day'));
+		foreach ($metrics as $metric) {
+			$total_ops += $metric->total_operations;
+			$total_success += $metric->successful_operations;
+			$total_failed += $metric->failed_operations;
+			$total_items += $metric->total_items_processed;
+		}
 
-        $message = "Daily Queue Performance Report for $yesterday\n\n";
+		$success_rate = round(($total_success / max(1, $total_ops)) * 100, 1);
 
-        $message       .= "SUMMARY:\n";
-        $total_ops     = 0;
-        $total_success = 0;
-        $total_failed  = 0;
-        $total_items   = 0;
+		$message = JVB()->email()->h1('Daily Queue Performance Report');
+		$message .= sprintf('<p>Report for <strong>%s</strong></p>', $yesterday);
 
-        foreach ($metrics as $metric) {
-            $total_ops     += $metric->total_operations;
-            $total_success += $metric->successful_operations;
-            $total_failed  += $metric->failed_operations;
-            $total_items   += $metric->total_items_processed;
-        }
+		// Summary stats in grid
+		$stats = [
+			JVB()->email()->stat($total_ops, 'Operations'),
+			JVB()->email()->stat($total_success, 'Successful', '✓'),
+			JVB()->email()->stat($total_failed, 'Failed', $total_failed > 0 ? '⚠' : ''),
+			JVB()->email()->stat($success_rate . '%', 'Success Rate')
+		];
+		$message .= JVB()->email()->grid($stats, 4);
 
-        $message .= "- Total Operations: $total_ops\n";
-        $message .= "- Successful: $total_success\n";
-        $message .= "- Failed: $total_failed\n";
-        $message .= "- Success Rate: " . round(($total_success / max(1, $total_ops)) * 100, 2) . "%\n";
-        $message .= "- Total Items Processed: $total_items\n\n";
+		$message .= JVB()->email()->spacer(20);
 
-        $message .= "DETAILS BY OPERATION TYPE:\n";
+		// Alert if success rate is low
+		if ($success_rate < 90) {
+			$message .= JVB()->email()->alert(
+				sprintf('Success rate of %s%% is below the 90%% threshold', $success_rate),
+				'warning'
+			);
+		}
 
-        foreach ($metrics as $metric) {
-            $message .= "• $metric->type:\n";
-            $message .= "  - Operations: $metric->total_operations\n";
-            $message .= "  - Success: $metric->successful_operations\n";
-            $message .= "  - Failed: $metric->failed_operations\n";
+		$message .= JVB()->email()->h2('Details by Operation Type');
 
-            if ($metric->average_duration) {
-                $message .= "  - Avg. Duration: " . round($metric->average_duration, 2) . " seconds\n";
-            }
+		// Details for each operation type
+		foreach ($metrics as $metric) {
+			$details = [];
+			$details[] = ['label' => 'Total', 'value' => $metric->total_operations];
+			$details[] = ['label' => 'Success', 'value' => JVB()->email()->badge($metric->successful_operations, 'success')];
+			$details[] = ['label' => 'Failed', 'value' => $metric->failed_operations > 0 ? JVB()->email()->badge($metric->failed_operations, 'error') : '0'];
 
-            $message .= "  - Items Processed: $metric->total_items_processed\n";
+			if ($metric->average_duration) {
+				$details[] = ['label' => 'Avg Duration', 'value' => round($metric->average_duration, 2) . 's'];
+			}
 
-            if ($metric->peak_queue_size) {
-                $message .= "  - Peak Queue Size: $metric->peak_queue_size\n";
-            }
+			$details[] = ['label' => 'Items Processed', 'value' => number_format($metric->total_items_processed)];
 
-            if ($metric->peak_memory_usage) {
-                $memory_mb = round($metric->peak_memory_usage / 1024 / 1024, 2);
-                $message   .= "  - Peak Memory Usage: $memory_mb MB\n";
-            }
+			if ($metric->peak_memory_usage) {
+				$memory_mb = round($metric->peak_memory_usage / 1024 / 1024, 2);
+				$details[] = ['label' => 'Peak Memory', 'value' => $memory_mb . ' MB'];
+			}
 
-            if ($metric->peak_cpu_usage) {
-                $cpu_percent = round($metric->peak_cpu_usage * 50, 2); // Assuming 2 cores
-                $message     .= "  - Peak CPU Usage: $cpu_percent%\n";
-            }
+			$message .= JVB()->email()->card(
+				JVB()->email()->table($details),
+				esc_html($metric->type)
+			);
+		}
 
-            $message .= "\n";
-        }
+		// Current queue status
+		$pending_count = $this->getCurrentQueueSize();
+		if ($pending_count > 0) {
+			$message .= JVB()->email()->spacer(20);
+			$message .= JVB()->email()->notice(
+				sprintf('<strong>Current Queue:</strong> %d operations pending', $pending_count)
+			);
+		}
 
-        // Add any outstanding queue items
-        $pending_count = $this->getCurrentQueueSize();
-        if ($pending_count > 0) {
-            $message .= "CURRENT QUEUE STATUS:\n";
-            $message .= "- $pending_count operations currently pending in the queue\n\n";
-        }
+		$message .= JVB()->email()->spacer(20);
+		$message .= JVB()->email()->button(admin_url('admin.php?page=jvb-queue'), 'View Queue Dashboard');
 
-        $message .= "This is an automated report. Please check the admin dashboard for more details.";
-
-        // Send email
-        jvbMail($admin_email, $subject, $message);
-    }
+		JVB()->email()->sendEmail($admin_email, $subject, $message, 'QUEUE REPORT');
+	}
 
     /**
      * @return int

--
Gitblit v1.10.0