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 / Product_Variations_Controller.php

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

502 lines 15.6 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Product_Variations_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_Product_Variations_Controller' ) ) {
13 return;
14 }
15
16 use Exception;
17 use WC_Data;
18 use WC_REST_Product_Variations_Controller;
19 use WCPOS\WooCommercePOS\Logger;
20 use WCPOS\WooCommercePOS\Services\Barcode_Field;
21 use WCPOS\WooCommercePOS\Sync\Pos_Visibility;
22 use WP_Error;
23 use WP_Query;
24 use WP_REST_Request;
25 use WP_REST_Response;
26 use WP_REST_Server;
27
28 /**
29 * Product Tgas controller class.
30 *
31 * @NOTE: methods not prefixed with wcpos_ will override WC_REST_Product_Variations_Controller methods
32 */
33 class Product_Variations_Controller extends WC_REST_Product_Variations_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 * Store the request object for use in lifecycle methods.
48 *
49 * @var WP_REST_Request
50 */
51 protected $wcpos_request;
52
53 /**
54 * Dispatch request to parent controller, or override if needed.
55 *
56 * @param mixed $dispatch_result Dispatch result, will be used if not empty.
57 * @param WP_REST_Request $request Request used to generate the response.
58 * @param string $route Route matched for the request.
59 * @param array $handler Route handler used for the request.
60 */
61 public function wcpos_dispatch_request( $dispatch_result, WP_REST_Request $request, $route, $handler ) {
62 $this->wcpos_request = $request;
63
64 add_filter( 'woocommerce_rest_prepare_product_variation_object', array( $this, 'wcpos_variation_response' ), 10, 3 );
65 add_action( 'woocommerce_rest_insert_product_variation_object', array( $this, 'wcpos_insert_product_variation_object' ), 10, 3 );
66 add_filter( 'woocommerce_rest_product_variation_object_query', array( $this, 'wcpos_product_variation_query' ), 10, 2 );
67 add_filter( 'posts_search', array( $this, 'wcpos_posts_search' ), 10, 2 );
68
69 /*
70 * Check if the request is for all products and if the 'posts_per_page' is set to -1.
71 * Optimised query for getting all product IDs.
72 */
73 if ( Bulk_ID_Fast_Path::supports_request( $request ) ) {
74 return $this->wcpos_get_all_posts( $request );
75 }
76
77 return $dispatch_result;
78 }
79
80 /**
81 * Register routes.
82 */
83 public function register_routes(): void {
84 parent::register_routes();
85
86 register_rest_route(
87 $this->namespace,
88 '/products/variations',
89 array(
90 array(
91 'methods' => WP_REST_Server::READABLE,
92 'callback' => array( $this, 'wcpos_get_all_items' ),
93 'permission_callback' => array( $this, 'get_items_permissions_check' ),
94 'args' => $this->get_collection_params(),
95 ),
96 'schema' => array( $this, 'get_public_item_schema' ),
97 )
98 );
99 }
100
101 /**
102 * Create a single variation.
103 *
104 * @param WP_REST_Request $request Full details about the request.
105 *
106 * @return WP_Error|WP_REST_Response
107 */
108 public function create_item( $request ) {
109 $invalid_meta = $this->wcpos_sanitize_meta_data_param( $request );
110 if ( is_wp_error( $invalid_meta ) ) {
111 return $invalid_meta;
112 }
113
114 return parent::create_item( $request );
115 }
116
117 /**
118 * Update a single variation.
119 *
120 * @param WP_REST_Request $request Full details about the request.
121 *
122 * @return WP_Error|WP_REST_Response
123 */
124 public function update_item( $request ) {
125 $invalid_meta = $this->wcpos_sanitize_meta_data_param( $request );
126 if ( is_wp_error( $invalid_meta ) ) {
127 return $invalid_meta;
128 }
129
130 return parent::update_item( $request );
131 }
132
133 /**
134 * Add custom fields to the product schema.
135 */
136 public function get_item_schema() {
137 $schema = parent::get_item_schema();
138
139 // Add the 'barcode' property if 'properties' exists and is an array.
140 if ( isset( $schema['properties'] ) && \is_array( $schema['properties'] ) ) {
141 $schema['properties']['barcode'] = array(
142 'description' => /* translators: REST API schema field label or error message. */ __( 'Barcode', 'woocommerce-pos' ),
143 'type' => 'string',
144 'context' => array( 'view', 'edit' ),
145 'readonly' => false,
146 );
147 }
148
149 // Check for 'stock_quantity' and allow decimal
150 // Note: 'number' is the valid JSON schema type for decimals (not 'float').
151 if ( $this->wcpos_allow_decimal_quantities() &&
152 isset( $schema['properties']['stock_quantity'] ) &&
153 \is_array( $schema['properties']['stock_quantity'] ) ) {
154 $schema['properties']['stock_quantity']['type'] = 'number';
155 }
156
157 return $schema;
158 }
159
160
161 /**
162 * Modify the collection params.
163 */
164 public function get_collection_params() {
165 $params = parent::get_collection_params();
166
167 // Check if 'per_page' parameter exists and has a 'minimum' key before modifying.
168 if ( isset( $params['per_page'] ) && \is_array( $params['per_page'] ) ) {
169 $params['per_page']['minimum'] = -1;
170 }
171
172 // Ensure 'orderby' is set and is an array before attempting to modify it.
173 if ( isset( $params['orderby']['enum'] ) && \is_array( $params['orderby']['enum'] ) ) {
174 // Define new sorting options.
175 $new_sort_options = array(
176 'sku',
177 'barcode',
178 'stock_quantity',
179 'stock_status',
180 );
181 // Merge new options, avoiding duplicates.
182 $params['orderby']['enum'] = array_unique( array_merge( $params['orderby']['enum'], $new_sort_options ) );
183 }
184
185 return $params;
186 }
187
188 /**
189 * Filter the variation response.
190 *
191 * @param WP_REST_Response $response The response object.
192 * @param WC_Data $variation Product data.
193 * @param WP_REST_Request $request Request object.
194 *
195 * @return WP_REST_Response $response The response object.
196 */
197 public function wcpos_variation_response( WP_REST_Response $response, WC_Data $variation, WP_REST_Request $request ): WP_REST_Response {
198 $data = $response->get_data();
199
200 // Add the UUID to the product response.
201 $this->maybe_add_post_uuid( $variation );
202
203 // Add the barcode to the product response.
204 $data['barcode'] = $this->wcpos_get_barcode( $variation ); // @phpstan-ignore-line
205
206 // Check if the response has an image.
207 if ( isset( $data['image'] ) && ! empty( $data['image'] ) && isset( $data['image']['id'] ) ) {
208 // Replace the full size 'src' with the URL of the medium size image.
209 $medium_image_data = image_downsize( $data['image']['id'], 'medium' );
210
211 if ( $medium_image_data ) {
212 $data['image']['src'] = $medium_image_data[0];
213 }
214 }
215
216 /*
217 * Backwards compatibility for WooCommerce < 8.3
218 *
219 * WooCommerce added 'parent_id' and 'name' to the variation response in 8.3
220 */
221 if ( ! isset( $data['parent_id'] ) ) {
222 $data['parent_id'] = $variation->get_parent_id();
223 }
224 if ( ! isset( $data['name'] ) ) {
225 $data['name'] = \function_exists( 'wc_get_formatted_variation' ) ? wc_get_formatted_variation( $variation, true, false, false ) : ''; // @phpstan-ignore-line
226 }
227
228 // Parse the meta data before returning the response.
229 $data['meta_data'] = $this->wcpos_parse_meta_data( $variation );
230
231 // Estimate response size and log if excessive.
232 $this->wcpos_estimate_response_size( $data, $variation->get_id(), 'Variation' );
233
234 $response->set_data( $data );
235
236 return $response;
237 }
238
239 /**
240 * Fires after a single object is created or updated via the REST API.
241 *
242 * @param WC_Data $object Inserted object.
243 * @param WP_REST_Request $request Request object.
244 * @param bool $creating True when creating object, false when updating.
245 */
246 public function wcpos_insert_product_variation_object( WC_Data $object, WP_REST_Request $request, $creating ): void {
247 // Update the barcode if it is set in the request.
248 if ( $request->has_param( 'barcode' ) ) {
249 Barcode_Field::write( $object, $request->get_param( 'barcode' ) );
250 }
251 }
252
253 /**
254 * Filter to adjust the WordPress search SQL query
255 * - Search for the variation SKU and barcode
256 * - Do not search variation description.
257 *
258 * @param string $search Search string.
259 * @param WP_Query $wp_query WP_Query object.
260 *
261 * @return string
262 */
263 public function wcpos_posts_search( string $search, WP_Query $wp_query ) {
264 global $wpdb;
265
266 if ( empty( $search ) ) {
267 return $search; // skip processing - no search term in query.
268 }
269
270 $q = $wp_query->query_vars;
271 $n = ! empty( $q['exact'] ) ? '' : '%';
272 $search_terms = (array) $q['search_terms'];
273
274 // Fields in the main 'posts' table.
275 $post_fields = array(); // nothing at the moment for variations.
276
277 // Meta fields to search.
278 $meta_fields = Barcode_Field::search_keys();
279
280 $search_conditions = array();
281
282 foreach ( $search_terms as $term ) {
283 $term = $n . $wpdb->esc_like( $term ) . $n;
284
285 // Search in meta fields.
286 foreach ( $meta_fields as $field ) {
287 $search_conditions[] = $wpdb->prepare( '(pm1.meta_value LIKE %s AND pm1.meta_key = %s)', $term, $field );
288 }
289 }
290
291 if ( ! empty( $search_conditions ) ) {
292 $search = ' AND (' . implode( ' OR ', $search_conditions ) . ') ';
293 if ( ! is_user_logged_in() ) {
294 $search .= " AND ($wpdb->posts.post_password = '') ";
295 }
296 }
297
298 return $search;
299 }
300
301 /**
302 * Filters the JOIN clause of the query.
303 *
304 * @param string $join The JOIN clause of the query.
305 * @param WP_Query $query The WP_Query instance (passed by reference).
306 *
307 * @return string
308 */
309 public function wcpos_posts_join_to_posts_search( string $join, WP_Query $query ) {
310 global $wpdb;
311
312 if ( ! empty( $query->query_vars['s'] ) && false === strpos( $join, 'pm1' ) ) {
313 $join .= " LEFT JOIN {$wpdb->postmeta} pm1 ON {$wpdb->posts}.ID = pm1.post_id ";
314 }
315
316 return $join;
317 }
318
319 /**
320 * Filters the GROUP BY clause of the query.
321 *
322 * @param string $groupby The GROUP BY clause of the query.
323 * @param WP_Query $query The WP_Query instance (passed by reference).
324 *
325 * @return string
326 */
327 public function wcpos_posts_groupby_posts_search( string $groupby, WP_Query $query ) {
328 global $wpdb;
329
330 if ( ! empty( $query->query_vars['s'] ) ) {
331 $groupby = "{$wpdb->posts}.ID";
332 }
333
334 return $groupby;
335 }
336
337 /**
338 * Filter the query arguments for a request.
339 *
340 * @param array $args Key value array of query var to query value.
341 * @param WP_REST_Request $request The request used.
342 *
343 * @return array $args Key value array of query var to query value.
344 */
345 public function wcpos_product_variation_query( array $args, WP_REST_Request $request ) {
346 if ( ! empty( $request['search'] ) ) {
347 // We need to set the query up for a postmeta join.
348 add_filter( 'posts_join', array( $this, 'wcpos_posts_join_to_posts_search' ), 10, 2 );
349 add_filter( 'posts_groupby', array( $this, 'wcpos_posts_groupby_posts_search' ), 10, 2 );
350 }
351
352 // if POS only products are enabled, exclude online-only products.
353 if ( $this->wcpos_pos_only_products_enabled() ) {
354 add_filter( 'posts_where', array( $this, 'wcpos_posts_where_product_variation_exclude_online_only' ), 10, 2 );
355 }
356
357 // Check for wcpos_include/wcpos_exclude parameter.
358 // NOTE: do this after POS visibility filter so that takes precedence.
359 if ( isset( $request['wcpos_include'] ) || isset( $request['wcpos_exclude'] ) ) {
360 add_filter( 'posts_where', array( $this, 'wcpos_posts_where_product_variation_include_exclude' ), 20, 2 );
361 }
362
363 return $args;
364 }
365
366 /**
367 * Filters the WHERE clause of the query.
368 *
369 * Exclusion set and feature gate both come from Sync\Pos_Visibility, the single POS visibility
370 * authority.
371 *
372 * @param string $where The WHERE clause of the query.
373 * @param WP_Query $query The WP_Query instance (passed by reference).
374 *
375 * @return string
376 */
377 public function wcpos_posts_where_product_variation_exclude_online_only( string $where, WP_Query $query ) {
378 global $wpdb;
379
380 return ( new Pos_Visibility() )->apply_to_sql_where( $where, "{$wpdb->posts}.ID", Pos_Visibility::VARIATIONS );
381 }
382
383 /**
384 * Filters the WHERE clause of the query.
385 *
386 * @param string $where The WHERE clause of the query.
387 * @param WP_Query $query The WP_Query instance (passed by reference).
388 *
389 * @return string
390 */
391 public function wcpos_posts_where_product_variation_include_exclude( string $where, WP_Query $query ) {
392 global $wpdb;
393
394 // Handle 'wcpos_include'.
395 if ( ! empty( $this->wcpos_request['wcpos_include'] ) ) {
396 $include_ids = array_map( 'intval', (array) $this->wcpos_request['wcpos_include'] );
397 $ids_format = implode( ',', array_fill( 0, \count( $include_ids ), '%d' ) );
398 $where .= $wpdb->prepare( " AND {$wpdb->posts}.ID IN ($ids_format) ", $include_ids ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- table name and format are safe.
399 }
400
401 // Handle 'wcpos_exclude'.
402 if ( ! empty( $this->wcpos_request['wcpos_exclude'] ) ) {
403 $exclude_ids = array_map( 'intval', (array) $this->wcpos_request['wcpos_exclude'] );
404 $ids_format = implode( ',', array_fill( 0, \count( $exclude_ids ), '%d' ) );
405 $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.
406 }
407
408 return $where;
409 }
410
411 /**
412 * Returns array of all product ids, name.
413 *
414 * @param WP_REST_Request $request Full details about the request.
415 *
416 * @return WP_Error|WP_REST_Response
417 */
418 public function wcpos_get_all_posts( $request ) {
419 global $wpdb;
420
421 $start_time = microtime( true );
422 $parent_id = (int) $this->wcpos_request->get_param( 'product_id' );
423 $select_fields = Bulk_ID_Fast_Path::select_fields( $request, 'ID', 'post_modified_gmt' );
424
425 // Initialize the SQL query.
426 $sql = "SELECT DISTINCT {$select_fields} FROM {$wpdb->posts}";
427 $sql .= " WHERE {$wpdb->posts}.post_type = 'product_variation' AND {$wpdb->posts}.post_status = 'publish'";
428
429 // Drop the POS-hidden ids — Sync\Pos_Visibility owns both the exclusion set and the feature gate.
430 $sql = ( new Pos_Visibility() )->apply_to_sql_where( $sql, 'ID', Pos_Visibility::VARIATIONS );
431
432 $modified_after_date = Bulk_ID_Fast_Path::modified_after_gmt( $request );
433 if ( $modified_after_date ) {
434 $sql .= $wpdb->prepare( ' AND post_modified_gmt > %s', $modified_after_date );
435 }
436
437 $sql = Bulk_ID_Fast_Path::append_id_filters_sql( $sql, $request, "{$wpdb->posts}.ID" );
438
439 // Dynamically add the post_parent clause if a parent ID is provided.
440 if ( $parent_id ) {
441 $sql .= $wpdb->prepare( " AND {$wpdb->posts}.post_parent = %d", $parent_id );
442 }
443
444 try {
445 $results = $wpdb->get_results( $sql, ARRAY_A ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- SQL is built with prepare() above.
446
447 return Bulk_ID_Fast_Path::response( $this, $results, $start_time );
448 } catch ( Exception $e ) {
449 return Bulk_ID_Fast_Path::fetch_error( 'Error fetching product variation IDs: ' . $e->getMessage(), 'Error fetching product variation IDs.' );
450 }
451 }
452
453 /**
454 * Endpoint for getting all product variations, eg: search for sku or barcode.
455 *
456 * @param WP_REST_Request $request Full details about the request.
457 */
458 public function wcpos_get_all_items( $request ) {
459 return parent::get_items( $request );
460 }
461
462
463 /**
464 * Prepare objects query.
465 *
466 * @param WP_REST_Request $request Full details about the request.
467 *
468 * @return array|WP_Error
469 */
470 protected function prepare_objects_query( $request ) {
471 $args = parent::prepare_objects_query( $request );
472
473 // Add custom 'orderby' options.
474 if ( isset( $request['orderby'] ) ) {
475 switch ( $request['orderby'] ) {
476 case 'sku':
477 $args['meta_key'] = '_sku';
478 $args['orderby'] = 'meta_value';
479
480 break;
481 case 'barcode':
482 $args['meta_key'] = Barcode_Field::orderby_key();
483 $args['orderby'] = 'meta_value';
484
485 break;
486 case 'stock_quantity':
487 $args['meta_key'] = '_stock';
488 $args['orderby'] = 'meta_value_num';
489
490 break;
491 case 'stock_status':
492 $args['meta_key'] = '_stock_status';
493 $args['orderby'] = 'meta_value';
494
495 break;
496 }
497 }
498
499 return $args;
500 }
501 }
502