PluginProbe
WCPOS – Point of Sale (POS) plugin for WooCommerce / 1.9.15
WCPOS – Point of Sale (POS) plugin for WooCommerce v1.9.15
1.10.19 1.10.18 1.10.17 1.10.16 1.10.15 1.10.13 1.10.14 1.10.12 1.10.11 1.10.10 1.10.9 1.10.8 untagged-3d9b7ccddc54df87c672 1.10.7 1.10.6 1.10.5 1.10.3 1.10.4 1.10.2 1.10.1 1.10.0 1.9.17 1.9.15 1.9.16 1.9.14 All 163 releases
woocommerce-pos / includes / API / Products_Controller.php

Products_Controller.php in WCPOS – Point of Sale (POS) plugin for WooCommerce 1.9.15, at includes/API/Products_Controller.php

934 lines 31.0 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Products_Controller.
4 *
5 * @package WCPOS\WooCommercePOS
6 */
7
8 namespace WCPOS\WooCommercePOS\API;
9
10 \defined( 'ABSPATH' ) || die;
11
12 if ( ! class_exists( 'WC_REST_Products_Controller' ) ) {
13 return;
14 }
15
16 use Exception;
17 use WC_Data;
18 use WC_Product;
19 use WC_Product_Variable;
20 use WC_REST_Products_Controller;
21 use WCPOS\WooCommercePOS\Logger;
22 use WCPOS\WooCommercePOS\Services\Settings;
23 use WP_Error;
24 use WP_Query;
25 use WP_REST_Request;
26 use WP_REST_Response;
27
28 /**
29 * Products controller class.
30 *
31 * @NOTE: methods not prefixed with wcpos_ will override WC_REST_Products_Controller methods
32 */
33 class Products_Controller extends WC_REST_Products_Controller {
34 use Traits\Product_Helpers;
35 use Traits\Query_Helpers;
36 use Traits\Uuid_Handler;
37 use Traits\WCPOS_REST_API;
38
39 /**
40 * Endpoint namespace.
41 *
42 * @var string
43 */
44 protected $namespace = 'wcpos/v1';
45
46 /**
47 * Allow decimal quantities.
48 *
49 * @var bool
50 */
51 protected $allow_decimal_quantities = false;
52
53 /**
54 * Store the current request object.
55 *
56 * @var WP_REST_Request|null
57 */
58 protected $wcpos_request;
59
60 /**
61 * Memoized parent collection params.
62 *
63 * @var array|null
64 */
65 protected $wcpos_parent_collection_params = null;
66
67 /**
68 * Dispatch request to parent controller, or override if needed.
69 *
70 * @param mixed $dispatch_result Dispatch result, will be used if not empty.
71 * @param WP_REST_Request $request Request used to generate the response.
72 * @param string $route Route matched for the request.
73 * @param array $handler Route handler used for the request.
74 *
75 * @return mixed $dispatch_result Dispatch result, will be used if not empty.
76 */
77 public function wcpos_dispatch_request( $dispatch_result, WP_REST_Request $request, $route, $handler ) {
78 $this->wcpos_request = $request;
79
80 add_filter( 'woocommerce_rest_prepare_product_object', array( $this, 'wcpos_product_response' ), 10, 3 );
81 add_action( 'woocommerce_rest_insert_product_object', array( $this, 'wcpos_insert_product_object' ), 10, 3 );
82 add_filter( 'woocommerce_rest_product_object_query', array( $this, 'wcpos_product_query' ), 10, 2 );
83 add_filter( 'posts_search', array( $this, 'wcpos_posts_search' ), 10, 2 );
84 add_filter( 'posts_clauses', array( $this, 'wcpos_posts_clauses' ), 10, 2 );
85
86 /*
87 * Check if the request is for all products and if the 'posts_per_page' is set to -1.
88 * Optimised query for getting all product IDs.
89 */
90 if ( -1 == $request->get_param( 'posts_per_page' ) && null !== $request->get_param( 'fields' ) ) {
91 return $this->wcpos_get_all_posts( $request );
92 }
93
94 return $dispatch_result;
95 }
96
97 /**
98 * Add custom fields to the product schema.
99 * - Add 'barcode' property to the product schema.
100 * - Allow decimal quantities if enabled.
101 *
102 * Overrides the parent method.
103 *
104 * @return array $schema The product schema.
105 */
106 public function get_item_schema() {
107 $schema = parent::get_item_schema();
108
109 // Add the 'barcode' property if 'properties' exists and is an array.
110 if ( isset( $schema['properties'] ) && \is_array( $schema['properties'] ) ) {
111 $schema['properties']['barcode'] = array(
112 'description' => /* translators: REST API schema field label or error message. */ __( 'Barcode', 'woocommerce-pos' ),
113 'type' => 'string',
114 'context' => array( 'view', 'edit' ),
115 'readonly' => false,
116 );
117 }
118
119 // Check for 'stock_quantity' and allow decimal.
120 // Note: 'number' is the valid JSON schema type for decimals (not 'float').
121 if ( $this->wcpos_allow_decimal_quantities() &&
122 isset( $schema['properties']['stock_quantity'] ) &&
123 \is_array( $schema['properties']['stock_quantity'] ) ) {
124 $schema['properties']['stock_quantity']['type'] = 'number';
125 }
126
127 return $schema;
128 }
129
130
131 /**
132 * Modify the collection params.
133 * - Allow 'per_page' to be set to -1.
134 * - Add custom sorting options.
135 *
136 * Overrides the parent method.
137 *
138 * @return array $params The collection parameters.
139 */
140 public function get_collection_params() {
141 $params = $this->wcpos_get_parent_collection_params();
142
143 // Check if 'per_page' parameter exists and has a 'minimum' key before modifying.
144 if ( isset( $params['per_page'] ) && \is_array( $params['per_page'] ) ) {
145 $params['per_page']['minimum'] = -1;
146 }
147
148 if ( ! $this->wcpos_parent_collection_supports_param( 'brand' ) ) {
149 $params['brand'] = array(
150 'description' => /* translators: REST API collection parameter description. */ __( 'Limit result set to products assigned to brand IDs or slugs, separated by commas.', 'woocommerce-pos' ),
151 'type' => 'string',
152 'validate_callback' => 'rest_validate_request_arg',
153 );
154 }
155
156 if ( ! $this->wcpos_parent_collection_supports_param( 'brand_operator' ) ) {
157 $params['brand_operator'] = array(
158 'description' => /* translators: REST API collection parameter description. */ __( 'Operator to compare product brand terms.', 'woocommerce-pos' ),
159 'type' => 'string',
160 'enum' => array( 'in', 'not_in', 'and' ),
161 'default' => 'in',
162 'validate_callback' => 'rest_validate_request_arg',
163 );
164 }
165
166 if ( ! $this->wcpos_parent_collection_supports_param( 'category_operator' ) ) {
167 $params['category_operator'] = array(
168 'description' => /* translators: REST API collection parameter description. */ __( 'Operator to compare product category terms.', 'woocommerce-pos' ),
169 'type' => 'string',
170 'enum' => array( 'in', 'not_in', 'and' ),
171 'default' => 'in',
172 'validate_callback' => 'rest_validate_request_arg',
173 );
174 }
175
176 if ( ! $this->wcpos_parent_collection_supports_param( 'tag_operator' ) ) {
177 $params['tag_operator'] = array(
178 'description' => /* translators: REST API collection parameter description. */ __( 'Operator to compare product tag terms.', 'woocommerce-pos' ),
179 'type' => 'string',
180 'enum' => array( 'in', 'not_in', 'and' ),
181 'default' => 'in',
182 'validate_callback' => 'rest_validate_request_arg',
183 );
184 }
185
186 // Ensure 'orderby' is set and is an array before attempting to modify it.
187 if ( isset( $params['orderby']['enum'] ) && \is_array( $params['orderby']['enum'] ) ) {
188 // Define new sorting options.
189 $new_sort_options = array(
190 'sku',
191 'barcode',
192 'stock_quantity',
193 'stock_status',
194 );
195 // Merge new options, avoiding duplicates.
196 $params['orderby']['enum'] = array_unique( array_merge( $params['orderby']['enum'], $new_sort_options ) );
197 }
198
199 return $params;
200 }
201
202 /**
203 * Filter the product response.
204 *
205 * @param WP_REST_Response $response The response object.
206 * @param WC_Product $product Product data.
207 * @param WP_REST_Request $request Request object.
208 *
209 * @return WP_REST_Response $response The response object.
210 */
211 public function wcpos_product_response( WP_REST_Response $response, WC_Product $product, WP_REST_Request $request ): WP_REST_Response {
212 $data = $response->get_data();
213
214 // Add the UUID to the product response.
215 $this->maybe_add_post_uuid( $product );
216
217 // Add the barcode to the product response.
218 $data['barcode'] = $this->wcpos_get_barcode( $product );
219
220 // Check if the response has an image.
221 if ( isset( $data['images'] ) && ! empty( $data['images'] ) ) {
222 foreach ( $data['images'] as $key => $image ) {
223 // Replace the full size 'src' with the URL of the medium size image.
224 $image_id = $image['id'];
225 $medium_image_data = image_downsize( $image_id, 'medium' );
226
227 if ( $medium_image_data ) {
228 $data['images'][ $key ]['src'] = $medium_image_data[0];
229 } else {
230 $data['images'][ $key ]['src'] = $image['src'];
231 }
232 }
233 }
234
235 /*
236 * If product is variable, add the max and min prices and add them to the meta data
237 * @TODO - only need to update if there is a change
238 */
239 if ( $product->is_type( 'variable' ) && $product instanceof WC_Product_Variable ) {
240 $minimum_price = '';
241 $price_array = $this->wcpos_get_variable_product_price_ranges( $product, $minimum_price );
242
243 // A simple-to-variable conversion can leave old simple price fields on the
244 // parent. Serve the current minimum, but do not pair independent regular and
245 // sale minima from different variations into a false parent-level sale.
246 if ( array_key_exists( 'price', $data ) ) {
247 $decimals = null !== $request->get_param( 'dp' ) ? absint( $request->get_param( 'dp' ) ) : wc_get_price_decimals();
248 $data['price'] = '' === $minimum_price ? '' : wc_format_decimal( $minimum_price, $decimals );
249 }
250 foreach ( array( 'regular_price', 'sale_price' ) as $price_key ) {
251 if ( array_key_exists( $price_key, $data ) ) {
252 $data[ $price_key ] = '';
253 }
254 }
255
256 // Try encoding the array into JSON.
257 $encoded_price = wp_json_encode( $price_array );
258
259 // Check if the encoding was successful.
260 if ( false === $encoded_price ) {
261 // JSON encode failed, log the original array for debugging.
262 Logger::log( 'JSON encoding of price array failed: ' . json_last_error_msg(), $price_array );
263 } else {
264 // Update the meta data with the successfully encoded price data.
265 $product->update_meta_data( '_woocommerce_pos_variable_prices', $encoded_price );
266 }
267 }
268
269 // Parse the meta data before returning the response.
270 $data['meta_data'] = $this->wcpos_parse_meta_data( $product );
271
272 // Estimate response size and log if excessive.
273 $this->wcpos_estimate_response_size( $data, $product->get_id(), 'Product' );
274
275 // Set any changes to the response data.
276 $response->set_data( $data );
277
278 return $response;
279 }
280
281 /**
282 * Build variable product price ranges from current variation data.
283 *
284 * WooCommerce caches variable product price ranges in a parent-product transient.
285 * If a variation price changes without that parent cache being refreshed, the POS
286 * listing response can keep serving stale parent prices. Read the visible child
287 * variations directly for WCPOS response metadata so the listing reflects the
288 * current variation prices used by variation selection and cart flows.
289 *
290 * @param WC_Product_Variable $product Variable product.
291 * @param string|null $minimum_price Unrounded filtered minimum price, passed by reference.
292 *
293 * @return array{price: array{min: string, max: string}, regular_price: array{min: string, max: string},
294 * sale_price: array{min: string, max: string}}
295 */
296 private function wcpos_get_variable_product_price_ranges( WC_Product_Variable $product, ?string &$minimum_price = null ): array {
297 $prices = array(
298 'price' => array(),
299 'regular_price' => array(),
300 'sale_price' => array(),
301 );
302
303 $price_decimals = wc_get_price_decimals();
304
305 foreach ( $product->get_visible_children() as $variation_id ) {
306 $variation = wc_get_product( $variation_id );
307
308 if ( ! $variation ) {
309 continue;
310 }
311
312 $price = apply_filters(
313 // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- intentionally invoking WC core filter.
314 'woocommerce_variation_prices_price',
315 $variation->get_price( 'edit' ),
316 $variation,
317 $product
318 );
319
320 if ( '' === $price ) {
321 continue;
322 }
323
324 $regular_price = apply_filters(
325 // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- intentionally invoking WC core filter.
326 'woocommerce_variation_prices_regular_price',
327 $variation->get_regular_price( 'edit' ),
328 $variation,
329 $product
330 );
331 $sale_price = apply_filters(
332 // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- intentionally invoking WC core filter.
333 'woocommerce_variation_prices_sale_price',
334 $variation->get_sale_price( 'edit' ),
335 $variation,
336 $product
337 );
338
339 $formatted_price = wc_format_decimal( $price, $price_decimals );
340 $formatted_regular_price = wc_format_decimal( $regular_price, $price_decimals );
341 $formatted_sale_price = wc_format_decimal( $sale_price, $price_decimals );
342
343 $prices['price'][ $variation_id ] = (string) $price;
344 $prices['regular_price'][ $variation_id ] = $formatted_regular_price;
345
346 if ( '' !== $sale_price
347 && $formatted_sale_price !== $formatted_regular_price
348 && $formatted_sale_price === $formatted_price ) {
349 $prices['sale_price'][ $variation_id ] = $formatted_sale_price;
350 }
351 }
352
353 foreach ( $prices as $key => $values ) {
354 asort( $values, SORT_NUMERIC );
355 $prices[ $key ] = $values;
356 }
357
358 $price_range = $this->wcpos_apply_variable_product_price_range_filter(
359 'woocommerce_get_variation_price',
360 $this->wcpos_get_min_max_price_range( $prices['price'] ),
361 $product
362 );
363 $minimum_price = $price_range['min'];
364 $price_range = array(
365 'min' => '' === $price_range['min'] ? '' : wc_format_decimal( $price_range['min'], $price_decimals ),
366 'max' => '' === $price_range['max'] ? '' : wc_format_decimal( $price_range['max'], $price_decimals ),
367 );
368 $regular_price_range = $this->wcpos_get_min_max_price_range( $prices['regular_price'] );
369 $sale_price_range = $this->wcpos_get_min_max_price_range( $prices['sale_price'] );
370
371 return array(
372 'price' => $price_range,
373 'regular_price' => $this->wcpos_apply_variable_product_price_range_filter(
374 'woocommerce_get_variation_regular_price',
375 $regular_price_range,
376 $product
377 ),
378 'sale_price' => $this->wcpos_apply_variable_product_price_range_filter(
379 'woocommerce_get_variation_sale_price',
380 $sale_price_range,
381 $product
382 ),
383 );
384 }
385
386 /**
387 * Apply WooCommerce variable product min/max price filters to a calculated range.
388 *
389 * @param string $hook_name WooCommerce price range filter name.
390 * @param array{min: string, max: string} $price_range Price range.
391 * @param WC_Product_Variable $product Variable product.
392 *
393 * @return array{min: string, max: string}
394 */
395 private function wcpos_apply_variable_product_price_range_filter( string $hook_name, array $price_range, WC_Product_Variable $product ): array {
396 if ( '' !== $price_range['min'] ) {
397 $price_range['min'] = (string) apply_filters(
398 $hook_name,
399 $price_range['min'],
400 $product,
401 'min',
402 false
403 );
404 }
405
406 if ( '' !== $price_range['max'] ) {
407 $price_range['max'] = (string) apply_filters(
408 $hook_name,
409 $price_range['max'],
410 $product,
411 'max',
412 false
413 );
414 }
415
416 return $price_range;
417 }
418
419 /**
420 * Convert a variation price list to a min/max range.
421 *
422 * @param array<int,string> $prices Prices keyed by variation ID.
423 *
424 * @return array{min: string, max: string}
425 */
426 private function wcpos_get_min_max_price_range( array $prices ): array {
427 if ( empty( $prices ) ) {
428 return array(
429 'min' => '',
430 'max' => '',
431 );
432 }
433
434 return array(
435 'min' => (string) reset( $prices ),
436 'max' => (string) end( $prices ),
437 );
438 }
439
440 /**
441 * Fires after a single object is created or updated via the REST API.
442 *
443 * @param WC_Data $object Inserted object.
444 * @param WP_REST_Request $request Request object.
445 * @param bool $creating True when creating object, false when updating.
446 */
447 public function wcpos_insert_product_object( WC_Data $object, WP_REST_Request $request, $creating ): void {
448 // Update the barcode if it is set in the request.
449 $barcode_field = $this->wcpos_get_barcode_field();
450 if ( $request->has_param( 'barcode' ) ) {
451 $barcode = $request->get_param( 'barcode' );
452 if ( '_sku' === $barcode_field ) {
453 $object->set_sku( $barcode );
454 $object->save();
455 } elseif ( '_global_unique_id' === $barcode_field ) {
456 $object->set_global_unique_id( $barcode );
457 $object->save();
458 } else {
459 $object->update_meta_data( $barcode_field, $barcode );
460 $object->save_meta_data();
461 }
462 }
463 }
464
465 /**
466 * Filter to adjust the WordPress search SQL query
467 * - Search for the product title and SKU and barcode
468 * - Do not search product description.
469 *
470 * @param string $search The search SQL query.
471 * @param WP_Query $wp_query The WP_Query instance (passed by reference).
472 *
473 * @return string
474 */
475 public function wcpos_posts_search( string $search, WP_Query $wp_query ) {
476 global $wpdb;
477
478 if ( empty( $search ) ) {
479 return $search; // skip processing - no search term in query.
480 }
481
482 $q = $wp_query->query_vars;
483 $n = ! empty( $q['exact'] ) ? '' : '%';
484 $search_terms = (array) $q['search_terms'];
485
486 // Fields in the main 'posts' table.
487 $post_fields = array( 'post_title' );
488
489 // Meta fields to search.
490 $meta_fields = array( '_sku' );
491 $barcode_field = $this->wcpos_get_barcode_field();
492 if ( '_sku' !== $barcode_field ) {
493 $meta_fields[] = $barcode_field;
494 }
495
496 $search_conditions = array();
497
498 foreach ( $search_terms as $term ) {
499 $term = $n . $wpdb->esc_like( $term ) . $n;
500
501 // Search in post fields.
502 foreach ( $post_fields as $field ) {
503 $search_conditions[] = $wpdb->prepare( "({$wpdb->posts}.$field LIKE %s)", $term ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- table name is safe.
504 }
505
506 // Search in meta fields.
507 foreach ( $meta_fields as $field ) {
508 $search_conditions[] = $wpdb->prepare( '(pm1.meta_value LIKE %s AND pm1.meta_key = %s)', $term, $field );
509 }
510 }
511
512 if ( ! empty( $search_conditions ) ) {
513 $search = ' AND (' . implode( ' OR ', $search_conditions ) . ') ';
514 if ( ! is_user_logged_in() ) {
515 $search .= " AND ($wpdb->posts.post_password = '') ";
516 }
517 }
518
519 return $search;
520 }
521
522 /**
523 * Filters all query clauses at once, for convenience.
524 *
525 * Covers the WHERE, GROUP BY, JOIN, ORDER BY, DISTINCT,
526 * fields (SELECT), and LIMIT clauses.
527 *
528 * @param string[] $clauses Associative array of the clauses for the query.
529 * @param WP_Query $wp_query The WP_Query instance (passed by reference).
530 */
531 public function wcpos_posts_clauses( array $clauses, WP_Query $wp_query ): array {
532 global $wpdb;
533
534 // Handle NULL values in stock_quantity sorting
535 // By default, MySQL sorts NULLs first in ASC and last in DESC
536 // We want NULLs to always be last regardless of sort direction.
537 if ( isset( $this->wcpos_request ) ) {
538 $orderby = $this->wcpos_request->get_param( 'orderby' );
539 $order = strtoupper( $this->wcpos_request->get_param( 'order' ) ?? 'ASC' );
540
541 if ( 'stock_quantity' === $orderby ) {
542 // Modify ORDER BY to put NULLs last
543 // Use CASE to assign a sort priority: non-NULL = 0, NULL = 1
544 // Then sort by the actual value.
545 $clauses['orderby'] = "{$wpdb->postmeta}.meta_value IS NULL ASC, {$wpdb->postmeta}.meta_value + 0 {$order}";
546 }
547 }
548
549 return $clauses;
550 }
551
552 /**
553 * Filter the query arguments for a request.
554 *
555 * @param array $args Key value array of query var to query value.
556 * @param WP_REST_Request $request The request used.
557 *
558 * @return array $args Key value array of query var to query value.
559 */
560 public function wcpos_product_query( array $args, WP_REST_Request $request ) {
561 if ( ! empty( $request['search'] ) ) {
562 // We need to set the query up for a postmeta join.
563 add_filter( 'posts_join', array( $this, 'wcpos_posts_join_to_products_search' ), 10, 2 );
564 add_filter( 'posts_groupby', array( $this, 'wcpos_posts_groupby_product_search' ), 10, 2 );
565 }
566
567 // if POS only products are enabled, exclude online-only products.
568 if ( $this->wcpos_pos_only_products_enabled() ) {
569 add_filter( 'posts_where', array( $this, 'wcpos_posts_where_product_exclude_online_only' ), 10, 2 );
570 }
571
572 // Check for wcpos_include/wcpos_exclude parameter.
573 if ( isset( $request['wcpos_include'] ) || isset( $request['wcpos_exclude'] ) ) {
574 add_filter( 'posts_where', array( $this, 'wcpos_posts_where_product_include_exclude' ), 20, 2 );
575 }
576
577 return $args;
578 }
579
580 /**
581 * Check whether the parent WooCommerce REST controller already supports a collection param.
582 *
583 * If WooCommerce adds native REST support for Store API-style product filters, WCPOS
584 * should defer to the parent implementation instead of adding duplicate tax queries.
585 *
586 * @param string $param Collection parameter name.
587 *
588 * @return bool
589 */
590 protected function wcpos_parent_collection_supports_param( string $param ): bool {
591 $params = $this->wcpos_get_parent_collection_params();
592
593 return isset( $params[ $param ] );
594 }
595
596 /**
597 * Get parent collection params once per controller instance.
598 *
599 * @return array
600 */
601 protected function wcpos_get_parent_collection_params(): array {
602 if ( null === $this->wcpos_parent_collection_params ) {
603 $this->wcpos_parent_collection_params = parent::get_collection_params();
604 }
605
606 return $this->wcpos_parent_collection_params;
607 }
608
609 /**
610 * Parse one or more taxonomy terms from a Store API-style request parameter.
611 *
612 * @param WP_REST_Request $request The request used.
613 * @param string $param Request parameter name.
614 *
615 * @return array{field?:string,terms?:array<int,int|string>}
616 */
617 protected function wcpos_get_store_api_tax_terms_from_request( WP_REST_Request $request, string $param ): array {
618 $value = $request->get_param( $param );
619
620 if ( empty( $value ) ) {
621 return array();
622 }
623
624 $terms = array_filter( array_map( 'trim', explode( ',', (string) $value ) ) );
625 if ( empty( $terms ) ) {
626 return array();
627 }
628
629 $ids = wp_parse_id_list( $terms );
630 if ( \count( $ids ) === \count( $terms ) ) {
631 return array(
632 'field' => 'term_id',
633 'terms' => $ids,
634 );
635 }
636
637 return array(
638 'field' => 'slug',
639 'terms' => $terms,
640 );
641 }
642
643 /**
644 * Convert Store API-style taxonomy operators to WP_Query tax query operators.
645 *
646 * @param string|null $operator Store API taxonomy operator.
647 *
648 * @return string
649 */
650 protected function wcpos_get_store_api_tax_operator( ?string $operator ): string {
651 $operators = array(
652 'and' => 'AND',
653 'in' => 'IN',
654 'not_in' => 'NOT IN',
655 );
656
657 return $operators[ $operator ?? 'in' ] ?? 'IN';
658 }
659
660 /**
661 * Apply Store API taxonomy fallback query behavior for params missing in Woo REST.
662 *
663 * @param array $args Prepared query args.
664 * @param WP_REST_Request $request The request used.
665 *
666 * @return array
667 */
668 protected function wcpos_apply_store_api_tax_operator_fallbacks( array $args, WP_REST_Request $request ): array {
669 if ( ! $this->wcpos_parent_collection_supports_param( 'brand' ) ) {
670 $brand_terms = $this->wcpos_get_store_api_tax_terms_from_request( $request, 'brand' );
671 if ( isset( $brand_terms['field'], $brand_terms['terms'] ) && taxonomy_exists( 'product_brand' ) ) {
672 if ( ! isset( $args['tax_query'] ) || ! \is_array( $args['tax_query'] ) ) {
673 $args['tax_query'] = array();
674 }
675
676 $args['tax_query'][] = array(
677 'taxonomy' => 'product_brand',
678 'field' => $brand_terms['field'],
679 'terms' => $brand_terms['terms'],
680 'operator' => $this->wcpos_get_store_api_tax_operator( $request->get_param( 'brand_operator' ) ),
681 );
682 }
683 }
684
685 $operator_fallbacks = array(
686 'category_operator' => 'product_cat',
687 'tag_operator' => 'product_tag',
688 );
689 $query_params = $request->get_query_params();
690
691 foreach ( $operator_fallbacks as $param => $taxonomy ) {
692 if ( $this->wcpos_parent_collection_supports_param( $param ) || ! array_key_exists( $param, $query_params ) ) {
693 continue;
694 }
695
696 if ( ! isset( $args['tax_query'] ) || ! \is_array( $args['tax_query'] ) ) {
697 continue;
698 }
699
700 $args['tax_query'] = $this->wcpos_replace_tax_query_operator_for_taxonomy(
701 $args['tax_query'],
702 $taxonomy,
703 $this->wcpos_get_store_api_tax_operator( $request->get_param( $param ) )
704 );
705 }
706
707 return $args;
708 }
709
710 /**
711 * Replace a tax query clause operator for one taxonomy.
712 *
713 * @param array $tax_query Tax query clauses.
714 * @param string $taxonomy Taxonomy to match.
715 * @param string $operator WP_Tax_Query operator.
716 *
717 * @return array
718 */
719 protected function wcpos_replace_tax_query_operator_for_taxonomy( array $tax_query, string $taxonomy, string $operator ): array {
720 foreach ( $tax_query as $key => $clause ) {
721 if ( ! \is_array( $clause ) || ! isset( $clause['taxonomy'] ) || $taxonomy !== $clause['taxonomy'] ) {
722 continue;
723 }
724
725 $tax_query[ $key ]['operator'] = $operator;
726 }
727
728 return $tax_query;
729 }
730
731 /**
732 * Filters the JOIN clause of the query.
733 *
734 * @param string $join The JOIN clause of the query.
735 * @param WP_Query $query The WP_Query instance (passed by reference).
736 *
737 * @return string
738 */
739 public function wcpos_posts_join_to_products_search( string $join, WP_Query $query ) {
740 global $wpdb;
741
742 if ( ! empty( $query->query_vars['s'] ) && false === strpos( $join, 'pm1' ) ) {
743 $join .= " LEFT JOIN {$wpdb->postmeta} pm1 ON {$wpdb->posts}.ID = pm1.post_id ";
744 }
745
746 return $join;
747 }
748
749 /**
750 * Filters the GROUP BY clause of the query.
751 *
752 * @param string $groupby The GROUP BY clause of the query.
753 * @param WP_Query $query The WP_Query instance (passed by reference).
754 *
755 * @return string
756 */
757 public function wcpos_posts_groupby_product_search( string $groupby, WP_Query $query ) {
758 global $wpdb;
759
760 if ( ! empty( $query->query_vars['s'] ) ) {
761 $groupby = "{$wpdb->posts}.ID";
762 }
763
764 return $groupby;
765 }
766
767 /**
768 * Filters the WHERE clause of the query.
769 *
770 * @param string $where The WHERE clause of the query.
771 * @param WP_Query $query The WP_Query instance (passed by reference).
772 *
773 * @return string
774 */
775 public function wcpos_posts_where_product_exclude_online_only( string $where, WP_Query $query ) {
776 global $wpdb;
777
778 $settings_instance = Settings::instance();
779 $online_only = $settings_instance->get_online_only_product_visibility_settings();
780 $online_only_ids = isset( $online_only['ids'] ) && \is_array( $online_only['ids'] ) ? $online_only['ids'] : array();
781
782 // Exclude online-only product IDs if POS only products are enabled.
783 if ( ! empty( $online_only_ids ) ) {
784 $online_only_ids = array_map( 'intval', (array) $online_only_ids );
785 $ids_format = implode( ',', array_fill( 0, \count( $online_only_ids ), '%d' ) );
786 $where .= $wpdb->prepare( " AND {$wpdb->posts}.ID NOT IN ($ids_format) ", $online_only_ids ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- table name and format are safe.
787 }
788
789 return $where;
790 }
791
792 /**
793 * Filters the WHERE clause of the query.
794 *
795 * @param string $where The WHERE clause of the query.
796 * @param WP_Query $query The WP_Query instance (passed by reference).
797 *
798 * @return string
799 */
800 public function wcpos_posts_where_product_include_exclude( string $where, WP_Query $query ) {
801 global $wpdb;
802
803 // Handle 'wcpos_include'.
804 if ( ! empty( $this->wcpos_request['wcpos_include'] ) ) {
805 $include_ids = array_map( 'intval', (array) $this->wcpos_request['wcpos_include'] );
806 $ids_format = implode( ',', array_fill( 0, \count( $include_ids ), '%d' ) );
807 $where .= $wpdb->prepare( " AND {$wpdb->posts}.ID IN ($ids_format) ", $include_ids ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- table name and format are safe.
808 }
809
810 // Handle 'wcpos_exclude'.
811 if ( ! empty( $this->wcpos_request['wcpos_exclude'] ) ) {
812 $exclude_ids = array_map( 'intval', (array) $this->wcpos_request['wcpos_exclude'] );
813 $ids_format = implode( ',', array_fill( 0, \count( $exclude_ids ), '%d' ) );
814 $where .= $wpdb->prepare( " AND {$wpdb->posts}.ID NOT IN ($ids_format) ", $exclude_ids ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- table name and format are safe.
815 }
816
817 return $where;
818 }
819
820
821 /**
822 * Returns array of all product ids, name.
823 *
824 * @param WP_REST_Request $request Full details about the request.
825 *
826 * @return WP_Error|WP_REST_Response
827 */
828 public function wcpos_get_all_posts( $request ) {
829 global $wpdb;
830
831 // Start timing execution.
832 $start_time = microtime( true );
833
834 $modified_after = $request->get_param( 'modified_after' );
835 $dates_are_gmt = true; // Dates are always in GMT.
836 $fields = $request->get_param( 'fields' );
837 $id_with_modified_date = array( 'id', 'date_modified_gmt' ) === $fields;
838 $select_fields = $id_with_modified_date ? 'ID as id, post_modified_gmt as date_modified_gmt' : 'ID as id';
839
840 // Use SELECT DISTINCT in the initial SQL statement for both cases.
841 $sql = "SELECT DISTINCT {$select_fields} FROM {$wpdb->posts}";
842 $sql .= " WHERE post_type = 'product' AND post_status = 'publish'";
843
844 // If the '_pos_visibility' condition needs to be applied.
845 if ( $this->wcpos_pos_only_products_enabled() ) {
846 $settings_instance = Settings::instance();
847 $online_only = $settings_instance->get_online_only_product_visibility_settings();
848 if ( isset( $online_only['ids'] ) && \is_array( $online_only['ids'] ) && ! empty( $online_only['ids'] ) ) {
849 $online_only_ids = array_map( 'intval', (array) $online_only['ids'] );
850 $ids_format = implode( ',', array_fill( 0, \count( $online_only_ids ), '%d' ) );
851 $sql .= $wpdb->prepare( " AND ID NOT IN ($ids_format) ", $online_only_ids ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQL.NotPrepared -- format string is safe.
852 }
853 }
854
855 // Add modified_after condition if provided.
856 if ( $modified_after ) {
857 $modified_after_date = wp_date( 'Y-m-d H:i:s', strtotime( $modified_after ) );
858 $sql .= $wpdb->prepare( ' AND post_modified_gmt > %s', $modified_after_date );
859 }
860
861 // Order by post_date DESC to maintain order consistency.
862 $sql .= " ORDER BY {$wpdb->posts}.post_date DESC";
863
864 try {
865 $results = $wpdb->get_results( $sql, ARRAY_A ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- SQL is built with prepare() above.
866 $formatted_results = $this->wcpos_format_all_posts_response( $results );
867
868 // Get the total number of orders for the given criteria.
869 $total = \count( $formatted_results );
870
871 // Collect execution time and server load.
872 $execution_time = microtime( true ) - $start_time;
873 $execution_time_ms = number_format( $execution_time * 1000, 2 );
874 $server_load = $this->get_server_load();
875
876 $response = rest_ensure_response( $formatted_results );
877 $response->header( 'X-WP-Total', (string) $total );
878 $response->header( 'X-Execution-Time', $execution_time_ms . ' ms' );
879 $response->header( 'X-Server-Load', json_encode( $server_load ) );
880
881 return $response;
882 } catch ( Exception $e ) {
883 Logger::log( 'Error fetching product data: ' . $e->getMessage() );
884
885 return new WP_Error(
886 'woocommerce_pos_rest_cannot_fetch',
887 'Error fetching product data.',
888 array( 'status' => 500 )
889 );
890 }
891 }
892
893 /**
894 * Prepare objects query.
895 *
896 * @param WP_REST_Request $request Full details about the request.
897 *
898 * @return array|WP_Error
899 */
900 protected function prepare_objects_query( $request ) {
901 $args = parent::prepare_objects_query( $request );
902 $args = $this->wcpos_apply_store_api_tax_operator_fallbacks( $args, $request );
903 $barcode_field = $this->wcpos_get_barcode_field();
904
905 // Add custom 'orderby' options.
906 if ( isset( $request['orderby'] ) ) {
907 switch ( $request['orderby'] ) {
908 case 'sku':
909 $args['meta_key'] = '_sku';
910 $args['orderby'] = 'meta_value';
911
912 break;
913 case 'barcode':
914 $args['meta_key'] = '_sku' !== $barcode_field ? $barcode_field : '_sku';
915 $args['orderby'] = 'meta_value';
916
917 break;
918 case 'stock_quantity':
919 $args['meta_key'] = '_stock';
920 $args['orderby'] = 'meta_value_num';
921
922 break;
923 case 'stock_status':
924 $args['meta_key'] = '_stock_status';
925 $args['orderby'] = 'meta_value';
926
927 break;
928 }
929 }
930
931 return $args;
932 }
933 }
934