Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
32.15% covered (danger)
32.15%
191 / 594
38.33% covered (danger)
38.33%
23 / 60
CRAP
0.00% covered (danger)
0.00%
0 / 1
WooCommerce_Analytics
32.26% covered (danger)
32.26%
191 / 592
38.33% covered (danger)
38.33%
23 / 60
13137.87
0.00% covered (danger)
0.00%
0 / 1
 is_woocommerce_supported
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 __construct
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 add_woocommerce_analytics_options_whitelist
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 add_woocommerce_analytics_post_meta_whitelist
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 name
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 id_field
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 table
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 init_listeners
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
12
 expand_data
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 init_full_sync_listeners
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 get_full_sync_actions
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_supported_object_types
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_objects_by_id
11.43% covered (danger)
11.43%
4 / 35
0.00% covered (danger)
0.00%
0 / 1
95.07
 get_object_by_id
25.00% covered (danger)
25.00%
2 / 8
0.00% covered (danger)
0.00%
0 / 1
10.75
 enqueue_full_sync_actions
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
2
 estimate_full_sync_actions
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
6
 get_where_sql
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
12
 init_before_send
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
2
 build_full_sync_action_array
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
2
 get_next_chunk
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
12
 filter_analytics_objects_by_size
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
4
 sync_analytics_reports_data
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 sync_imported_analytics_reports_data
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
20
 sync_deleted_analytics_data
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
2
 build_woocommerce_analytics_reports_data
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
3
 build_woocommerce_analytics_reports_lookup_data
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
20
 get_order_attribution_data
93.33% covered (success)
93.33%
28 / 30
0.00% covered (danger)
0.00%
0 / 1
7.01
 get_order_attribution_meta_prefix
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 get_order_stats_data
9.33% covered (danger)
9.33%
7 / 75
0.00% covered (danger)
0.00%
0 / 1
490.83
 get_core_order_stats_row
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
12
 build_order_stats_data_from_core_row
0.00% covered (danger)
0.00%
0 / 22
0.00% covered (danger)
0.00%
0 / 1
90
 row_date_to_object
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
20
 refund_dates_follow_parent
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
6
 should_split_full_refund_using_parent_order
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
30
 get_order_fulfillment_status
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
30
 uses_new_full_refund_data
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
2.15
 get_num_items_sold
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
6
 get_net_total
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 get_total_fees_tax
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
2
 get_order_stats_item
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 get_order_stats_items
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
2
 get_analytics_order
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
5
 get_analytics_orders
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
5
 is_cogs_enabled
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_order_product_data
12.24% covered (danger)
12.24%
6 / 49
0.00% covered (danger)
0.00%
0 / 1
63.74
 get_order_product_cogs_value
45.45% covered (danger)
45.45%
5 / 11
0.00% covered (danger)
0.00%
0 / 1
18.39
 get_signed_cogs_amount
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 get_order_product_data_from_db
96.15% covered (success)
96.15%
25 / 26
0.00% covered (danger)
0.00%
0 / 1
3
 is_refund_order
75.00% covered (warning)
75.00%
6 / 8
0.00% covered (danger)
0.00%
0 / 1
5.39
 get_order_coupon_data
0.00% covered (danger)
0.00%
0 / 19
0.00% covered (danger)
0.00%
0 / 1
30
 get_order_coupon_data_from_db
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
12
 get_order_tax_data
0.00% covered (danger)
0.00%
0 / 23
0.00% covered (danger)
0.00%
0 / 1
30
 get_order_tax_data_from_db
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 1
12
 get_order_lookup_data_from_db
87.50% covered (warning)
87.50%
7 / 8
0.00% covered (danger)
0.00%
0 / 1
2.01
 get_order_stats_data_from_db
