PluginProbe
WCPOS – Point of Sale (POS) plugin for WooCommerce / 1.10.17
WCPOS – Point of Sale (POS) plugin for WooCommerce v1.10.17
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.17, at includes/API/V1/Product_Variations_Controller.php

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