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.2.0 10.0.1 5.2.0-beta.1 10.0.2 5.2.0-rc.1 10.0.3 5.2.0-rc.2 10.0.4 5.2.1 10.0.5 5.2.2 10.0.6 5.2.3 10.1.0 5.2.4 10.1.0-rc.1 5.2.5 10.1.0-rc.2 5.3.0 10.1.0-rc.3 5.3.0-beta.1 10.1.0-rc.4 5.3.0-rc.1 10.1.1 5.3.0-rc.2 10.1.2 5.3.1 10.1.3 5.3.2 10.1.4 5.3.3 10.2.0 5.4.0 10.2.0-beta.1 5.4.0-beta.1 10.2.0-beta.2 5.4.0-rc.1 10.2.0-rc.1 5.4.1 10.2.1 5.4.2 10.2.2 5.4.3 10.2.3 5.4.4 10.2.4 5.4.5 10.3.0 5.5.0 10.3.0-beta.1 5.5.0-beta.1 10.3.0-beta.2 5.5.0-rc.1 10.3.0-rc.1 5.5.0-rc.2 10.3.0-rc.2 5.5.1 10.3.1 5.5.2 10.3.2 5.5.3 10.3.3 5.5.4 10.3.4 5.5.5 10.3.5 5.6.0 10.3.6 5.6.0-beta.1 10.3.7 5.6.0-rc.1 10.3.8 5.6.0-rc.2 10.4.0 5.6.1 10.4.0-beta.1 5.6.2 10.4.0-beta.2 5.6.3 10.4.0-rc.1 5.7.0 10.4.1 5.7.0-beta.1 10.4.2 5.7.0-rc.1 10.4.3 5.7.1 10.4.4 5.7.2 10.5.0 5.7.3 10.5.0-beta.1 5.8.0 10.5.0-beta.2 5.8.0-beta.1 10.5.0-rc.1 5.8.0-beta.2 10.5.0-rc.2 5.8.0-rc.1 10.5.0-rc.3 5.8.1 10.5.1 5.8.2 10.5.2 5.9.0 10.5.3 5.9.0-beta.1 10.6.0 5.9.0-rc.1 10.6.0-beta.1 5.9.0-rc.2 10.6.0-beta.2 5.9.1 10.6.0-rc.1 5.9.2 10.6.1 6.0.0 10.6.2 6.0.0-beta.1 10.7.0 6.0.0-rc.1 10.7.0-beta.1 6.0.1 10.7.0-beta.2 6.0.2 10.7.0-rc.1 6.1.0 3.0.0 6.1.0-beta.1 3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.7.0-rc.2 7.1.0-rc.1 3.7.1 7.1.0-rc.2 3.7.2 7.1.1
woocommerce / src / Admin / API / Reports / Variations / DataStore.php
woocommerce / src / Admin / API / Reports / Variations Last commit date
Stats 2 months ago Controller.php 5 months ago DataStore.php 1 month ago Query.php 1 year ago
DataStore.php
546 lines
1 <?php
2 /**
3 * API\Reports\Variations\DataStore class file.
4 */
5
6 namespace Automattic\WooCommerce\Admin\API\Reports\Variations;
7
8 defined( 'ABSPATH' ) || exit;
9
10 use Automattic\WooCommerce\Admin\API\Reports\DataStore as ReportsDataStore;
11 use Automattic\WooCommerce\Admin\API\Reports\DataStoreInterface;
12 use Automattic\WooCommerce\Admin\API\Reports\SqlQuery;
13
14 /**
15 * API\Reports\Variations\DataStore.
16 */
17 class DataStore extends ReportsDataStore implements DataStoreInterface {
18
19 /**
20 * Table used to get the data.
21 *
22 * @override ReportsDataStore::$table_name
23 *
24 * @var string
25 */
26 protected static $table_name = 'wc_order_product_lookup';
27
28 /**
29 * Cache identifier.
30 *
31 * @override ReportsDataStore::$cache_key
32 *
33 * @var string
34 */
35 protected $cache_key = 'variations';
36
37 /**
38 * Mapping columns to data type to return correct response types.
39 *
40 * @override ReportsDataStore::$column_types
41 *
42 * @var array
43 */
44 protected $column_types = array(
45 'date_start' => 'strval',
46 'date_end' => 'strval',
47 'product_id' => 'intval',
48 'variation_id' => 'intval',
49 'items_sold' => 'intval',
50 'net_revenue' => 'floatval',
51 'orders_count' => 'intval',
52 'name' => 'strval',
53 'price' => 'floatval',
54 'image' => 'strval',
55 'permalink' => 'strval',
56 'sku' => 'strval',
57 );
58
59 /**
60 * Extended product attributes to include in the data.
61 *
62 * @var array
63 */
64 protected $extended_attributes = array(
65 'name',
66 'price',
67 'image',
68 'permalink',
69 'stock_status',
70 'stock_quantity',
71 'low_stock_amount',
72 'sku',
73 );
74
75 /**
76 * Data store context used to pass to filters.
77 *
78 * @override ReportsDataStore::$context
79 *
80 * @var string
81 */
82 protected $context = 'variations';
83
84 /**
85 * Assign report columns once full table name has been assigned.
86 *
87 * @override ReportsDataStore::assign_report_columns()
88 */
89 protected function assign_report_columns() {
90 $table_name = self::get_db_table_name();
91 $this->report_columns = array(
92 'product_id' => 'product_id',
93 'variation_id' => 'variation_id',
94 'items_sold' => 'SUM(product_qty) as items_sold',
95 'net_revenue' => 'SUM(product_net_revenue) AS net_revenue',
96 'orders_count' => "COUNT(DISTINCT {$table_name}.order_id) as orders_count",
97 );
98 }
99
100 /**
101 * Fills FROM clause of SQL request based on user supplied parameters.
102 *
103 * @param array $query_args Parameters supplied by the user.
104 * @param string $arg_name Target of the JOIN sql param.
105 */
106 protected function add_from_sql_params( $query_args, $arg_name ) {
107 global $wpdb;
108
109 if ( 'sku' !== $query_args['orderby'] ) {
110 return;
111 }
112
113 $table_name = self::get_db_table_name();
114 $join = "LEFT JOIN {$wpdb->postmeta} AS postmeta ON {$table_name}.variation_id = postmeta.post_id AND postmeta.meta_key = '_sku'";
115
116 if ( 'inner' === $arg_name ) {
117 $this->subquery->add_sql_clause( 'join', $join );
118 } else {
119 $this->add_sql_clause( 'join', $join );
120 }
121 }
122
123 /**
124 * Generate a subquery for order_item_id based on the attribute filters.
125 *
126 * @param array $query_args Query arguments supplied by the user.
127 * @return string
128 */
129 protected function get_order_item_by_attribute_subquery( $query_args ) {
130 $order_product_lookup_table = self::get_db_table_name();
131 $attribute_subqueries = $this->get_attribute_subqueries( $query_args );
132
133 if ( $attribute_subqueries['join'] && $attribute_subqueries['where'] ) {
134 // Perform a subquery for DISTINCT order items that match our attribute filters.
135 $attr_subquery = new SqlQuery( $this->context . '_attribute_subquery' );
136 $attr_subquery->add_sql_clause( 'select', "DISTINCT {$order_product_lookup_table}.order_item_id" );
137 $attr_subquery->add_sql_clause( 'from', $order_product_lookup_table );
138
139 if ( $this->should_exclude_simple_products( $query_args ) ) {
140 $attr_subquery->add_sql_clause( 'where', "AND {$order_product_lookup_table}.variation_id != 0" );
141 }
142
143 foreach ( $attribute_subqueries['join'] as $attribute_join ) {
144 $attr_subquery->add_sql_clause( 'join', $attribute_join );
145 }
146
147 $operator = $this->get_match_operator( $query_args );
148 $attr_subquery->add_sql_clause( 'where', 'AND (' . implode( " {$operator} ", $attribute_subqueries['where'] ) . ')' );
149
150 return "AND {$order_product_lookup_table}.order_item_id IN ({$attr_subquery->get_query_statement()})";
151 }
152
153 return false;
154 }
155
156 /**
157 * Updates the database query with parameters used for Products report: categories and order status.
158 *
159 * @param array $query_args Query arguments supplied by the user.
160 */
161 protected function add_sql_query_params( $query_args ) {
162 global $wpdb;
163 $order_product_lookup_table = self::get_db_table_name();
164 $order_stats_lookup_table = $wpdb->prefix . 'wc_order_stats';
165 $order_item_meta_table = $wpdb->prefix . 'woocommerce_order_itemmeta';
166 $where_subquery = array();
167
168 $this->add_time_period_sql_params( $query_args, $order_product_lookup_table );
169 $this->get_limit_sql_params( $query_args );
170 $this->add_order_by_sql_params( $query_args );
171
172 $included_variations = $this->get_included_variations( $query_args );
173 if ( $included_variations > 0 ) {
174 $this->add_from_sql_params( $query_args, 'outer' );
175 } else {
176 $this->add_from_sql_params( $query_args, 'inner' );
177 }
178
179 $included_products = $this->get_included_products( $query_args );
180 if ( $included_products ) {
181 $this->subquery->add_sql_clause( 'where', "AND {$order_product_lookup_table}.product_id IN ({$included_products})" );
182 }
183
184 $excluded_products = $this->get_excluded_products( $query_args );
185 if ( $excluded_products ) {
186 $this->subquery->add_sql_clause( 'where', "AND {$order_product_lookup_table}.product_id NOT IN ({$excluded_products})" );
187 }
188
189 if ( $included_variations ) {
190 $this->subquery->add_sql_clause( 'where', "AND {$order_product_lookup_table}.variation_id IN ({$included_variations})" );
191 } elseif ( $this->should_exclude_simple_products( $query_args ) ) {
192 $this->subquery->add_sql_clause( 'where', "AND {$order_product_lookup_table}.variation_id != 0" );
193 }
194
195 $order_status_filter = $this->get_status_subquery( $query_args );
196 if ( $order_status_filter ) {
197 $this->subquery->add_sql_clause( 'join', "JOIN {$order_stats_lookup_table} ON {$order_product_lookup_table}.order_id = {$order_stats_lookup_table}.order_id" );
198 $this->subquery->add_sql_clause( 'where', "AND ( {$order_status_filter} )" );
199 }
200
201 $attribute_order_items_subquery = $this->get_order_item_by_attribute_subquery( $query_args );
202 if ( $attribute_order_items_subquery ) {
203 // JOIN on product lookup if we haven't already.
204 if ( ! $order_status_filter ) {
205 $this->subquery->add_sql_clause( 'join', "JOIN {$order_product_lookup_table} ON {$order_stats_lookup_table}.order_id = {$order_product_lookup_table}.order_id" );
206 }
207
208 // Add subquery for matching attributes to WHERE.
209 $this->subquery->add_sql_clause( 'where', $attribute_order_items_subquery );
210 }
211
212 if ( 0 < count( $where_subquery ) ) {
213 $operator = $this->get_match_operator( $query_args );
214 $this->subquery->add_sql_clause( 'where', 'AND (' . implode( " {$operator} ", $where_subquery ) . ')' );
215 }
216 }
217
218 /**
219 * Maps ordering specified by the user to columns in the database/fields in the data.
220 *
221 * @override ReportsDataStore::normalize_order_by()
222 *
223 * @param string $order_by Sorting criterion.
224 *
225 * @return string
226 */
227 protected function normalize_order_by( $order_by ) {
228 if ( 'date' === $order_by ) {
229 return self::get_db_table_name() . '.date_created';
230 }
231 if ( 'sku' === $order_by ) {
232 return 'meta_value';
233 }
234
235 return $order_by;
236 }
237
238 /**
239 * Enriches the product data with attributes specified by the extended_attributes.
240 *
241 * @param array $products_data Product data.
242 * @param array $query_args Query parameters.
243 */
244 protected function include_extended_info( &$products_data, $query_args ) {
245 if ( $query_args['extended_info'] ) {
246 self::prime_object_caches(
247 array_merge(
248 array_column( $products_data, 'product_id' ),
249 array_column( $products_data, 'variation_id' )
250 )
251 );
252 }
253
254 foreach ( $products_data as $key => $product_data ) {
255 $extended_info = new \ArrayObject();
256 if ( $query_args['extended_info'] ) {
257 $extended_attributes = apply_filters( 'woocommerce_rest_reports_variations_extended_attributes', $this->extended_attributes, $product_data );
258 $parent_product = wc_get_product( $product_data['product_id'] );
259 $attributes = array();
260
261 // Base extended info off the parent variable product if the variation ID is 0.
262 // This is caused by simple products with prior sales being converted into variable products.
263 // See: https://github.com/woocommerce/woocommerce-admin/issues/2719.
264 $variation_id = (int) $product_data['variation_id'];
265 $variation_product = ( 0 === $variation_id ) ? $parent_product : wc_get_product( $variation_id );
266
267 // Fall back to the parent product if the variation can't be found.
268 $extended_attributes_product = is_a( $variation_product, 'WC_Product' ) ? $variation_product : $parent_product;
269 // If both product and variation is not found, set deleted to true.
270 if ( ! $extended_attributes_product ) {
271 $extended_info['deleted'] = true;
272 }
273 foreach ( $extended_attributes as $extended_attribute ) {
274 $function = 'get_' . $extended_attribute;
275 if ( is_callable( array( $extended_attributes_product, $function ) ) ) {
276 $value = $extended_attributes_product->{$function}();
277 $extended_info[ $extended_attribute ] = $value;
278 }
279 }
280
281 // If this is a variation, add its attributes.
282 // NOTE: We don't fall back to the parent product here because it will include all possible attribute options.
283 if (
284 0 < $variation_id &&
285 is_callable( array( $variation_product, 'get_variation_attributes' ) )
286 ) {
287 $variation_attributes = $variation_product->get_variation_attributes();
288
289 foreach ( $variation_attributes as $attribute_name => $attribute ) {
290 $name = str_replace( 'attribute_', '', $attribute_name );
291 $option_term = get_term_by( 'slug', $attribute, $name );
292 $attributes[] = array(
293 'id' => wc_attribute_taxonomy_id_by_name( $name ),
294 'name' => str_replace( 'pa_', '', $name ),
295 'option' => $option_term && ! is_wp_error( $option_term ) ? $option_term->name : $attribute,
296 );
297 }
298 }
299
300 $extended_info['attributes'] = $attributes;
301
302 // If there is no set low_stock_amount, use the one in user settings.
303 if ( '' === $extended_info['low_stock_amount'] ) {
304 $extended_info['low_stock_amount'] = absint( max( get_option( 'woocommerce_notify_low_stock_amount' ), 1 ) );
305 }
306 $extended_info = $this->cast_numbers( $extended_info );
307 }
308 $products_data[ $key ]['extended_info'] = $extended_info;
309 }
310 }
311
312 /**
313 * Returns if simple products should be excluded from the report.
314 *
315 * @internal
316 *
317 * @param array $query_args Query parameters.
318 *
319 * @return boolean
320 */
321 protected function should_exclude_simple_products( array $query_args ) {
322 return apply_filters( 'experimental_woocommerce_analytics_variations_should_exclude_simple_products', true, $query_args );
323 }
324
325 /**
326 * Fill missing extended_info.name for the deleted products.
327 *
328 * @param array $products Product data.
329 */
330 protected function fill_deleted_product_name( array &$products ) {
331 global $wpdb;
332 $product_variation_ids = array();
333 // Find products with missing extended_info.name.
334 foreach ( $products as $key => $product ) {
335 if ( ! isset( $product['extended_info']['name'] ) ) {
336 $product_variation_ids[ $key ] = array(
337 'product_id' => $product['product_id'],
338 'variation_id' => $product['variation_id'],
339 );
340 }
341 }
342
343 if ( ! count( $product_variation_ids ) ) {
344 return;
345 }
346
347 $where_clauses = implode(
348 ' or ',
349 array_map(
350 function ( $ids ) {
351 return "(
352 product_lookup.product_id = {$ids['product_id']}
353 and
354 product_lookup.variation_id = {$ids['variation_id']}
355 )";
356 },
357 $product_variation_ids
358 )
359 );
360
361 $query = "
362 select
363 product_lookup.product_id,
364 product_lookup.variation_id,
365 order_items.order_item_name
366 from
367 {$wpdb->prefix}wc_order_product_lookup as product_lookup
368 left join {$wpdb->prefix}woocommerce_order_items as order_items
369 on product_lookup.order_item_id = order_items.order_item_id
370 where
371 {$where_clauses}
372 group by
373 product_lookup.product_id,
374 product_lookup.variation_id,
375 order_items.order_item_name
376 ";
377
378 // phpcs:ignore
379 $results = $wpdb->get_results( $query );
380 $index = array();
381 foreach ( $results as $result ) {
382 $index[ $result->product_id . '_' . $result->variation_id ] = $result->order_item_name;
383 }
384
385 foreach ( $product_variation_ids as $product_key => $ids ) {
386 $product = $products[ $product_key ];
387 $index_key = $product['product_id'] . '_' . $product['variation_id'];
388 if ( isset( $index[ $index_key ] ) ) {
389 $products[ $product_key ]['extended_info']['name'] = $index[ $index_key ];
390 }
391 }
392 }
393
394 /**
395 * Get the default query arguments to be used by get_data().
396 * These defaults are only partially applied when used via REST API, as that has its own defaults.
397 *
398 * @override ReportsDataStore::get_default_query_vars()
399 *
400 * @return array Query parameters.
401 */
402 public function get_default_query_vars() {
403 $defaults = parent::get_default_query_vars();
404 $defaults['product_includes'] = array();
405 $defaults['variation_includes'] = array();
406 $defaults['extended_info'] = false;
407
408 return $defaults;
409 }
410
411 /**
412 * Returns the report data based on normalized parameters.
413 * Will be called by `get_data` if there is no data in cache.
414 *
415 * @override ReportsDataStore::get_noncached_data()
416 *
417 * @see get_data
418 * @param array $query_args Query parameters.
419 * @return stdClass|WP_Error Data object `{ totals: *, intervals: array, total: int, pages: int, page_no: int }`, or error.
420 */
421 public function get_noncached_data( $query_args ) {
422 global $wpdb;
423
424 $table_name = self::get_db_table_name();
425
426 $this->initialize_queries();
427
428 $data = (object) array(
429 'data' => array(),
430 'total' => 0,
431 'pages' => 0,
432 'page_no' => 0,
433 );
434
435 $selections = $this->selected_columns( $query_args );
436 $included_variations =
437 ( isset( $query_args['variation_includes'] ) && is_array( $query_args['variation_includes'] ) )
438 ? $query_args['variation_includes']
439 : array();
440 $params = $this->get_limit_params( $query_args );
441 $this->add_sql_query_params( $query_args );
442
443 if ( count( $included_variations ) > 0 ) {
444 $total_results = count( $included_variations );
445 $total_pages = (int) ceil( $total_results / $params['per_page'] );
446
447 $this->subquery->clear_sql_clause( 'select' );
448 $this->subquery->add_sql_clause( 'select', $selections );
449
450 if ( 'date' === $query_args['orderby'] ) {
451 $this->subquery->add_sql_clause( 'select', ", {$table_name}.date_created" );
452 }
453
454 $fields = $this->get_fields( $query_args );
455 $join_selections = $this->format_join_selections( $fields, array( 'variation_id' ) );
456 $ids_table = $this->get_ids_table( $included_variations, 'variation_id' );
457
458 $this->add_sql_clause( 'select', $join_selections );
459 $this->add_sql_clause( 'from', '(' );
460 $this->add_sql_clause( 'from', $this->subquery->get_query_statement() );
461 $this->add_sql_clause( 'from', ") AS {$table_name}" );
462 $this->add_sql_clause(
463 'right_join',
464 "RIGHT JOIN ( {$ids_table} ) AS default_results
465 ON default_results.variation_id = {$table_name}.variation_id"
466 );
467
468 $variations_query = $this->get_query_statement();
469 } else {
470
471 $this->subquery->clear_sql_clause( 'select' );
472 $this->subquery->add_sql_clause( 'select', $selections );
473
474 /**
475 * Experimental: Filter the Variations SQL query allowing extensions to add additional SQL clauses.
476 *
477 * @since 7.4.0
478 * @param array $query_args Query parameters.
479 * @param SqlQuery $subquery Variations query class.
480 */
481 apply_filters( 'experimental_woocommerce_analytics_variations_additional_clauses', $query_args, $this->subquery );
482
483 /* phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared */
484 $db_records_count = (int) $wpdb->get_var(
485 "SELECT COUNT(*) FROM (
486 {$this->subquery->get_query_statement()}
487 ) AS tt"
488 );
489 /* phpcs:enable */
490
491 $total_results = $db_records_count;
492 $total_pages = (int) ceil( $db_records_count / $params['per_page'] );
493
494 if ( $query_args['page'] < 1 || $query_args['page'] > $total_pages ) {
495 return $data;
496 }
497
498 if ( in_array( $query_args['orderby'], array( 'items_sold', 'net_revenue', 'orders_count' ), true ) ) {
499 $this->subquery->add_sql_clause( 'order_by', $this->get_sql_clause( 'order_by' ) . ', product_id, variation_id' );
500 } else {
501 $this->subquery->add_sql_clause( 'order_by', $this->get_sql_clause( 'order_by' ) );
502 }
503 $this->subquery->add_sql_clause( 'limit', $this->get_sql_clause( 'limit' ) );
504 $variations_query = $this->subquery->get_query_statement();
505 }
506
507 /* phpcs:disable WordPress.DB.PreparedSQL.NotPrepared */
508 $product_data = $wpdb->get_results(
509 $variations_query,
510 ARRAY_A
511 );
512 /* phpcs:enable */
513
514 if ( null === $product_data ) {
515 return $data;
516 }
517
518 $this->include_extended_info( $product_data, $query_args );
519
520 if ( $query_args['extended_info'] ) {
521 $this->fill_deleted_product_name( $product_data );
522 }
523
524 $product_data = array_map( array( $this, 'cast_numbers' ), $product_data );
525 $data = (object) array(
526 'data' => $product_data,
527 'total' => $total_results,
528 'pages' => $total_pages,
529 'page_no' => (int) $query_args['page'],
530 );
531
532 return $data;
533 }
534
535 /**
536 * Initialize query objects.
537 */
538 protected function initialize_queries() {
539 $this->clear_all_clauses();
540 $this->subquery = new SqlQuery( $this->context . '_subquery' );
541 $this->subquery->add_sql_clause( 'select', 'product_id' );
542 $this->subquery->add_sql_clause( 'from', self::get_db_table_name() );
543 $this->subquery->add_sql_clause( 'group_by', 'product_id, variation_id' );
544 }
545 }
546