Commit 091d52be249 for woocommerce
commit 091d52be249c06f243a12fd015381318c63f093c
Author: Neeraj <64060864+Indian-boult@users.noreply.github.com>
Date: Thu Dec 3 13:02:18 2026 +0530
Count only what earlier refunds left when syncing a full refund to the products lookup (#71545)
* Count only what earlier refunds left when syncing a full refund to the products lookup
A full refund without line items wrote each parent line with its whole quantity and took off earlier refunded revenue summed per product, so partial then full refunds counted units twice and two lines of one product each took off the whole sum. Use the parent order's per line refunded quantity and total instead.
* Remove an earlier row when a re-synced full refund leaves nothing on a line
A line with nothing left to refund was taken off the cleanup list before it was skipped, so a row an earlier sync wrote for it stayed in the products lookup.
* Round each earlier refund item like its lookup row when syncing a full refund
get_total_refunded_for_item() rounds the sum, while each earlier refund row is rounded on its own, so two refunds of an uneven unit price left a cent. Sum the refund items once before the loop and round each one. The tests are now one data provider with that case added.
* Let the existing cleanup remove the row of a line a full refund skips
Take a line off the cleanup list only after the full refund block, so a skipped line's earlier row is removed by the delete at the end and the extra delete is not needed.
* Read earlier refunds like their lookup rows when syncing a full refund
Read refund items in edit context, as the lookup writes do, and count their quantities as whole numbers, as the %d writes store them, so fractional refunds leave a fully refunded line at zero units.
* Store nothing more for a line an earlier refund took more than its total from
When an earlier refund took more than a line's total, the full refund row added the difference as a further refund, so Products went below Revenue. Cap what is left at zero, and update the comment on the parent order items.
---------
Co-authored-by: Chi-Hsuan Huang <chihsuan.tw@gmail.com>
diff --git a/plugins/woocommerce/changelog/fix-analytics-products-full-refund-after-partial b/plugins/woocommerce/changelog/fix-analytics-products-full-refund-after-partial
new file mode 100644
index 00000000000..29766de1c25
--- /dev/null
+++ b/plugins/woocommerce/changelog/fix-analytics-products-full-refund-after-partial
@@ -0,0 +1,4 @@
+Significance: patch
+Type: fix
+
+Analytics: stop counting refunded units and revenue twice when an order is marked refunded after a partial refund.
diff --git a/plugins/woocommerce/src/Admin/API/Reports/Products/DataStore.php b/plugins/woocommerce/src/Admin/API/Reports/Products/DataStore.php
index 4b6b00e2ef7..7764e351676 100644
--- a/plugins/woocommerce/src/Admin/API/Reports/Products/DataStore.php
+++ b/plugins/woocommerce/src/Admin/API/Reports/Products/DataStore.php
@@ -582,14 +582,15 @@ class DataStore extends ReportsDataStore implements DataStoreInterface {
$round_tax = 'no' === get_option( 'woocommerce_tax_round_at_subtotal' );
$is_full_refund_without_line_items = false;
- $partial_refund_product_revenue = array();
$refund_type = $order->get_meta( '_refund_type' );
$uses_new_full_refund_data = OrderUtil::uses_new_full_refund_data();
- $parent_order = null;
+ $parent_order = null;
+ $prior_refunded_qty = array();
+ $prior_refunded_net = array();
// When changing the order status to "Refunded", the refund order's type will be full refund, and the order items will be empty.
- // We need to get the parent order items, and exclude the items that are already being partially refunded.
+ // We need to get the parent order items, and take off what earlier partial refunds already recorded for each line.
if (
'shop_order_refund' === $order->get_type() &&
'full' === $refund_type &&
@@ -602,45 +603,24 @@ class DataStore extends ReportsDataStore implements DataStoreInterface {
$parent_order = wc_get_order( $parent_order_id );
$order_items = $parent_order->get_items();
- // Get the partially refunded product and variation IDs along with their sum of product_net_revenue from the parent order.
- $partial_refund_products = $wpdb->get_results(
- $wpdb->prepare(
- "
- SELECT
- product_lookup.product_id,
- product_lookup.variation_id,
- SUM( product_lookup.product_net_revenue ) AS product_net_revenue
- FROM %i AS product_lookup
- INNER JOIN {$wpdb->prefix}wc_order_stats AS order_stats
- ON order_stats.order_id = product_lookup.order_id
- WHERE 1 = 1
- AND order_stats.parent_id = %d
- AND product_lookup.product_net_revenue < 0
- GROUP BY product_lookup.product_id, product_lookup.variation_id
- ",
- $table_name,
- $parent_order_id
- )
- );
-
- /**
- * Create a lookup table for partially refunded products.
- * E.g. [
- * '1' => -20,
- * '2' => -40,
- * '51' => -10,
- * '52' => -30,
- * ]
- */
- foreach ( $partial_refund_products as $product ) {
- $id = $product->variation_id ? $product->variation_id : $product->product_id;
- $partial_refund_product_revenue[ $id ] = (float) $product->product_net_revenue;
+ // Sum what earlier refunds took from each line, read and rounded like the rows those refunds wrote,
+ // which store the quantity as a whole number.
+ if ( $parent_order instanceof \WC_Order ) {
+ foreach ( $parent_order->get_refunds() as $prior_refund ) {
+ foreach ( $prior_refund->get_items() as $refunded_item ) {
+ if ( ! $refunded_item instanceof \WC_Order_Item_Product ) {
+ continue;
+ }
+ $refunded_item_id = absint( $refunded_item->get_meta( '_refunded_item_id' ) );
+ $prior_refunded_qty[ $refunded_item_id ] = ( $prior_refunded_qty[ $refunded_item_id ] ?? 0 ) + (int) $refunded_item->get_quantity( 'edit' );
+ $prior_refunded_net[ $refunded_item_id ] = ( $prior_refunded_net[ $refunded_item_id ] ?? 0 ) + round( (float) $refunded_item->get_total( 'edit' ), $decimals );
+ }
+ }
}
}
foreach ( $order_items as $order_item ) {
- $order_item_id = $order_item->get_id();
- unset( $existing_items[ $order_item_id ] );
+ $order_item_id = $order_item->get_id();
$product_qty = $order_item->get_quantity( 'edit' );
$product_id = $order_item->get_product_id( 'edit' );
$variation_id = $order_item->get_variation_id( 'edit' );
@@ -652,19 +632,19 @@ class DataStore extends ReportsDataStore implements DataStoreInterface {
// If the order is a full refund and there is no order items. The order item here is the parent order item.
if ( $is_full_refund_without_line_items ) {
- $id = $variation_id ? $variation_id : $product_id;
- $partial_refund = $partial_refund_product_revenue[ $id ] ?? 0;
- // If a single line item was refunded 60% then fully refunded after, we need store the difference in the product lookup table.
- // E.g. A product costs $100, it was previously partially refunded $60, then fully refunded $40.
- // So it will be -abs( 100 + (-60) ) = -40.
- $net_revenue = -abs( $net_revenue + $partial_refund );
+ // Earlier refunds of this line already have their own rows, so only store what they left.
+ // For example, when 1 of 4 units at $25 was refunded before, this row is -3 units and -$75.
+ // Refund items are negative, so adding them takes the earlier refunds off.
+ // An earlier refund larger than the line leaves nothing, rather than a further refund.
+ $net_revenue = -max( 0.0, round( $net_revenue + ( $prior_refunded_net[ $order_item_id ] ?? 0 ), $decimals ) );
// Skip items that have already been fully refunded (single or multiple partial refunds).
+ // The line stays in $existing_items, so the cleanup below removes a row an earlier sync wrote for it.
if ( 0.0 === $net_revenue ) {
continue;
}
- $product_qty = -abs( $product_qty );
+ $product_qty = -abs( (int) $product_qty + ( $prior_refunded_qty[ $order_item_id ] ?? 0 ) );
// Set coupon amount to 0 for full refunds without line items.
$coupon_amount = 0;
@@ -695,6 +675,8 @@ class DataStore extends ReportsDataStore implements DataStoreInterface {
}
}
+ unset( $existing_items[ $order_item_id ] );
+
$is_refund = $net_revenue < 0;
// Skip line items without changes to product quantity.
diff --git a/plugins/woocommerce/tests/legacy/unit-tests/woocommerce-admin/reports/class-wc-tests-reports-products.php b/plugins/woocommerce/tests/legacy/unit-tests/woocommerce-admin/reports/class-wc-tests-reports-products.php
index 1e656d293b3..14f8c611077 100644
--- a/plugins/woocommerce/tests/legacy/unit-tests/woocommerce-admin/reports/class-wc-tests-reports-products.php
+++ b/plugins/woocommerce/tests/legacy/unit-tests/woocommerce-admin/reports/class-wc-tests-reports-products.php
@@ -438,6 +438,306 @@ class WC_Admin_Tests_Reports_Products extends WC_Unit_Test_Case {
$this->assertEquals( $expected_data, $query->get_data() );
}
+ /**
+ * Partial refunds made before an order is set to Refunded.
+ *
+ * Each line is a quantity and a total. Each refund is a line index, a quantity and a total.
+ *
+ * @return array[]
+ */
+ public function provide_partial_refunds_then_full_refund() {
+ return array(
+ 'one unit of a line' => array(
+ array( array( 4, 100 ) ),
+ array( array( 0, 1, 25 ) ),
+ ),
+ 'one of two lines of the same product' => array(
+ array( array( 4, 100 ), array( 1, 25 ) ),
+ array( array( 1, 1, 25 ) ),
+ ),
+ 'two refunds of an uneven unit price' => array(
+ array( array( 3, 29 ) ),
+ array( array( 0, 1, 29 / 3 ), array( 0, 1, 29 / 3 ) ),
+ ),
+ );
+ }
+
+ /**
+ * Tests that a full refund after partial refunds counts only what the partial refunds left.
+ *
+ * @dataProvider provide_partial_refunds_then_full_refund
+ *
+ * @param array $lines Order lines as quantity and total.
+ * @param array $refunds Partial refunds as line index, quantity and total.
+ */
+ public function test_populate_partial_refunds_then_full_refund( $lines, $refunds ) {
+ WC_Helper_Reports::reset_stats_dbs();
+
+ $product = new WC_Product_Simple();
+ $product->set_name( 'Test Product' );
+ $product->set_regular_price( 25 );
+ $product->save();
+
+ $order = new WC_Order();
+ $items = array();
+ foreach ( $lines as $line ) {
+ $item = new WC_Order_Item_Product();
+ $item->set_product( $product );
+ $item->set_quantity( $line[0] );
+ $item->set_subtotal( $line[1] );
+ $item->set_total( $line[1] );
+ $order->add_item( $item );
+ $items[] = $item;
+ }
+ $order->set_status( OrderStatus::COMPLETED );
+ $order->calculate_totals( false );
+ $order->save();
+
+ foreach ( $refunds as $refund ) {
+ wc_create_refund(
+ array(
+ 'amount' => round( $refund[2], 2 ),
+ 'order_id' => $order->get_id(),
+ 'line_items' => array(
+ $items[ $refund[0] ]->get_id() => array(
+ 'qty' => $refund[1],
+ 'refund_total' => $refund[2],
+ ),
+ ),
+ )
+ );
+ }
+ WC_Helper_Queue::run_all_pending( 'wc-admin-data' );
+
+ $order = wc_get_order( $order->get_id() );
+ $order->set_status( OrderStatus::REFUNDED );
+ $order->save();
+ WC_Helper_Queue::run_all_pending( 'wc-admin-data' );
+
+ $start_time = gmdate( 'Y-m-d H:00:00', $order->get_date_created()->getOffsetTimestamp() );
+ $end_time = gmdate( 'Y-m-d H:00:00', $order->get_date_created()->getOffsetTimestamp() + HOUR_IN_SECONDS );
+ $data = ( new ProductsDataStore() )->get_data(
+ array(
+ 'after' => $start_time,
+ 'before' => $end_time,
+ )
+ );
+
+ $this->assertSame( 0, (int) $data->data[0]['items_sold'] );
+ $this->assertEquals( 0.0, $data->data[0]['net_revenue'] );
+ }
+
+ /**
+ * Tests that a full refund after fractional partial refunds leaves the line at zero units.
+ *
+ * Lookup rows store the quantity as a whole number, so two refunds of half a unit store zero units each.
+ */
+ public function test_populate_fractional_partial_refunds_then_full_refund() {
+ global $wpdb;
+ WC_Helper_Reports::reset_stats_dbs();
+
+ // Allow decimal quantities as a decimal stock setup does.
+ remove_filter( 'woocommerce_stock_amount', 'intval' );
+ add_filter( 'woocommerce_stock_amount', 'floatval' );
+
+ try {
+ $product = new WC_Product_Simple();
+ $product->set_name( 'Test Product' );
+ $product->set_regular_price( 25 );
+ $product->save();
+
+ $order = new WC_Order();
+ $item = new WC_Order_Item_Product();
+ $item->set_product( $product );
+ $item->set_quantity( 4 );
+ $item->set_subtotal( 100 );
+ $item->set_total( 100 );
+ $order->add_item( $item );
+ $order->set_status( OrderStatus::COMPLETED );
+ $order->calculate_totals( false );
+ $order->save();
+
+ for ( $i = 0; $i < 2; $i++ ) {
+ wc_create_refund(
+ array(
+ 'amount' => 12.5,
+ 'order_id' => $order->get_id(),
+ 'line_items' => array(
+ $item->get_id() => array(
+ 'qty' => 0.5,
+ 'refund_total' => 12.5,
+ ),
+ ),
+ )
+ );
+ }
+ WC_Helper_Queue::run_all_pending( 'wc-admin-data' );
+
+ $order = wc_get_order( $order->get_id() );
+ $order->set_status( OrderStatus::REFUNDED );
+ $order->save();
+ WC_Helper_Queue::run_all_pending( 'wc-admin-data' );
+
+ $units = (int) $wpdb->get_var(
+ $wpdb->prepare(
+ 'SELECT SUM( product_qty ) FROM %i WHERE product_id = %d',
+ $wpdb->prefix . 'wc_order_product_lookup',
+ $product->get_id()
+ )
+ );
+ $this->assertSame( 0, $units );
+ } finally {
+ remove_filter( 'woocommerce_stock_amount', 'floatval' );
+ add_filter( 'woocommerce_stock_amount', 'intval' );
+ }
+ }
+
+ /**
+ * Tests that a full refund adds nothing for a line an earlier refund took more than its total from.
+ */
+ public function test_populate_full_refund_after_line_over_refunded() {
+ global $wpdb;
+ WC_Helper_Reports::reset_stats_dbs();
+
+ $over_refunded = new WC_Product_Simple();
+ $over_refunded->set_regular_price( 25 );
+ $over_refunded->save();
+
+ $other = new WC_Product_Simple();
+ $other->set_regular_price( 25 );
+ $other->save();
+
+ $order = new WC_Order();
+ $line = new WC_Order_Item_Product();
+ $line->set_product( $over_refunded );
+ $line->set_quantity( 4 );
+ $line->set_subtotal( 100 );
+ $line->set_total( 100 );
+ $order->add_item( $line );
+ $other_line = new WC_Order_Item_Product();
+ $other_line->set_product( $other );
+ $other_line->set_quantity( 1 );
+ $other_line->set_subtotal( 25 );
+ $other_line->set_total( 25 );
+ $order->add_item( $other_line );
+ $order->set_status( OrderStatus::COMPLETED );
+ $order->calculate_totals( false );
+ $order->save();
+
+ wc_create_refund(
+ array(
+ 'amount' => 120,
+ 'order_id' => $order->get_id(),
+ 'line_items' => array(
+ $line->get_id() => array(
+ 'qty' => 4,
+ 'refund_total' => 120,
+ ),
+ ),
+ )
+ );
+ WC_Helper_Queue::run_all_pending( 'wc-admin-data' );
+
+ $order = wc_get_order( $order->get_id() );
+ $order->set_status( OrderStatus::REFUNDED );
+ $order->save();
+ WC_Helper_Queue::run_all_pending( 'wc-admin-data' );
+
+ $totals = $wpdb->get_row(
+ $wpdb->prepare(
+ 'SELECT SUM( product_qty ) AS units, SUM( product_net_revenue ) AS net FROM %i WHERE product_id = %d',
+ $wpdb->prefix . 'wc_order_product_lookup',
+ $over_refunded->get_id()
+ )
+ );
+
+ $this->assertSame( 0, (int) $totals->units, 'The over-refunded line should net to zero units.' );
+ $this->assertEquals( -20.0, (float) $totals->net, 'Only the earlier refund should take the line below zero, not the full refund as well.' );
+ }
+
+ /**
+ * Tests that re-syncing a full refund removes an earlier row for a line that has nothing left to refund.
+ */
+ public function test_resync_full_refund_removes_row_for_line_with_nothing_left() {
+ global $wpdb;
+ WC_Helper_Reports::reset_stats_dbs();
+
+ $product = new WC_Product_Simple();
+ $product->set_name( 'Test Product' );
+ $product->set_regular_price( 25 );
+ $product->save();
+
+ $order = WC_Helper_Order::create_order( 1, $product );
+ $second = new WC_Order_Item_Product();
+ $second->set_product( $product );
+ $second->set_quantity( 1 );
+ $second->set_subtotal( 25 );
+ $second->set_total( 25 );
+ $order->add_item( $second );
+ $order->set_status( OrderStatus::COMPLETED );
+ $order->calculate_totals();
+ $order->save();
+
+ wc_create_refund(
+ array(
+ 'amount' => 25,
+ 'order_id' => $order->get_id(),
+ 'line_items' => array(
+ $second->get_id() => array(
+ 'qty' => 1,
+ 'refund_total' => 25,
+ ),
+ ),
+ )
+ );
+ WC_Helper_Queue::run_all_pending( 'wc-admin-data' );
+
+ $order = wc_get_order( $order->get_id() );
+ $order->set_status( OrderStatus::REFUNDED );
+ $order->save();
+ WC_Helper_Queue::run_all_pending( 'wc-admin-data' );
+
+ $full_refund = null;
+ foreach ( wc_get_order( $order->get_id() )->get_refunds() as $refund ) {
+ if ( 'full' === $refund->get_meta( '_refund_type' ) ) {
+ $full_refund = $refund;
+ }
+ }
+ $table = $wpdb->prefix . 'wc_order_product_lookup';
+
+ // A row for the already refunded line, as an earlier calculation could have written it.
+ $wpdb->insert(
+ $table,
+ array(
+ 'order_item_id' => $second->get_id(),
+ 'order_id' => $full_refund->get_id(),
+ 'product_id' => $product->get_id(),
+ 'variation_id' => 0,
+ 'customer_id' => 0,
+ 'date_created' => $full_refund->get_date_created()->date( 'Y-m-d H:i:s' ),
+ 'product_qty' => -1,
+ 'product_net_revenue' => -25,
+ 'product_gross_revenue' => -25,
+ 'coupon_amount' => 0,
+ 'tax_amount' => 0,
+ 'shipping_amount' => 0,
+ 'shipping_tax_amount' => 0,
+ )
+ );
+
+ ProductsDataStore::sync_order_products( $full_refund->get_id() );
+
+ $rows = (int) $wpdb->get_var(
+ $wpdb->prepare(
+ 'SELECT COUNT(*) FROM %i WHERE order_id = %d AND order_item_id = %d',
+ $table,
+ $full_refund->get_id(),
+ $second->get_id()
+ )
+ );
+ $this->assertSame( 0, $rows );
+ }
+
/**
* @testdox Should not throw DivisionByZeroError when syncing a monetary-only refund (qty 0) with float quantities.
*