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