From 25be5747a6e462a3d09fc6607b3639b79e4d9374 Mon Sep 17 00:00:00 2001
From: Jake Vanderwerf <get@jakevanderwerf.ca>
Date: Tue, 23 Dec 2025 20:11:26 +0000
Subject: [PATCH] =EmailManager.php refactor, Turnstile properly integrated with form submissions

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

diff --git a/inc/managers/OperationQueue.php b/inc/managers/OperationQueue.php
index 07f2104..182ca97 100644
--- a/inc/managers/OperationQueue.php
+++ b/inc/managers/OperationQueue.php
@@ -599,9 +599,7 @@
 	}
 
 	protected function updateLastModified(int $user_id) {
-		if (Features::forSite()->has('dashboard')) {
-			JVB()->routes('queue')->updateUserQueueTimestamp($user_id);
-		}
+		CacheManager::updateTimestamp("user_{$user_id}");
 	}
 
 	protected function deepMerge(array $existing, array $new): array
@@ -1182,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);
     }
 
     /**
@@ -1559,8 +1557,8 @@
 
     protected function updateUserQueueTimestamp(int $user_id)
     {
-        $key = "{$user_id}_queue_timestamp";
-		$this->cache->set($key, time());
+
+		CacheManager::updateTimestamp("user_{$user_id}");
     }
 
 	/**
@@ -1686,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