Commit a9233eeced0 for woocommerce

commit a9233eeced00c9cc120daff14da5ccdce33120b7
Author: Neeraj <64060864+Indian-boult@users.noreply.github.com>
Date:   Thu Dec 3 09:43:07 2026 +0530

    Keep coupon lookup rows of coupons without an ID when an order syncs again (#71584)

    * Keep coupon lookup rows of coupons without an ID when an order syncs again

    sync_order_coupons dropped the old row of a coupon whose ID resolves to 0 before swapping in its negative placeholder ID, so the cleanup deleted the row it had just written on every second sync. Unset the row after the swap instead.

    * Check each coupon ID against its discount in the lookup row assertions

    ---------

    Co-authored-by: Chi-Hsuan Huang <chihsuan.tw@gmail.com>

diff --git a/plugins/woocommerce/changelog/fix-analytics-coupon-id-zero-sync b/plugins/woocommerce/changelog/fix-analytics-coupon-id-zero-sync
new file mode 100644
index 00000000000..d58f8736160
--- /dev/null
+++ b/plugins/woocommerce/changelog/fix-analytics-coupon-id-zero-sync
@@ -0,0 +1,4 @@
+Significance: patch
+Type: fix
+
+Analytics: keep discounts from coupons that have no saved coupon post when an order is imported again.
diff --git a/plugins/woocommerce/src/Admin/API/Reports/Coupons/DataStore.php b/plugins/woocommerce/src/Admin/API/Reports/Coupons/DataStore.php
index 3b6dfcb365c..092483c8b6f 100644
--- a/plugins/woocommerce/src/Admin/API/Reports/Coupons/DataStore.php
+++ b/plugins/woocommerce/src/Admin/API/Reports/Coupons/DataStore.php
@@ -413,7 +413,6 @@ class DataStore extends ReportsDataStore implements DataStoreInterface {

 		foreach ( $coupon_items as $coupon_item ) {
 			$coupon_id = self::get_coupon_id( $coupon_item );
-			unset( $existing_items[ $coupon_id ] );

 			if ( ! $coupon_id ) {
 				// Insert a unique, but obviously invalid ID for this deleted coupon.
@@ -421,6 +420,9 @@ class DataStore extends ReportsDataStore implements DataStoreInterface {
 				$coupon_id = -1 * $num_deleted;
 			}

+			// Unset after the swap to a negative ID, or the cleanup below deletes the row just written for a coupon without an ID.
+			unset( $existing_items[ $coupon_id ] );
+
 			$result = $wpdb->replace(
 				self::get_db_table_name(),
 				array(
diff --git a/plugins/woocommerce/tests/legacy/unit-tests/woocommerce-admin/reports/class-wc-tests-reports-coupons.php b/plugins/woocommerce/tests/legacy/unit-tests/woocommerce-admin/reports/class-wc-tests-reports-coupons.php
index 3ebf9cc05aa..cff7cfbbed3 100644
--- a/plugins/woocommerce/tests/legacy/unit-tests/woocommerce-admin/reports/class-wc-tests-reports-coupons.php
+++ b/plugins/woocommerce/tests/legacy/unit-tests/woocommerce-admin/reports/class-wc-tests-reports-coupons.php
@@ -5,9 +5,11 @@
  * @package WooCommerce\Admin\Tests\Coupons
  */

+use Automattic\WooCommerce\Admin\API\Reports\Cache as ReportsCache;
 use Automattic\WooCommerce\Admin\API\Reports\GenericQuery;
 use Automattic\WooCommerce\Admin\ReportCSVExporter;
 use Automattic\WooCommerce\Admin\API\Reports\Coupons\DataStore as CouponsDataStore;
+use Automattic\WooCommerce\Admin\API\Reports\Revenue\Query as RevenueQuery;
 use Automattic\WooCommerce\Admin\API\Reports\TimeInterval;
 use Automattic\WooCommerce\Enums\OrderStatus;

@@ -486,4 +488,134 @@ class WC_Admin_Tests_Reports_Coupons extends WC_Unit_Test_Case {
 		);
 		$this->assertEquals( $expected_data, $data );
 	}
+
+	/**
+	 * Make coupon codes that exist only through the woocommerce_get_shop_coupon_data filter, so their ID is 0.
+	 *
+	 * @param array $amounts Fixed cart discount for each code, keyed by code.
+	 */
+	private function add_coupons_without_id( array $amounts ): void {
+		add_filter(
+			'woocommerce_get_shop_coupon_data',
+			function ( $data, $code ) use ( $amounts ) {
+				if ( ! isset( $amounts[ $code ] ) ) {
+					return $data;
+				}
+
+				return array(
+					'amount'        => $amounts[ $code ],
+					'discount_type' => 'fixed_cart',
+				);
+			},
+			10,
+			2
+		);
+	}
+
+	/**
+	 * Read the coupon lookup rows of an order as discount amounts keyed by coupon ID.
+	 *
+	 * @param int $order_id Order ID.
+	 * @return array
+	 */
+	private function get_coupon_lookup_rows( int $order_id ): array {
+		global $wpdb;
+
+		$rows = $wpdb->get_results(
+			$wpdb->prepare( "SELECT coupon_id, discount_amount FROM {$wpdb->prefix}wc_order_coupon_lookup WHERE order_id = %d", $order_id ),
+			ARRAY_A
+		);
+
+		return array_map( 'floatval', array_column( $rows, 'discount_amount', 'coupon_id' ) );
+	}
+
+	/**
+	 * Test that syncing an order again keeps the rows of coupons without an ID, and still removes the row of one taken off the order.
+	 */
+	public function test_resync_keeps_rows_of_coupons_without_id() {
+		WC_Helper_Reports::reset_stats_dbs();
+		$this->add_coupons_without_id(
+			array(
+				'no_id_five'  => 5,
+				'no_id_three' => 3,
+			)
+		);
+
+		$product = new WC_Product_Simple();
+		$product->set_regular_price( 25 );
+		$product->save();
+
+		$coupon = WC_Helper_Coupon::create_coupon( 'saved_coupon' );
+		$coupon->set_amount( 2 );
+		$coupon->save();
+
+		$order = WC_Helper_Order::create_order( 1, $product );
+		$order->set_status( OrderStatus::PROCESSING );
+		$order->apply_coupon( 'no_id_five' );
+		$order->apply_coupon( 'no_id_three' );
+		$order->apply_coupon( 'saved_coupon' );
+		$order->calculate_totals();
+		$order->save();
+
+		$expected = array(
+			-1                => 5.0,
+			-2                => 3.0,
+			$coupon->get_id() => 2.0,
+		);
+		for ( $sync = 1; $sync <= 3; $sync++ ) {
+			$this->assertTrue( CouponsDataStore::sync_order_coupons( $order->get_id() ), "Sync {$sync} should report every coupon as stored." );
+			$this->assertEquals( $expected, $this->get_coupon_lookup_rows( $order->get_id() ), "Sync {$sync} should keep a row for each coupon." );
+		}
+
+		$order->remove_coupon( 'no_id_three' );
+		$order->save();
+		CouponsDataStore::sync_order_coupons( $order->get_id() );
+
+		$this->assertEquals(
+			array(
+				-1                => 5.0,
+				$coupon->get_id() => 2.0,
+			),
+			$this->get_coupon_lookup_rows( $order->get_id() ),
+			'The row of the removed coupon should be deleted and the others kept.'
+		);
+	}
+
+	/**
+	 * Test that Revenue keeps the discount of a coupon without an ID after the order is imported again on completion.
+	 */
+	public function test_revenue_keeps_coupon_without_id_after_order_is_completed() {
+		WC_Helper_Reports::reset_stats_dbs();
+		$this->add_coupons_without_id( array( 'no_id_five' => 5 ) );
+
+		$product = new WC_Product_Simple();
+		$product->set_regular_price( 25 );
+		$product->save();
+
+		$order = WC_Helper_Order::create_order( 1, $product );
+		$order->set_status( OrderStatus::PROCESSING );
+		$order->apply_coupon( 'no_id_five' );
+		$order->calculate_totals();
+		$order->save();
+		WC_Helper_Queue::run_all_pending( 'wc-admin-data' );
+
+		$order->set_status( OrderStatus::COMPLETED );
+		$order->save();
+		WC_Helper_Queue::run_all_pending( 'wc-admin-data' );
+		ReportsCache::invalidate();
+
+		$day    = $order->get_date_created()->getOffsetTimestamp();
+		$totals = ( new RevenueQuery(
+			array(
+				'after'    => gmdate( 'Y-m-d 00:00:00', $day ),
+				'before'   => gmdate( 'Y-m-d 23:59:59', $day ),
+				'interval' => 'day',
+				'fields'   => array( 'coupons', 'coupons_count', 'gross_sales' ),
+			)
+		) )->get_data()->totals;
+
+		$this->assertEquals( 5, $totals->coupons, 'Revenue should keep the coupon discount.' );
+		$this->assertEquals( 1, $totals->coupons_count, 'Revenue should keep counting the coupon.' );
+		$this->assertEquals( 100, $totals->gross_sales, 'Gross sales should include the coupon discount.' );
+	}
 }