Commit 14e1b1f4491 for woocommerce

commit 14e1b1f4491acc4e357415719ad91d2a8b5923a1
Author: Vlad Olaru <vlad.olaru@automattic.com>
Date:   Thu Nov 26 12:21:21 2026 +0200

    Keep a resumed order's items when a classic checkout retry fails on HPOS (#70977)

    fix(checkout): Keep a resumed order's items when the retry fails on HPOS

    When classic checkout resumes a pending order, create_order() stages
    the removal of the order's items for the next save() and adds the new
    items in memory, so a retry that fails leaves the order as it was. That
    is what #64326 set out to guarantee after #63553 (orders left with a
    total but no items).

    The catch block undid it on HPOS. It released held coupons with
    wc_release_coupons_for_order( $order ), which ends in save_meta_data().
    There is always a pending meta write there (set_data_from_cart()
    rewrites is_vat_exempt), and OrdersTableDataStore::after_meta_change()
    turns a meta write into a full save() when the order has no prop
    changes and was last modified in an earlier second. A shopper retrying
    with the same form meets both conditions, so the full save wrote the
    staged removals and the new items although checkout failed:
    extension-added items were deleted, rebuilt items got new IDs, and a
    failure at the coupon hold could leave the order with no items.

    The catch block now releases the coupon holds without saving the order
    until this attempt has saved it. Coupon holds are still released right
    away, since they live on the coupon. Before the save, the order keeps
    its previous _coupon_held_keys meta, which only points at released
    holds: the next attempt overwrites it, and add_coupon_used_by() inserts
    _used_by when a held row is gone. After the save, the order is written
    as before.

    The resume-failure test passed only when both saves fell in the same
    second, which is why it was flaky. It now backdates the order and runs
    for both resume paths, with new tests for a failure at the coupon hold
    and for the coupon hold release before and after the order is saved.

    Refs WOOPLUG-8239
    Refs #70970

    Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

diff --git a/plugins/woocommerce/changelog/70970-keep-items-when-checkout-retry-fails b/plugins/woocommerce/changelog/70970-keep-items-when-checkout-retry-fails
new file mode 100644
index 00000000000..c9e9742f9f0
--- /dev/null
+++ b/plugins/woocommerce/changelog/70970-keep-items-when-checkout-retry-fails
@@ -0,0 +1,4 @@
+Significance: patch
+Type: fix
+
+Keep an unpaid order's items unchanged when a classic checkout retry fails on stores using HPOS.
diff --git a/plugins/woocommerce/includes/class-wc-checkout.php b/plugins/woocommerce/includes/class-wc-checkout.php
index 5e6016ac09e..e0b53a46ce4 100644
--- a/plugins/woocommerce/includes/class-wc-checkout.php
+++ b/plugins/woocommerce/includes/class-wc-checkout.php
@@ -467,7 +467,8 @@ class WC_Checkout {
 			return $order_id;
 		}

