Commit 005170243ee for woocommerce
commit 005170243ee7eb9541c7363a3f201d36153efc50
Author: Luigi Teschio <gigitux@gmail.com>
Date: Mon Nov 23 17:40:18 2026 +0100
Fix coupon usage counts on canceled, failed or trashed orders (#71255)
Forward-port of Automattic/woocommerce#519.
Co-authored-by: Rostislav Wolny <rosta.wolny@automattic.com>
diff --git a/plugins/woocommerce/includes/data-stores/class-wc-order-data-store-cpt.php b/plugins/woocommerce/includes/data-stores/class-wc-order-data-store-cpt.php
index 3dfaaa9cefe..0551e1435b9 100644
--- a/plugins/woocommerce/includes/data-stores/class-wc-order-data-store-cpt.php
+++ b/plugins/woocommerce/includes/data-stores/class-wc-order-data-store-cpt.php
@@ -724,6 +724,50 @@ class WC_Order_Data_Store_CPT extends Abstract_WC_Order_Data_Store_CPT implement
update_post_meta( $order_id, '_recorded_coupon_usage_counts', wc_bool_to_string( $set ) );
}
+ /**
+ * Clears the "coupon usage counted" flag, if it is still set and the stored order status still matches the order object.
+ *
+ * The check and the write are one database update, so the flag is cleared by at most one call.
+ *
+ * @since 11.3.1
+ *
+ * @internal For use by wc_update_coupon_usage_counts() only.
+ *
+ * @param WC_Order $order Order object.
+ * @return bool True if this call cleared the flag.
+ */
+ public function clear_recorded_coupon_usage_counts( $order ): bool {
+ global $wpdb;
+
+ $order_id = $order->get_id();
+ $status = $order->get_status( 'edit' );
+ if ( ! $order_id || ! $status ) {
+ return false;
+ }
+
+ // Whether a status is stored with the "wc-" prefix depends on the post statuses registered when the order was saved.
+ $cleared = $wpdb->query(
+ $wpdb->prepare(
+ "UPDATE {$wpdb->postmeta} SET meta_value = 'no'
+ WHERE post_id = %d AND meta_key = '_recorded_coupon_usage_counts' AND meta_value IN ( 'yes', 'true', '1' )
+ AND EXISTS ( SELECT 1 FROM {$wpdb->posts} WHERE ID = %d AND post_status IN ( %s, %s ) )",
+ $order_id,
+ $order_id,
+ $status,
+ 'wc-' . $status
+ )
+ );
+
+ if ( (int) $cleared < 1 ) {
+ return false;
+ }
+
+ // The update above skips the meta cache, and the setter below finds nothing to change, so it would keep a stale 'yes' cached.
+ wp_cache_delete( $order_id, 'post_meta' );
+ $this->set_recorded_coupon_usage_counts( $order, false );
+ return true;
+ }
+
/**
* Whether email have been sent for this order.
*
diff --git a/plugins/woocommerce/includes/wc-order-functions.php b/plugins/woocommerce/includes/wc-order-functions.php
index 8c3679e9f54..2cd53faefb0 100644
--- a/plugins/woocommerce/includes/wc-order-functions.php
+++ b/plugins/woocommerce/includes/wc-order-functions.php
@@ -1082,7 +1082,16 @@ function wc_update_coupon_usage_counts( $order_id ) {
if ( $is_invalid && $has_recorded ) {
$action = 'reduce';
- $order->get_data_store()->set_recorded_coupon_usage_counts( $order, false );
+ if ( $data_store->has_callable( 'clear_recorded_coupon_usage_counts' ) ) {
+ // @phpstan-ignore-next-line method.notFound (Guarded by has_callable() and called via __call() on the underlying order data store instance.)
+ if ( ! $data_store->clear_recorded_coupon_usage_counts( $order ) ) {
+ // Another request already gave the uses back, or changed the order status since this order was loaded.
+ wc_release_coupons_for_order( $order );
+ return;
+ }
+ } else {
+ $order->get_data_store()->set_recorded_coupon_usage_counts( $order, false );
+ }
} elseif ( ! $is_invalid && $coupon_codes && ! $has_recorded ) {
$action = 'increase';
$order->get_data_store()->set_recorded_coupon_usage_counts( $order, true );
diff --git a/plugins/woocommerce/src/Internal/DataStores/Orders/OrdersTableDataStore.php b/plugins/woocommerce/src/Internal/DataStores/Orders/OrdersTableDataStore.php
index b472c4efd49..0000759dcf7 100644
--- a/plugins/woocommerce/src/Internal/DataStores/Orders/OrdersTableDataStore.php
+++ b/plugins/woocommerce/src/Internal/DataStores/Orders/OrdersTableDataStore.php
@@ -995,6 +995,53 @@ class OrdersTableDataStore extends \Abstract_WC_Order_Data_Store_CPT implements
$order->save();
}
+ /**
+ * Clears the "coupon usage counted" flag, if it is still set and the stored order status still matches the order object.
+ *
+ * The check and the write are one database update, so the flag is cleared by at most one call.
+ *
+ * @since 11.3.1
+ *
+ * @internal For use by wc_update_coupon_usage_counts() only.
+ *
+ * @param \WC_Order $order Order object.
+ * @return bool True if this call cleared the flag.
+ */
+ public function clear_recorded_coupon_usage_counts( $order ): bool {
+ global $wpdb;
+
+ $order_id = $order->get_id();
+ $status = $order->get_status( 'edit' );
+ if ( ! $order_id || ! $status ) {
+ return false;
+ }
+
+ $operational_data_table = self::get_operational_data_table_name();
+ $orders_table = self::get_orders_table_name();
+
+ // Whether a status is stored with the "wc-" prefix depends on the post statuses registered when the order was saved.
+ // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- trusted table names.
+ $cleared = $wpdb->query(
+ $wpdb->prepare(
+ "UPDATE {$operational_data_table} SET coupon_usages_are_counted = 0
+ WHERE order_id = %d AND coupon_usages_are_counted = 1
+ AND EXISTS ( SELECT 1 FROM {$orders_table} WHERE id = %d AND status IN ( %s, %s ) )",
+ $order_id,
+ $order_id,
+ $status,
+ 'wc-' . $status
+ )
+ );
+ // phpcs:enable
+
+ if ( (int) $cleared < 1 ) {
+ return false;
+ }
+
+ $this->set_recorded_coupon_usage_counts( $order, false );
+ return true;
+ }
+
/**
* Whether email have been sent for this order.
*
diff --git a/plugins/woocommerce/tests/php/includes/data-stores/class-wc-order-data-store-cpt-test.php b/plugins/woocommerce/tests/php/includes/data-stores/class-wc-order-data-store-cpt-test.php
index f24edba1405..72c67842dc6 100644
--- a/plugins/woocommerce/tests/php/includes/data-stores/class-wc-order-data-store-cpt-test.php
+++ b/plugins/woocommerce/tests/php/includes/data-stores/class-wc-order-data-store-cpt-test.php
@@ -2124,4 +2124,40 @@ class WC_Order_Data_Store_CPT_Test extends WC_Unit_Test_Case {
$this->assertArrayHasKey( WC_Order_Data_Store_CPT::class . '::query', $messages, 'Unsupported arguments should raise a notice.' );
$this->assertStringStartsWith( $expected_message, $messages[ WC_Order_Data_Store_CPT::class . '::query' ], 'The notice should use the English wording for the argument count.' );
}
+
+ /**
+ * @testdox clear_recorded_coupon_usage_counts() clears a set flag once, and only while the stored status matches the order object.
+ */
+ public function test_clear_recorded_coupon_usage_counts(): void {
+ $sut = new WC_Order_Data_Store_CPT();
+ $order = $this->create_cancelled_order_with_counted_coupon_usage( $sut );
+ $other_order = $this->create_cancelled_order_with_counted_coupon_usage( $sut );
+
+ $copy_with_other_status = clone $order;
+ $copy_with_other_status->set_status( OrderStatus::FAILED );
+ $this->assertFalse( $sut->clear_recorded_coupon_usage_counts( $copy_with_other_status ), 'The flag should not be cleared when the stored status differs' );
+ $this->assertTrue( $sut->get_recorded_coupon_usage_counts( $order->get_id() ), 'The flag should stay set' );
+
+ $this->assertTrue( $sut->clear_recorded_coupon_usage_counts( $order ), 'A set flag should be cleared' );
+ $this->assertFalse( $sut->get_recorded_coupon_usage_counts( $order->get_id() ), 'The flag should read as cleared' );
+ $this->assertFalse( $order->get_recorded_coupon_usage_counts(), 'The order object should be updated' );
+ $this->assertTrue( $sut->get_recorded_coupon_usage_counts( $other_order->get_id() ), 'Other orders should keep their flag' );
+
+ $this->assertFalse( $sut->clear_recorded_coupon_usage_counts( $order ), 'A cleared flag should not be cleared again' );
+ }
+
+ /**
+ * Create a cancelled order marked as having its coupon usage counted.
+ *
+ * @param WC_Order_Data_Store_CPT $data_store Data store to mark the order with.
+ * @return WC_Order
+ */
+ private function create_cancelled_order_with_counted_coupon_usage( WC_Order_Data_Store_CPT $data_store ): WC_Order {
+ $order = WC_Helper_Order::create_order();
+ $order->set_status( OrderStatus::CANCELLED );
+ $order->save();
+ $data_store->set_recorded_coupon_usage_counts( $order, true );
+
+ return $order;
+ }
}
diff --git a/plugins/woocommerce/tests/php/includes/wc-update-coupon-usage-counts-test.php b/plugins/woocommerce/tests/php/includes/wc-update-coupon-usage-counts-test.php
new file mode 100644
index 00000000000..114bb792459
--- /dev/null
+++ b/plugins/woocommerce/tests/php/includes/wc-update-coupon-usage-counts-test.php
@@ -0,0 +1,271 @@
+<?php
+declare( strict_types = 1 );
+
+use Automattic\WooCommerce\Enums\OrderInternalStatus;
+use Automattic\WooCommerce\Enums\OrderStatus;
+use Automattic\WooCommerce\Internal\DataStores\Orders\OrdersTableDataStore;
+use Automattic\WooCommerce\RestApi\UnitTests\HPOSToggleTrait;
+use Automattic\WooCommerce\RestApi\UnitTests\Helpers\OrderHelper;
+use Automattic\WooCommerce\Utilities\OrderUtil;
+
+/**
+ * Tests for wc_update_coupon_usage_counts() when another request changes the same order while it runs.
+ *
+ * Kept apart from WC_Order_Functions_Test because each test switches the order storage.
+ */
+class WC_Update_Coupon_Usage_Counts_Test extends \WC_Unit_Test_Case {
+
+ use HPOSToggleTrait;
+
+ /**
+ * Ensure permanent HPOS tables exist before per-test transactions start.
+ */
+ public static function wpSetUpBeforeClass(): void {
+ $previous_hpos_state = OrderUtil::custom_orders_table_usage_is_enabled();
+ add_filter( 'wc_allow_changing_orders_storage_while_sync_is_pending', '__return_true' );
+ try {
+ self::setup_cot_tables();
+ if ( OrderUtil::custom_orders_table_usage_is_enabled() !== $previous_hpos_state ) {
+ OrderHelper::toggle_cot_feature_and_usage( $previous_hpos_state );
+ }
+ } finally {
+ remove_filter( 'wc_allow_changing_orders_storage_while_sync_is_pending', '__return_true' );
+ }
+ }
+
+ /**
+ * Whether HPOS was enabled before the test.
+ *
+ * @var bool
+ */
+ private $prev_hpos_enabled;
+
+ /**
+ * Set up test.
+ */
+ public function setUp(): void {
+ parent::setUp();
+
+ add_filter( 'wc_allow_changing_orders_storage_while_sync_is_pending', '__return_true' );
+ $this->prev_hpos_enabled = OrderUtil::custom_orders_table_usage_is_enabled();
+ remove_filter( 'query', array( $this, '_create_temporary_tables' ) );
+ remove_filter( 'query', array( $this, '_drop_temporary_tables' ) );
+ $this->toggle_cot_feature_and_usage( true );
+ }
+
+ /**
+ * Tear down test.
+ */
+ public function tearDown(): void {
+ try {
+ $this->clean_up_cot_setup();
+ $this->toggle_cot_feature_and_usage( $this->prev_hpos_enabled );
+ } finally {
+ parent::tearDown();
+ }
+ }
+
+ /**
+ * @testdox Cancelling an order gives its coupon use back only once when another request already gave it back.
+ *
+ * @testWith [true]
+ * [false]
+ *
+ * @param bool $hpos_enabled Whether HPOS is the authoritative order storage.
+ */
+ public function test_gives_coupon_use_back_once_when_another_request_already_did( bool $hpos_enabled ): void {
+ $this->toggle_cot_authoritative( $hpos_enabled );
+ $order = $this->create_pending_order_with_counted_coupon( 'give-back-once' );
+
+ $count_after_other_request = null;
+ $this->run_once_between_flag_read_and_write(
+ function () use ( $order, &$count_after_other_request ) {
+ wc_update_coupon_usage_counts( $order->get_id() );
+ $count_after_other_request = ( new WC_Coupon( 'give-back-once' ) )->get_usage_count();
+ }
+ );
+ $order->update_status( OrderStatus::CANCELLED );
+
+ $coupon = new WC_Coupon( 'give-back-once' );
+ $this->assertSame( 1, $count_after_other_request, 'The other request should give the use back' );
+ $this->assertSame( 1, $coupon->get_usage_count(), 'The use should be given back only once' );
+ $this->assertCount( 1, $coupon->get_used_by(), 'Only one customer use record should be removed' );
+ }
+
+ /**
+ * @testdox Cancelling an order keeps its coupon use counted when another request marks the order as paid first.
+ *
+ * @testWith [true]
+ * [false]
+ *
+ * @param bool $hpos_enabled Whether HPOS is the authoritative order storage.
+ */
+ public function test_keeps_coupon_use_counted_when_order_is_paid_meanwhile( bool $hpos_enabled ): void {
+ $this->toggle_cot_authoritative( $hpos_enabled );
+ $order = $this->create_pending_order_with_counted_coupon( 'paid-meanwhile' );
+
+ $this->run_once_between_flag_read_and_write(
+ function () use ( $order ) {
+ $this->store_order_status( $order->get_id(), OrderInternalStatus::PROCESSING );
+ }
+ );
+ $order->update_status( OrderStatus::CANCELLED );
+
+ $coupon = new WC_Coupon( 'paid-meanwhile' );
+ $this->assertSame( 2, $coupon->get_usage_count(), 'A paid order should keep its coupon use' );
+ $this->assertCount( 2, $coupon->get_used_by(), 'A paid order should keep its customer use record' );
+ $this->assertTrue( $order->get_data_store()->get_recorded_coupon_usage_counts( $order->get_id() ), 'A paid order should stay marked as counted' );
+ }
+
+ /**
+ * @testdox A custom status added to the invalid statuses gives the coupon use back, also when it is not a registered post status.
+ *
+ * @testWith [true]
+ * [false]
+ *
+ * @param bool $hpos_enabled Whether HPOS is the authoritative order storage.
+ */
+ public function test_gives_coupon_use_back_for_custom_invalid_status( bool $hpos_enabled ): void {
+ $this->toggle_cot_authoritative( $hpos_enabled );
+ add_filter(
+ 'wc_order_statuses',
+ function ( $statuses ) {
+ $statuses['wc-expired'] = 'Expired';
+ return $statuses;
+ }
+ );
+ add_filter(
+ 'woocommerce_update_coupon_usage_invalid_statuses',
+ function ( $statuses ) {
+ $statuses[] = 'expired';
+ return $statuses;
+ }
+ );
+ add_action( 'woocommerce_order_status_expired', 'wc_update_coupon_usage_counts' );
+ $order = $this->create_pending_order_with_counted_coupon( 'custom-status' );
+
+ $order->update_status( 'expired' );
+
+ $this->assertSame( 1, ( new WC_Coupon( 'custom-status' ) )->get_usage_count(), 'The use should be given back' );
+ }
+
+ /**
+ * @testdox Cancelling an order gives its coupon use back when the order data store cannot clear the counted flag conditionally.
+ */
+ public function test_gives_coupon_use_back_with_data_store_without_conditional_clear(): void {
+ $this->toggle_cot_authoritative( false );
+ $order = $this->create_pending_order_with_counted_coupon( 'basic-data-store' );
+ $order_id = $order->get_id();
+ $this->store_order_status( $order_id, OrderInternalStatus::CANCELLED );
+ clean_post_cache( $order_id );
+
+ add_filter(
+ 'woocommerce_data_stores',
+ function ( $stores ) {
+ $stores['test-order-without-conditional-clear'] = new class() extends Abstract_WC_Order_Data_Store_CPT {
+ /**
+ * Get whether coupon usage was counted for the order.
+ *
+ * @param WC_Order|int $order Order or order ID.
+ * @return bool
+ */
+ public function get_recorded_coupon_usage_counts( $order ) {
+ return wc_string_to_bool( get_post_meta( WC_Order_Factory::get_order_id( $order ), '_recorded_coupon_usage_counts', true ) );
+ }
+
+ /**
+ * Set whether coupon usage was counted for the order.
+ *
+ * @param WC_Order|int $order Order or order ID.
+ * @param bool $set Whether the usage was counted.
+ */
+ public function set_recorded_coupon_usage_counts( $order, $set ) {
+ update_post_meta( WC_Order_Factory::get_order_id( $order ), '_recorded_coupon_usage_counts', wc_bool_to_string( $set ) );
+ }
+ };
+ return $stores;
+ }
+ );
+ $order_class = get_class(
+ new class() extends WC_Order {
+ /**
+ * Get a data store without clear_recorded_coupon_usage_counts().
+ *
+ * @return WC_Data_Store
+ */
+ public function get_data_store() {
+ return WC_Data_Store::load( 'test-order-without-conditional-clear' );
+ }
+ }
+ );
+ add_filter(
+ 'woocommerce_order_class',
+ function () use ( $order_class ) {
+ return $order_class;
+ }
+ );
+
+ $this->assertFalse( wc_get_order( $order_id )->get_data_store()->has_callable( 'clear_recorded_coupon_usage_counts' ), 'The order should use the data store without the conditional clear' );
+
+ wc_update_coupon_usage_counts( $order_id );
+
+ $this->assertSame( 1, ( new WC_Coupon( 'basic-data-store' ) )->get_usage_count(), 'The use should be given back' );
+ $this->assertSame( 'no', get_post_meta( $order_id, '_recorded_coupon_usage_counts', true ), 'The order should no longer be marked as counted' );
+ }
+
+ /**
+ * Create a pending order whose coupon use is counted, after another order already used the same coupon.
+ *
+ * @param string $code Coupon code.
+ * @return WC_Order The order; the coupon's usage count is 2.
+ */
+ private function create_pending_order_with_counted_coupon( string $code ): WC_Order {
+ WC_Helper_Coupon::create_coupon( $code );
+ WC_Helper_Order::create_order()->apply_coupon( $code );
+
+ $order = WC_Helper_Order::create_order();
+ $order->apply_coupon( $code );
+
+ $this->assertSame( 2, ( new WC_Coupon( $code ) )->get_usage_count(), 'Both orders should count their coupon use' );
+ $this->assertTrue( $order->get_data_store()->get_recorded_coupon_usage_counts( $order->get_id() ), 'The order should be marked as counted' );
+
+ return $order;
+ }
+
+ /**
+ * Run a callback once, after wc_update_coupon_usage_counts() reads the order's counted flag and before it changes it.
+ *
+ * The invalid statuses filter runs in that gap, so the callback acts like another request that lands there.
+ *
+ * @param callable $callback Callback to run.
+ */
+ private function run_once_between_flag_read_and_write( callable $callback ): void {
+ $has_run = false;
+ add_filter(
+ 'woocommerce_update_coupon_usage_invalid_statuses',
+ function ( $statuses ) use ( $callback, &$has_run ) {
+ if ( ! $has_run ) {
+ $has_run = true;
+ $callback();
+ }
+ return $statuses;
+ }
+ );
+ }
+
+ /**
+ * Write an order status straight to the authoritative storage, leaving order objects already loaded unchanged.
+ *
+ * @param int $order_id Order ID.
+ * @param string $status Stored status, e.g. 'wc-processing'.
+ */
+ private function store_order_status( int $order_id, string $status ): void {
+ global $wpdb;
+
+ if ( OrderUtil::custom_orders_table_usage_is_enabled() ) {
+ $wpdb->update( OrdersTableDataStore::get_orders_table_name(), array( 'status' => $status ), array( 'id' => $order_id ) );
+ } else {
+ $wpdb->update( $wpdb->posts, array( 'post_status' => $status ), array( 'ID' => $order_id ) );
+ }
+ }
+}
diff --git a/plugins/woocommerce/tests/php/src/Internal/DataStores/Orders/OrdersTableDataStoreTests.php b/plugins/woocommerce/tests/php/src/Internal/DataStores/Orders/OrdersTableDataStoreTests.php
index 8320fd787e7..28fc3202703 100644
--- a/plugins/woocommerce/tests/php/src/Internal/DataStores/Orders/OrdersTableDataStoreTests.php
+++ b/plugins/woocommerce/tests/php/src/Internal/DataStores/Orders/OrdersTableDataStoreTests.php
@@ -4814,4 +4814,39 @@ class OrdersTableDataStoreTests extends \HposTestCase {
$this->assertInstanceOf( \Exception::class, $error, 'The update should throw when a value does not fit its column.' );
$this->assertStringContainsString( 'phone', $error->getMessage(), 'The error should name the column that is too long.' );
}
+
+ /**
+ * @testDox clear_recorded_coupon_usage_counts() clears a set flag once, and only while the stored status matches the order object.
+ */
+ public function test_clear_recorded_coupon_usage_counts(): void {
+ $this->toggle_cot_feature_and_usage( true );
+ $order = $this->create_cancelled_order_with_counted_coupon_usage();
+ $other_order = $this->create_cancelled_order_with_counted_coupon_usage();
+
+ $copy_with_other_status = clone $order;
+ $copy_with_other_status->set_status( OrderStatus::FAILED );
+ $this->assertFalse( $this->sut->clear_recorded_coupon_usage_counts( $copy_with_other_status ), 'The flag should not be cleared when the stored status differs' );
+ $this->assertTrue( $this->sut->get_recorded_coupon_usage_counts( $order->get_id() ), 'The flag should stay set' );
+
+ $this->assertTrue( $this->sut->clear_recorded_coupon_usage_counts( $order ), 'A set flag should be cleared' );
+ $this->assertFalse( $this->sut->get_recorded_coupon_usage_counts( $order->get_id() ), 'The flag should read as cleared' );
+ $this->assertFalse( $order->get_recorded_coupon_usage_counts(), 'The order object should be updated' );
+ $this->assertTrue( $this->sut->get_recorded_coupon_usage_counts( $other_order->get_id() ), 'Other orders should keep their flag' );
+
+ $this->assertFalse( $this->sut->clear_recorded_coupon_usage_counts( $order ), 'A cleared flag should not be cleared again' );
+ }
+
+ /**
+ * Create a cancelled order marked as having its coupon usage counted.
+ *
+ * @return WC_Order
+ */
+ private function create_cancelled_order_with_counted_coupon_usage(): WC_Order {
+ $order = OrderHelper::create_order();
+ $order->set_status( OrderStatus::CANCELLED );
+ $order->save();
+ $this->sut->set_recorded_coupon_usage_counts( $order, true );
+
+ return $order;
+ }
}