PluginProbe
WCPOS – Point of Sale (POS) plugin for WooCommerce / 1.10.1
WCPOS – Point of Sale (POS) plugin for WooCommerce v1.10.1
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 / V1 / Products_Controller.php

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

772 lines 25.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\V1;
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\Barcode_Field;
23 use WCPOS\WooCommercePOS\Services\Variable_Price_Range;
24 use WCPOS\WooCommercePOS\Sync\Pos_Visibility;
25 use WP_Error;
26 use WP_Query;
27 use WP_REST_Request;
28 use WP_REST_Response;
29
30 /**
31 * Products controller class.
32 *
33 * @NOTE: methods not prefixed with wcpos_ will override WC_REST_Products_Controller methods
34 */
35 class Products_Controller extends WC_REST_Products_Controller {
36 use Traits\Product_Helpers;
37 use Traits\Query_Helpers;
38 use Traits\Uuid_Handler;
39 use Traits\WCPOS_REST_API;
40
41 /**
42 * Endpoint namespace.
43 *
44 * @var string
45 */
46 protected $namespace = 'wcpos/v1';
47
48 /**
49 * Allow decimal quantities.
50 *
51 * @var bool
52 */
53 protected $allow_decimal_quantities = false;
54
55 /**
56 * Store the current request object.
57 *
58 * @var WP_REST_Request|null
59 */
60 protected $wcpos_request;
61
62 /**
63 * Memoized parent collection params.
64 *
65 * @var array|null
66 */
67 protected $wcpos_parent_collection_params = null;
68
69 /**
70 * Dispatch request to parent controller, or override if needed.
71 *
72 * @param mixed $dispatch_result Dispatch result, will be used if not empty.
73 * @param WP_REST_Request $request Request used to generate the response.
74 * @param string $route Route matched for the request.
75 * @param array $handler Route handler used for the request.
76 *
77 * @return mixed $dispatch_result Dispatch result, will be used if not empty.
78 */
79 public function wcpos_dispatch_request( $dispatch_result, WP_REST_Request $request, $route, $handler ) {
80 $this->wcpos_request = $request;
81
82 add_filter( 'woocommerce_rest_prepare_product_object', array( $this, 'wcpos_product_response' ), 10, 3 );
83 add_action( 'woocommerce_rest_insert_product_object', array( $this, 'wcpos_insert_product_object' ), 10, 3 );
84 add_filter( 'woocommerce_rest_product_object_query', array( $this, 'wcpos_product_query' ), 10, 2 );
85 add_filter( 'posts_search', array( $this, 'wcpos_posts_search' ), 10, 2 );
86 add_filter( 'posts_clauses', array( $this, 'wcpos_posts_clauses' ), 10, 2 );
87
88 /*
89 * Check if the request is for all products and if the 'posts_per_page' is set to -1.
90 * Optimised query for getting all product IDs.
91 */
92 if ( Bulk_ID_Fast_Path::supports_request( $request ) ) {
93 return $this->wcpos_get_all_posts( $request );
94 }
95
96 return $dispatch_result;
97 }
98
99 /**
100 * Create a single product.
101 *
102 * @param WP_REST_Request $request Full details about the request.
103 *
104 * @return WP_Error|WP_REST_Response
105 */
106 public function create_item( $request ) {
107 $invalid_meta = $this->wcpos_sanitize_meta_data_param( $request );
108 if ( is_wp_error( $invalid_meta ) ) {
109 return $invalid_meta;
110 }
111
112 return parent::create_item( $request );
113 }
114
115 /**
116 * Update a single product.
117 *
118 * @param WP_REST_Request $request Full details about the request.
119 *
120 * @return WP_Error|WP_REST_Response
121 */
122 public function update_item( $request ) {
123 $invalid_meta = $this->wcpos_sanitize_meta_data_param( $request );
124 if ( is_wp_error( $invalid_meta ) ) {
125 return $invalid_meta;
126 }
127
128 return parent::update_item( $request );
129 }
130
131 /**
132 * Add custom fields to the product schema.
133 * - Add 'barcode' property to the product schema.
134 * - Allow decimal quantities if enabled.
135 *
136 * Overrides the parent method.
137 *
138 * @return array $schema The product schema.
139 */
140 public function get_item_schema() {
141 $schema = parent::get_item_schema();
142
143 // Add the 'barcode' property if 'properties' exists and is an array.
144 if ( isset( $schema['properties'] ) && \is_array( $schema['properties'] ) ) {
145 $schema['properties']['barcode'] = array(
146 'description' => /* translators: REST API schema field label or error message. */ __( 'Barcode', 'woocommerce-pos' ),
147 'type' => 'string',
148 'context' => array( 'view', 'edit' ),
149 'readonly' => false,
150 );
151 }
152
153 // Check for 'stock_quantity' and allow decimal.
154 // Note: 'number' is the valid JSON schema type for decimals (not 'float').
155 if ( $this->wcpos_allow_decimal_quantities() &&
156 isset( $schema['properties']['stock_quantity'] ) &&
157 \is_array( $schema['properties']['stock_quantity'] ) ) {
158 $schema['properties']['stock_quantity']['type'] = 'number';
159 }
160
161 return $schema;
162 }
163
164
165 /**
166 * Modify the collection params.
167 * - Allow 'per_page' to be set to -1.
168 * - Add custom sorting options.
169 *
170 * Overrides the parent method.
171 *
172 * @return array $params The collection parameters.
173 */
174 public function get_collection_params() {
175 $params = $this->wcpos_get_parent_collection_params();
176
177 // Check if 'per_page' parameter exists and has a 'minimum' key before modifying.
178 if ( isset( $params['per_page'] ) && \is_array( $params['per_page'] ) ) {
179 $params['per_page']['minimum'] = -1;
180 }
181
182 if ( ! $this->wcpos_parent_collection_supports_param( 'brand' ) ) {
183 $params['brand'] = array(
184 'description' => /* translators: REST API collection parameter description. */ __( 'Limit result set to products assigned to brand IDs or slugs, separated by commas.', 'woocommerce-pos' ),
185 'type' => 'string',
186 'validate_callback' => 'rest_validate_request_arg',
187 );
188 }
189
190 if ( ! $this->wcpos_parent_collection_supports_param( 'brand_operator' ) ) {
191 $params['brand_operator'] = array(
192 'description' => /* translators: REST API collection parameter description. */ __( 'Operator to compare product brand terms.', 'woocommerce-pos' ),
193 'type' => 'string',
194 'enum' => array( 'in', 'not_in', 'and' ),
195 'default' => 'in',
196 'validate_callback' => 'rest_validate_request_arg',
197 );
198 }
199
200 if ( ! $this->wcpos_parent_collection_supports_param( 'category_operator' ) ) {
201 $params['category_operator'] = array(
202 'description' => /* translators: REST API collection parameter description. */ __( 'Operator to compare product category terms.', 'woocommerce-pos' ),
203 'type' => 'string',
204 'enum' => array( 'in', 'not_in', 'and' ),
205 'default' => 'in',
206 'validate_callback' => 'rest_validate_request_arg',
207 );
208 }
209
210 if ( ! $this->wcpos_parent_collection_supports_param( 'tag_operator' ) ) {
211 $params['tag_operator'] = array(
212 'description' => /* translators: REST API collection parameter description. */ __( 'Operator to compare product tag terms.', 'woocommerce-pos' ),
213 'type' => 'string',
214 'enum' => array( 'in', 'not_in', 'and' ),
215 'default' => 'in',
216 'validate_callback' => 'rest_validate_request_arg',
217 );
218 }
219
220 // Ensure 'orderby' is set and is an array before attempting to modify it.
221 if ( isset( $params['orderby']['enum'] ) && \is_array( $params['orderby']['enum'] ) ) {
222 // Define new sorting options.
223 $new_sort_options = array(
224 'sku',
225 'barcode',
226 'stock_quantity',
227 'stock_status',
228 );
229 // Merge new options, avoiding duplicates.
230 $params['orderby']['enum'] = array_unique( array_merge( $params['orderby']['enum'], $new_sort_options ) );
231 }
232
233 return $params;
234 }
235
236 /**
237 * Filter the product response.
238 *
239 * @param WP_REST_Response $response The response object.
240 * @param WC_Product $product Product data.
241 * @param WP_REST_Request $request Request object.
242 *
243 * @return WP_REST_Response $response The response object.
244 */
245 public function wcpos_product_response( WP_REST_Response $response, WC_Product $product, WP_REST_Request $request ): WP_REST_Response {
246 $data = $response->get_data();
247
248 // Add the UUID to the product response.
249 $this->maybe_add_post_uuid( $product );
250
251 // Add the barcode to the product response.
252 $data['barcode'] = $this->wcpos_get_barcode( $product );
253
254 // Check if the response has an image.
255 if ( isset( $data['images'] ) && ! empty( $data['images'] ) ) {
256 foreach ( $data['images'] as $key => $image ) {
257 // Replace the full size 'src' with the URL of the medium size image.
258 $image_id = $image['id'];
259 $medium_image_data = image_downsize( $image_id, 'medium' );
260
261 if ( $medium_image_data ) {
262 $data['images'][ $key ]['src'] = $medium_image_data[0];
263 } else {
264 $data['images'][ $key ]['src'] = $image['src'];
265 }
266 }
267 }
268
269 /*
270 * If product is variable, add the max and min prices and add them to the meta data
271 * @TODO - only need to update if there is a change
272 */
273 if ( $product->is_type( 'variable' ) && $product instanceof WC_Product_Variable ) {
274 $minimum_price = '';
275 $price_array = $this->wcpos_get_variable_product_price_ranges( $product, $minimum_price );
276
277 // A simple-to-variable conversion can leave old simple price fields on the
278 // parent. Serve the current minimum, but do not pair independent regular and
279 // sale minima from different variations into a false parent-level sale.
280 if ( array_key_exists( 'price', $data ) ) {
281 $decimals = null !== $request->get_param( 'dp' ) ? absint( $request->get_param( 'dp' ) ) : wc_get_price_decimals();
282 $data['price'] = '' === $minimum_price ? '' : wc_format_decimal( $minimum_price, $decimals );
283 }
284 foreach ( array( 'regular_price', 'sale_price' ) as $price_key ) {
285 if ( array_key_exists( $price_key, $data ) ) {
286 $data[ $price_key ] = '';
287 }
288 }
289
290 // Try encoding the array into JSON.
291 $encoded_price = wp_json_encode( $price_array );
292
293 // Check if the encoding was successful.
294 if ( false === $encoded_price ) {
295 // JSON encode failed, log the original array for debugging.
296 Logger::log( 'JSON encoding of price array failed: ' . json_last_error_msg(), $price_array );
297 } else {
298 // Update the meta data with the successfully encoded price data.
299 $product->update_meta_data( '_woocommerce_pos_variable_prices', $encoded_price );
300 }
301 }
302
303 // Parse the meta data before returning the response.
304 $data['meta_data'] = $this->wcpos_parse_meta_data( $product );
305
306 // Estimate response size and log if excessive.
307 $this->wcpos_estimate_response_size( $data, $product->get_id(), 'Product' );
308
309 // Set any changes to the response data.
310 $response->set_data( $data );
311
312 return $response;
313 }
314
315 /**
316 * Build variable product price ranges from current variation data.
317 *
318 * Thin adapter over {@see Variable_Price_Range}, THE canonical computation
319 * shared with the V2 sync read lane. This lane persists the DECIMAL rendering
320 * to `_woocommerce_pos_variable_prices` postmeta: every value formatted at the
321 * store's price precision, all three sub-ranges always present.
322 *
323 * @param WC_Product_Variable $product Variable product.
324 * @param string|null $minimum_price Unrounded filtered minimum price, passed by reference.
325 *
326 * @phpstan-param-out string $minimum_price
327 *
328 * @return array{price: array{min: string, max: string}, regular_price: array{min: string, max: string},
329 * sale_price: array{min: string, max: string}}
330 */
331 private function wcpos_get_variable_product_price_ranges( WC_Product_Variable $product, ?string &$minimum_price = null ): array {
332 $computed = Variable_Price_Range::for( $product, Variable_Price_Range::FORMAT_DECIMAL );
333 $minimum_price = $computed['minimum_price'];
334
335 return $computed['ranges'];
336 }
337
338 /**
339 * Fires after a single object is created or updated via the REST API.
340 *
341 * @param WC_Data $object Inserted object.
342 * @param WP_REST_Request $request Request object.
343 * @param bool $creating True when creating object, false when updating.
344 */
345 public function wcpos_insert_product_object( WC_Data $object, WP_REST_Request $request, $creating ): void {
346 // Update the barcode if it is set in the request.
347 if ( $request->has_param( 'barcode' ) ) {
348 Barcode_Field::write( $object, $request->get_param( 'barcode' ) );
349 }
350 }
351
352 /**
353 * Filter to adjust the WordPress search SQL query
354 * - Search for the product title and SKU and barcode
355 * - Do not search product description.
356 *
357 * @param string $search The search SQL query.
358 * @param WP_Query $wp_query The WP_Query instance (passed by reference).
359 *
360 * @return string
361 */
362 public function wcpos_posts_search( string $search, WP_Query $wp_query ) {
363 global $wpdb;
364
365 if ( empty( $search ) ) {
366 return $search; // skip processing - no search term in query.
367 }
368
369 $q = $wp_query->query_vars;
370 $n = ! empty( $q['exact'] ) ? '' : '%';
371 $search_terms = (array) $q['search_terms'];
372
373 // Fields in the main 'posts' table.
374 $post_fields = array( 'post_title' );
375
376 // Meta fields to search.
377 $meta_fields = Barcode_Field::search_keys();
378
379 $search_conditions = array();
380
381 foreach ( $search_terms as $term ) {
382 $term = $n . $wpdb->esc_like( $term ) . $n;
383
384 // Search in post fields.
385 foreach ( $post_fields as $field ) {
386 $search_conditions[] = $wpdb->prepare( "({$wpdb->posts}.$field LIKE %s)", $term ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- table name is safe.
387 }
388
389 // Search in meta fields.
390 foreach ( $meta_fields as $field ) {
391 $search_conditions[] = $wpdb->prepare( '(pm1.meta_value LIKE %s AND pm1.meta_key = %s)', $term, $field );
392 }
393 }
394
395 if ( ! empty( $search_conditions ) ) {
396 $search = ' AND (' . implode( ' OR ', $search_conditions ) . ') ';
397 if ( ! is_user_logged_in() ) {
398 $search .= " AND ($wpdb->posts.post_password = '') ";
399 }
400 }
401
402 return $search;
403 }
404
405 /**
406 * Filters all query clauses at once, for convenience.
407 *
408 * Covers the WHERE, GROUP BY, JOIN, ORDER BY, DISTINCT,
409 * fields (SELECT), and LIMIT clauses.
410 *
411 * @param string[] $clauses Associative array of the clauses for the query.
412 * @param WP_Query $wp_query The WP_Query instance (passed by reference).
413 */
414 public function wcpos_posts_clauses( array $clauses, WP_Query $wp_query ): array {
415 global $wpdb;
416
417 // Handle NULL values in stock_quantity sorting
418 // By default, MySQL sorts NULLs first in ASC and last in DESC
419 // We want NULLs to always be last regardless of sort direction.
420 if ( isset( $this->wcpos_request ) ) {
421 $orderby = $this->wcpos_request->get_param( 'orderby' );
422 $order = strtoupper( $this->wcpos_request->get_param( 'order' ) ?? 'ASC' );
423
424 if ( 'stock_quantity' === $orderby ) {
425 // Modify ORDER BY to put NULLs last
426 // Use CASE to assign a sort priority: non-NULL = 0, NULL = 1
427 // Then sort by the actual value.
428 $clauses['orderby'] = "{$wpdb->postmeta}.meta_value IS NULL ASC, {$wpdb->postmeta}.meta_value + 0 {$order}";
429 }
430 }
431
432 return $clauses;
433 }
434
435 /**
436 * Filter the query arguments for a request.
437 *
438 * @param array $args Key value array of query var to query value.
439 * @param WP_REST_Request $request The request used.
440 *
441 * @return array $args Key value array of query var to query value.
442 */
443 public function wcpos_product_query( array $args, WP_REST_Request $request ) {
444 if ( ! empty( $request['search'] ) ) {
445 // We need to set the query up for a postmeta join.
446 add_filter( 'posts_join', array( $this, 'wcpos_posts_join_to_products_search' ), 10, 2 );
447 add_filter( 'posts_groupby', array( $this, 'wcpos_posts_groupby_product_search' ), 10, 2 );
448 }
449
450 // if POS only products are enabled, exclude online-only products.
451 if ( $this->wcpos_pos_only_products_enabled() ) {
452 add_filter( 'posts_where', array( $this, 'wcpos_posts_where_product_exclude_online_only' ), 10, 2 );
453 }
454
455 // Check for wcpos_include/wcpos_exclude parameter.
456 if ( isset( $request['wcpos_include'] ) || isset( $request['wcpos_exclude'] ) ) {
457 add_filter( 'posts_where', array( $this, 'wcpos_posts_where_product_include_exclude' ), 20, 2 );
458 }
459
460 return $args;
461 }
462
463 /**
464 * Check whether the parent WooCommerce REST controller already supports a collection param.
465 *
466 * If WooCommerce adds native REST support for Store API-style product filters, WCPOS
467 * should defer to the parent implementation instead of adding duplicate tax queries.
468 *
469 * @param string $param Collection parameter name.
470 *
471 * @return bool
472 */
473 protected function wcpos_parent_collection_supports_param( string $param ): bool {
474 $params = $this->wcpos_get_parent_collection_params();
475
476 return isset( $params[ $param ] );
477 }
478
479 /**
480 * Get parent collection params once per controller instance.
481 *
482 * @return array
483 */
484 protected function wcpos_get_parent_collection_params(): array {
485 if ( null === $this->wcpos_parent_collection_params ) {
486 $this->wcpos_parent_collection_params = parent::get_collection_params();
487 }
488
489 return $this->wcpos_parent_collection_params;
490 }
491
492 /**
493 * Parse one or more taxonomy terms from a Store API-style request parameter.
494 *
495 * @param WP_REST_Request $request The request used.
496 * @param string $param Request parameter name.
497 *
498 * @return array{field?:string,terms?:array<int,int|string>}
499 */
500 protected function wcpos_get_store_api_tax_terms_from_request( WP_REST_Request $request, string $param ): array {
501 $value = $request->get_param( $param );
502
503 if ( empty( $value ) ) {
504 return array();
505 }
506
507 $terms = array_filter( array_map( 'trim', explode( ',', (string) $value ) ) );
508 if ( empty( $terms ) ) {
509 return array();
510 }
511
512 $ids = wp_parse_id_list( $terms );
513 if ( \count( $ids ) === \count( $terms ) ) {
514 return array(
515 'field' => 'term_id',
516 'terms' => $ids,
517 );
518 }
519
520 return array(
521 'field' => 'slug',
522 'terms' => $terms,
523 );
524 }
525
526 /**
527 * Convert Store API-style taxonomy operators to WP_Query tax query operators.
528 *
529 * @param string|null $operator Store API taxonomy operator.
530 *
531 * @return string
532 */
533 protected function wcpos_get_store_api_tax_operator( ?string $operator ): string {
534 $operators = array(
535 'and' => 'AND',
536 'in' => 'IN',
537 'not_in' => 'NOT IN',
538 );
539
540 return $operators[ $operator ?? 'in' ] ?? 'IN';
541 }
542
543 /**
544 * Apply Store API taxonomy fallback query behavior for params missing in Woo REST.
545 *
546 * @param array $args Prepared query args.
547 * @param WP_REST_Request $request The request used.
548 *
549 * @return array
550 */
551 protected function wcpos_apply_store_api_tax_operator_fallbacks( array $args, WP_REST_Request $request ): array {
552 if ( ! $this->wcpos_parent_collection_supports_param( 'brand' ) ) {
553 $brand_terms = $this->wcpos_get_store_api_tax_terms_from_request( $request, 'brand' );
554 if ( isset( $brand_terms['field'], $brand_terms['terms'] ) && taxonomy_exists( 'product_brand' ) ) {
555 if ( ! isset( $args['tax_query'] ) || ! \is_array( $args['tax_query'] ) ) {
556 $args['tax_query'] = array();
557 }
558
559 $args['tax_query'][] = array(
560 'taxonomy' => 'product_brand',
561 'field' => $brand_terms['field'],
562 'terms' => $brand_terms['terms'],
563 'operator' => $this->wcpos_get_store_api_tax_operator( $request->get_param( 'brand_operator' ) ),
564 );
565 }
566 }
567
568 $operator_fallbacks = array(
569 'category_operator' => 'product_cat',
570 'tag_operator' => 'product_tag',
571 );
572 $query_params = $request->get_query_params();
573
574 foreach ( $operator_fallbacks as $param => $taxonomy ) {
575 if ( $this->wcpos_parent_collection_supports_param( $param ) || ! array_key_exists( $param, $query_params ) ) {
576 continue;
577 }
578
579 if ( ! isset( $args['tax_query'] ) || ! \is_array( $args['tax_query'] ) ) {
580 continue;
581 }
582
583 $args['tax_query'] = $this->wcpos_replace_tax_query_operator_for_taxonomy(
584 $args['tax_query'],
585 $taxonomy,
586 $this->wcpos_get_store_api_tax_operator( $request->get_param( $param ) )
587 );
588 }
589
590 return $args;
591 }
592
593 /**
594 * Replace a tax query clause operator for one taxonomy.
595 *
596 * @param array $tax_query Tax query clauses.
597 * @param string $taxonomy Taxonomy to match.
598 * @param string $operator WP_Tax_Query operator.
599 *
600 * @return array
601 */
602 protected function wcpos_replace_tax_query_operator_for_taxonomy( array $tax_query, string $taxonomy, string $operator ): array {
603 foreach ( $tax_query as $key => $clause ) {
604 if ( ! \is_array( $clause ) || ! isset( $clause['taxonomy'] ) || $taxonomy !== $clause['taxonomy'] ) {
605 continue;
606 }
607
608 $tax_query[ $key ]['operator'] = $operator;
609 }
610
611 return $tax_query;
612 }
613
614 /**
615 * Filters the JOIN clause of the query.
616 *
617 * @param string $join The JOIN clause of the query.
618 * @param WP_Query $query The WP_Query instance (passed by reference).
619 *
620 * @return string
621 */
622 public function wcpos_posts_join_to_products_search( string $join, WP_Query $query ) {
623 global $wpdb;
624
625 if ( ! empty( $query->query_vars['s'] ) && false === strpos( $join, 'pm1' ) ) {
626 $join .= " LEFT JOIN {$wpdb->postmeta} pm1 ON {$wpdb->posts}.ID = pm1.post_id ";
627 }
628
629 return $join;
630 }
631
632 /**
633 * Filters the GROUP BY clause of the query.
634 *
635 * @param string $groupby The GROUP BY clause of the query.
636 * @param WP_Query $query The WP_Query instance (passed by reference).
637 *
638 * @return string
639 */
640 public function wcpos_posts_groupby_product_search( string $groupby, WP_Query $query ) {
641 global $wpdb;
642
643 if ( ! empty( $query->query_vars['s'] ) ) {
644 $groupby = "{$wpdb->posts}.ID";
645 }
646
647 return $groupby;
648 }
649
650 /**
651 * Filters the WHERE clause of the query.
652 *
653 * Exclusion set and feature gate both come from Sync\Pos_Visibility, the single POS visibility
654 * authority.
655 *
656 * @param string $where The WHERE clause of the query.
657 * @param WP_Query $query The WP_Query instance (passed by reference).
658 *
659 * @return string
660 */
661 public function wcpos_posts_where_product_exclude_online_only( string $where, WP_Query $query ) {
662 global $wpdb;
663
664 return ( new Pos_Visibility() )->apply_to_sql_where( $where, "{$wpdb->posts}.ID", Pos_Visibility::PRODUCTS );
665 }
666
667 /**
668 * Filters the WHERE clause of the query.
669 *
670 * @param string $where The WHERE clause of the query.
671 * @param WP_Query $query The WP_Query instance (passed by reference).
672 *
673 * @return string
674 */
675 public function wcpos_posts_where_product_include_exclude( string $where, WP_Query $query ) {
676 global $wpdb;
677
678 // Handle 'wcpos_include'.
679 if ( ! empty( $this->wcpos_request['wcpos_include'] ) ) {
680 $include_ids = array_map( 'intval', (array) $this->wcpos_request['wcpos_include'] );
681 $ids_format = implode( ',', array_fill( 0, \count( $include_ids ), '%d' ) );
682 $where .= $wpdb->prepare( " AND {$wpdb->posts}.ID IN ($ids_format) ", $include_ids ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- table name and format are safe.
683 }
684
685 // Handle 'wcpos_exclude'.
686 if ( ! empty( $this->wcpos_request['wcpos_exclude'] ) ) {
687 $exclude_ids = array_map( 'intval', (array) $this->wcpos_request['wcpos_exclude'] );
688 $ids_format = implode( ',', array_fill( 0, \count( $exclude_ids ), '%d' ) );
689 $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.
690 }
691
692 return $where;
693 }
694
695
696 /**
697 * Returns array of all product ids, name.
698 *
699 * @param WP_REST_Request $request Full details about the request.
700 *
701 * @return WP_Error|WP_REST_Response
702 */
703 public function wcpos_get_all_posts( $request ) {
704 global $wpdb;
705
706 $start_time = microtime( true );
707 $select_fields = Bulk_ID_Fast_Path::select_fields( $request, 'ID', 'post_modified_gmt' );
708
709 $sql = "SELECT DISTINCT {$select_fields} FROM {$wpdb->posts}";
710 $sql .= " WHERE post_type = 'product' AND post_status = 'publish'";
711
712 // Drop the POS-hidden ids — Sync\Pos_Visibility owns both the exclusion set and the feature gate.
713 $sql = ( new Pos_Visibility() )->apply_to_sql_where( $sql, 'ID', Pos_Visibility::PRODUCTS );
714
715 $modified_after_date = Bulk_ID_Fast_Path::modified_after_gmt( $request );
716 if ( $modified_after_date ) {
717 $sql .= $wpdb->prepare( ' AND post_modified_gmt > %s', $modified_after_date );
718 }
719
720 $sql = Bulk_ID_Fast_Path::append_id_filters_sql( $sql, $request, "{$wpdb->posts}.ID" );
721 $sql .= " ORDER BY {$wpdb->posts}.post_date DESC";
722
723 try {
724 $results = $wpdb->get_results( $sql, ARRAY_A ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- SQL is built with prepare() above.
725
726 return Bulk_ID_Fast_Path::response( $this, $results, $start_time );
727 } catch ( Exception $e ) {
728 return Bulk_ID_Fast_Path::fetch_error( 'Error fetching product data: ' . $e->getMessage(), 'Error fetching product data.' );
729 }
730 }
731
732 /**
733 * Prepare objects query.
734 *
735 * @param WP_REST_Request $request Full details about the request.
736 *
737 * @return array|WP_Error
738 */
739 protected function prepare_objects_query( $request ) {
740 $args = parent::prepare_objects_query( $request );
741 $args = $this->wcpos_apply_store_api_tax_operator_fallbacks( $args, $request );
742
743 // Add custom 'orderby' options.
744 if ( isset( $request['orderby'] ) ) {
745 switch ( $request['orderby'] ) {
746 case 'sku':
747 $args['meta_key'] = '_sku';
748 $args['orderby'] = 'meta_value';
749
750 break;
751 case 'barcode':
752 $args['meta_key'] = Barcode_Field::orderby_key();
753 $args['orderby'] = 'meta_value';
754
755 break;
756 case 'stock_quantity':
757 $args['meta_key'] = '_stock';
758 $args['orderby'] = 'meta_value_num';
759
760 break;
761 case 'stock_status':
762 $args['meta_key'] = '_stock_status';
763 $args['orderby'] = 'meta_value';
764
765 break;
766 }
767 }
768
769 return $args;
770 }
771 }
772