-		$order = null;
+		$order          = null;
+		$is_order_saved = false;

 		try {
 			$order_id = absint( WC()->session->get( 'order_awaiting_payment' ) );
@@ -585,7 +586,8 @@ class WC_Checkout {
 			do_action( 'woocommerce_checkout_create_order', $order, $data );

 			// Save the order.
-			$order_id = $order->save();
+			$order_id       = $order->save();
+			$is_order_saved = true;

 			// This acquires the lock for a new order, or confirms ownership of a resumed order.
 			if ( ! OrderController::lock_order( $order_id ) ) {
@@ -629,7 +631,9 @@ class WC_Checkout {
 			return $order_id;
 		} catch ( Exception $e ) {
 			if ( $order instanceof WC_Order ) {
-				wc_release_coupons_for_order( $order );
+				// Until it is saved, the order holds this attempt's changes, such as a resumed order's staged item removals.
+				// Saving its meta would write them on HPOS, so release the coupon holds without saving the order.
+				wc_release_coupons_for_order( $order, $is_order_saved );
 				/**
 				 * Action hook fired when an order is discarded due to Exception.
 				 *
diff --git a/plugins/woocommerce/tests/php/includes/class-wc-checkout-test.php b/plugins/woocommerce/tests/php/includes/class-wc-checkout-test.php
index 4dca3f25c08..3846b5fe3e1 100644
--- a/plugins/woocommerce/tests/php/includes/class-wc-checkout-test.php
+++ b/plugins/woocommerce/tests/php/includes/class-wc-checkout-test.php
@@ -1870,9 +1870,13 @@ class WC_Checkout_Test extends \WC_Unit_Test_Case {
 	}

 	/**
-	 * @testdox Resuming a pending order keeps every original item when checkout fails before the order is saved.
+	 * @testdox Resuming a pending order in a later request keeps every original item when checkout fails before the order is saved, with $keep_items keeping unchanged items.
+	 * @testWith [true]
+	 *           [false]
+	 *
+	 * @param bool $keep_items The woocommerce_checkout_keep_order_items_on_resume value.
 	 */
-	public function test_create_order_resume_keeps_original_items_when_checkout_fails(): void {
+	public function test_create_order_resume_keeps_original_items_when_checkout_fails( bool $keep_items ): void {
 		$order_id = $this->create_order_with_line_item_and_fee();
 		$this->change_cart_section( $order_id, 'fee' );
 		wc_add_order_item(
@@ -1882,7 +1886,69 @@ class WC_Checkout_Test extends \WC_Unit_Test_Case {
 				'order_item_type' => 'line_item',
 			)
 		);
+		$this->set_order_modified_an_hour_ago( $order_id );
+		$before = $this->get_order_item_ids_by_type( $order_id );
+		add_filter( 'woocommerce_checkout_keep_order_items_on_resume', $keep_items ? '__return_true' : '__return_false' );
+		$fail = function () {
+			throw new Exception( 'Simulated checkout failure' );
+		};
+		add_action( 'woocommerce_checkout_create_order', $fail );
+
+		$result = $this->resume_order( $order_id );
+
+		$this->assertInstanceOf( WP_Error::class, $result );
+		$this->assertSame( 'Simulated checkout failure', $result->get_error_message() );
+		$this->assertCount( 2, $before['line_item'], 'The extension line item should be on the order before resuming.' );
+		$this->assertSame( $before, $this->get_order_item_ids_by_type( $order_id ), 'The order should keep its items and their IDs.' );
+
+		remove_action( 'woocommerce_checkout_create_order', $fail );
+		$this->assertSame( $order_id, $this->resume_order( $order_id ), 'A later retry should resume the same order.' );
+		$this->assert_line_items_match_cart( $order_id );
+	}
+
+	/**
+	 * @testdox Resuming a pending order keeps every original item when its coupon can no longer be held, with $keep_items keeping unchanged items.
+	 * @testWith [true]
+	 *           [false]
+	 *
+	 * @param bool $keep_items The woocommerce_checkout_keep_order_items_on_resume value.
+	 */
+	public function test_create_order_resume_keeps_original_items_when_coupon_cannot_be_held( bool $keep_items ): void {
+		$coupon   = $this->create_coupon_with_usage_limit( 1 );
+		$data     = array( 'billing_email' => 'shopper@example.com' );
+		$order_id = $this->create_order_with_line_item_and_coupon( $coupon, $data );
+		wc_add_order_item(
+			$order_id,
+			array(
+				'order_item_name' => 'Extension gift',
+				'order_item_type' => 'line_item',
+			)
+		);
+		// Another order uses the coupon's last use before the shopper retries.
+		$coupon->set_usage_count( 1 );
+		$coupon->save();
+		$this->set_order_modified_an_hour_ago( $order_id );
 		$before = $this->get_order_item_ids_by_type( $order_id );
+		add_filter( 'woocommerce_checkout_keep_order_items_on_resume', $keep_items ? '__return_true' : '__return_false' );
+
+		$result = $this->resume_order( $order_id, $data );
+
+		$this->assertInstanceOf( WP_Error::class, $result );
+		$this->assertStringContainsString( 'coupon usage limit is reached', $result->get_error_message() );
+		$this->assertSame( array( 'coupon', 'line_item' ), array_keys( $before ), 'The order should have a coupon and line items before resuming.' );
+		$this->assertSame( $before, $this->get_order_item_ids_by_type( $order_id ), 'The order should keep its items and their IDs.' );
+	}
+
+	/**
+	 * @testdox A failed retry of a pending order releases the coupon hold it took.
+	 */
+	public function test_create_order_resume_failure_releases_coupon_hold(): void {
+		$coupon   = $this->create_coupon_with_usage_limit( 5 );
+		$data     = array( 'billing_email' => 'shopper@example.com' );
+		$order_id = $this->create_order_with_line_item_and_coupon( $coupon, $data );
+		$this->set_order_modified_an_hour_ago( $order_id );
+		$holds = $this->get_coupon_hold_keys( $coupon->get_id() );
+		$this->assertCount( 1, $holds, 'The first checkout should hold the coupon.' );
 		add_action(
 			'woocommerce_checkout_create_order',
 			function () {
@@ -1890,12 +1956,31 @@ class WC_Checkout_Test extends \WC_Unit_Test_Case {
 			}
 		);

-		$result = $this->resume_order( $order_id );
+		$this->assertInstanceOf( WP_Error::class, $this->resume_order( $order_id, $data ) );
+
+		$this->assertSame( $holds, $this->get_coupon_hold_keys( $coupon->get_id() ), 'The retry should release the hold it took.' );
+	}
+
+	/**
+	 * @testdox Checkout that fails after saving a new order removes the released coupon holds from the order.
+	 */
+	public function test_create_order_failure_after_save_removes_coupon_holds_from_order(): void {
+		$coupon   = $this->create_coupon_with_usage_limit( 5 );
+		$order_id = 0;
+		add_action(
+			'woocommerce_checkout_order_created',
+			function ( WC_Order $order ) use ( &$order_id ) {
+				$order_id = $order->get_id();
+				throw new Exception( 'Simulated failure after save' );
+			}
+		);
+
+		$result = $this->create_order_with_line_item_and_coupon( $coupon, array( 'billing_email' => 'shopper@example.com' ), false );

 		$this->assertInstanceOf( WP_Error::class, $result );
-		$this->assertSame( 'Simulated checkout failure', $result->get_error_message() );
-		$this->assertCount( 2, $before['line_item'], 'The extension line item should be on the order before resuming.' );
-		$this->assertSame( $before, $this->get_order_item_ids_by_type( $order_id ), 'The changed fee and the extension line item should not be deleted.' );
+		$this->assertGreaterThan( 0, $order_id, 'The order should have been saved before the failure.' );
+		$this->assertSame( array(), $this->get_coupon_hold_keys( $coupon->get_id() ), 'The coupon hold should be released.' );
+		$this->assertSame( '', wc_get_order( $order_id )->get_meta( '_coupon_held_keys' ), 'The stored order should no longer list the released hold.' );
 	}

 	/**
@@ -2529,6 +2614,71 @@ class WC_Checkout_Test extends \WC_Unit_Test_Case {
 		return $order_id;
 	}

+	/**
+	 * Creates a coupon with a usage limit, so checkout holds a use of it for each order.
+	 *
+	 * @param int $usage_limit The coupon's usage limit.
+	 * @return WC_Coupon
+	 */
+	private function create_coupon_with_usage_limit( int $usage_limit ): WC_Coupon {
+		$coupon = WC_Helper_Coupon::create_coupon( 'limited-coupon' );
+		$coupon->set_usage_limit( $usage_limit );
+		$coupon->save();
+
+		return $coupon;
+	}
+
+	/**
+	 * Creates an order from a cart with one product and the given coupon.
+	 *
+	 * @param WC_Coupon $coupon      The coupon to apply.
+	 * @param array     $data        Posted checkout data to add.
+	 * @param bool      $must_create Whether to assert that the order was created.
+	 * @return int|WP_Error The order ID, or the checkout error.
+	 */
+	private function create_order_with_line_item_and_coupon( WC_Coupon $coupon, array $data, bool $must_create = true ) {
+		$product = WC_Helper_Product::create_simple_product();
+		WC()->cart->add_to_cart( $product->get_id(), 1 );
+		WC()->cart->apply_coupon( $coupon->get_code() );
+		WC()->cart->calculate_totals();
+
+		$order_id = $this->sut->create_order( array_merge( array( 'payment_method' => WC_Gateway_BACS::ID ), $data ) );
+		if ( $must_create ) {
+			$this->assertIsInt( $order_id );
+		}
+
+		return $order_id;
+	}
+
+	/**
+	 * Moves an order's modified date an hour back, as when the shopper retries checkout in a later request.
+	 *
+	 * @param int $order_id The order ID.
+	 */
+	private function set_order_modified_an_hour_ago( int $order_id ): void {
+		$order = wc_get_order( $order_id );
+		$order->set_date_modified( time() - HOUR_IN_SECONDS );
+		$order->save();
+	}
+
+	/**
+	 * Reads the meta keys of a coupon's held uses.
+	 *
+	 * @param int $coupon_id The coupon ID.
+	 * @return string[]
+	 */
+	private function get_coupon_hold_keys( int $coupon_id ): array {
+		global $wpdb;
+
+		return $wpdb->get_col(
+			$wpdb->prepare(
+				"SELECT meta_key FROM {$wpdb->postmeta} WHERE post_id = %d AND meta_key LIKE %s ORDER BY meta_key",
+				$coupon_id,
+				$wpdb->esc_like( '_coupon_held_' ) . '%'
+			)
+		);
+	}
+
 	/**
 	 * Creates an order from a cart taxed at two rates, with one product, one fee, a coupon and flat rate shipping, shipped to Germany.
 	 *