PluginProbe
WooCommerce / 11.1.0-rc.2
WooCommerce v11.1.0-rc.2
11.1.0 11.1.0-rc.2 11.1.0-rc.1 11.1.0-beta.2 11.1.0-beta.1 11.0.1 11.0.0 11.0.0-rc.3 11.0.0-rc.2 11.0.0-rc.1 11.0.0-beta.2 11.0.0-beta.1 10.9.4 10.9.3 10.9.2 10.9.1 10.9.0 10.9.0-rc.1 10.9.0-beta.2 10.9.0-beta.1 10.8.1 10.8.0 10.8.0-rc.1 10.8.0-beta.2 10.8.0-beta.1 All 648 releases
woocommerce / src / Admin / API / AnalyticsImports.php
AnalyticsImports.php
485 lines 15.8 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * REST API Analytics Imports Controller
4 *
5 * Handles requests to get batch import status and trigger manual imports.
6 */
7
8 declare( strict_types = 1 );
9
10 namespace Automattic\WooCommerce\Admin\API;
11
12 use WP_Error;
13 use Automattic\WooCommerce\Internal\Admin\Schedulers\OrdersScheduler;
14
15 defined( 'ABSPATH' ) || exit;
16
17 /**
18 * REST API Analytics Imports Controller.
19 *
20 * @internal
21 */
22 class AnalyticsImports extends \WC_REST_Data_Controller {
23 /**
24 * Endpoint namespace.
25 *
26 * @var string
27 */
28 protected $namespace = 'wc-analytics';
29
30 /**
31 * Route base.
32 *
33 * @var string
34 */
35 protected $rest_base = 'imports';
36
37 /**
38 * Register routes.
39 *
40 * @return void
41 */
42 public function register_routes(): void {
43 register_rest_route(
44 $this->namespace,
45 '/' . $this->rest_base . '/status',
46 array(
47 array(
48 'methods' => \WP_REST_Server::READABLE,
49 'callback' => array( $this, 'get_status' ),
50 'permission_callback' => array( $this, 'permissions_check' ),
51 ),
52 'schema' => array( $this, 'get_status_schema' ),
53 )
54 );
55
56 register_rest_route(
57 $this->namespace,
58 '/' . $this->rest_base . '/trigger',
59 array(
60 array(
61 'methods' => \WP_REST_Server::CREATABLE,
62 'callback' => array( $this, 'trigger_import' ),
63 'permission_callback' => array( $this, 'permissions_check' ),
64 ),
65 'schema' => array( $this, 'get_trigger_schema' ),
66 )
67 );
68
69 register_rest_route(
70 $this->namespace,
71 '/' . $this->rest_base . '/retry-failed',
72 array(
73 array(
74 'methods' => \WP_REST_Server::CREATABLE,
75 'callback' => array( $this, 'retry_failed_imports' ),
76 'permission_callback' => array( $this, 'permissions_check' ),
77 ),
78 'schema' => array( $this, 'get_retry_failed_schema' ),
79 )
80 );
81 }
82
83 /**
84 * Check if a given request has access to analytics imports.
85 *
86 * @param \WP_REST_Request<array<string, mixed>> $request Full details about the request.
87 * @return WP_Error|boolean
88 */
89 public function permissions_check( $request ) {
90 if ( ! current_user_can( 'manage_woocommerce' ) ) {
91 return new WP_Error(
92 'woocommerce_rest_cannot_access',
93 __( 'Sorry, you cannot access analytics imports.', 'woocommerce' ),
94 array( 'status' => rest_authorization_required_code() )
95 );
96 }
97
98 return true;
99 }
100
101 /**
102 * Get the current import status.
103 *
104 * @param \WP_REST_Request<array<string, mixed>> $request Full details about the request.
105 * @return \WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
106 */
107 public function get_status( $request ) {
108 $is_scheduled_mode = $this->is_scheduled_import_enabled();
109 $mode = $is_scheduled_mode ? 'scheduled' : 'immediate';
110
111 $failed_imports = OrdersScheduler::get_failed_order_imports();
112
113 $response = array(
114 'mode' => $mode,
115 'last_processed_date' => null,
116 'next_scheduled' => null,
117 'import_in_progress_or_due' => null,
118 'failed_count' => count( $failed_imports['ids'] ),
119 'failed_overflow_count' => $failed_imports['overflow'],
120 );
121
122 // For scheduled mode, populate additional fields.
123 if ( $is_scheduled_mode ) {
124 $last_processed_gmt = get_option( OrdersScheduler::LAST_PROCESSED_ORDER_DATE_OPTION, null );
125 $response['last_processed_date'] = ( is_string( $last_processed_gmt ) && $last_processed_gmt ) ? get_date_from_gmt( $last_processed_gmt, 'Y-m-d H:i:s' ) : null;
126 $response['next_scheduled'] = $this->get_next_scheduled_time();
127 $response['import_in_progress_or_due'] = $this->is_import_in_progress_or_due();
128 }
129
130 return rest_ensure_response( $response );
131 }
132
133 /**
134 * Trigger a manual import.
135 *
136 * @param \WP_REST_Request<array<string, mixed>> $request Full details about the request.
137 * @return \WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
138 */
139 public function trigger_import( $request ) {
140 $is_scheduled_mode = $this->is_scheduled_import_enabled();
141
142 // Return error if in immediate mode.
143 if ( ! $is_scheduled_mode ) {
144 return new WP_Error(
145 'woocommerce_rest_analytics_import_immediate_mode',
146 __( 'Manual import is not available in immediate mode. Imports happen automatically.', 'woocommerce' ),
147 array( 'status' => 400 )
148 );
149 }
150
151 // Check if an import is already in progress or due to run soon.
152 if ( $this->is_import_in_progress_or_due() ) {
153 return new WP_Error(
154 'woocommerce_rest_analytics_import_in_progress',
155 __( 'A batch import is already in progress or scheduled to run soon. Please wait for it to complete before triggering a new import.', 'woocommerce' ),
156 array( 'status' => 400 )
157 );
158 }
159
160 // Trigger the batch import immediately by rescheduling the recurring processor.
161 // This unschedules the current recurring action and reschedules it to run now.
162 $action_hook = OrdersScheduler::get_action( OrdersScheduler::PROCESS_PENDING_ORDERS_BATCH_ACTION );
163 if ( ! is_string( $action_hook ) ) {
164 return new WP_Error(
165 'woocommerce_rest_analytics_import_invalid_action',
166 __( 'Invalid action hook for batch import.', 'woocommerce' ),
167 array( 'status' => 500 )
168 );
169 }
170 WC()->queue()->cancel_all( $action_hook, array(), (string) OrdersScheduler::$group );
171 OrdersScheduler::schedule_recurring_batch_processor();
172
173 return rest_ensure_response(
174 array(
175 'success' => true,
176 'message' => __( 'Batch import triggered successfully.', 'woocommerce' ),
177 )
178 );
179 }
180
181 /**
182 * Re-schedule imports for orders that previously failed.
183 *
184 * Order IDs whose orders no longer exist are pruned (they can never import
185 * successfully). Orders with an import already pending are skipped and
186 * reported separately, so repeated requests don't claim to schedule new
187 * work. The remaining IDs stay recorded until their import succeeds, so a
188 * retry that fails again remains visible.
189 *
190 * @param \WP_REST_Request<array<string, mixed>> $request Full details about the request.
191 * @return \WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
192 */
193 public function retry_failed_imports( $request ) {
194 $failed = OrdersScheduler::get_failed_order_imports();
195
196 if ( empty( $failed['ids'] ) ) {
197 return new WP_Error(
198 'woocommerce_rest_analytics_no_failed_imports',
199 __( 'There are no failed order imports to retry.', 'woocommerce' ),
200 array( 'status' => 400 )
201 );
202 }
203
204 $retried_count = 0;
205 $pruned_count = 0;
206 $already_scheduled_count = 0;
207 $error_count = 0;
208 foreach ( $failed['ids'] as $order_id ) {
209 if ( ! wc_get_order( $order_id ) ) {
210 OrdersScheduler::clear_failed_order_import( $order_id );
211 ++$pruned_count;
212 continue;
213 }
214
215 // schedule_action() silently no-ops when the same import is
216 // already pending, so check first to report an accurate count.
217 if ( OrdersScheduler::has_existing_jobs( 'import', array( $order_id ) ) ) {
218 ++$already_scheduled_count;
219 continue;
220 }
221
222 try {
223 OrdersScheduler::schedule_action( 'import', array( $order_id ) );
224 ++$retried_count;
225 } catch ( \Throwable $e ) {
226 // schedule_action() may run the import synchronously (e.g. when
227 // Action Scheduler is unavailable); a failing order must not
228 // abort the whole retry request.
229 ++$error_count;
230 wc_get_logger()->error(
231 sprintf( 'Failed to schedule analytics re-import for order %d: %s', $order_id, $e->getMessage() ),
232 array( 'source' => 'wc-analytics-order-import' )
233 );
234 }
235 }
236
237 // Nothing was scheduled and nothing is pending: surface the failure
238 // instead of reporting success for work that didn't happen.
239 if ( 0 === $retried_count && 0 === $already_scheduled_count && $error_count > 0 ) {
240 return new WP_Error(
241 'woocommerce_rest_analytics_retry_failed',
242 __( 'The failed orders could not be scheduled for re-import. Check the order import log for details.', 'woocommerce' ),
243 array( 'status' => 500 )
244 );
245 }
246
247 if ( $retried_count > 0 ) {
248 $message = sprintf(
249 /* translators: %d: number of orders scheduled for re-import */
250 _n( 'Re-import scheduled for %d order.', 'Re-import scheduled for %d orders.', $retried_count, 'woocommerce' ),
251 $retried_count
252 );
253 } elseif ( $already_scheduled_count > 0 ) {
254 $message = __( 'Re-import is already scheduled for the previously failed orders.', 'woocommerce' );
255 } else {
256 $message = __( 'No orders were scheduled for re-import. The previously failed orders no longer exist.', 'woocommerce' );
257 }
258
259 if ( $error_count > 0 ) {
260 $message .= ' ' . sprintf(
261 /* translators: %d: number of orders that could not be scheduled for re-import */
262 _n( '%d order could not be scheduled. Check the order import log for details.', '%d orders could not be scheduled. Check the order import log for details.', $error_count, 'woocommerce' ),
263 $error_count
264 );
265 }
266
267 return rest_ensure_response(
268 array(
269 'success' => true,
270 'message' => $message,
271 'retried_count' => $retried_count,
272 'pruned_count' => $pruned_count,
273 'already_scheduled_count' => $already_scheduled_count,
274 'error_count' => $error_count,
275 )
276 );
277 }
278
279 /**
280 * Get the schema for the retry-failed endpoint, conforming to JSON Schema.
281 *
282 * @return array
283 */
284 public function get_retry_failed_schema() {
285 $schema = array(
286 '$schema' => 'https://json-schema.org/draft-04/schema#',
287 'title' => 'analytics_import_retry_failed',
288 'type' => 'object',
289 'properties' => array(
290 'success' => array(
291 'type' => 'boolean',
292 'description' => __( 'Whether the retry was scheduled successfully.', 'woocommerce' ),
293 'context' => array( 'view' ),
294 'readonly' => true,
295 ),
296 'message' => array(
297 'type' => 'string',
298 'description' => __( 'Result message.', 'woocommerce' ),
299 'context' => array( 'view' ),
300 'readonly' => true,
301 ),
302 'retried_count' => array(
303 'type' => 'integer',
304 'description' => __( 'Number of orders scheduled for re-import.', 'woocommerce' ),
305 'context' => array( 'view' ),
306 'readonly' => true,
307 ),
308 'pruned_count' => array(
309 'type' => 'integer',
310 'description' => __( 'Number of failed records removed because their orders no longer exist.', 'woocommerce' ),
311 'context' => array( 'view' ),
312 'readonly' => true,
313 ),
314 'already_scheduled_count' => array(
315 'type' => 'integer',
316 'description' => __( 'Number of orders skipped because their re-import is already pending.', 'woocommerce' ),
317 'context' => array( 'view' ),
318 'readonly' => true,
319 ),
320 'error_count' => array(
321 'type' => 'integer',
322 'description' => __( 'Number of orders that could not be scheduled for re-import.', 'woocommerce' ),
323 'context' => array( 'view' ),
324 'readonly' => true,
325 ),
326 ),
327 );
328
329 return $this->add_additional_fields_schema( $schema );
330 }
331
332 /**
333 * Check if scheduled import is enabled.
334 *
335 * Delegates to OrdersScheduler so the API reflects the same mode the
336 * scheduler actually runs in (feature flag check + legacy option fallback).
337 *
338 * @return bool
339 */
340 private function is_scheduled_import_enabled() {
341 return OrdersScheduler::is_scheduled_import_enabled();
342 }
343
344 /**
345 * Get the next scheduled time for the batch processor.
346 *
347 * @return string|null Datetime string in site timezone or null if not scheduled.
348 */
349 private function get_next_scheduled_time() {
350 $action_hook = OrdersScheduler::get_action( OrdersScheduler::PROCESS_PENDING_ORDERS_BATCH_ACTION );
351 if ( ! is_string( $action_hook ) ) {
352 return null;
353 }
354 $next_time = WC()->queue()->get_next( $action_hook, array(), (string) OrdersScheduler::$group );
355
356 if ( ! $next_time ) {
357 return null;
358 }
359
360 // Convert UTC timestamp to site timezone.
361 return get_date_from_gmt( $next_time->format( 'Y-m-d H:i:s' ), 'Y-m-d H:i:s' );
362 }
363
364 /**
365 * Get the schema for the status endpoint, conforming to JSON Schema.
366 *
367 * @return array
368 */
369 public function get_status_schema() {
370 $schema = array(
371 '$schema' => 'https://json-schema.org/draft-04/schema#',
372 'title' => 'analytics_import_status',
373 'type' => 'object',
374 'properties' => array(
375 'mode' => array(
376 'type' => 'string',
377 'enum' => array( 'scheduled', 'immediate' ),
378 'description' => __( 'Current import mode.', 'woocommerce' ),
379 'context' => array( 'view' ),
380 'readonly' => true,
381 ),
382 'last_processed_date' => array(
383 'type' => array( 'string', 'null' ),
384 'description' => __( 'Last processed order date (null in immediate mode).', 'woocommerce' ),
385 'context' => array( 'view' ),
386 'readonly' => true,
387 ),
388 'next_scheduled' => array(
389 'type' => array( 'string', 'null' ),
390 'description' => __( 'Next scheduled import time (null in immediate mode).', 'woocommerce' ),
391 'context' => array( 'view' ),
392 'readonly' => true,
393 ),
394 'import_in_progress_or_due' => array(
395 'type' => array( 'boolean', 'null' ),
396 'description' => __( 'Whether a batch import is currently running or scheduled to run within the next minute (null in immediate mode).', 'woocommerce' ),
397 'context' => array( 'view' ),
398 'readonly' => true,
399 ),
400 'failed_count' => array(
401 'type' => 'integer',
402 'description' => __( 'Number of orders that failed analytics import and are pending retry.', 'woocommerce' ),
403 'context' => array( 'view' ),
404 'readonly' => true,
405 ),
406 'failed_overflow_count' => array(
407 'type' => 'integer',
408 'description' => __( 'Number of failed order IDs dropped because the stored list reached its limit.', 'woocommerce' ),
409 'context' => array( 'view' ),
410 'readonly' => true,
411 ),
412 ),
413 );
414
415 return $this->add_additional_fields_schema( $schema );
416 }
417
418 /**
419 * Get the schema for the trigger endpoint, conforming to JSON Schema.
420 *
421 * @return array
422 */
423 public function get_trigger_schema() {
424 $schema = array(
425 '$schema' => 'https://json-schema.org/draft-04/schema#',
426 'title' => 'analytics_import_trigger',
427 'type' => 'object',
428 'properties' => array(
429 'success' => array(
430 'type' => 'boolean',
431 'description' => __( 'Whether the trigger was successful.', 'woocommerce' ),
432 'context' => array( 'view' ),
433 'readonly' => true,
434 ),
435 'message' => array(
436 'type' => 'string',
437 'description' => __( 'Result message.', 'woocommerce' ),
438 'context' => array( 'view' ),
439 'readonly' => true,
440 ),
441 ),
442 );
443
444 return $this->add_additional_fields_schema( $schema );
445 }
446
447 /**
448 * Check if a batch import is currently in progress or due to run soon.
449 *
450 * @return bool True if a batch import is in progress or scheduled to run within the next minute, false otherwise.
451 */
452 private function is_import_in_progress_or_due() {
453 $hook = OrdersScheduler::get_action( OrdersScheduler::PROCESS_PENDING_ORDERS_BATCH_ACTION );
454 if ( ! is_string( $hook ) ) {
455 return false;
456 }
457
458 // Check for actions with 'in-progress' status.
459 $in_progress_actions = WC()->queue()->search(
460 array(
461 'hook' => $hook,
462 'status' => 'in-progress',
463 'per_page' => 1,
464 ),
465 'ids'
466 );
467
468 if ( ! empty( $in_progress_actions ) ) {
469 return true;
470 }
471
472 // Check if the next scheduled import is due within 1 minute.
473 $next_scheduled = WC()->queue()->get_next( $hook, array(), (string) OrdersScheduler::$group );
474 if ( $next_scheduled ) {
475 $time_until_next = $next_scheduled->getTimestamp() - time();
476 // Consider it "due" if it's scheduled to run within the next 60 seconds.
477 if ( $time_until_next <= MINUTE_IN_SECONDS ) {
478 return true;
479 }
480 }
481
482 return false;
483 }
484 }
485