85.71% covered (warning)
85.71%
6 / 7
0.00% covered (danger)
0.00%
0 / 1
2.01
 do_order_status_discrepancy_check
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
30
 normalize_order_status
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 datetime_to_object
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
5
 format_utc_offset
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 get_site_datetimezone
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2/**
3 * WooCommerce Analytics sync module.
4 *
5 * Syncs the data behind WooCommerce Analytics reports (wc_order_stats and the
6 * order product/coupon/tax lookup tables) to WordPress.com.
7 *
8 * Sync module name: `woocommerce_analytics`. The name, the action names, and the
9 * payload shapes are consumed by the WPCOM receiving side and by consumer packages
10 * (Premium Analytics, the standalone WooCommerce Analytics plugin); treat them as a public contract.
11 *
12 * This module is NOT registered by default. Consumers own its registration,
13 * WooCommerce runtime guard ({@see self::is_woocommerce_supported()}), full-sync policy, and any additional Sync data
14 * configuration. The module provides the minimum option and post meta requirements.
15 *
16 * WooCommerce is a runtime (not composer) dependency. The WC classes
17 * referenced here resolve via WooCommerce's autoloader at runtime; registration is
18 * guarded so this class is only instantiated when WooCommerce is active.
19 *
20 * @package automattic/jetpack-sync
21 */
22
23namespace Automattic\Jetpack\Sync\Modules;
24
25use Automattic\WooCommerce\Admin\API\Reports\Coupons\DataStore as CouponsDataStore;
26use Automattic\WooCommerce\Admin\API\Reports\Orders\Stats\DataStore as OrderStatsDataStore;
27use Automattic\WooCommerce\Utilities\FeaturesUtil;
28use Automattic\WooCommerce\Utilities\OrderUtil;
29use DateTimeZone;
30use WC_Abstract_Order;
31use WC_Coupon;
32use WC_DateTime;
33use WC_Order;
34use WC_Order_Factory;
35use WC_Order_Refund;
36use WC_Tax;
37
38if ( ! defined( 'ABSPATH' ) ) {
39    exit( 0 );
40}
41
42/**
43 * WooCommerce Analytics Module class.
44 */
45class WooCommerce_Analytics extends Module {
46
47    /**
48     * Oldest supported WooCommerce: older versions do not store paid and completed dates.
49     *
50     * @var string
51     */
52    private const MIN_WOOCOMMERCE_VERSION = '7.5';
53
54    /**
55     * Whether the active WooCommerce is one consumers may register this module on.
56     *
57     * @return bool
58     */
59    public static function is_woocommerce_supported(): bool {
60        return defined( 'WC_VERSION' ) && version_compare( WC_VERSION, self::MIN_WOOCOMMERCE_VERSION, '>=' );
61    }
62
63    /**
64     * Options required by WooCommerce Analytics Sync.
65     *
66     * @var string[]
67     */
68    private static $options_whitelist = array(
69        'woocommerce_excluded_report_order_statuses',
70    );
71
72    /**
73     * Post meta required by WooCommerce Analytics Sync.
74     *
75     * @var string[]
76     */
77    private static $post_meta_whitelist = array(
78        '_stock',
79        '_stock_quantity',
80        '_cogs_total_value',
81        '_global_unique_id',
82    );
83
84    /**
85     * WooCommerce Analytics' order class for each plain order class, which adds the report methods used here.
86     *
87     * @var string[]
88     */
89    private static $analytics_order_classes = array(
90        'WC_Order'        => 'Automattic\WooCommerce\Admin\Overrides\Order',
91        'WC_Order_Refund' => 'Automattic\WooCommerce\Admin\Overrides\OrderRefund',
92    );
93
94    /**
95     * Constructor.
96     */
97    public function __construct() {
98        add_filter( 'jetpack_sync_options_whitelist', array( $this, 'add_woocommerce_analytics_options_whitelist' ), 10 );
99        add_filter( 'jetpack_sync_post_meta_whitelist', array( $this, 'add_woocommerce_analytics_post_meta_whitelist' ), 10 );
100    }
101
102    /**
103     * Add the options required by WooCommerce Analytics Sync.
104     *
105     * @param array $list Existing options whitelist.
106     * @return array Updated options whitelist.
107     */
108    public function add_woocommerce_analytics_options_whitelist( $list ) {
109        return array_values( array_unique( array_merge( $list, self::$options_whitelist ) ) );
110    }
111
112    /**
113     * Add the post meta required by WooCommerce Analytics Sync.
114     *
115     * @param array $list Existing post meta whitelist.
116     * @return array Updated post meta whitelist.
117     */
118    public function add_woocommerce_analytics_post_meta_whitelist( $list ) {
119        return array_values( array_unique( array_merge( $list, self::$post_meta_whitelist ) ) );
120    }
121
122    /**
123     * Get the module name.
124     *
125     * @return string
126     */
127    public function name() {
128        return 'woocommerce_analytics';
129    }
130
131    /**
132     * Get the ID field for the module.
133     *
134     * @return string
135     */
136    public function id_field() {
137        return 'order_id';
138    }
139
140    /**
141     * Get the table in the database.
142     *
143     * @return string
144     */
145    public function table() {
146        global $wpdb;
147        return $wpdb->prefix . 'wc_order_stats';
148    }
149
150    /**
151     * Init listeners.
152     *
153     * @param callable $handler Action handler callable.
154     *
155     * @return void
156     */
157    public function init_listeners( $handler ) {
158        // Actions to update order stats.
159        add_action( 'woocommerce_analytics_delete_order_stats', array( $this, 'sync_deleted_analytics_data' ) );
160
161        // In WooCommerce 10.3+ the new action is available.
162        if ( defined( 'WC_VERSION' ) && version_compare( WC_VERSION, '10.3', '>=' ) ) {
163            add_action( 'woocommerce_order_scheduler_after_import_order', array( $this, 'sync_imported_analytics_reports_data' ) );
164        } else {
165            add_action( 'woocommerce_analytics_update_order_stats', array( $this, 'sync_analytics_reports_data' ) );
166        }
167
168        // Sync actions.
169        add_action( 'woocommerce_analytics_sync_reports_data', $handler );
170        add_action( 'woocommerce_analytics_delete_reports_data', $handler );
171
172        // Expand data.
173        add_filter( 'jetpack_sync_before_enqueue_woocommerce_analytics_sync_reports_data', array( $this, 'expand_data' ) );
174        add_filter( 'jetpack_sync_before_enqueue_woocommerce_analytics_delete_reports_data', array( $this, 'expand_data' ) );
175    }
176
177    /**
178     * Expand order stats data and attribution data.
179     *
180     * @param array|mixed $args List of arguments.
181     *
182     * @return array|false
183     */
184    public function expand_data( $args ) {
185        if ( ! is_array( $args ) || ! isset( $args[0] ) ) {
186            return false;
187        }
188
189        $data = $args[0];
190
191        return $data;
192    }
193
194    /**
195     * Init full sync listeners.
196     *
197     * @param callable $handler Action handler callable.
198     *
199     * @return void
200     */
201    public function init_full_sync_listeners( $handler ) {
202        add_action( 'jetpack_full_sync_woocommerce_analytics', $handler );
203    }
204
205    /**
206     * Get full sync actions.
207     *
208     * @return string[] The full sync actions.
209     */
210    public function get_full_sync_actions() {
211        return array( 'jetpack_full_sync_woocommerce_analytics' );
212    }
213
214    /**
215     * Get the supported object types.
216     *
217     * @return array The supported object types.
218     */
219    private function get_supported_object_types() {
220        return array( 'order', 'order_tax_lookup', 'order_product_lookup', 'order_coupon_lookup' );
221    }
222
223    /**
224     * Retrieves multiple orders data by their ID.
225     *
226     * @param string $object_type Type of object to retrieve. Should be `order`.
227     * @param array  $ids         List of order IDs.
228     *
229     * @return array
230     */
231    public function get_objects_by_id( $object_type, $ids ) {
232        if ( empty( $ids ) || ! is_array( $ids ) || empty( $object_type ) ) {
233            return array();
234        }
235
236        if ( ! in_array( $object_type, $this->get_supported_object_types(), true ) ) {
237            return array();
238        }
239
240        $orders = self::get_analytics_orders(
241            array(
242                'post__in'    => $ids,
243                'post_status' => WooCommerce_HPOS_Orders::get_all_possible_order_status_keys(),
244                'limit'       => -1,
245                'orderby'     => 'id',
246                'order'       => 'DESC',
247            )
248        );
249
250        // Get the order stats data for the orders.
251        $order_stats_items = $this->get_order_stats_items( $ids );
252        $order_stats_data  = array();
253        if ( ! empty( $order_stats_items ) ) {
254            $order_stats_data = array_column( $order_stats_items, null, 'order_id' );
255        }
256
257        $orders_data     = array();
258        $found_order_ids = array();
259        foreach ( $orders as $order ) {
260            $order_id          = $order->get_id();
261            $found_order_ids[] = $order_id;
262            if ( 'order' === $object_type ) {
263                // Sync everything if the object type is order.
264                $orders_data[ $order_id ] = $this->build_woocommerce_analytics_reports_data( $order );
265            } else {
266                $orders_data[ $order_id ] = $this->build_woocommerce_analytics_reports_lookup_data( $order, $object_type );
267            }
268            if ( isset( $order_stats_data[ $order_id ] ) ) {
269                $this->do_order_status_discrepancy_check( $order, $order_stats_data[ $order_id ] );
270            }
271        }
272
273        // Check for missing order_ids in wc_order_stats table for orders that were not found.
274        $missing_order_ids = array_diff( $ids, $found_order_ids );
275
276        /**
277         * Trigger missing orders detected action.
278         *
279         * @param array $missing_order_ids The missing order IDs.
280         */
281        do_action( 'woocommerce_analytics_missing_orders_detected', $missing_order_ids );
282
283        foreach ( $missing_order_ids as $missing_order_id ) {
284            if ( 'order' === $object_type ) {
285                $orders_data[ $missing_order_id ] = $this->build_woocommerce_analytics_reports_data( $missing_order_id );
286            } else {
287                $orders_data[ $missing_order_id ] = $this->build_woocommerce_analytics_reports_lookup_data( $missing_order_id, $object_type );
288            }
289        }
290        // Let's sort the orders by ID in descending order. This is useful for the full sync to ensure that the latest orders are processed first.
291        krsort( $orders_data, SORT_NUMERIC );
292        return $orders_data;
293    }
294
295    /**
296     * Retrieve the analytics order data by its ID.
297     *
298     * @param string $object_type Type of the sync object.
299     * @param int    $id          ID of the sync object.
300     * @return mixed Object, or false if the object is invalid.
301     */
302    public function get_object_by_id( $object_type, $id ) {
303        if ( ! in_array( $object_type, $this->get_supported_object_types(), true ) ) {
304            return false;
305        }
306
307        $order = wc_get_order( $id );
308
309        if ( ! $order instanceof WC_Abstract_Order ) {
310            $order = $id; // If the order does not exists. We'll check if the order_id exists in wc_order_stats table.
311        }
312
313        if ( 'order' === $object_type ) {
314            return $this->build_woocommerce_analytics_reports_data( $order );
315        }
316
317        return $this->build_woocommerce_analytics_reports_lookup_data( $order, $object_type );
318    }
319
320    /**
321     * Enqueue full sync actions.
322     *
323     * @param array   $config               Full sync configuration.
324     * @param int     $max_items_to_enqueue Maximum number of items to enqueue.
325     * @param boolean $state                True if full sync has finished enqueueing this module.
326     * @return array Number of actions enqueued, and next module state.
327     */
328    public function enqueue_full_sync_actions( $config, $max_items_to_enqueue, $state ) {
329        return $this->enqueue_all_ids_as_action(
330            'jetpack_full_sync_woocommerce_analytics',
331            $this->table(),
332            $this->id_field(),
333            $this->get_where_sql( $config ),
334            $max_items_to_enqueue,
335            $state
336        );
337    }
338
339    /**
340     * Estimate full sync actions.
341     *
342     * @param array $config Full sync configuration.
343     * @return int Number of items yet to be enqueued.
344     */
345    public function estimate_full_sync_actions( $config ) {
346        global $wpdb;
347
348        $query = "SELECT COUNT(*) FROM {$this->table()}";
349
350        $where_sql = $this->get_where_sql( $config );
351        if ( $where_sql ) {
352            $query .= ' WHERE ' . $where_sql;
353        }
354
355        // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
356        $count = (int) $wpdb->get_var( $query );
357
358        return (int) ceil( $count / self::ARRAY_CHUNK_SIZE );
359    }
360
361    /**
362     * Get where SQL clause for the module.
363     *
364     * @param array $config Full sync configuration.
365     * @return string
366     */
367    public function get_where_sql( $config ) {
368        global $wpdb;
369
370        $where = '1=1';
371
372        if ( ! empty( $config['start_date'] ) ) {
373            $where .= $wpdb->prepare( ' AND date_created >= %s', $config['start_date'] );
374        }
375        if ( ! empty( $config['end_date'] ) ) {
376            $where .= $wpdb->prepare( ' AND date_created <= %s', $config['end_date'] );
377        }
378
379        /**
380         * Filter the WHERE SQL for analytics full sync
381         *
382         * @param string $where The WHERE SQL clause
383         * @param array  $config The sync configuration
384         */
385        return apply_filters( 'woocommerce_analytics_full_sync_where_sql', $where, $config );
386    }
387
388    /**
389     * Initialize module in the sender.
390     */
391    public function init_before_send() {
392        // Full sync.
393        add_filter(
394            'jetpack_sync_before_send_jetpack_full_sync_woocommerce_analytics',
395            array( $this, 'build_full_sync_action_array' )
396        );
397    }
398
399    /**
400     * Build the full sync action object.
401     *
402     * @param array $args An array with filtered objects and previous end.
403     *
404     * @return array An array with orders and previous end.
405     */
406    public function build_full_sync_action_array( $args ) {
407        list( $filtered_orders, $previous_end ) = $args;
408        return array(
409            'orders'       => $filtered_orders['objects'],
410            'previous_end' => $previous_end,
411        );
412    }
413
414    /**
415     * Given the Module Configuration and Status return the next chunk of items to send.
416     * This function also expands the posts and metadata and filters them based on the maximum size constraints.
417     *
418     * @param array $config This module Full Sync configuration.
419     * @param array $status This module Full Sync status.
420     * @param int   $chunk_size Chunk size.
421     *
422     * @return array
423     */
424    public function get_next_chunk( $config, $status, $chunk_size ) {
425
426        $order_ids = parent::get_next_chunk( $config, $status, $chunk_size );
427
428        if ( empty( $order_ids ) ) {
429            return array();
430        }
431
432        $orders = $this->get_objects_by_id( 'order', $order_ids );
433
434        // If no orders were fetched, make sure to return the expected structure so that status is updated correctly.
435        if ( empty( $orders ) ) {
436            return array(
437                'object_ids' => $order_ids,
438                'objects'    => array(),
439            );
440        }
441
442        // Filter the orders based on the maximum size constraints.
443        list( $filtered_order_ids, $filtered_orders, ) = $this->filter_analytics_objects_by_size( $orders );
444
445        return array(
446            'object_ids' => $filtered_order_ids,
447            'objects'    => $filtered_orders,
448        );
449    }
450
451    /**
452     * Filters objects and metadata based on maximum size constraints.
453     * It always allows the first object with its metadata, even if they exceed the limit.
454     *
455     * @param array $objects The array of objects to filter.
456     *
457     * @return array An array containing the filtered object IDsand  filtered objects
458     */
459    public function filter_analytics_objects_by_size( $objects ) {
460        $filtered_objects    = array();
461        $filtered_object_ids = array();
462        $current_size        = 0;
463
464        foreach ( $objects as $key => $value ) {
465            $object_size = strlen( maybe_serialize( $value ) );
466
467            // Always allow the first object.
468            if ( empty( $filtered_object_ids ) || ( $current_size + $object_size ) <= self::MAX_SIZE_FULL_SYNC ) {
469                $filtered_object_ids[]    = $key;
470                $filtered_objects[ $key ] = $value;
471                $current_size            += $object_size;
472            } else {
473                break;
474            }
475        }
476
477        return array(
478            $filtered_object_ids,
479            $filtered_objects,
480        );
481    }
482
483    /**
484     * Handle Sync analytics reports data.
485     *
486     * @param int $order_id The order ID.
487     * @return void
488     */
489    public function sync_analytics_reports_data( $order_id ) {
490
491        $data = $this->get_object_by_id( 'order', $order_id );
492
493        if ( ! $data ) {
494            return;
495        }
496
497        /**
498         * Trigger the action to sync the reports data.
499         *
500         * @param array $data Analytics reports sync data.
501         */
502        do_action( 'woocommerce_analytics_sync_reports_data', $data );
503    }
504
505    /**
506     * Sync a record WooCommerce has just imported, plus an imported order's refunds.
507     *
508     * Importing an order rewrites its refunds' stats rows, but fires the action only once, for the order.
509     *
510     * @param int $order_id The imported order or refund ID.
511     * @return void
512     */
513    public function sync_imported_analytics_reports_data( $order_id ) {
514        $this->sync_analytics_reports_data( $order_id );
515
516        $order = wc_get_order( $order_id );
517        if ( ! $order instanceof WC_Order ) {
518            return;
519        }
520
521        $refund_ids = array_map(
522            static function ( $refund ) {
523                return $refund->get_id();
524            },
525            $order->get_refunds()
526        );
527        if ( ! $refund_ids ) {
528            return;
529        }
530
531        // A refund the import excluded or deleted has no row, and resending it would add one core does not have.
532        $stored_ids = array_map( 'intval', wp_list_pluck( (array) $this->get_order_stats_items( $refund_ids ), 'order_id' ) );
533        foreach ( array_intersect( $refund_ids, $stored_ids ) as $refund_id ) {
534            $this->sync_analytics_reports_data( $refund_id );
535        }
536    }
537
538    /**
539     * Handle syncing of analytics deletion data.
540     *
541     * @param int $order_id The order ID.
542     * @return void
543     */
544    public function sync_deleted_analytics_data( $order_id ) {
545        if ( empty( $order_id ) ) {
546            return;
547        }
548
549        $data = array(
550            'id' => $order_id,
551        );
552
553        /**
554         * Filter the deletion data before syncing.
555         *
556         * @param array $data The deletion data.
557         */
558        $data = apply_filters( 'woocommerce_analytics_deletion_data', $data );
559
560        /**
561         * Trigger the action to sync the deletion.
562         *
563         * @param array $data The deletion sync data.
564         */
565        do_action( 'woocommerce_analytics_delete_reports_data', $data );
566    }
567
568    /**
569     * Build the WooCommerce analytics reports data.
570     *
571     * @param mixed $order The order ID or the WC_Order object.
572     * @return array The reports data.
573     */
574    protected function build_woocommerce_analytics_reports_data( $order ) {
575        // Reload once here, or each getter below would read the order again.
576        $report_order = $order;
577        if ( $order instanceof WC_Abstract_Order ) {
578            $analytics_order = self::get_analytics_order( $order );
579            if ( $analytics_order ) {
580                $report_order = $analytics_order;
581            }
582        }
583
584        $data_types = array(
585            'order_stats'            => $this->get_order_stats_data( $report_order ),
586            'order_attribution_data' => $this->get_order_attribution_data( $report_order ),
587            'order_product_data'     => $this->get_order_product_data( $report_order ),
588            'order_coupon_data'      => $this->get_order_coupon_data( $report_order ),
589            'order_tax_data'         => $this->get_order_tax_data( $report_order ),
590        );
591
592        $reports_data = array_filter( $data_types );
593
594        /**
595         * Filter the reports data before syncing.
596         *
597         * @param array                        $data  The reports data.
598         * @param WC_Abstract_Order|int|string $order The order object or ID.
599         */
600        return apply_filters( 'woocommerce_analytics_reports_data', $reports_data, $order );
601    }
602
603    /**
604     * Build the WooCommerce analytics reports data for lookup tables.
605     *
606     * @param mixed  $order The order ID or the WC_Order object.
607     * @param string $object_type The object type.
608     * @return array The reports data.
609     */
610    protected function build_woocommerce_analytics_reports_lookup_data( $order, $object_type ) {
611        $report_data = array();
612        switch ( $object_type ) {
613            case 'order_product_lookup':
614                $report_data['order_product_data'] = $this->get_order_product_data( $order );
615                break;
616            case 'order_coupon_lookup':
617                $report_data['order_coupon_data'] = $this->get_order_coupon_data( $order );
618                break;
619            case 'order_tax_lookup':
620                $report_data['order_tax_data'] = $this->get_order_tax_data( $order );
621                break;
622        }
623
624        /**
625         * Filter the reports lookup data before syncing.
626         *
627         * @param array                        $data        The reports lookup data.
628         * @param WC_Abstract_Order|int|string $order       The order object or ID.
629         * @param string                       $object_type The object type.
630         */
631        return apply_filters( 'woocommerce_analytics_reports_lookup_data', $report_data, $order, $object_type );
632    }
633
634    /**
635     * Get order attribution data.
636     *
637     * @param mixed $order The order ID or the WC_Order object.
638     * @return array|bool The order attribution data or false if the order is invalid.
639     */
640    protected function get_order_attribution_data( $order ) {
641        if ( is_numeric( $order ) ) {
642            $order = wc_get_order( $order );
643        }
644
645        if ( ! $order ) {
646            return false;
647        }
648
649        $order_id           = $order->get_id();
650        $type               = $order->get_type();
651        $attribution_prefix = $this->get_order_attribution_meta_prefix();
652        $allowed_keys       = array(
653            'utm_campaign',
654            'utm_source',
655            'utm_medium',
656            'utm_content',
657            'utm_term',
658            'utm_source_platform',
659            'origin',
660            'device_type',
661            'source_type',
662        );
663
664        // Refunds inherit attribution from their parent order. Fall back to the refund
665        // itself when the parent can no longer be loaded.
666        $order_object_to_use = $order;
667        if ( 'shop_order_refund' === $type && ! empty( $order->get_parent_id() ) ) {
668            $parent_order = wc_get_order( $order->get_parent_id() );
669            if ( $parent_order ) {
670                $order_object_to_use = $parent_order;
671            }
672        }
673
674        $attribution_data = array(
675            'order_id' => $order_id,
676        );
677
678        foreach ( $allowed_keys as $key ) {
679            $meta_key                 = $attribution_prefix . $key;
680            $attribution_data[ $key ] = $order_object_to_use->get_meta( $meta_key, true );
681        }
682
683        return $attribution_data;
684    }
685
686    /**
687     * Get the filtered WooCommerce order attribution meta prefix.
688     *
689     * @return string The normalized meta prefix.
690     */
691    private function get_order_attribution_meta_prefix() {
692        /**
693         * Filters the prefix used for order attribution meta keys.
694         *
695         * @since 5.1.0
696         *
697         * @param string $prefix The order attribution meta key prefix.
698         */
699        $prefix = (string) apply_filters(
700            'wc_order_attribution_tracking_field_prefix',
701            'wc_order_attribution_'
702        );
703
704        return '_' . trim( $prefix, '_' ) . '_';
705    }
706
707    /**
708     * Handler order stats update.
709     *
710     * @param mixed $order The order ID or the WC_Order object.
711     * @return array|bool The order attribution data or false if the order stats item does not exist.
712     */
713    protected function get_order_stats_data( $order ) {
714        if ( is_numeric( $order ) ) {
715            $order_id = $order;
716            $order    = wc_get_order( $order );
717        } elseif ( $order instanceof WC_Abstract_Order ) {
718            $order_id = $order->get_id();
719        } else {
720            return false;
721        }
722
723        // If the order does not exist or cannot have report methods, read its wc_order_stats row instead.
724        $order = self::get_analytics_order( $order );
725        if ( ! $order ) {
726            $order_stats_data_from_db = $this->get_order_stats_data_from_db( $order_id );
727            return $order_stats_data_from_db;
728        }
729
730        $core_row = self::get_core_order_stats_row( $order );
731        if ( $core_row ) {
732            return $this->build_order_stats_data_from_core_row( $order, $core_row );
733        }
734        if ( false === $core_row ) {
735            // Core skips the order now, but a row it stored earlier (a test order imported before
736            // core excluded them) is still in the local table the checksum compares against.
737            return $this->get_order_stats_data_from_db( $order->get_id() );
738        }
739
740        $order_stats_item         = null;
741        $order_fulfillment_status = null;
742        // @phan-suppress-next-line PhanUndeclaredStaticMethod -- Guarded by is_callable(); absent from the older WooCommerce stubs used by the "old Woo" Phan job.
743        if ( is_callable( array( OrderStatsDataStore::class, 'has_fulfillment_status_column' ) ) && OrderStatsDataStore::has_fulfillment_status_column() ) {
744            $order_stats_item         = $this->get_order_stats_item( $order->get_id() );
745            $order_fulfillment_status = $order_stats_item['fulfillment_status'] ?? null;
746        } elseif ( $order instanceof WC_Order ) {
747            $order_fulfillment_status = self::get_order_fulfillment_status( $order );
748        }
749
750        $order_stats_data = array(
751            'order_id'           => $order->get_id(),
752            'parent_id'          => $order->get_parent_id(),
753            'date_created'       => self::datetime_to_object( $order->get_date_created() ),
754            // The `get_date_paid()` and `get_date_completed()` methods were moved to WC_Abstract_Order in Woo 7.5, so refunds only have them after that point. We set the values later for refunds anyway.
755            'date_paid'          => $order instanceof WC_Order ? self::datetime_to_object( $order->get_date_paid() ) : null,
756            'date_completed'     => $order instanceof WC_Order ? self::datetime_to_object( $order->get_date_completed() ) : null,
757            'num_items_sold'     => self::get_num_items_sold( $order ),
758            'total_sales'        => $order->get_total(),
759            'tax_total'          => $order->get_total_tax(),
760            'total_fees'         => $order->get_total_fees(),
761            'total_fees_tax'     => self::get_total_fees_tax( $order ),
762            'shipping_total'     => $order->get_shipping_total(),
763            'shipping_tax'       => $order->get_shipping_tax(),
764            'discount_total'     => $order->get_discount_total(),
765            'discount_tax'       => $order->get_discount_tax(),
766            'net_total'          => self::get_net_total( $order ),
767            'returning_customer' => $order->is_returning_customer(),
768            'status'             => self::normalize_order_status( $order->get_status() ),
769            'customer_id'        => $order->get_report_customer_id(),
770            'fulfillment_status' => $order_fulfillment_status,
771        );
772
773        // Mirrors the refund block of WooCommerce's Orders\Stats\DataStore::update().
774        if ( 'shop_order_refund' === $order->get_type() ) {
775            $parent_order = wc_get_order( $order->get_parent_id() );
776            // Refunds attach to the original order. Skip if the parent is another refund.
777            if ( $parent_order && ! $parent_order instanceof WC_Order_Refund ) {
778                $order_stats_data['parent_id'] = $parent_order->get_id();
779                // Unlike core, keep the refund's own status: the WooCommerce Analytics plugin writes it back to core's row.
780
781                $refund_type               = $order->get_meta( '_refund_type' );
782                $uses_new_full_refund_data = self::uses_new_full_refund_data();
783                $use_parent_refund_amounts = $uses_new_full_refund_data && (
784                    'full' === $refund_type
785                    || self::should_split_full_refund_using_parent_order( $order, $parent_order )
786                );
787                if ( $use_parent_refund_amounts ) {
788                    $order_stats_data['num_items_sold'] = -1 * self::get_num_items_sold( $parent_order );
789                    $order_stats_data['tax_total']      = -1 * $parent_order->get_total_tax();
790                    $order_stats_data['net_total']      = -1 * self::get_net_total( $parent_order );
791                    $order_stats_data['shipping_total'] = -1 * (float) $parent_order->get_shipping_total();
792
793                    // Subtract what earlier refunds recorded, so this row only holds the remainder.
794                    foreach ( $parent_order->get_refunds() as $prior_refund ) {
795                        if ( $prior_refund->get_id() === $order->get_id() ) {
796                            continue;
797                        }
798                        $order_stats_data['num_items_sold'] -= self::get_num_items_sold( $prior_refund );
799                        $order_stats_data['tax_total']      -= (float) $prior_refund->get_total_tax();
800                        $order_stats_data['net_total']      -= self::get_net_total( $prior_refund );
801                        $order_stats_data['shipping_total'] -= (float) $prior_refund->get_shipping_total();
802                    }
803                }
804            }
805            // Refunds have no paid or completed date; backfill each from date_created, but only where the parent has it.
806            // Follow core's stored row when there is one: rows an older WooCommerce wrote keep their dates, and the checksum compares both.
807            $order_stats_item ??= $this->get_order_stats_item( $order->get_id() );
808            if ( $order_stats_item ) {
809                $has_date_completed = null !== $order_stats_item['date_completed'];
810                $has_date_paid      = null !== $order_stats_item['date_paid'];
811            } else {
812                $dates_follow_parent = $parent_order instanceof WC_Order && self::refund_dates_follow_parent();
813                $has_date_completed  = ! $dates_follow_parent || $parent_order->get_date_completed();
814                $has_date_paid       = ! $dates_follow_parent || $parent_order->get_date_paid();
815            }
816            $order_stats_data['date_completed'] = $has_date_completed ? $order_stats_data['date_created'] : null;
817            $order_stats_data['date_paid']      = $has_date_paid ? $order_stats_data['date_created'] : null;
818        }
819
820        return $order_stats_data;
821    }
822
823    /**
824     * Get the wc_order_stats row WooCommerce would store for the order.
825     *
826     * @param WC_Abstract_Order $order Order or refund.
827     * @return array|false|null The row, false when WooCommerce would not store one, or null when WooCommerce cannot build it.
828     */
829    private static function get_core_order_stats_row( $order ) {
830        $callback = array( OrderStatsDataStore::class, 'get_order_stats_row_data' );
831        if ( ! is_callable( $callback ) ) {
832            return null;
833        }
834
835        // @phan-suppress-next-line PhanUndeclaredStaticMethodInCallable -- Guarded by is_callable(); added in WooCommerce 11.5, so absent from the WooCommerce stubs.
836        $row = call_user_func( $callback, $order );
837        return is_array( $row ) ? $row : false;
838    }
839
840    /**
841     * Build the sync payload from core's row, adding the columns only the hosted table has.
842     *
843     * @param WC_Abstract_Order $order Order or refund.
844     * @param array             $row   Row from get_order_stats_row_data().
845     * @return array
846     */
847    private function build_order_stats_data_from_core_row( $order, array $row ) {
848        $data = array_merge(
849            $row,
850            array(
851                'date_created'   => self::datetime_to_object( new WC_DateTime( $row['date_created_gmt'], new DateTimeZone( 'UTC' ) ) ),
852                'date_paid'      => self::row_date_to_object( $row['date_paid'], $order instanceof WC_Order ? $order->get_date_paid() : $order->get_date_created() ),
853                'date_completed' => self::row_date_to_object( $row['date_completed'], $order instanceof WC_Order ? $order->get_date_completed() : $order->get_date_created() ),
854                'total_fees'     => $order->get_total_fees(),
855                'total_fees_tax' => self::get_total_fees_tax( $order ),
856                'shipping_tax'   => $order->get_shipping_tax(),
857                'discount_total' => $order->get_discount_total(),
858                'discount_tax'   => $order->get_discount_tax(),
859            )
860        );
861
862        // Core leaves the status out when the store lacks the column, but the hosted table has one.
863        if ( ! array_key_exists( 'fulfillment_status', $data ) ) {
864            $data['fulfillment_status'] = $order instanceof WC_Order ? self::get_order_fulfillment_status( $order ) : null;
865        }
866
867        // The WooCommerce Analytics plugin rewrites a stored refund's status after the write, and older
868        // WooCommerce versions set refund dates the parent lacks. Follow the stored row so the checksum matches.
869        if ( 'shop_order_refund' === $order->get_type() ) {
870            $stored = $this->get_order_stats_item( $order->get_id() );
871            if ( $stored ) {
872                $data['status']         = $stored['status'];
873                $data['date_paid']      = null !== $stored['date_paid'] ? $data['date_created'] : null;
874                $data['date_completed'] = null !== $stored['date_completed'] ? $data['date_created'] : null;
875            }
876        }
877
878        return $data;
879    }
880
881    /**
882     * Convert a site-local date from core's row to an object for encoding.
883     *
884     * Uses the order's own date when the row holds it unchanged, because a local time inside the hour a DST
885     * change repeats does not say which instant it was. Otherwise parses it in the site's own timezone.
886     *
887     * @param string|null      $date       Date as 'Y-m-d H:i:s' in the site's timezone.
888     * @param WC_DateTime|null $order_date The order's date the row was built from.
889     * @return object|null
890     */
891    private static function row_date_to_object( $date, $order_date ) {
892        if ( ! $date ) {
893            return null;
894        }
895
896        if ( $order_date instanceof WC_DateTime && $order_date->date( 'Y-m-d H:i:s' ) === $date ) {
897            return self::datetime_to_object( clone $order_date );
898        }
899
900        return self::datetime_to_object( new WC_DateTime( $date, wp_timezone() ) );
901    }
902
903    /**
904     * Whether WooCommerce leaves a refund's paid and completed dates empty when its parent order has none.
905     *
906     * @return bool
907     */
908    private static function refund_dates_follow_parent() {
909        return defined( 'WC_VERSION' ) && version_compare( WC_VERSION, '11.2', '>=' );
910    }
911
912    /**
913     * Whether this refund is a single lump-sum refund for the full order. Copied from WooCommerce's Orders\Stats\DataStore, where it is protected.
914     *
915     * @param WC_Abstract_Order $refund       Refund order.
916     * @param WC_Abstract_Order $parent_order Parent order (not a refund).
917     * @return bool
918     */
919    private static function should_split_full_refund_using_parent_order( $refund, $parent_order ) {
920        // The parent must be the original order, not another refund.
921        if ( ! $parent_order instanceof WC_Order || 'shop_order_refund' === $parent_order->get_type() ) {
922            return false;
923        }
924
925        if ( self::get_num_items_sold( $refund ) > 0 ) {
926            return false;
927        }
928
929        $parent_refunds = $parent_order->get_refunds();
930        if ( 1 !== count( $parent_refunds ) ) {
931            return false;
932        }
933
934        $refund_total = wc_format_decimal( abs( (float) $refund->get_total() ) );
935        $order_total  = wc_format_decimal( (float) $parent_order->get_total() );
936
937        return $refund_total === $order_total;
938    }
939
940    /**
941     * Get the fulfillment status WooCommerce would store for the order, or null for none.
942     *
943     * @param WC_Order $order The order.
944     * @return string|null
945     */
946    private static function get_order_fulfillment_status( $order ) {
947        if ( ! FeaturesUtil::feature_is_enabled( 'fulfillments' ) ) {
948            return null;
949        }
950
951        // FulfillmentUtils moved namespace in WooCommerce 10.7.
952        $classes = array(
953            'Automattic\WooCommerce\Admin\Features\Fulfillments\FulfillmentUtils',
954            'Automattic\WooCommerce\Internal\Fulfillments\FulfillmentUtils',
955        );
956        foreach ( $classes as $class ) {
957            if ( is_callable( array( $class, 'get_order_fulfillment_status' ) ) ) {
958                $status = call_user_func( array( $class, 'get_order_fulfillment_status' ), $order );
959                return 'no_fulfillments' !== $status ? $status : null;
960            }
961        }
962
963        return null;
964    }
965
966    /**
967     * Check whether WooCommerce stores full refunds using the new data format.
968     *
969     * @return bool Whether the new full-refund data format is in use.
970     */
971    private static function uses_new_full_refund_data() {
972        if ( ! is_callable( array( OrderUtil::class, 'uses_new_full_refund_data' ) ) ) {
973            return false;
974        }
975
976        // @phan-suppress-next-line PhanUndeclaredStaticMethod -- Guarded by is_callable(); absent from the older WooCommerce stubs used by the "old Woo" Phan job.
977        return OrderUtil::uses_new_full_refund_data();
978    }
979
980    /**
981     * Calculation methods.
982     */
983
984    /**
985     * Get number of items sold among all orders.
986     *
987     * @param WC_Abstract_Order $order Order or refund.
988     * @return int
989     */
990    protected static function get_num_items_sold( $order ) {
991        $num_items = 0;
992
993        $line_items = $order->get_items( 'line_item' );
994        foreach ( $line_items as $line_item ) {
995            $num_items += $line_item->get_quantity();
996        }
997
998        return $num_items;
999    }
1000
1001    /**
1002     * Get the net amount from an order without shipping, tax, or refunds.
1003     *
1004     * @param WC_Abstract_Order $order Order or refund.
1005     * @return float
1006     */
1007    protected static function get_net_total( $order ) {
1008        $net_total = floatval( $order->get_total() ) - floatval( $order->get_total_tax() ) - floatval( $order->get_shipping_total() );
1009        return $net_total;
1010    }
1011
1012    /**
1013     * Get the total fees tax from an order.
1014     *
1015     * @param WC_Abstract_Order $order Order or refund.
1016     * @return float
1017     */
1018    protected static function get_total_fees_tax( $order ) {
1019        $total_fees_tax = array_sum(
1020            array_map(
1021                function ( $item ) {
1022                    return $item->get_total_tax();
1023                },
1024                array_values( $order->get_items( 'fee' ) )
1025            )
1026        );
1027
1028        return $total_fees_tax;
1029    }
1030
1031    /**
1032     * Get the order stats row for a given order ID.
1033     *
1034     * @param int $order_id The order ID.
1035     * @return array|null|void Database query result in format specified by $output or null on failure.
1036     */
1037    private function get_order_stats_item( $order_id ) {
1038        global $wpdb;
1039
1040        $query = $wpdb->prepare(
1041            "SELECT * FROM {$this->table()} WHERE order_id = %d", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
1042            $order_id
1043        );
1044
1045        return $wpdb->get_row( $query, ARRAY_A ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
1046    }
1047
1048    /**
1049     * Get the order stats rows for a given order IDs.
1050     *
1051     * @param array $order_ids The order IDs.
1052     * @return array|null Database query result in format specified by $output or null on failure.
1053     */
1054    private function get_order_stats_items( $order_ids ) {
1055        global $wpdb;
1056
1057        $placeholders = implode( ',', array_fill( 0, count( $order_ids ), '%d' ) );
1058        $query        = $wpdb->prepare(
1059            "SELECT * FROM {$this->table()} WHERE order_id IN ( $placeholders )", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
1060            $order_ids
1061        );
1062
1063        return $wpdb->get_results( $query, ARRAY_A ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
1064    }
1065
1066    /**
1067     * Get the order as WooCommerce Analytics' order class, which adds the report methods used here.
1068     *
1069     * WooCommerce swaps that class in only while Analytics is enabled, and an object cache can outlive the switch.
1070     *
1071     * @param WC_Abstract_Order|false $order The order object.
1072     * @return WC_Abstract_Order|false The order with report methods, or false if it cannot have them.
1073     */
1074    private static function get_analytics_order( $order ) {
1075        if ( ! $order || method_exists( $order, 'get_report_customer_id' ) ) {
1076            return $order;
1077        }
1078
1079        // Mirrors the exact-class check in WooCommerce's order_class_name filters, which leave subclasses alone.
1080        $analytics_class = self::$analytics_order_classes[ get_class( $order ) ] ?? null;
1081        if ( null === $analytics_class || ! class_exists( $analytics_class ) ) {
1082            return false;
1083        }
1084
1085        return new $analytics_class( $order->get_id() );
1086    }
1087
1088    /**
1089     * Query orders, loading them as WooCommerce Analytics' order classes even while Analytics is disabled.
1090     *
1091     * @param array $query_args Arguments for wc_get_orders().
1092     * @return WC_Order[]|\stdClass What wc_get_orders() returns.
1093     */
1094    private static function get_analytics_orders( $query_args ) {
1095        $added_callbacks = array();
1096        foreach ( self::$analytics_order_classes as $analytics_class ) {
1097            $callback = array( $analytics_class, 'order_class_name' );
1098            // Only add, and later remove, what WooCommerce has not, or its own filter goes with it.
1099            if ( class_exists( $analytics_class ) && false === has_filter( 'woocommerce_order_class', $callback ) ) {
1100                add_filter( 'woocommerce_order_class', $callback, 10, 3 );
1101                $added_callbacks[] = $callback;
1102            }
1103        }
1104
1105        try {
1106            return wc_get_orders( $query_args );
1107        } finally {
1108            foreach ( $added_callbacks as $callback ) {
1109                remove_filter( 'woocommerce_order_class', $callback, 10 );
1110            }
1111        }
1112    }
1113
1114    /**
1115     * Check if the COGS feature is enabled.
1116     *
1117     * @return bool True if the COGS feature is enabled, false otherwise.
1118     */
1119    private function is_cogs_enabled() {
1120        return FeaturesUtil::feature_is_enabled( 'cost_of_goods_sold' );
1121    }
1122
1123    /**
1124     * Get order product lookup data.
1125     *
1126     * @param mixed $order The order ID or the WC_Order object.
1127     * @return array|bool The order product data or false if no data exists.
1128     */
1129    protected function get_order_product_data( $order ) {
1130        if ( is_numeric( $order ) ) {
1131            $order_id = $order;
1132            $order    = wc_get_order( $order );
1133        } elseif ( $order instanceof WC_Abstract_Order ) {
1134            $order_id = $order->get_id();
1135        } else {
1136            return false;
1137        }
1138
1139        // If the order does not exist or cannot have report methods, read its lookup rows instead.
1140        $order = self::get_analytics_order( $order );
1141        if ( ! $order ) {
1142            return $this->get_order_product_data_from_db( $order_id );
1143        }
1144
1145        // Get the order product data from the order object.
1146        $order_products = $order->get_items( 'line_item' );
1147
1148        if ( empty( $order_products ) ) {
1149            // Not a common use case, but there could be a case where this returns empty.
1150            return $this->get_order_product_data_from_db( $order_id );
1151        }
1152
1153        $is_refund_order = $this->is_refund_order( $order_id );
1154        $round_tax       = 'no' === get_option( 'woocommerce_tax_round_at_subtotal' );
1155        $decimals        = wc_get_price_decimals();
1156
1157        $results = array();
1158        foreach ( $order_products as $order_product ) {
1159            $shipping_amount     = $order->get_item_shipping_amount( $order_product );
1160            $shipping_tax_amount = $order->get_item_shipping_tax_amount( $order_product );
1161            $coupon_amount       = $order->get_item_coupon_amount( $order_product );
1162            // Tax amount.
1163            $tax_amount  = 0;
1164            $order_taxes = $order->get_taxes();
1165            $tax_data    = $order_product->get_taxes();
1166            foreach ( $order_taxes as $tax_item ) {
1167                $tax_item_id = $tax_item->get_rate_id();
1168                $tax_amount += isset( $tax_data['total'][ $tax_item_id ] ) ? (float) $tax_data['total'][ $tax_item_id ] : 0;
1169            }
1170
1171            $net_revenue = round( $order_product->get_total( 'edit' ), $decimals );
1172            if ( $round_tax ) {
1173                $tax_amount = round( $tax_amount, $decimals );
1174            }
1175
1176            $product_id  = $order_product->get_product_id();
1177            $cogs_amount = $this->get_order_product_cogs_value( $order_product );
1178
1179            $product_data = array(
1180                'order_id'              => $order_id,
1181                'order_item_id'         => $order_product->get_id(),
1182                'product_id'            => $product_id,
1183                'variation_id'          => $order_product->get_variation_id(),
1184                'product_qty'           => $order_product->get_quantity(),
1185                'product_net_revenue'   => $net_revenue,
1186                'product_gross_revenue' => $net_revenue + $tax_amount + $shipping_amount + $shipping_tax_amount,
1187                'shipping_amount'       => $shipping_amount,
1188                'shipping_tax_amount'   => $shipping_tax_amount,
1189                'coupon_amount'         => $coupon_amount,
1190                'tax_amount'            => $tax_amount,
1191                'customer_id'           => $order->get_report_customer_id(),
1192                'date_created'          => self::datetime_to_object( $order->get_date_created() ),
1193                'cogs_amount'           => $this->get_signed_cogs_amount( $cogs_amount, $is_refund_order ),
1194            );
1195
1196            $results[] = $product_data;
1197        }
1198
1199        return $results;
1200    }
1201
1202    /**
1203     * Get COGS value for an order product.
1204     *
1205     * @param object|false $order_product The order product object, or false if it no longer exists.
1206     * @return float|null The COGS amount or null if not available.
1207     */
1208    private function get_order_product_cogs_value( $order_product ) {
1209        if ( ! is_object( $order_product ) || ! method_exists( $order_product, 'get_cogs_value' ) || ! $this->is_cogs_enabled() ) {
1210            return null;
1211        }
1212
1213        $cogs_amount = $order_product->get_cogs_value();
1214
1215        // Only fallback to product's COGS value if order product's COGS is null (not set).
1216        if ( null === $cogs_amount ) {
1217            $product_id = $order_product->get_product_id();
1218            $product    = wc_get_product( $product_id );
1219
1220            if ( $product && method_exists( $product, 'get_cogs_value' ) ) {
1221                $product_cogs_value = $product->get_cogs_value();
1222                if ( null !== $product_cogs_value ) {
1223                    $cogs_amount = $product_cogs_value;
1224                }
1225            }
1226        }
1227
1228        return $cogs_amount;
1229    }
1230
1231    /**
1232     * Negate a COGS amount for refund orders, keeping null as "no COGS value".
1233     *
1234     * @param float|null $cogs_amount     The COGS amount.
1235     * @param bool       $is_refund_order Whether the order is a refund.
1236     * @return float|null The signed COGS amount, or null if not available.
1237     */
1238    private function get_signed_cogs_amount( $cogs_amount, $is_refund_order ) {
1239        if ( null === $cogs_amount || ! $is_refund_order ) {
1240            return $cogs_amount;
1241        }
1242
1243        return -abs( $cogs_amount );
1244    }
1245
1246    /**
1247     * Get order product lookup data from database.
1248     *
1249     * @param int $order_id The order ID.
1250     * @return array|bool The order product data or false if no data exists.
1251     */
1252    protected function get_order_product_data_from_db( $order_id ) {
1253        $results = $this->get_order_lookup_data_from_db( 'wc_order_product_lookup', $order_id );
1254
1255        if ( empty( $results ) ) {
1256            return false;
1257        }
1258
1259        $is_refund_order = $this->is_refund_order( $order_id );
1260
1261        $parsed_results = array();
1262        foreach ( $results as $result ) {
1263            $order_item  = WC_Order_Factory::get_order_item( absint( $result['order_item_id'] ) );
1264            $cogs_amount = $this->get_order_product_cogs_value( $order_item );
1265
1266            $product_data = array(
1267                'date_created'          => self::datetime_to_object( $result['date_created'] ),
1268                'product_net_revenue'   => floatval( $result['product_net_revenue'] ),
1269                'product_gross_revenue' => floatval( $result['product_gross_revenue'] ),
1270                'shipping_amount'       => floatval( $result['shipping_amount'] ),
1271                'shipping_tax_amount'   => floatval( $result['shipping_tax_amount'] ),
1272                'product_qty'           => intval( $result['product_qty'] ),
1273                'variation_id'          => intval( $result['variation_id'] ),
1274                'product_id'            => intval( $result['product_id'] ),
1275                'customer_id'           => intval( $result['customer_id'] ),
1276                'coupon_amount'         => floatval( $result['coupon_amount'] ),
1277                'tax_amount'            => floatval( $result['tax_amount'] ),
1278                'order_item_id'         => intval( $result['order_item_id'] ),
1279                'order_id'              => intval( $result['order_id'] ),
1280                'cogs_amount'           => $this->get_signed_cogs_amount( $cogs_amount, $is_refund_order ),
1281            );
1282
1283            $parsed_results[] = $product_data;
1284        }
1285
1286        return $parsed_results;
1287    }
1288
1289    /**
1290     * Check if the order is a refund order.
1291     *
1292     * @param int $order_id The order ID.
1293     * @return bool True if the order is a refund order, false otherwise.
1294     */
1295    private function is_refund_order( $order_id ) {
1296        $order_stats_data = $this->get_order_stats_item( $order_id );
1297
1298        if ( ! $order_stats_data || empty( $order_stats_data['parent_id'] ) ) {
1299            return false;
1300        }
1301
1302        $parent_id               = $order_stats_data['parent_id'];
1303        $parent_order_stats_data = $this->get_order_stats_item( $parent_id );
1304
1305        if ( ! $parent_order_stats_data || empty( $parent_order_stats_data['status'] ) ) {
1306            return false;
1307        }
1308
1309        // OrderInternalStatus is unavailable before WooCommerce 9.5.
1310        return 'wc-refunded' === $parent_order_stats_data['status'];
1311    }
1312
1313    /**
1314     * Get order coupon lookup data.
1315     *
1316     * @param mixed $order The order ID or the WC_Order object.
1317     * @return array|bool The order coupon data or false if no data exists.
1318     */
1319    protected function get_order_coupon_data( $order ) {
1320        if ( is_numeric( $order ) ) {
1321            $order_id = $order;
1322            $order    = wc_get_order( $order );
1323        } elseif ( $order instanceof WC_Abstract_Order ) {
1324            $order_id = $order->get_id();
1325        } else {
1326            return false;
1327        }
1328
1329        // If the order does not exist, check if coupon lookup data exists in the database.
1330        if ( ! $order ) {
1331            return $this->get_order_coupon_data_from_db( $order_id );
1332        }
1333
1334        // Get the order coupon data from the order object.
1335        $order_coupons = $order->get_coupons();
1336
1337        $results = array();
1338        foreach ( $order_coupons as $coupon ) {
1339            $results[] = array(
1340                'order_id'        => $order_id,
1341                'coupon_id'       => CouponsDataStore::get_coupon_id( $coupon ),
1342                'discount_amount' => $coupon->get_discount(),
1343                'date_created'    => self::datetime_to_object( $order->get_date_created() ),
1344                'coupon_code'     => $coupon->get_code(),
1345            );
1346        }
1347
1348        return $results;
1349    }
1350
1351    /**
1352     * Get order coupon lookup data from database.
1353     *
1354     * @param int $order_id The order ID.
1355     * @return array|bool The order coupon data or false if no data exists.
1356     */
1357    protected function get_order_coupon_data_from_db( $order_id ) {
1358        $results = $this->get_order_lookup_data_from_db( 'wc_order_coupon_lookup', $order_id );
1359
1360        if ( empty( $results ) ) {
1361            return false;
1362        }
1363
1364        $parsed_results = array();
1365        foreach ( $results as $result ) {
1366            $result_data                = array(
1367                'date_created'    => self::datetime_to_object( $result['date_created'] ),
1368                'discount_amount' => floatval( $result['discount_amount'] ),
1369                'order_id'        => intval( $result['order_id'] ),
1370                'coupon_id'       => intval( $result['coupon_id'] ),
1371            );
1372            $coupon                     = new WC_Coupon( absint( $result['coupon_id'] ) );
1373            $result_data['coupon_code'] = $coupon->get_code();
1374            $parsed_results[]           = $result_data;
1375        }
1376
1377        return $parsed_results;
1378    }
1379
1380    /**
1381     * Get order tax lookup data.
1382     *
1383     * @param mixed $order The order ID or the WC_Order object.
1384     * @return array|bool The order tax data or false if no data exists.
1385     */
1386    protected function get_order_tax_data( $order ) {
1387        if ( is_numeric( $order ) ) {
1388            $order_id = $order;
1389            $order    = wc_get_order( $order );
1390        } elseif ( $order instanceof WC_Abstract_Order ) {
1391            $order_id = $order->get_id();
1392        } else {
1393            return false;
1394        }
1395
1396        // If the order does not exist, check if tax lookup data exists in the database.
1397        if ( ! $order ) {
1398            return $this->get_order_tax_data_from_db( $order_id );
1399        }
1400
1401        // Get the order tax data from the order object.
1402        $order_taxes = $order->get_taxes();
1403
1404        $results = array();
1405        foreach ( $order_taxes as $tax ) {
1406            $order_tax    = (float) $tax->get_tax_total();
1407            $shipping_tax = (float) $tax->get_shipping_tax_total();
1408            $results[]    = array(
1409                'order_id'      => $order_id,
1410                'tax_rate_id'   => $tax->get_rate_id(),
1411                'order_tax'     => $order_tax,
1412                'shipping_tax'  => $shipping_tax,
1413                'total_tax'     => $order_tax + $shipping_tax,
1414                'date_created'  => self::datetime_to_object( $order->get_date_created() ),
1415                'tax_rate_code' => $tax->get_rate_code(),
1416            );
1417        }
1418
1419        return $results;
1420    }
1421
1422    /**
1423     * Get order tax lookup data from database.
1424     *
1425     * @param int $order_id The order ID.
1426     * @return array|bool The order tax data or false if no data exists.
1427     */
1428    protected function get_order_tax_data_from_db( $order_id ) {
1429        $results = $this->get_order_lookup_data_from_db( 'wc_order_tax_lookup', $order_id );
1430
1431        if ( empty( $results ) ) {
1432            return false;
1433        }
1434
1435        $parsed_results = array();
1436        foreach ( $results as $result ) {
1437            $result_data      = array(
1438                'date_created'  => self::datetime_to_object( $result['date_created'] ),
1439                'order_tax'     => floatval( $result['order_tax'] ),
1440                'total_tax'     => floatval( $result['total_tax'] ),
1441                'shipping_tax'  => floatval( $result['shipping_tax'] ),
1442                'order_id'      => intval( $result['order_id'] ),
1443                'tax_rate_id'   => intval( $result['tax_rate_id'] ),
1444                'tax_rate_code' => WC_Tax::get_rate_code( $result['tax_rate_id'] ) ?? '',
1445            );
1446            $parsed_results[] = $result_data;
1447        }
1448
1449        return $parsed_results;
1450    }
1451
1452    /**
1453     * Get order lookup data from database.
1454     *
1455     * @param string $table_name The name of the table.
1456     * @param int    $order_id The order ID.
1457     * @return array|bool The order lookup data or false if no data exists.
1458     */
1459    protected function get_order_lookup_data_from_db( $table_name, $order_id ) {
1460        global $wpdb;
1461
1462        // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
1463        $query = $wpdb->prepare(
1464            "SELECT * FROM {$wpdb->prefix}{$table_name} WHERE order_id = %d",
1465            $order_id
1466        );
1467        // phpcs:enable
1468
1469        // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
1470        $results = $wpdb->get_results( $query, ARRAY_A );
1471
1472        if ( empty( $results ) ) {
1473            return false;
1474        }
1475
1476        return $results;
1477    }
1478
1479    /**
1480     * Get the order stats data from the database.
1481     *
1482     * @param int $order_id The order ID.
1483     * @return array|bool The order stats data or false if the order stats item does not exist.
1484     */
1485    private function get_order_stats_data_from_db( $order_id ) {
1486        $order_stats_data = $this->get_order_stats_item( $order_id );
1487
1488        if ( ! $order_stats_data ) {
1489            return false;
1490        }
1491
1492        // Convert date strings to datetime objects.
1493        $order_stats_data['date_created']   = self::datetime_to_object( $order_stats_data['date_created'] );
1494        $order_stats_data['date_completed'] = self::datetime_to_object( $order_stats_data['date_completed'] );
1495        $order_stats_data['date_paid']      = self::datetime_to_object( $order_stats_data['date_paid'] );
1496
1497        return $order_stats_data;
1498    }
1499
1500    /**
1501     * Perform an order status discrepancy check between the order object and the item in the wc_order_stats table.
1502     *
1503     * @param WC_Order $order WC_Order object.
1504     * @param array    $order_stats_item The order stats item.
1505     *
1506     * @return void
1507     */
1508    private function do_order_status_discrepancy_check( $order, $order_stats_item = array() ) {
1509        if ( ! $order instanceof WC_Abstract_Order ) {
1510            return;
1511        }
1512
1513        $order_id = $order->get_id();
1514
1515        // If the order_stats_item is empty, then fetch it from the wc_order_stats table.
1516        if ( empty( $order_stats_item ) ) {
1517            $order_stats_item = $this->get_order_stats_data_from_db( $order_id );
1518        }
1519
1520        // Check for discrepancy in the order status. Happens in old orders that were not updated and hence the OrderStatsFixer did not run.
1521        $normalized_order_status = self::normalize_order_status( $order->get_status() );
1522        if ( $order_stats_item && $normalized_order_status !== $order_stats_item['status'] ) {
1523            /**
1524             * Trigger the action to fix the order stats. The OrderStatusFixer should be hooked to this action.
1525             *
1526             * @param int $order_id The order ID.
1527             */
1528            do_action( 'woocommerce_analytics_incorrect_order_status_detected', $order_id );
1529        }
1530    }
1531
1532    /**
1533     * Maps an order status to the value used in the database.
1534     *
1535     * @param string $status Order status.
1536     * @return string
1537     */
1538    protected static function normalize_order_status( $status ) {
1539        return WooCommerce_HPOS_Orders::get_wc_order_status_with_prefix( str_replace( 'wc-', '', $status ) );
1540    }
1541
1542    /**
1543     * Convert a WooCommerce datetime to an object for encoding.
1544     *
1545     * @param WC_DateTime|mixed $wc_datetime The datetime object.
1546     * @return object|null
1547     */
1548    protected static function datetime_to_object( $wc_datetime ) {
1549        if ( is_string( $wc_datetime ) ) {
1550            $wc_datetime = new WC_DateTime( $wc_datetime, self::get_site_datetimezone() );
1551        }
1552
1553        if ( $wc_datetime instanceof \WC_DateTime ) {
1554            $wc_datetime->setTimezone( self::get_site_datetimezone() );
1555            $date_properties = (array) $wc_datetime;
1556
1557            // Remove protected properties, whose NUL-prefixed names cannot be processed by the receiver.
1558            foreach ( array_keys( $date_properties ) as $property_name ) {
1559                if ( false !== strpos( $property_name, "\0" ) ) {
1560                    unset( $date_properties[ $property_name ] );
1561                }
1562            }
1563
1564            return (object) $date_properties;
1565        }
1566    }
1567
1568    /**
1569     * Convert seconds to an ISO 8601 timezone offset.
1570     *
1571     * @param int|float $offset_seconds The timezone offset in seconds.
1572     * @return string The ISO 8601 timezone offset.
1573     */
1574    protected static function format_utc_offset( $offset_seconds ) {
1575        $hours   = intval( abs( $offset_seconds ) / HOUR_IN_SECONDS );
1576        $minutes = intval( ( abs( $offset_seconds ) % HOUR_IN_SECONDS ) / MINUTE_IN_SECONDS );
1577        $sign    = $offset_seconds >= 0 ? '+' : '-';
1578
1579        return sprintf( '%s%02d:%02d', $sign, $hours, $minutes );
1580    }
1581
1582    /**
1583     * Get the site timezone as a fixed offset.
1584     *
1585     * @return DateTimeZone The site timezone.
1586     */
1587    protected static function get_site_datetimezone() {
1588        return new DateTimeZone( self::format_utc_offset( wc_timezone_offset() ) );
1589    }
1590}