Commit 8a143438296 for woocommerce
commit 8a143438296ed96e298f8f64f65cb25cea0da01c
Author: louwie17 <lourensschep@gmail.com>
Date: Fri Dec 4 11:17:51 2026 +0100
Expose the order stats row calculation as a public method (#69399)
* Expose the order stats row calculation as a public method
Split Orders Stats DataStore::update() so the row it writes is built by
the new public get_order_stats_row_data(). Integrations such as the
Jetpack sync module can call it instead of keeping their own copy.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MJBgApoVUo1PMA1a1oDxwf
* Build the order stats row from the order passed in, without side effects
Reading the row no longer reloads the order, so unsaved changes and
custom order classes are kept, and it no longer rewrites the returning
customer flags of the customer's other orders. update() keeps its
existing writes and its handling of non-array filter results.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MJBgApoVUo1PMA1a1oDxwf
* Return false for a non-array filter result before the refund adjustments
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MJBgApoVUo1PMA1a1oDxwf
* Skip records the import conditions exclude when building the order stats row
update() gained an import-conditions check in #69031. Apply the same check in
get_order_stats_row_data() so it still returns false wherever update() writes
no row, and move its @since to 11.5.0, the current trunk version.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015zLZv1EBMpYLwN6oYL5sJF
* Return no stats row for orders the Analytics import skips
Address review feedback on get_order_stats_row_data():
- Return false for non-order types and for trashed records Analytics does not
hold yet, as OrdersScheduler::import() skips both.
- Do not create a customer lookup row for a guest order without a billing
email. Nothing could match it again, so every read and the later import
would each add one.
- Test the failed exclusion check, the new skips, and fixed fixture values.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015zLZv1EBMpYLwN6oYL5sJF
* Fix assignment alignment lint warning in the order stats data store test
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015zLZv1EBMpYLwN6oYL5sJF
* Share the Analytics import skip rules with the order stats row read path
Address review feedback:
- Move import()'s skip rules into OrdersScheduler::get_import_skip_reason(), and
use it in get_order_stats_row_data() instead of a copy of each rule, so a new
skip rule applies to both. import() keeps its own logging and failed-list
handling per reason.
- Assert the customer ID in the row test, including a plain refund's parent.
- Document the site-timezone dates, the guest customer case, the failed
exclusion check and the read path in the method, update() and filter docblocks.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015zLZv1EBMpYLwN6oYL5sJF
* Read the customer from the saved order and skip deleted orders in the stats row
Address review feedback:
- get_order_stats_row_data() reloads the saved order or refund and returns false
when it no longer exists, instead of throwing in the customer lookup.
- It resolves the customer from that saved order for every order class, so an
unsaved billing email on an Analytics order no longer creates a customer.
- The row builder returns the column formats with the row, so update() uses one
fulfillment and payment method decision for both, as before this PR.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015zLZv1EBMpYLwN6oYL5sJF
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
diff --git a/plugins/woocommerce/changelog/wooa7s-2260-expose-order-stats-row-data b/plugins/woocommerce/changelog/wooa7s-2260-expose-order-stats-row-data
new file mode 100644
index 00000000000..f7fd4623748
--- /dev/null
+++ b/plugins/woocommerce/changelog/wooa7s-2260-expose-order-stats-row-data
@@ -0,0 +1,4 @@
+Significance: minor
+Type: dev
+
+Add `get_order_stats_row_data()` to the Analytics Orders Stats data store, so integrations can build an order's stats row without saving it.
diff --git a/plugins/woocommerce/phpstan-baseline.neon b/plugins/woocommerce/phpstan-baseline.neon
index 023c5aa452e..d591ffe69a1 100644
--- a/plugins/woocommerce/phpstan-baseline.neon
+++ b/plugins/woocommerce/phpstan-baseline.neon
@@ -40399,18 +40399,6 @@ parameters:
count: 1
path: src/Admin/API/Reports/Orders/Stats/DataStore.php
- -
- message: '#^Parameter \#1 \$customer_id of static method Automattic\\WooCommerce\\Admin\\API\\Reports\\Customers\\DataStore\:\:get_oldest_orders\(\) expects int, int\<min, \-1\>\|int\<1, max\>\|true given\.$#'
- identifier: argument.type
- count: 1
- path: src/Admin/API/Reports/Orders/Stats/DataStore.php
-
- -
- message: '#^Parameter \#1 \$customer_id of static method Automattic\\WooCommerce\\Admin\\API\\Reports\\Orders\\Stats\\DataStore\:\:set_customer_first_order\(\) expects int, int\<min, \-1\>\|int\<1, max\>\|true given\.$#'
- identifier: argument.type
- count: 2
- path: src/Admin/API/Reports/Orders/Stats/DataStore.php
-
-
message: '#^Parameter \#1 \$order of static method Automattic\\WooCommerce\\Admin\\API\\Reports\\Customers\\DataStore\:\:get_existing_customer_id_from_order\(\) expects object, WC_Order\|WC_Order_Refund\|false given\.$#'
identifier: argument.type
diff --git a/plugins/woocommerce/src/Admin/API/Reports/Orders/Stats/DataStore.php b/plugins/woocommerce/src/Admin/API/Reports/Orders/Stats/DataStore.php
index 6b7850d343a..91aaf0d5cd7 100644
--- a/plugins/woocommerce/src/Admin/API/Reports/Orders/Stats/DataStore.php
+++ b/plugins/woocommerce/src/Admin/API/Reports/Orders/Stats/DataStore.php
@@ -20,6 +20,8 @@ use Automattic\WooCommerce\Utilities\OrderUtil;
use Automattic\WooCommerce\Admin\API\Reports\StatsDataStoreTrait;
use Automattic\WooCommerce\Utilities\FeaturesUtil;
use stdClass;
+use WC_Abstract_Order;
+use WC_DateTime;
use WC_Order;
use WC_Order_Refund;
use Automattic\WooCommerce\Admin\Overrides\Order;
@@ -530,21 +532,14 @@ class DataStore extends ReportsDataStore implements DataStoreInterface {
/**
* Update the database with stats data.
*
- * @param Order|OrderRefund $order Order or refund to update row for.
+ * @param WC_Order|WC_Order_Refund $order Order or refund to update row for.
* @return int|bool Returns -1 if order won't be processed, or a boolean indicating processing success.
*/
public static function update( $order ) {
global $wpdb;
- $table_name = self::get_db_table_name();
-
- if ( ! $order->get_id() || ! $order->get_date_created() ) {
- return -1;
- }
- // Exclude test orders (e.g., WCPay test mode) from analytics stats.
- // Defense-in-depth: also checked in OrdersScheduler::import(), but
- // update() can be called directly outside of the import flow.
- if ( OrdersScheduler::is_test_order( $order ) ) {
+ $date_created = self::get_tracked_order_date_created( $order );
+ if ( ! $date_created ) {
return -1;
}
@@ -558,40 +553,122 @@ class DataStore extends ReportsDataStore implements DataStoreInterface {
return -1;
}
- $format = array(
- '%d',
- '%d',
- '%s',
- '%s',
- '%s',
- '%s',
- '%d',
- '%f',
- '%f',
- '%f',
- '%f',
- '%s',
- '%d',
- '%d',
- );
+ list( $data, $format ) = self::build_order_stats_row( $order, $date_created, self::get_report_customer_id( $order ), true );
+
+ // Update or add the information to the DB.
+ $result = $wpdb->replace( self::get_db_table_name(), $data, $format );
+
+ /**
+ * Fires when order's stats reports are updated.
+ *
+ * @param int $order_id Order ID.
+ *
+ * @since 4.0.0.
+ */
+ do_action( 'woocommerce_analytics_update_order_stats', $order->get_id() );
+
+ // Check the rows affected for success. Using REPLACE can affect 2 rows if the row already exists.
+ return ( 1 === $result || 2 === $result );
+ }
+
+ /**
+ * Get the wc_order_stats row for an order or refund, as update() writes it.
+ *
+ * Includes the `woocommerce_analytics_update_order_stats_data` filter and the refund adjustments.
+ * Like update(), it adds the order's customer to the customer lookup table if missing, except for a guest
+ * order without a billing email, whose `customer_id` stays empty until the order is imported. It leaves
+ * the stats rows of the customer's other orders unchanged. Customer fields use the saved order. Dates are
+ * in the site's timezone, as stored.
+ *
+ * @since 11.5.0
+ *
+ * @param WC_Order|WC_Order_Refund $order Order or refund to build the row for.
+ * @return array|false Row data keyed by column name, or false when the Analytics import would not store a row for it,
+ * the import exclusion check fails, or the order no longer exists.
+ */
+ public static function get_order_stats_row_data( $order ) {
+ $date_created = $order instanceof WC_Abstract_Order ? $order->get_date_created() : null;
+ if ( ! $date_created || null !== OrdersScheduler::get_import_skip_reason( $order ) ) {
+ return false;
+ }
+
+ $saved_order = wc_get_order( $order->get_id() );
+ if ( ! $saved_order instanceof WC_Abstract_Order ) {
+ return false;
+ }
+
+ list( $data ) = self::build_order_stats_row( $order, $date_created, self::get_saved_customer_id( $saved_order ), false );
+
+ return is_array( $data ) ? $data : false;
+ }
+
+ /**
+ * Get the creation date of an order or refund that analytics tracks.
+ *
+ * @param mixed $order Order or refund.
+ * @return WC_DateTime|null Null for unsaved orders, orders without a creation date, and test orders.
+ */
+ private static function get_tracked_order_date_created( $order ): ?WC_DateTime {
+ if ( ! $order instanceof WC_Abstract_Order || ! $order->get_id() ) {
+ return null;
+ }
+
+ $date_created = $order->get_date_created();
+ if ( ! $date_created ) {
+ return null;
+ }
+
+ // Exclude test orders (e.g., WCPay test mode) from analytics stats.
+ // Defense-in-depth: also checked in OrdersScheduler::import(), but
+ // update() can be called directly outside of the import flow.
+ if ( OrdersScheduler::is_test_order( $order ) ) {
+ return null;
+ }
+
+ return $date_created;
+ }
+
+ /**
+ * Build the stats row for an order or refund, running the order stats data filter.
+ *
+ * @param WC_Order|WC_Order_Refund $order Order or refund.
+ * @param WC_DateTime $date_created The order's creation date.
+ * @param int|bool $customer_id The order's customer lookup ID, or false when there is none.
+ * @param bool $for_update Whether update() will store the row. Only then does it fix up the
+ * returning-customer flags of the customer's other orders.
+ * @return array{0: mixed, 1: string[]} The row data, or whatever the filter returned, and the column formats for the unfiltered row.
+ */
+ private static function build_order_stats_row( $order, WC_DateTime $date_created, $customer_id, bool $for_update ): array {
+ if ( $for_update && method_exists( $order, 'is_returning_customer' ) ) {
+ $returning_customer = $order->is_returning_customer();
+ } elseif ( $order instanceof WC_Order_Refund ) {
+ // Refunds don't count towards returning customers.
+ $returning_customer = null;
+ } elseif ( $for_update ) {
+ $returning_customer = self::is_returning_customer( $order, $customer_id );
+ } else {
+ $returning_customer = self::get_returning_customer_status( $order, $customer_id )['is_returning'];
+ }
$data = array(
'order_id' => $order->get_id(),
'parent_id' => $order->get_parent_id(),
- 'date_created' => $order->get_date_created()->date( 'Y-m-d H:i:s' ),
+ 'date_created' => $date_created->date( 'Y-m-d H:i:s' ),
'date_paid' => $order->get_date_paid() ? $order->get_date_paid()->date( 'Y-m-d H:i:s' ) : null,
'date_completed' => $order->get_date_completed() ? $order->get_date_completed()->date( 'Y-m-d H:i:s' ) : null,
- 'date_created_gmt' => gmdate( 'Y-m-d H:i:s', $order->get_date_created()->getTimestamp() ),
+ 'date_created_gmt' => gmdate( 'Y-m-d H:i:s', $date_created->getTimestamp() ),
'num_items_sold' => self::get_num_items_sold( $order ),
'total_sales' => $order->get_total(),
'tax_total' => $order->get_total_tax(),
'shipping_total' => $order->get_shipping_total(),
'net_total' => self::get_net_total( $order ),
'status' => self::normalize_order_status( $order->get_status() ),
- 'customer_id' => $order->get_report_customer_id(),
- 'returning_customer' => $order->is_returning_customer(),
+ 'customer_id' => $customer_id,
+ 'returning_customer' => $returning_customer,
);
+ $format = array( '%d', '%d', '%s', '%s', '%s', '%s', '%d', '%f', '%f', '%f', '%f', '%s', '%d', '%d' );
+
if ( self::has_payment_method_column() ) {
// An order without a gateway is stored as NULL, the same as the backfill leaves it. A refund
// carries no payment method of its own; the refund branch below takes the parent's.
@@ -599,8 +676,7 @@ class DataStore extends ReportsDataStore implements DataStoreInterface {
$format[] = '%s';
}
- $order_fulfillment_status = '';
- if ( FeaturesUtil::feature_is_enabled( 'fulfillments' ) && true === self::has_fulfillment_status_column() && $order instanceof WC_Order ) {
+ if ( self::stores_fulfillment_status( $order ) ) {
$order_fulfillment_status = FulfillmentUtils::get_order_fulfillment_status( $order );
$data['fulfillment_status'] = ( 'no_fulfillments' !== $order_fulfillment_status ) ? $order_fulfillment_status : null;
$format[] = '%s';
@@ -609,13 +685,19 @@ class DataStore extends ReportsDataStore implements DataStoreInterface {
/**
* Filters order stats data.
*
- * @param array $data Data written to order stats lookup table.
- * @param Order|OrderRefund $order Order object.
+ * @param array $data Order stats row data. Also filtered when get_order_stats_row_data() builds a row without saving it.
+ * @param WC_Order|WC_Order_Refund $order Order object. The analytics import passes Overrides\Order or Overrides\OrderRefund.
+ * On the get_order_stats_row_data() path it may hold unsaved changes.
*
* @since 4.0.0
*/
$data = apply_filters( 'woocommerce_analytics_update_order_stats_data', $data, $order );
+ // The read path returns false rather than a malformed row. update() keeps passing the result through.
+ if ( ! $for_update && ! is_array( $data ) ) {
+ return array( false, $format );
+ }
+
if ( 'shop_order_refund' === $order->get_type() ) {
$parent_order = wc_get_order( $order->get_parent_id() );
// Refunds attach to the original order. Skip if the parent is another refund.
@@ -669,20 +751,65 @@ class DataStore extends ReportsDataStore implements DataStoreInterface {
$data['date_paid'] = $parent_is_order && ! $parent_order->get_date_paid() ? null : $data['date_created'];
}
- // Update or add the information to the DB.
- $result = $wpdb->replace( $table_name, $data, $format );
+ return array( $data, $format );
+ }
- /**
- * Fires when order's stats reports are updated.
- *
- * @param int $order_id Order ID.
- *
- * @since 4.0.0.
- */
- do_action( 'woocommerce_analytics_update_order_stats', $order->get_id() );
+ /**
+ * Get the customer lookup ID for an order or refund, creating the customer if missing.
+ *
+ * Uses the order's own get_report_customer_id() when it has one. A plain order, which wc_get_order() returns
+ * until OrdersScheduler is set up, gets the same lookup as Overrides\Order and Overrides\OrderRefund.
+ *
+ * @param WC_Order|WC_Order_Refund $order Order or refund.
+ * @return int|bool Customer ID, or false when there is none.
+ */
+ private static function get_report_customer_id( $order ) {
+ if ( method_exists( $order, 'get_report_customer_id' ) ) {
+ return $order->get_report_customer_id();
+ }
- // Check the rows affected for success. Using REPLACE can affect 2 rows if the row already exists.
- return ( 1 === $result || 2 === $result );
+ if ( $order instanceof WC_Order_Refund ) {
+ $order = wc_get_order( $order->get_parent_id() );
+ if ( ! $order instanceof WC_Order ) {
+ return false;
+ }
+ }
+
+ return CustomersDataStore::get_or_create_customer_from_order( $order );
+ }
+
+ /**
+ * Get the customer lookup ID for the read path from the saved order, creating the customer only when it can be found again.
+ *
+ * A guest order without a billing email has nothing to match a new customer on, so each read and the later import
+ * would each add one. For those, only a customer already linked through the order's stats row is used.
+ *
+ * @param WC_Abstract_Order $saved_order The order or refund as saved.
+ * @return int|bool Customer ID, or false when there is none.
+ */
+ private static function get_saved_customer_id( WC_Abstract_Order $saved_order ) {
+ $customer_order = $saved_order instanceof WC_Order_Refund ? wc_get_order( $saved_order->get_parent_id() ) : $saved_order;
+ if ( ! $customer_order instanceof WC_Order ) {
+ return false;
+ }
+
+ if ( ! $customer_order->get_customer_id() && ! $customer_order->get_billing_email( 'edit' ) ) {
+ return CustomersDataStore::get_existing_customer_id_from_order( $customer_order );
+ }
+
+ return CustomersDataStore::get_or_create_customer_from_order( $customer_order );
+ }
+
+ /**
+ * Whether the order's row includes the fulfillment_status column.
+ *
+ * @param WC_Order|WC_Order_Refund $order Order or refund.
+ * @return bool
+ *
+ * @phpstan-assert-if-true =WC_Order $order
+ */
+ private static function stores_fulfillment_status( $order ): bool {
+ return FeaturesUtil::feature_is_enabled( 'fulfillments' ) && true === self::has_fulfillment_status_column() && $order instanceof WC_Order;
}
/**
@@ -801,8 +928,8 @@ class DataStore extends ReportsDataStore implements DataStoreInterface {
/**
* Whether this refund is a single lump-sum refund for the full order (e.g. status set to refunded without line items).
*
- * @param WC_Order_Refund|OrderRefund|Order $refund Refund order.
- * @param WC_Order|Order $parent_order Parent order (not a refund).
+ * @param WC_Order_Refund|WC_Order $refund Refund order.
+ * @param WC_Order|Order $parent_order Parent order (not a refund).
* @return bool
*/
protected static function should_split_full_refund_using_parent_order( $refund, $parent_order ) {
@@ -918,8 +1045,8 @@ class DataStore extends ReportsDataStore implements DataStoreInterface {
/**
* Check to see if an order's customer has made previous orders or not
*
- * @param WC_Order $order WC_Order object.
- * @param int|false $customer_id Customer ID. Optional.
+ * @param WC_Order $order WC_Order object.
+ * @param int|bool|null $customer_id Customer ID, as the customer lookups return it. Optional.
* @return bool
*/
public static function is_returning_customer( $order, $customer_id = null ) {
@@ -927,14 +1054,36 @@ class DataStore extends ReportsDataStore implements DataStoreInterface {
$customer_id = \Automattic\WooCommerce\Admin\API\Reports\Customers\DataStore::get_existing_customer_id_from_order( $order );
}
+ $status = self::get_returning_customer_status( $order, $customer_id );
+ if ( null !== $status['first_order_id'] ) {
+ self::set_customer_first_order( (int) $customer_id, $status['first_order_id'] );
+ }
+
+ return $status['is_returning'];
+ }
+
+ /**
+ * Work out whether an order is from a returning customer, without changing any stats rows.
+ *
+ * @param WC_Order $order Order.
+ * @param int|bool $customer_id Customer ID.
+ * @return array{is_returning: bool, first_order_id: int|null} The flag, and the order that is now the customer's first, if that changed.
+ */
+ private static function get_returning_customer_status( $order, $customer_id ): array {
+ $not_returning = array(
+ 'is_returning' => false,
+ 'first_order_id' => null,
+ );
+
if ( ! $customer_id ) {
- return false;
+ return $not_returning;
}
+ $customer_id = (int) $customer_id;
$oldest_orders = \Automattic\WooCommerce\Admin\API\Reports\Customers\DataStore::get_oldest_orders( $customer_id );
if ( empty( $oldest_orders ) ) {
- return false;
+ return $not_returning;
}
$first_order = $oldest_orders[0];
@@ -955,8 +1104,10 @@ class DataStore extends ReportsDataStore implements DataStoreInterface {
);
if ( $is_older && ! in_array( $order_status, $excluded_statuses, true ) ) {
- self::set_customer_first_order( $customer_id, $order->get_id() );
- return false;
+ return array(
+ 'is_returning' => false,
+ 'first_order_id' => (int) $order->get_id(),
+ );
}
// The current order is the oldest known order.
@@ -969,11 +1120,16 @@ class DataStore extends ReportsDataStore implements DataStoreInterface {
$status_change = $second_order &&
in_array( $order_status, $excluded_statuses, true );
if ( $is_first_order && ( $date_change || $status_change ) ) {
- self::set_customer_first_order( $customer_id, $second_order->order_id );
- return true;
+ return array(
+ 'is_returning' => true,
+ 'first_order_id' => (int) $second_order->order_id,
+ );
}
- return (int) $order->get_id() !== (int) $first_order->order_id;
+ return array(
+ 'is_returning' => (int) $order->get_id() !== (int) $first_order->order_id,
+ 'first_order_id' => null,
+ );
}
/**
diff --git a/plugins/woocommerce/src/Internal/Admin/Schedulers/OrdersScheduler.php b/plugins/woocommerce/src/Internal/Admin/Schedulers/OrdersScheduler.php
index 57466396762..4f9fb0ff11b 100644
--- a/plugins/woocommerce/src/Internal/Admin/Schedulers/OrdersScheduler.php
+++ b/plugins/woocommerce/src/Internal/Admin/Schedulers/OrdersScheduler.php
@@ -63,6 +63,31 @@ class OrdersScheduler extends ImportScheduler {
*/
const SCHEDULED_IMPORT_OPTION = 'woocommerce_analytics_scheduled_import';
+ /**
+ * Skip reason: the record is not an order or refund with an ID and creation date.
+ */
+ private const SKIP_NOT_TRACKED = 'not_tracked';
+
+ /**
+ * Skip reason: the record is a test order (e.g., WCPay test mode).
+ */
+ private const SKIP_TEST_ORDER = 'test_order';
+
+ /**
+ * Skip reason: the `woocommerce_analytics_orders_import_where_clauses` conditions exclude the record.
+ */
+ private const SKIP_EXCLUDED = 'excluded';
+
+ /**
+ * Skip reason: the exclusion check failed, so whether the record is excluded is unknown.
+ */
+ private const SKIP_EXCLUSION_CHECK_FAILED = 'exclusion_check_failed';
+
+ /**
+ * Skip reason: the record is trashed and Analytics does not hold it yet.
+ */
+ private const SKIP_TRASHED = 'trashed';
+
/**
* Legacy option name before the rename in 10.5.0.
*
@@ -404,48 +429,26 @@ AND status NOT IN ( 'wc-auto-draft', 'trash', 'auto-draft' )
return;
}
- $type = $order->get_type();
-
- // If the order isn't the right type, skip sync.
- if ( 'shop_order' !== $type && 'shop_order_refund' !== $type ) {
- return;
- }
-
- // If the order has no id or date created, skip sync.
- if ( ! $order->get_id() || ! $order->get_date_created() ) {
- return;
- }
-
- // Skip test orders (e.g., WCPay test mode) from analytics.
- if ( self::is_test_order( $order ) ) {
+ $skip_reason = self::get_import_skip_reason( $order );
+ if ( self::SKIP_TEST_ORDER === $skip_reason ) {
wc_get_logger()->debug(
sprintf( 'Skipping test order #%d from analytics import.', $order_id ),
array( 'source' => 'wc-analytics-order-import' )
);
- return;
- }
-
- $excluded = self::is_excluded_from_import( (int) $order_id );
- if ( null === $excluded ) {
+ } elseif ( self::SKIP_EXCLUSION_CHECK_FAILED === $skip_reason ) {
// The exclusion is unknown, so neither import the record nor drop it: keep it on the list
// Analytics settings retries.
self::record_failed_order_import( $order_id );
- return;
- }
- if ( $excluded ) {
+ } elseif ( self::SKIP_EXCLUDED === $skip_reason ) {
// The record is excluded, so drop it from the list Analytics settings retries.
self::clear_failed_order_import( $order_id );
- return;
}
-
- // Skip trashed records Analytics does not already hold: importing one creates a
- // wc_customer_lookup row via Order::get_report_customer_id() that nothing removes
- // while the order stays trashed. Records trashed after being imported keep their
- // stats row, so their status still syncs.
- if ( OrderStatus::TRASH === $order->get_status() && ! self::has_order_stats_row( $order_id ) ) {
+ if ( null !== $skip_reason ) {
return;
}
+ $type = $order->get_type();
+
OrdersStatsDataStore::sync_order( $order_id );
ProductsDataStore::sync_order_products( $order_id );
CouponsDataStore::sync_order_coupons( $order_id );
@@ -483,6 +486,44 @@ AND status NOT IN ( 'wc-auto-draft', 'trash', 'auto-draft' )
do_action( 'woocommerce_order_scheduler_after_import_order', $order_id );
}
+ /**
+ * Get why the import would skip an order or refund, so code that builds Analytics rows outside it applies the same rules.
+ *
+ * @internal
+ *
+ * @since 11.5.0
+ *
+ * @param \WC_Abstract_Order $order Order or refund.
+ * @return string|null The skip reason, or null when the import stores the record.
+ */
+ public static function get_import_skip_reason( \WC_Abstract_Order $order ): ?string {
+ $type = $order->get_type();
+ if ( ( 'shop_order' !== $type && 'shop_order_refund' !== $type ) || ! $order->get_id() || ! $order->get_date_created() ) {
+ return self::SKIP_NOT_TRACKED;
+ }
+
+ if ( self::is_test_order( $order ) ) {
+ return self::SKIP_TEST_ORDER;
+ }
+
+ $excluded = self::is_excluded_from_import( (int) $order->get_id() );
+ if ( null === $excluded ) {
+ return self::SKIP_EXCLUSION_CHECK_FAILED;
+ }
+ if ( $excluded ) {
+ return self::SKIP_EXCLUDED;
+ }
+
+ // Importing a trashed record Analytics does not hold yet would create a wc_customer_lookup row via
+ // Order::get_report_customer_id() that nothing removes while the order stays trashed. Records trashed
+ // after being imported keep their stats row, so their status still syncs.
+ if ( OrderStatus::TRASH === $order->get_status() && ! self::has_order_stats_row( (int) $order->get_id() ) ) {
+ return self::SKIP_TRASHED;
+ }
+
+ return null;
+ }
+
/**
* Check whether an order or refund already has a row in the order stats table.
*
diff --git a/plugins/woocommerce/tests/php/src/Admin/API/Reports/Orders/Stats/DataStoreTest.php b/plugins/woocommerce/tests/php/src/Admin/API/Reports/Orders/Stats/DataStoreTest.php
index 614eae57863..a442da62e1e 100644
--- a/plugins/woocommerce/tests/php/src/Admin/API/Reports/Orders/Stats/DataStoreTest.php
+++ b/plugins/woocommerce/tests/php/src/Admin/API/Reports/Orders/Stats/DataStoreTest.php
@@ -3,8 +3,11 @@ declare( strict_types = 1 );
namespace Automattic\WooCommerce\Tests\Admin\API\Reports\Orders\Stats;
+use Automattic\WooCommerce\Admin\API\Reports\Customers\DataStore as CustomersDataStore;
use Automattic\WooCommerce\Admin\API\Reports\Orders\Stats\DataStore as OrdersStatsDataStore;
use Automattic\WooCommerce\Caches\OrderCache;
+use Automattic\WooCommerce\Enums\OrderInternalStatus;
+use Automattic\WooCommerce\Enums\OrderStatus;
use Automattic\WooCommerce\Internal\Admin\Schedulers\OrdersScheduler;
use Automattic\WooCommerce\Internal\DataStores\Orders\OrdersTableDataStore;
use Automattic\WooCommerce\Utilities\OrderUtil;
@@ -657,4 +660,310 @@ class DataStoreTest extends WC_Unit_Test_Case {
'The next oldest order should be reassigned as the customer\'s first order.'
);
}
+
+ /**
+ * @testdox get_order_stats_row_data() returns the same row that update() writes for an order and its refund.
+ */
+ public function test_get_order_stats_row_data_matches_stored_row(): void {
+ global $wpdb;
+
+ $order = WC_Helper_Order::create_order();
+ $order->update_status( OrderStatus::COMPLETED );
+ $refund = wc_create_refund(
+ array(
+ 'order_id' => $order->get_id(),
+ 'amount' => 10,
+ )
+ );
+
+ // The fixture has 4 items at 10 plus 10 shipping. Check it independently of the shared builder.
+ $order_data = OrdersStatsDataStore::get_order_stats_row_data( $order );
+ foreach ( array( 'order_id', 'date_created', 'date_created_gmt', 'num_items_sold', 'total_sales', 'net_total', 'status', 'customer_id', 'returning_customer' ) as $column ) {
+ $this->assertArrayHasKey( $column, $order_data, "The row should include {$column}." );
+ }
+ $this->assertSame( 4, (int) $order_data['num_items_sold'], 'The row should count the fixture items.' );
+ $this->assertEquals( 50, (float) $order_data['total_sales'], 'The row should carry the fixture total.' );
+ $this->assertEquals( 40, (float) $order_data['net_total'], 'The net total should leave out shipping.' );
+ $this->assertSame(
+ (int) CustomersDataStore::get_customer_id_by_user_id( $order->get_customer_id() ),
+ (int) $order_data['customer_id'],
+ 'The row should carry the customer lookup ID of the order\'s customer.'
+ );
+ $this->assertNotEmpty( $order_data['customer_id'], 'The order\'s customer should be in the customer lookup table.' );
+ $this->assertInstanceOf( \WC_Order_Refund::class, $refund, 'wc_create_refund() returns a plain refund, so the parent lookup runs.' );
+ $this->assertSame(
+ (int) $order_data['customer_id'],
+ (int) OrdersStatsDataStore::get_order_stats_row_data( $refund )['customer_id'],
+ 'A refund row should carry its parent order\'s customer.'
+ );
+
+ foreach ( array( $order, $refund ) as $object ) {
+ $data = OrdersStatsDataStore::get_order_stats_row_data( $object );
+ $this->assertIsArray( $data, 'A saved, non-test order should produce a row.' );
+
+ OrdersStatsDataStore::update( $object );
+ $row = $wpdb->get_row(
+ $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}wc_order_stats WHERE order_id = %d", $object->get_id() ),
+ ARRAY_A
+ );
+
+ foreach ( $data as $column => $value ) {
+ if ( is_numeric( $value ) ) {
+ $value = (float) $value;
+ $row[ $column ] = (float) $row[ $column ];
+ }
+ $this->assertEquals( $value, $row[ $column ], "Column {$column} should match the stored row for #{$object->get_id()}." );
+ }
+ }
+
+ $refund_data = OrdersStatsDataStore::get_order_stats_row_data( $refund );
+ $this->assertSame( $order->get_id(), $refund_data['parent_id'], 'A refund row should point at its parent order.' );
+ $this->assertSame( OrderInternalStatus::COMPLETED, $refund_data['status'], 'A refund row should carry the parent order status.' );
+ }
+
+ /**
+ * @testdox get_order_stats_row_data() does not write to the stats table.
+ */
+ public function test_get_order_stats_row_data_does_not_write(): void {
+ global $wpdb;
+
+ $order = WC_Helper_Order::create_order();
+ $wpdb->delete( "{$wpdb->prefix}wc_order_stats", array( 'order_id' => $order->get_id() ) );
+
+ OrdersStatsDataStore::get_order_stats_row_data( $order );
+
+ $count = (int) $wpdb->get_var(
+ $wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->prefix}wc_order_stats WHERE order_id = %d", $order->get_id() )
+ );
+ $this->assertSame( 0, $count, 'Building the row should not store it.' );
+ }
+
+ /**
+ * @testdox get_order_stats_row_data() does not change the returning-customer flags of the customer's other orders.
+ */
+ public function test_get_order_stats_row_data_does_not_reassign_first_order(): void {
+ global $wpdb;
+
+ $customer_id = $this->factory->user->create( array( 'role' => 'customer' ) );
+ $first_order = WC_Helper_Order::create_order( $customer_id );
+ $first_order->set_date_created( '2024-01-10 10:00:00' );
+ $first_order->set_status( OrderStatus::PROCESSING );
+ $first_order->save();
+ OrdersStatsDataStore::sync_order( $first_order->get_id() );
+
+ // An older order that analytics has not imported yet.
+ $older_order = WC_Helper_Order::create_order( $customer_id );
+ $older_order->set_date_created( '2024-01-01 10:00:00' );
+ $older_order->set_status( OrderStatus::PROCESSING );
+ $older_order->save();
+ $wpdb->delete( "{$wpdb->prefix}wc_order_stats", array( 'order_id' => $older_order->get_id() ) );
+
+ $returning_flag = static function ( $id ) use ( $wpdb ) {
+ return $wpdb->get_var(
+ $wpdb->prepare( "SELECT returning_customer FROM {$wpdb->prefix}wc_order_stats WHERE order_id = %d", $id )
+ );
+ };
+ $this->assertSame( '0', $returning_flag( $first_order->get_id() ), 'The imported order should start as the first order.' );
+
+ $data = OrdersStatsDataStore::get_order_stats_row_data( $older_order );
+
+ $this->assertFalse( $data['returning_customer'], 'The older order should be reported as the first order.' );
+ $this->assertSame( '0', $returning_flag( $first_order->get_id() ), 'Building a row should not change other stats rows.' );
+
+ OrdersStatsDataStore::update( $older_order );
+
+ $this->assertSame( '1', $returning_flag( $first_order->get_id() ), 'update() should still mark the later order as returning.' );
+ }
+
+ /**
+ * @testdox get_order_stats_row_data() uses unsaved changes on the order passed in.
+ */
+ public function test_get_order_stats_row_data_uses_unsaved_changes(): void {
+ $order = WC_Helper_Order::create_order();
+ $order->set_total( 123.45 );
+
+ $data = OrdersStatsDataStore::get_order_stats_row_data( $order );
+
+ $this->assertEquals( 123.45, $data['total_sales'], 'The row should use the in-memory total.' );
+ }
+
+ /**
+ * @testdox get_order_stats_row_data() returns false when the order stats data filter returns a non-array.
+ */
+ public function test_get_order_stats_row_data_returns_false_for_non_array_filter_result(): void {
+ $order = WC_Helper_Order::create_order();
+ $order->update_status( OrderStatus::COMPLETED );
+ $refund = wc_create_refund(
+ array(
+ 'order_id' => $order->get_id(),
+ 'amount' => 10,
+ )
+ );
+ add_filter( 'woocommerce_analytics_update_order_stats_data', '__return_null' );
+
+ $this->assertFalse( OrdersStatsDataStore::get_order_stats_row_data( $order ), 'A non-array order row should be returned as false.' );
+ $this->assertFalse( OrdersStatsDataStore::get_order_stats_row_data( $refund ), 'A non-array refund row should be returned as false.' );
+ }
+
+ /**
+ * @testdox get_order_stats_row_data() applies the woocommerce_analytics_update_order_stats_data filter.
+ */
+ public function test_get_order_stats_row_data_applies_filter(): void {
+ $order = WC_Helper_Order::create_order();
+ add_filter(
+ 'woocommerce_analytics_update_order_stats_data',
+ static function ( $data ) {
+ $data['num_items_sold'] = 99;
+ return $data;
+ }
+ );
+
+ $data = OrdersStatsDataStore::get_order_stats_row_data( $order );
+
+ $this->assertSame( 99, $data['num_items_sold'], 'The filtered value should be returned.' );
+ }
+
+ /**
+ * @testdox get_order_stats_row_data() returns false for unsaved and test orders, and update() then skips them.
+ */
+ public function test_get_order_stats_row_data_returns_false_for_untracked_orders(): void {
+ $this->assertFalse( OrdersStatsDataStore::get_order_stats_row_data( new \WC_Order() ), 'An unsaved order has no row.' );
+ $this->assertSame( -1, OrdersStatsDataStore::update( new \WC_Order() ), 'update() should skip an unsaved order.' );
+
+ $order = WC_Helper_Order::create_order();
+ $order->update_meta_data( '_wcpay_mode', 'test' );
+ $order->save();
+
+ $this->assertFalse( OrdersStatsDataStore::get_order_stats_row_data( $order ), 'A test order has no row.' );
+ $this->assertSame( -1, OrdersStatsDataStore::update( $order ), 'update() should skip a test order.' );
+ }
+
+ /**
+ * @testdox get_order_stats_row_data() returns false for a record the import conditions exclude, as update() skips it.
+ */
+ public function test_get_order_stats_row_data_returns_false_for_excluded_record(): void {
+ global $wpdb;
+
+ $order = WC_Helper_Order::create_order();
+ // A record Analytics already holds is never excluded, so start without its row.
+ $wpdb->delete( "{$wpdb->prefix}wc_order_stats", array( 'order_id' => $order->get_id() ) );
+ add_filter(
+ 'woocommerce_analytics_orders_import_where_clauses',
+ static function ( $clauses ) {
+ $clauses[] = '0';
+ return $clauses;
+ }
+ );
+
+ $this->assertFalse( OrdersStatsDataStore::get_order_stats_row_data( $order ), 'An excluded record has no row.' );
+ $this->assertSame( -1, OrdersStatsDataStore::update( $order ), 'update() should skip an excluded record.' );
+ }
+
+ /**
+ * @testdox get_order_stats_row_data() returns false when the import exclusion check fails, as update() then writes nothing.
+ */
+ public function test_get_order_stats_row_data_returns_false_when_exclusion_check_fails(): void {
+ global $wpdb;
+
+ $order = WC_Helper_Order::create_order();
+ $wpdb->delete( "{$wpdb->prefix}wc_order_stats", array( 'order_id' => $order->get_id() ) );
+ add_filter(
+ 'woocommerce_analytics_orders_import_where_clauses',
+ static function ( $clauses ) {
+ $clauses[] = 'no_such_column_for_this_test = 1';
+ return $clauses;
+ }
+ );
+
+ $suppress = $wpdb->suppress_errors();
+ $data = OrdersStatsDataStore::get_order_stats_row_data( $order );
+ $updated = OrdersStatsDataStore::update( $order );
+ $wpdb->suppress_errors( $suppress );
+
+ $this->assertFalse( $data, 'A failed exclusion check should not produce a row.' );
+ $this->assertFalse( $updated, 'update() should report the failed check and write nothing.' );
+ }
+
+ /**
+ * @testdox get_order_stats_row_data() returns false for a trashed order Analytics does not hold yet.
+ */
+ public function test_get_order_stats_row_data_returns_false_for_trashed_order_not_imported(): void {
+ global $wpdb;
+
+ $order = WC_Helper_Order::create_order();
+ $order->set_status( OrderStatus::TRASH );
+ $order->save();
+ $wpdb->delete( "{$wpdb->prefix}wc_order_stats", array( 'order_id' => $order->get_id() ) );
+ $trashed = wc_get_order( $order->get_id() );
+ $this->assertInstanceOf( \WC_Order::class, $trashed, 'The trashed order should still load.' );
+ $this->assertSame( OrderStatus::TRASH, $trashed->get_status(), 'The order should be in the trash.' );
+
+ $this->assertFalse( OrdersStatsDataStore::get_order_stats_row_data( $trashed ), 'The import skips this order, so it has no row.' );
+ }
+
+ /**
+ * @testdox get_order_stats_row_data() does not add a customer for a guest order without a billing email.
+ */
+ public function test_get_order_stats_row_data_does_not_add_customer_for_guest_without_email(): void {
+ global $wpdb;
+
+ $order = WC_Helper_Order::create_order( 0 );
+ $order->set_billing_email( '' );
+ $order->save();
+ $wpdb->delete( "{$wpdb->prefix}wc_order_stats", array( 'order_id' => $order->get_id() ) );
+
+ $customer_count = static function () use ( $wpdb ) {
+ return (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->prefix}wc_customer_lookup" );
+ };
+
+ $before = $customer_count();
+
+ $first = OrdersStatsDataStore::get_order_stats_row_data( wc_get_order( $order->get_id() ) );
+ $second = OrdersStatsDataStore::get_order_stats_row_data( wc_get_order( $order->get_id() ) );
+
+ $this->assertSame( $before, $customer_count(), 'Reading the row should not add a customer that nothing could find again.' );
+ $this->assertEmpty( $first['customer_id'], 'The row should have no customer before the import.' );
+ $this->assertEmpty( $second['customer_id'], 'A second read should not add one either.' );
+
+ OrdersStatsDataStore::update( wc_get_order( $order->get_id() ) );
+
+ $this->assertSame( $before + 1, $customer_count(), 'The import should add the one customer.' );
+ $this->assertNotEmpty( OrdersStatsDataStore::get_order_stats_row_data( wc_get_order( $order->get_id() ) )['customer_id'], 'After the import, the row should use that customer.' );
+ }
+
+ /**
+ * @testdox get_order_stats_row_data() takes the customer from the saved order, not from unsaved changes on an Analytics order.
+ */
+ public function test_get_order_stats_row_data_ignores_unsaved_customer_changes(): void {
+ global $wpdb;
+
+ $order = WC_Helper_Order::create_order( 0 );
+ $order->set_billing_email( '' );
+ $order->save();
+ $wpdb->delete( "{$wpdb->prefix}wc_order_stats", array( 'order_id' => $order->get_id() ) );
+
+ $customer_count = static function () use ( $wpdb ) {
+ return (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->prefix}wc_customer_lookup" );
+ };
+
+ $before = $customer_count();
+ $analytics = new \Automattic\WooCommerce\Admin\Overrides\Order( $order->get_id() );
+ $analytics->set_billing_email( 'unsaved@example.com' );
+ $data = OrdersStatsDataStore::get_order_stats_row_data( $analytics );
+
+ $this->assertIsArray( $data, 'The order should still produce a row.' );
+ $this->assertEmpty( $data['customer_id'], 'The saved guest order has no email, so no customer should be resolved.' );
+ $this->assertSame( $before, $customer_count(), 'No customer should be created from the unsaved email.' );
+ }
+
+ /**
+ * @testdox get_order_stats_row_data() returns false for an order deleted after the caller loaded it.
+ */
+ public function test_get_order_stats_row_data_returns_false_for_deleted_order(): void {
+ $order = WC_Helper_Order::create_order();
+ $held = new \WC_Order( $order->get_id() );
+ $order->delete( true );
+
+ $this->assertFalse( OrdersStatsDataStore::get_order_stats_row_data( $held ), 'A deleted order has no row, and reading it should not throw.' );
+ }
}