Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
33.75% covered (danger)
33.75%
191 / 566
39.66% covered (danger)
39.66%
23 / 58
CRAP
0.00% covered (danger)
0.00%
0 / 1
WooCommerce_Analytics
33.87% covered (danger)
33.87%
191 / 564
39.66% covered (danger)
39.66%
23 / 58
10411.62
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
10.00% covered (danger)
10.00%
7 / 70
0.00% covered (danger)
0.00%
0 / 1
408.64
 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
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
6
 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        $order_stats_item         = null;
731        $order_fulfillment_status = null;
732        // @phan-suppress-next-line PhanUndeclaredStaticMethod -- Guarded by is_callable(); absent from the older WooCommerce stubs used by the "old Woo" Phan job.
733        if ( is_callable( array( OrderStatsDataStore::class, 'has_fulfillment_status_column' ) ) && OrderStatsDataStore::has_fulfillment_status_column() ) {
734            $order_stats_item         = $this->get_order_stats_item( $order->get_id() );
735            $order_fulfillment_status = $order_stats_item['fulfillment_status'] ?? null;
736        } elseif ( $order instanceof WC_Order ) {
737            $order_fulfillment_status = self::get_order_fulfillment_status( $order );
738        }
739
740        $order_stats_data = array(
741            'order_id'           => $order->get_id(),
742            'parent_id'          => $order->get_parent_id(),
743            'date_created'       => self::datetime_to_object( $order->get_date_created() ),
744            // 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.
745            'date_paid'          => $order instanceof WC_Order ? self::datetime_to_object( $order->get_date_paid() ) : null,
746            'date_completed'     => $order instanceof WC_Order ? self::datetime_to_object( $order->get_date_completed() ) : null,
747            'num_items_sold'     => self::get_num_items_sold( $order ),
748            'total_sales'        => $order->get_total(),
749            'tax_total'          => $order->get_total_tax(),
750            'total_fees'         => self::get_total_fees( $order ),
751            'total_fees_tax'     => self::get_total_fees_tax( $order ),
752            'shipping_total'     => $order->get_shipping_total(),
753            'shipping_tax'       => $order->get_shipping_tax(),
754            'discount_total'     => $order->get_discount_total(),
755            'discount_tax'       => $order->get_discount_tax(),
756            'net_total'          => self::get_net_total( $order ),
757            'returning_customer' => $order->is_returning_customer(),
758            'status'             => self::normalize_order_status( $order->get_status() ),
759            'customer_id'        => $order->get_report_customer_id(),
760            'fulfillment_status' => $order_fulfillment_status,
761        );
762
763        // Mirrors the refund block of WooCommerce's Orders\Stats\DataStore::update().
764        if ( 'shop_order_refund' === $order->get_type() ) {
765            $parent_order = wc_get_order( $order->get_parent_id() );
766            // Refunds attach to the original order. Skip if the parent is another refund.
767            if ( $parent_order && ! $parent_order instanceof WC_Order_Refund ) {
768                $order_stats_data['parent_id'] = $parent_order->get_id();
769                // Unlike core, keep the refund's own status: the WooCommerce Analytics plugin writes it back to core's row.
770
771                $refund_type               = $order->get_meta( '_refund_type' );
772                $uses_new_full_refund_data = self::uses_new_full_refund_data();
773                $use_parent_refund_amounts = $uses_new_full_refund_data && (
774                    'full' === $refund_type
775                    || self::should_split_full_refund_using_parent_order( $order, $parent_order )
776                );
777                if ( $use_parent_refund_amounts ) {
778                    $order_stats_data['num_items_sold'] = -1 * self::get_num_items_sold( $parent_order );
779                    $order_stats_data['tax_total']      = -1 * $parent_order->get_total_tax();
780                    $order_stats_data['net_total']      = -1 * self::get_net_total( $parent_order );
781                    $order_stats_data['shipping_total'] = -1 * (float) $parent_order->get_shipping_total();
782
783                    // Subtract what earlier refunds recorded, so this row only holds the remainder.
784                    foreach ( $parent_order->get_refunds() as $prior_refund ) {
785                        if ( $prior_refund->get_id() === $order->get_id() ) {
786                            continue;
787                        }
788                        $order_stats_data['num_items_sold'] -= self::get_num_items_sold( $prior_refund );
789                        $order_stats_data['tax_total']      -= (float) $prior_refund->get_total_tax();
790                        $order_stats_data['net_total']      -= self::get_net_total( $prior_refund );
791                        $order_stats_data['shipping_total'] -= (float) $prior_refund->get_shipping_total();
792                    }
793                }
794            }
795            // Refunds have no paid or completed date; backfill each from date_created, but only where the parent has it.
796            // Follow core's stored row when there is one: rows an older WooCommerce wrote keep their dates, and the checksum compares both.
797            $order_stats_item ??= $this->get_order_stats_item( $order->get_id() );
798            if ( $order_stats_item ) {
799                $has_date_completed = isset( $order_stats_item['date_completed'] );
800                $has_date_paid      = isset( $order_stats_item['date_paid'] );
801            } else {
802                $dates_follow_parent = $parent_order instanceof WC_Order && self::refund_dates_follow_parent();
803                $has_date_completed  = ! $dates_follow_parent || $parent_order->get_date_completed();
804                $has_date_paid       = ! $dates_follow_parent || $parent_order->get_date_paid();
805            }
806            $order_stats_data['date_completed'] = $has_date_completed ? $order_stats_data['date_created'] : null;
807            $order_stats_data['date_paid']      = $has_date_paid ? $order_stats_data['date_created'] : null;
808        }
809
810        return $order_stats_data;
811    }
812
813    /**
814     * Whether WooCommerce leaves a refund's paid and completed dates empty when its parent order has none.
815     *
816     * @return bool
817     */
818    private static function refund_dates_follow_parent() {
819        return defined( 'WC_VERSION' ) && version_compare( WC_VERSION, '11.2', '>=' );
820    }
821
822    /**
823     * Whether this refund is a single lump-sum refund for the full order. Copied from WooCommerce's Orders\Stats\DataStore, where it is protected.
824     *
825     * @param WC_Abstract_Order $refund       Refund order.
826     * @param WC_Abstract_Order $parent_order Parent order (not a refund).
827     * @return bool
828     */
829    private static function should_split_full_refund_using_parent_order( $refund, $parent_order ) {
830        // The parent must be the original order, not another refund.
831        if ( ! $parent_order instanceof WC_Order || 'shop_order_refund' === $parent_order->get_type() ) {
832            return false;
833        }
834
835        if ( self::get_num_items_sold( $refund ) > 0 ) {
836            return false;
837        }
838
839        $parent_refunds = $parent_order->get_refunds();
840        if ( 1 !== count( $parent_refunds ) ) {
841            return false;
842        }
843
844        $refund_total = wc_format_decimal( abs( (float) $refund->get_total() ) );
845        $order_total  = wc_format_decimal( (float) $parent_order->get_total() );
846
847        return $refund_total === $order_total;
848    }
849
850    /**
851     * Get the fulfillment status WooCommerce would store for the order, or null for none.
852     *
853     * @param WC_Order $order The order.
854     * @return string|null
855     */
856    private static function get_order_fulfillment_status( $order ) {
857        if ( ! FeaturesUtil::feature_is_enabled( 'fulfillments' ) ) {
858            return null;
859        }
860
861        // FulfillmentUtils moved namespace in WooCommerce 10.7.
862        $classes = array(
863            'Automattic\WooCommerce\Admin\Features\Fulfillments\FulfillmentUtils',
864            'Automattic\WooCommerce\Internal\Fulfillments\FulfillmentUtils',
865        );
866        foreach ( $classes as $class ) {
867            if ( is_callable( array( $class, 'get_order_fulfillment_status' ) ) ) {
868                $status = call_user_func( array( $class, 'get_order_fulfillment_status' ), $order );
869                return 'no_fulfillments' !== $status ? $status : null;
870            }
871        }
872
873        return null;
874    }
875
876    /**
877     * Check whether WooCommerce stores full refunds using the new data format.
878     *
879     * @return bool Whether the new full-refund data format is in use.
880     */
881    private static function uses_new_full_refund_data() {
882        if ( ! is_callable( array( OrderUtil::class, 'uses_new_full_refund_data' ) ) ) {
883            return false;
884        }
885
886        // @phan-suppress-next-line PhanUndeclaredStaticMethod -- Guarded by is_callable(); absent from the older WooCommerce stubs used by the "old Woo" Phan job.
887        return OrderUtil::uses_new_full_refund_data();
888    }
889
890    /**
891     * Calculation methods.
892     */
893
894    /**
895     * Get number of items sold among all orders.
896     *
897     * @param WC_Abstract_Order $order Order or refund.
898     * @return int
899     */
900    protected static function get_num_items_sold( $order ) {
901        $num_items = 0;
902
903        $line_items = $order->get_items( 'line_item' );
904        foreach ( $line_items as $line_item ) {
905            $num_items += $line_item->get_quantity();
906        }
907
908        return $num_items;
909    }
910
911    /**
912     * Get the net amount from an order without shipping, tax, or refunds.
913     *
914     * @param WC_Abstract_Order $order Order or refund.
915     * @return float
916     */
917    protected static function get_net_total( $order ) {
918        $net_total = floatval( $order->get_total() ) - floatval( $order->get_total_tax() ) - floatval( $order->get_shipping_total() );
919        return $net_total;
920    }
921
922    /**
923     * Get the total fees from an order.
924     *
925     * @param WC_Abstract_Order $order Order or refund.
926     * @return float
927     */
928    protected static function get_total_fees( $order ) {
929        // Added in WooCommerce 4.0; the fallback mirrors WC_Abstract_Order::get_total_fees().
930        if ( method_exists( $order, 'get_total_fees' ) ) {
931            return $order->get_total_fees();
932        }
933
934        return array_reduce(
935            $order->get_fees(),
936            function ( $carry, $item ) {
937                return $carry + (float) $item->get_total();
938            },
939            0.0
940        );
941    }
942
943    /**
944     * Get the total fees tax from an order.
945     *
946     * @param WC_Abstract_Order $order Order or refund.
947     * @return float
948     */
949    protected static function get_total_fees_tax( $order ) {
950        $total_fees_tax = array_sum(
951            array_map(
952                function ( $item ) {
953                    return $item->get_total_tax();
954                },
955                array_values( $order->get_items( 'fee' ) )
956            )
957        );
958
959        return $total_fees_tax;
960    }
961
962    /**
963     * Get the order stats row for a given order ID.
964     *
965     * @param int $order_id The order ID.
966     * @return array|null|void Database query result in format specified by $output or null on failure.
967     */
968    private function get_order_stats_item( $order_id ) {
969        global $wpdb;
970
971        $query = $wpdb->prepare(
972            "SELECT * FROM {$this->table()} WHERE order_id = %d", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
973            $order_id
974        );
975
976        return $wpdb->get_row( $query, ARRAY_A ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
977    }
978
979    /**
980     * Get the order stats rows for a given order IDs.
981     *
982     * @param array $order_ids The order IDs.
983     * @return array|null Database query result in format specified by $output or null on failure.
984     */
985    private function get_order_stats_items( $order_ids ) {
986        global $wpdb;
987
988        $placeholders = implode( ',', array_fill( 0, count( $order_ids ), '%d' ) );
989        $query        = $wpdb->prepare(
990            "SELECT * FROM {$this->table()} WHERE order_id IN ( $placeholders )", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
991            $order_ids
992        );
993
994        return $wpdb->get_results( $query, ARRAY_A ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
995    }
996
997    /**
998     * Get the order as WooCommerce Analytics' order class, which adds the report methods used here.
999     *
1000     * WooCommerce swaps that class in only while Analytics is enabled, and an object cache can outlive the switch.
1001     *
1002     * @param WC_Abstract_Order|false $order The order object.
1003     * @return WC_Abstract_Order|false The order with report methods, or false if it cannot have them.
1004     */
1005    private static function get_analytics_order( $order ) {
1006        if ( ! $order || method_exists( $order, 'get_report_customer_id' ) ) {
1007            return $order;
1008        }
1009
1010        // Mirrors the exact-class check in WooCommerce's order_class_name filters, which leave subclasses alone.
1011        $analytics_class = self::$analytics_order_classes[ get_class( $order ) ] ?? null;
1012        if ( null === $analytics_class || ! class_exists( $analytics_class ) ) {
1013            return false;
1014        }
1015
1016        return new $analytics_class( $order->get_id() );
1017    }
1018
1019    /**
1020     * Query orders, loading them as WooCommerce Analytics' order classes even while Analytics is disabled.
1021     *
1022     * @param array $query_args Arguments for wc_get_orders().
1023     * @return WC_Order[]|\stdClass What wc_get_orders() returns.
1024     */
1025    private static function get_analytics_orders( $query_args ) {
1026        $added_callbacks = array();
1027        foreach ( self::$analytics_order_classes as $analytics_class ) {
1028            $callback = array( $analytics_class, 'order_class_name' );
1029            // Only add, and later remove, what WooCommerce has not, or its own filter goes with it.
1030            if ( class_exists( $analytics_class ) && false === has_filter( 'woocommerce_order_class', $callback ) ) {
1031                add_filter( 'woocommerce_order_class', $callback, 10, 3 );
1032                $added_callbacks[] = $callback;
1033            }
1034        }
1035
1036        try {
1037            return wc_get_orders( $query_args );
1038        } finally {
1039            foreach ( $added_callbacks as $callback ) {
1040                remove_filter( 'woocommerce_order_class', $callback, 10 );
1041            }
1042        }
1043    }
1044
1045    /**
1046     * Check if the COGS feature is enabled.
1047     *
1048     * @return bool True if the COGS feature is enabled, false otherwise.
1049     */
1050    private function is_cogs_enabled() {
1051        return FeaturesUtil::feature_is_enabled( 'cost_of_goods_sold' );
1052    }
1053
1054    /**
1055     * Get order product lookup data.
1056     *
1057     * @param mixed $order The order ID or the WC_Order object.
1058     * @return array|bool The order product data or false if no data exists.
1059     */
1060    protected function get_order_product_data( $order ) {
1061        if ( is_numeric( $order ) ) {
1062            $order_id = $order;
1063            $order    = wc_get_order( $order );
1064        } elseif ( $order instanceof WC_Abstract_Order ) {
1065            $order_id = $order->get_id();
1066        } else {
1067            return false;
1068        }
1069
1070        // If the order does not exist or cannot have report methods, read its lookup rows instead.
1071        $order = self::get_analytics_order( $order );
1072        if ( ! $order ) {
1073            return $this->get_order_product_data_from_db( $order_id );
1074        }
1075
1076        // Get the order product data from the order object.
1077        $order_products = $order->get_items( 'line_item' );
1078
1079        if ( empty( $order_products ) ) {
1080            // Not a common use case, but there could be a case where this returns empty.
1081            return $this->get_order_product_data_from_db( $order_id );
1082        }
1083
1084        $is_refund_order = $this->is_refund_order( $order_id );
1085        $round_tax       = 'no' === get_option( 'woocommerce_tax_round_at_subtotal' );
1086        $decimals        = wc_get_price_decimals();
1087
1088        $results = array();
1089        foreach ( $order_products as $order_product ) {
1090            $shipping_amount     = $order->get_item_shipping_amount( $order_product );
1091            $shipping_tax_amount = $order->get_item_shipping_tax_amount( $order_product );
1092            $coupon_amount       = $order->get_item_coupon_amount( $order_product );
1093            // Tax amount.
1094            $tax_amount  = 0;
1095            $order_taxes = $order->get_taxes();
1096            $tax_data    = $order_product->get_taxes();
1097            foreach ( $order_taxes as $tax_item ) {
1098                $tax_item_id = $tax_item->get_rate_id();
1099                $tax_amount += isset( $tax_data['total'][ $tax_item_id ] ) ? (float) $tax_data['total'][ $tax_item_id ] : 0;
1100            }
1101
1102            $net_revenue = round( $order_product->get_total( 'edit' ), $decimals );
1103            if ( $round_tax ) {
1104                $tax_amount = round( $tax_amount, $decimals );
1105            }
1106
1107            $product_id  = $order_product->get_product_id();
1108            $cogs_amount = $this->get_order_product_cogs_value( $order_product );
1109
1110            $product_data = array(
1111                'order_id'              => $order_id,
1112                'order_item_id'         => $order_product->get_id(),
1113                'product_id'            => $product_id,
1114                'variation_id'          => $order_product->get_variation_id(),
1115                'product_qty'           => $order_product->get_quantity(),
1116                'product_net_revenue'   => $net_revenue,
1117                'product_gross_revenue' => $net_revenue + $tax_amount + $shipping_amount + $shipping_tax_amount,
1118                'shipping_amount'       => $shipping_amount,
1119                'shipping_tax_amount'   => $shipping_tax_amount,
1120                'coupon_amount'         => $coupon_amount,
1121                'tax_amount'            => $tax_amount,
1122                'customer_id'           => $order->get_report_customer_id(),
1123                'date_created'          => self::datetime_to_object( $order->get_date_created() ),
1124                'cogs_amount'           => $this->get_signed_cogs_amount( $cogs_amount, $is_refund_order ),
1125            );
1126
1127            $results[] = $product_data;
1128        }
1129
1130        return $results;
1131    }
1132
1133    /**
1134     * Get COGS value for an order product.
1135     *
1136     * @param object|false $order_product The order product object, or false if it no longer exists.
1137     * @return float|null The COGS amount or null if not available.
1138     */
1139    private function get_order_product_cogs_value( $order_product ) {
1140        if ( ! is_object( $order_product ) || ! method_exists( $order_product, 'get_cogs_value' ) || ! $this->is_cogs_enabled() ) {
1141            return null;
1142        }
1143
1144        $cogs_amount = $order_product->get_cogs_value();
1145
1146        // Only fallback to product's COGS value if order product's COGS is null (not set).
1147        if ( null === $cogs_amount ) {
1148            $product_id = $order_product->get_product_id();
1149            $product    = wc_get_product( $product_id );
1150
1151            if ( $product && method_exists( $product, 'get_cogs_value' ) ) {
1152                $product_cogs_value = $product->get_cogs_value();
1153                if ( null !== $product_cogs_value ) {
1154                    $cogs_amount = $product_cogs_value;
1155                }
1156            }
1157        }
1158
1159        return $cogs_amount;
1160    }
1161
1162    /**
1163     * Negate a COGS amount for refund orders, keeping null as "no COGS value".
1164     *
1165     * @param float|null $cogs_amount     The COGS amount.
1166     * @param bool       $is_refund_order Whether the order is a refund.
1167     * @return float|null The signed COGS amount, or null if not available.
1168     */
1169    private function get_signed_cogs_amount( $cogs_amount, $is_refund_order ) {
1170        if ( null === $cogs_amount || ! $is_refund_order ) {
1171            return $cogs_amount;
1172        }
1173
1174        return -abs( $cogs_amount );
1175    }
1176
1177    /**
1178     * Get order product lookup data from database.
1179     *
1180     * @param int $order_id The order ID.
1181     * @return array|bool The order product data or false if no data exists.
1182     */
1183    protected function get_order_product_data_from_db( $order_id ) {
1184        $results = $this->get_order_lookup_data_from_db( 'wc_order_product_lookup', $order_id );
1185
1186        if ( empty( $results ) ) {
1187            return false;
1188        }
1189
1190        $is_refund_order = $this->is_refund_order( $order_id );
1191
1192        $parsed_results = array();
1193        foreach ( $results as $result ) {
1194            $order_item  = WC_Order_Factory::get_order_item( absint( $result['order_item_id'] ) );
1195            $cogs_amount = $this->get_order_product_cogs_value( $order_item );
1196
1197            $product_data = array(
1198                'date_created'          => self::datetime_to_object( $result['date_created'] ),
1199                'product_net_revenue'   => floatval( $result['product_net_revenue'] ),
1200                'product_gross_revenue' => floatval( $result['product_gross_revenue'] ),
1201                'shipping_amount'       => floatval( $result['shipping_amount'] ),
1202                'shipping_tax_amount'   => floatval( $result['shipping_tax_amount'] ),
1203                'product_qty'           => intval( $result['product_qty'] ),
1204                'variation_id'          => intval( $result['variation_id'] ),
1205                'product_id'            => intval( $result['product_id'] ),
1206                'customer_id'           => intval( $result['customer_id'] ),
1207                'coupon_amount'         => floatval( $result['coupon_amount'] ),
1208                'tax_amount'            => floatval( $result['tax_amount'] ),
1209                'order_item_id'         => intval( $result['order_item_id'] ),
1210                'order_id'              => intval( $result['order_id'] ),
1211                'cogs_amount'           => $this->get_signed_cogs_amount( $cogs_amount, $is_refund_order ),
1212            );
1213
1214            $parsed_results[] = $product_data;
1215        }
1216
1217        return $parsed_results;
1218    }
1219
1220    /**
1221     * Check if the order is a refund order.
1222     *
1223     * @param int $order_id The order ID.
1224     * @return bool True if the order is a refund order, false otherwise.
1225     */
1226    private function is_refund_order( $order_id ) {
1227        $order_stats_data = $this->get_order_stats_item( $order_id );
1228
1229        if ( ! $order_stats_data || empty( $order_stats_data['parent_id'] ) ) {
1230            return false;
1231        }
1232
1233        $parent_id               = $order_stats_data['parent_id'];
1234        $parent_order_stats_data = $this->get_order_stats_item( $parent_id );
1235
1236        if ( ! $parent_order_stats_data || empty( $parent_order_stats_data['status'] ) ) {
1237            return false;
1238        }
1239
1240        // OrderInternalStatus is unavailable before WooCommerce 9.5.
1241        return 'wc-refunded' === $parent_order_stats_data['status'];
1242    }
1243
1244    /**
1245     * Get order coupon lookup data.
1246     *
1247     * @param mixed $order The order ID or the WC_Order object.
1248     * @return array|bool The order coupon data or false if no data exists.
1249     */
1250    protected function get_order_coupon_data( $order ) {
1251        if ( is_numeric( $order ) ) {
1252            $order_id = $order;
1253            $order    = wc_get_order( $order );
1254        } elseif ( $order instanceof WC_Abstract_Order ) {
1255            $order_id = $order->get_id();
1256        } else {
1257            return false;
1258        }
1259
1260        // If the order does not exist, check if coupon lookup data exists in the database.
1261        if ( ! $order ) {
1262            return $this->get_order_coupon_data_from_db( $order_id );
1263        }
1264
1265        // Get the order coupon data from the order object.
1266        $order_coupons = $order->get_coupons();
1267
1268        $results = array();
1269        foreach ( $order_coupons as $coupon ) {
1270            $results[] = array(
1271                'order_id'        => $order_id,
1272                'coupon_id'       => CouponsDataStore::get_coupon_id( $coupon ),
1273                'discount_amount' => $coupon->get_discount(),
1274                'date_created'    => self::datetime_to_object( $order->get_date_created() ),
1275                'coupon_code'     => $coupon->get_code(),
1276            );
1277        }
1278
1279        return $results;
1280    }
1281
1282    /**
1283     * Get order coupon lookup data from database.
1284     *
1285     * @param int $order_id The order ID.
1286     * @return array|bool The order coupon data or false if no data exists.
1287     */
1288    protected function get_order_coupon_data_from_db( $order_id ) {
1289        $results = $this->get_order_lookup_data_from_db( 'wc_order_coupon_lookup', $order_id );
1290
1291        if ( empty( $results ) ) {
1292            return false;
1293        }
1294
1295        $parsed_results = array();
1296        foreach ( $results as $result ) {
1297            $result_data                = array(
1298                'date_created'    => self::datetime_to_object( $result['date_created'] ),
1299                'discount_amount' => floatval( $result['discount_amount'] ),
1300                'order_id'        => intval( $result['order_id'] ),
1301                'coupon_id'       => intval( $result['coupon_id'] ),
1302            );
1303            $coupon                     = new WC_Coupon( absint( $result['coupon_id'] ) );
1304            $result_data['coupon_code'] = $coupon->get_code();
1305            $parsed_results[]           = $result_data;
1306        }
1307
1308        return $parsed_results;
1309    }
1310
1311    /**
1312     * Get order tax lookup data.
1313     *
1314     * @param mixed $order The order ID or the WC_Order object.
1315     * @return array|bool The order tax data or false if no data exists.
1316     */
1317    protected function get_order_tax_data( $order ) {
1318        if ( is_numeric( $order ) ) {
1319            $order_id = $order;
1320            $order    = wc_get_order( $order );
1321        } elseif ( $order instanceof WC_Abstract_Order ) {
1322            $order_id = $order->get_id();
1323        } else {
1324            return false;
1325        }
1326
1327        // If the order does not exist, check if tax lookup data exists in the database.
1328        if ( ! $order ) {
1329            return $this->get_order_tax_data_from_db( $order_id );
1330        }
1331
1332        // Get the order tax data from the order object.
1333        $order_taxes = $order->get_taxes();
1334
1335        $results = array();
1336        foreach ( $order_taxes as $tax ) {
1337            $order_tax    = (float) $tax->get_tax_total();
1338            $shipping_tax = (float) $tax->get_shipping_tax_total();
1339            $results[]    = array(
1340                'order_id'      => $order_id,
1341                'tax_rate_id'   => $tax->get_rate_id(),
1342                'order_tax'     => $order_tax,
1343                'shipping_tax'  => $shipping_tax,
1344                'total_tax'     => $order_tax + $shipping_tax,
1345                'date_created'  => self::datetime_to_object( $order->get_date_created() ),
1346                'tax_rate_code' => $tax->get_rate_code(),
1347            );
1348        }
1349
1350        return $results;
1351    }
1352
1353    /**
1354     * Get order tax lookup data from database.
1355     *
1356     * @param int $order_id The order ID.
1357     * @return array|bool The order tax data or false if no data exists.
1358     */
1359    protected function get_order_tax_data_from_db( $order_id ) {
1360        $results = $this->get_order_lookup_data_from_db( 'wc_order_tax_lookup', $order_id );
1361
1362        if ( empty( $results ) ) {
1363            return false;
1364        }
1365
1366        $parsed_results = array();
1367        foreach ( $results as $result ) {
1368            $result_data      = array(
1369                'date_created'  => self::datetime_to_object( $result['date_created'] ),
1370                'order_tax'     => floatval( $result['order_tax'] ),
1371                'total_tax'     => floatval( $result['total_tax'] ),
1372                'shipping_tax'  => floatval( $result['shipping_tax'] ),
1373                'order_id'      => intval( $result['order_id'] ),
1374                'tax_rate_id'   => intval( $result['tax_rate_id'] ),
1375                'tax_rate_code' => WC_Tax::get_rate_code( $result['tax_rate_id'] ) ?? '',
1376            );
1377            $parsed_results[] = $result_data;
1378        }
1379
1380        return $parsed_results;
1381    }
1382
1383    /**
1384     * Get order lookup data from database.
1385     *
1386     * @param string $table_name The name of the table.
1387     * @param int    $order_id The order ID.
1388     * @return array|bool The order lookup data or false if no data exists.
1389     */
1390    protected function get_order_lookup_data_from_db( $table_name, $order_id ) {
1391        global $wpdb;
1392
1393        // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
1394        $query = $wpdb->prepare(
1395            "SELECT * FROM {$wpdb->prefix}{$table_name} WHERE order_id = %d",
1396            $order_id
1397        );
1398        // phpcs:enable
1399
1400        // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
1401        $results = $wpdb->get_results( $query, ARRAY_A );
1402
1403        if ( empty( $results ) ) {
1404            return false;
1405        }
1406
1407        return $results;
1408    }
1409
1410    /**
1411     * Get the order stats data from the database.
1412     *
1413     * @param int $order_id The order ID.
1414     * @return array|bool The order stats data or false if the order stats item does not exist.
1415     */
1416    private function get_order_stats_data_from_db( $order_id ) {
1417        $order_stats_data = $this->get_order_stats_item( $order_id );
1418
1419        if ( ! $order_stats_data ) {
1420            return false;
1421        }
1422
1423        // Convert date strings to datetime objects.
1424        $order_stats_data['date_created']   = self::datetime_to_object( $order_stats_data['date_created'] );
1425        $order_stats_data['date_completed'] = self::datetime_to_object( $order_stats_data['date_completed'] ?? null );
1426        $order_stats_data['date_paid']      = self::datetime_to_object( $order_stats_data['date_paid'] ?? null );
1427
1428        return $order_stats_data;
1429    }
1430
1431    /**
1432     * Perform an order status discrepancy check between the order object and the item in the wc_order_stats table.
1433     *
1434     * @param WC_Order $order WC_Order object.
1435     * @param array    $order_stats_item The order stats item.
1436     *
1437     * @return void
1438     */
1439    private function do_order_status_discrepancy_check( $order, $order_stats_item = array() ) {
1440        if ( ! $order instanceof WC_Abstract_Order ) {
1441            return;
1442        }
1443
1444        $order_id = $order->get_id();
1445
1446        // If the order_stats_item is empty, then fetch it from the wc_order_stats table.
1447        if ( empty( $order_stats_item ) ) {
1448            $order_stats_item = $this->get_order_stats_data_from_db( $order_id );
1449        }
1450
1451        // Check for discrepancy in the order status. Happens in old orders that were not updated and hence the OrderStatsFixer did not run.
1452        $normalized_order_status = self::normalize_order_status( $order->get_status() );
1453        if ( $order_stats_item && $normalized_order_status !== $order_stats_item['status'] ) {
1454            /**
1455             * Trigger the action to fix the order stats. The OrderStatusFixer should be hooked to this action.
1456             *
1457             * @param int $order_id The order ID.
1458             */
1459            do_action( 'woocommerce_analytics_incorrect_order_status_detected', $order_id );
1460        }
1461    }
1462
1463    /**
1464     * Maps an order status to the value used in the database.
1465     *
1466     * @param string $status Order status.
1467     * @return string
1468     */
1469    protected static function normalize_order_status( $status ) {
1470        return WooCommerce_HPOS_Orders::get_wc_order_status_with_prefix( str_replace( 'wc-', '', $status ) );
1471    }
1472
1473    /**
1474     * Convert a WooCommerce datetime to an object for encoding.
1475     *
1476     * @param WC_DateTime|mixed $wc_datetime The datetime object.
1477     * @return object|null
1478     */
1479    protected static function datetime_to_object( $wc_datetime ) {
1480        if ( is_string( $wc_datetime ) ) {
1481            $wc_datetime = new WC_DateTime( $wc_datetime, self::get_site_datetimezone() );
1482        }
1483
1484        if ( $wc_datetime instanceof \WC_DateTime ) {
1485            $wc_datetime->setTimezone( self::get_site_datetimezone() );
1486            $date_properties = (array) $wc_datetime;
1487
1488            // Remove protected properties, whose NUL-prefixed names cannot be processed by the receiver.
1489            foreach ( array_keys( $date_properties ) as $property_name ) {
1490                if ( false !== strpos( $property_name, "\0" ) ) {
1491                    unset( $date_properties[ $property_name ] );
1492                }
1493            }
1494
1495            return (object) $date_properties;
1496        }
1497    }
1498
1499    /**
1500     * Convert seconds to an ISO 8601 timezone offset.
1501     *
1502     * @param int|float $offset_seconds The timezone offset in seconds.
1503     * @return string The ISO 8601 timezone offset.
1504     */
1505    protected static function format_utc_offset( $offset_seconds ) {
1506        $hours   = intval( abs( $offset_seconds ) / HOUR_IN_SECONDS );
1507        $minutes = intval( ( abs( $offset_seconds ) % HOUR_IN_SECONDS ) / MINUTE_IN_SECONDS );
1508        $sign    = $offset_seconds >= 0 ? '+' : '-';
1509
1510        return sprintf( '%s%02d:%02d', $sign, $hours, $minutes );
1511    }
1512
1513    /**
1514     * Get the site timezone as a fixed offset.
1515     *
1516     * @return DateTimeZone The site timezone.
1517     */
1518    protected static function get_site_datetimezone() {
1519        return new DateTimeZone( self::format_utc_offset( wc_timezone_offset() ) );
1520    }
1521}