From ccf5e61a075c35d24befc175994b5cb8957ca322 Mon Sep 17 00:00:00 2001
From: Jake Vanderwerf <get@jakevanderwerf.ca>
Date: Wed, 26 Aug 2026 21:45:53 +0000
Subject: [PATCH] =Extra JVB() calls replaced, minor tweaks

---
 inc/rest/routes/QueueRoutes.php |  116 ++++++++++++++++++++++++++++++++++++---------------------
 1 files changed, 73 insertions(+), 43 deletions(-)

diff --git a/inc/rest/routes/QueueRoutes.php b/inc/rest/routes/QueueRoutes.php
index 21fa98f..f9a8142 100644
--- a/inc/rest/routes/QueueRoutes.php
+++ b/inc/rest/routes/QueueRoutes.php
@@ -1,8 +1,10 @@
 <?php
 namespace JVBase\rest\routes;
 
+use JVBase\Instance;
 use JVBase\managers\Cache;
 use JVBase\managers\queue\Operation;
+use JVBase\managers\queue\Queue;
 use JVBase\rest\Rest;
 use JVBase\rest\Route;
 use JVBase\rest\Response;
@@ -15,15 +17,15 @@
 
 class QueueRoutes extends Rest
 {
+	use Instance;
 	public function __construct()
 	{
 		$this->cacheName = 'queue';
 		$this->cacheTtl = 300;
 		parent::__construct();
+		$this->cache = Cache::for($this->cacheName, 'custom', $this->cacheTtl)->user();
 
-		if (JVB_TESTING) {
-			$this->cache->flush();
-		}
+
 	}
 
 	/**
@@ -41,14 +43,15 @@
 				'limit' => 'integer|default:50|min:1|max:100',
 			])
 			->auth('user')
-			->rateLimit(30)
+			->rateLimit()
 			->post([$this, 'handleAction'])
 			->args([
 				'ids' => 'array|required',
 				'action' => 'string|required|enum:dismiss,retry,cancel',
 			])
 			->auth('user')
-			->rateLimit(30);
+			->rateLimit()
+			->register();
 
 		// Poll endpoint
 		Route::for('queue/poll')
@@ -58,20 +61,23 @@
 				'ids' => 'string',
 			])
 			->auth('user')
-			->rateLimit(15);
+			->rateLimit()
+			->register();
 
 		// Errors endpoint
 		Route::for('queue/errors')
 			->get([$this, 'getOperationErrors'])
 			->auth('user')
-			->rateLimit(15);
+			->rateLimit()
+			->register();
 
 		// Single operation with dynamic ID
 		Route::for(Route::pattern('queue/{id}'))
 			->get([$this, 'getOperation'])
 			->arg('id', 'string|required')
 			->auth('user')
-			->rateLimit(15);
+			->rateLimit()
+			->register();
 	}
 
 	/**
@@ -83,30 +89,20 @@
 	public function getQueue(WP_REST_Request $request): WP_REST_Response
 	{
 		$params = $request->get_params();
-		$user_id = absint($params['user']);
-		$status = sanitize_text_field($params['status']);
-		$ids = array_map('trim', array_map('sanitize_text_field', explode(',', $params['ids'])));
-		$limit = absint($params['limit']);
-
-		$cacheKey = $this->cache->generateKey(compact('user_id', 'status', 'ids', 'limit'));
-		if ($cached = $this->checkHeaders($request, $cacheKey)) {
-			return $cached;
+		$user_id = get_current_user_id();
+		if (!$user_id) {
+			return $this->unauthorized();
 		}
 
-		$data = $this->cache->remember($cacheKey, function() use ($user_id, $params) {
-			$filters = $this->buildFilters($params);
-			$operations = JVB()->queue()->getUserOperations($user_id, $filters);
+		$filters = $this->buildFilters($params);
+		$ops = Queue::getInstance()->getUserOperations($user_id, $filters);
 
-			return [
-				'items' => array_map([$this, 'formatOperation'], $operations),
-				'total' => count($operations),
-				'queue_stats' => $this->getQueueStats($user_id),
-				'server_time' => date('c'),
-			];
-		});
-
-		$response = Response::success($data);
-		return $this->addCacheHeaders($response);
+		return Response::success([
+			'items'	=> array_map([$this, 'formatOperation'], $ops),
+			'total'	=> count($ops),
+			'queue_stats' => $this->getQueueStats($user_id),
+			'server_time'	=> date('c')
+		]);
 	}
 
 	private function buildFilters(array $params): array
@@ -136,9 +132,17 @@
 	public function handleAction(WP_REST_Request $request): WP_REST_Response
 	{
 		$data = $request->get_params();
-		$ids = array_map('trim', array_map('sanitize_text_field', explode(',', $data['ids'])));
+		$ids = is_array($data['ids'])
+			? array_map('trim', array_map('sanitize_text_field', $data['ids']))
+			: array_map('trim', array_map('sanitize_text_field', explode(',', $data['ids'])));
+
 		$action = sanitize_text_field($data['action'] ?? '');
-		$user_id = absint($data['user']);
+		$user_id = get_current_user_id();
+		if (!$user_id) {
+			return $this->unauthorized();
+		}
+
+		$this->cache = Cache::for($user_id.'_queue');
 
 		// Validate input
 		if (empty($ids)) {
@@ -150,7 +154,7 @@
 		}
 
 		// Get operations via Queue - verifies ownership
-		$operations = JVB()->queue()->getUserOperations($user_id, [
+		$operations = Queue::getInstance()->getUserOperations($user_id, [
 			'ids' => $ids,
 			'limit' => count($ids),
 		]);
@@ -170,7 +174,11 @@
 
 	public function pollQueue(WP_REST_Request $request): WP_REST_Response
 	{
-		$userId = $request->get_param('user');
+		$userId = get_current_user_id();
+		if (!$userId) {
+			return $this->unauthorized();
+		}
+		$this->cache = Cache::for($userId.'_queue');
 		$since = $request->get_param('since');
 		$ids = $request->get_param('ids');
 
@@ -180,7 +188,7 @@
 			$filters['ids'] = array_map('trim', explode(',', $ids));
 		}
 
-		$operations = JVB()->queue()->getUserOperations($userId, $filters);
+		$operations = Queue::getInstance()->getUserOperations($userId, $filters);
 
 		if ($since) {
 			$sinceTime = strtotime($since);
@@ -192,6 +200,7 @@
 		$items = array_map(fn($op) => [
 			'id' => $op->id,
 			'status' => $this->mapStateToStatus($op->state, $op->outcome),
+			'progress_percentage'	=> $this->formatPercentage($op),
 			'progress_count' => $op->processedItems,
 			'count' => $op->totalItems,
 			'updated_at' => $this->formatTimestamp($op->completedAt ?? $op->startedAt ?? $op->scheduledAt),
@@ -207,8 +216,12 @@
 
 	public function getOperationErrors(WP_REST_Request $request): WP_REST_Response
 	{
-		$user_id = absint($request->get_param('user'));
-		$operations = JVB()->queue()->getUserOperations($user_id, [
+		$user_id = get_current_user_id();
+		if (!$user_id) {
+			return $this->unauthorized();
+		}
+		$this->cache = Cache::for($user_id.'_queue');
+		$operations = Queue::getInstance()->getUserOperations($user_id, [
 			'state' => 'completed',
 			'outcome' => ['failed', 'failed_permanent', 'partial'],
 			'has_errors' => true,
@@ -232,9 +245,13 @@
 	public function getOperation(WP_REST_Request $request): WP_REST_Response
 	{
 		$id = $request->get_param('id');
-		$userId = $request->get_param('user');
+		$userId = get_current_user_id();
+		if (!$userId) {
+			return $this->unauthorized();
+		}
+		$this->cache = Cache::for($userId.'_queue');
 
-		$op = JVB()->queue()->get($id);
+		$op = Queue::getInstance()->get($id);
 
 		if (!$op || $op->userId !== $userId) {
 			return Response::notFound('Operation not found');
@@ -251,25 +268,26 @@
 	{
 		return array_merge(
 			['queued' => 0, 'localProcessing' => 0, 'uploading' => 0],
-			JVB()->queue()->getUserStats($userId)
+			Queue::getInstance()->getUserStats($userId)
 		);
 	}
 
-	private function formatOperation(Operation $op, bool $full = false): array
+	private function formatOperation(Operation $op, bool $full = true): array
 	{
 		$formatted = [
 			'id' => $op->id,
 			'type' => $op->type,
 			'status' => $this->mapStateToStatus($op->state, $op->outcome),
 			'progress_count' => $op->processedItems,
+			'progress_percentage'	=> $this->formatPercentage($op),
 			'count' => $op->totalItems,
 			'title' => $this->getOperationTitle($op->type, $op->requestData),
 			'created_at' => $this->formatTimestamp($op->scheduledAt),
 			'updated_at' => $this->formatTimestamp($op->completedAt ?? $op->startedAt ?? $op->scheduledAt),
 		];
 
-		if ($op->processedItems > 0 && $op->totalItems > 0) {
-			$formatted['progress_percentage'] = round(($op->processedItems / $op->totalItems) * 100);
+		if (!empty($op->result['merged_into'])) {
+			$formatted['merged_into'] = $op->result['merged_into'];
 		}
 
 		if ($op->errorMessage) {
@@ -292,6 +310,18 @@
 		return $formatted;
 	}
 
+	protected function formatPercentage(Operation $op):int
+	{
+		if ($op->totalItems > 0){
+			return round(($op->processedItems / $op->totalItems) * 100);
+		} else {
+			return match($op->state) {
+				'pending','scheduled=' => 0,
+				'processing' => 45,
+				'completed'	=> 100
+			};
+		}
+	}
 	/**
 	 * Map backend state/outcome to frontend status
 	 * Backend uses: state (pending, scheduled, processing, completed) + outcome (pending, success, partial, failed, failed_permanent)
@@ -346,7 +376,7 @@
 
 	private function processAction(string $action, array $operations, int $userId): array
 	{
-		$queue = JVB()->queue();
+		$queue = Queue::getInstance();
 		$processed = 0;
 		$processedIds = [];
 

--
Gitblit v1.10.0