Commit 8ee573e4c81 for woocommerce
commit 8ee573e4c810034404539e24dc43a5f240c3819a
Author: Luigi Teschio <gigitux@gmail.com>
Date: Mon Nov 23 12:16:02 2026 +0100
Keep stock holds counted until the stock they cover is reduced (#71201)
* Keep stock holds counted until the stock they cover is reduced
(cherry picked from commit 9c7add265df5546cf1f11344536ea5da058a9d91)
* chore: Retrigger CI now the PR is marked as needing no changelog
---------
Co-authored-by: Chris Lilitsas <1105590+xristos3490@users.noreply.github.com>
diff --git a/plugins/woocommerce/includes/class-wc-cart.php b/plugins/woocommerce/includes/class-wc-cart.php
index e79f0412585..c86e0856e20 100644
--- a/plugins/woocommerce/includes/class-wc-cart.php
+++ b/plugins/woocommerce/includes/class-wc-cart.php
@@ -913,7 +913,7 @@ class WC_Cart extends WC_Legacy_Cart {
continue;
}
- // Check stock based on all items in the cart and consider any held stock within pending orders.
+ // Check stock based on all items in the cart and consider any stock held by other orders.
$held_stock = wc_get_held_stock_quantity( $product, $current_session_order_id );
$required_stock = $product_qty_in_cart[ $product->get_stock_managed_by_id() ];
diff --git a/plugins/woocommerce/includes/shortcodes/class-wc-shortcode-checkout.php b/plugins/woocommerce/includes/shortcodes/class-wc-shortcode-checkout.php
index 15af3478363..2ecbcc4a089 100644
--- a/plugins/woocommerce/includes/shortcodes/class-wc-shortcode-checkout.php
+++ b/plugins/woocommerce/includes/shortcodes/class-wc-shortcode-checkout.php
@@ -172,7 +172,7 @@ class WC_Shortcode_Checkout {
continue;
}
- // Check stock based on all items in the cart and consider any held stock within pending orders.
+ // Check stock based on all items in the cart and consider any stock held by other orders.
$held_stock = wc_get_held_stock_quantity( $product, $order->get_id() );
$required_stock = $quantities[ $product->get_stock_managed_by_id() ];
diff --git a/plugins/woocommerce/includes/wc-stock-functions.php b/plugins/woocommerce/includes/wc-stock-functions.php
index 69926fc739b..a87fc7ae70d 100644
--- a/plugins/woocommerce/includes/wc-stock-functions.php
+++ b/plugins/woocommerce/includes/wc-stock-functions.php
@@ -179,7 +179,8 @@ function wc_reduce_stock_levels( $order_id ) {
return;
}
- $changes = array();
+ $changes = array();
+ $reserve_stock = new ReserveStock();
// Loop over all items.
foreach ( $order->get_items() as $item ) {
@@ -212,6 +213,9 @@ function wc_reduce_stock_levels( $order_id ) {
continue;
}
+ // The reduced stock now covers these units, so lower the hold before they are counted twice.
+ $reserve_stock->lower_held_stock_for_product( $order->get_id(), $product->get_stock_managed_by_id(), wc_stock_amount( $qty ) );
+
$item->add_meta_data( '_reduced_stock', $qty, true );
$item->save();
@@ -233,6 +237,11 @@ function wc_reduce_stock_levels( $order_id ) {
do_action( 'woocommerce_reduce_order_item_stock', $item, $change, $order );
}
+ // Drop whatever is left of the hold, e.g. for items that were skipped or changed since it was placed.
+ if ( $order instanceof WC_Order ) {
+ wc_release_stock_for_order( $order );
+ }
+
wc_trigger_stock_change_notifications( $order, $changes );
do_action( 'woocommerce_reduce_order_stock', $order );
@@ -412,9 +421,11 @@ function wc_increase_stock_levels( $order_id ) {
}
/**
- * See how much stock is being held in pending orders.
+ * See how much stock is held by orders that have not yet reduced it.
*
* @since 3.5.0
+ * @since 11.3.1 Also counts holds for failed, processing, on-hold and completed orders until the
+ * hold is released or expires. See the woocommerce_reserved_stock_order_statuses filter.
* @param WC_Product $product Product to check.
* @param integer $exclude_order_id Order ID to exclude.
* @return int
@@ -467,21 +478,14 @@ add_action( 'woocommerce_checkout_order_created', 'wc_reserve_stock_for_order' )
/**
* Release held stock for an order.
*
+ * Not subject to woocommerce_hold_stock_for_checkout: a hold counts against stock until it is
+ * released or expires, so a release must never be skipped because of the context it runs in.
+ *
* @since 4.3.0
+ * @since 11.3.1 No longer skipped when woocommerce_hold_stock_for_checkout returns false.
* @param \WC_Order|int $order Order ID or instance.
*/
function wc_release_stock_for_order( $order ) {
- /**
- * Filter: woocommerce_hold_stock_for_checkout
- * Allows enable/disable hold stock functionality on checkout.
- *
- * @since 4.3.0
- * @param bool $enabled Default to true if managing stock globally.
- */
- if ( ! apply_filters( 'woocommerce_hold_stock_for_checkout', wc_string_to_bool( get_option( 'woocommerce_manage_stock', 'yes' ) ) ) ) {
- return;
- }
-
$order = $order instanceof WC_Order ? $order : wc_get_order( $order );
if ( $order ) {
@@ -492,6 +496,7 @@ function wc_release_stock_for_order( $order ) {
add_action( 'woocommerce_checkout_order_exception', 'wc_release_stock_for_order' );
add_action( 'woocommerce_payment_complete', 'wc_release_stock_for_order', 11 );
add_action( 'woocommerce_order_status_cancelled', 'wc_release_stock_for_order', 11 );
+add_action( 'woocommerce_order_status_failed', 'wc_release_stock_for_order', 11 );
add_action( 'woocommerce_order_status_completed', 'wc_release_stock_for_order', 11 );
add_action( 'woocommerce_order_status_processing', 'wc_release_stock_for_order', 11 );
add_action( 'woocommerce_order_status_on-hold', 'wc_release_stock_for_order', 11 );
diff --git a/plugins/woocommerce/src/Checkout/Helpers/ReserveStock.php b/plugins/woocommerce/src/Checkout/Helpers/ReserveStock.php
index e507401040e..61d3a64314a 100644
--- a/plugins/woocommerce/src/Checkout/Helpers/ReserveStock.php
+++ b/plugins/woocommerce/src/Checkout/Helpers/ReserveStock.php
@@ -34,6 +34,27 @@ final class ReserveStock {
*/
private const MAX_OWN_ORDERS = 10;
+ /**
+ * Internal statuses whose holds have always counted as held stock.
+ *
+ * The reserved stock query keeps them as a literal pair. See get_status_clause().
+ */
+ private const LEGACY_COUNTED_ORDER_STATUSES = array(
+ 'wc-' . OrderStatus::CHECKOUT_DRAFT,
+ OrderInternalStatus::PENDING,
+ );
+
+ /**
+ * Internal statuses an order can still be resumed and paid from.
+ *
+ * Only holds on these orders are ever excluded as the shopper's own. A paid
+ * order's hold keeps counting until wc_reduce_stock_levels() releases it.
+ */
+ private const UNPAID_ORDER_STATUSES = array(
+ ...self::LEGACY_COUNTED_ORDER_STATUSES,
+ OrderInternalStatus::FAILED,
+ );
+
/**
* Is stock reservation enabled?
*
@@ -231,6 +252,35 @@ final class ReserveStock {
);
}
+ /**
+ * Lower an order's hold on one product by the quantity just taken from stock.
+ *
+ * Must run right after the decrement so the units are not counted twice.
+ *
+ * @internal
+ * @since 11.3.1
+ *
+ * @param int $order_id Order holding the stock.
+ * @param int $product_id Stock-managed product ID.
+ * @param int|float $quantity Quantity that was taken from stock.
+ */
+ public function lower_held_stock_for_product( int $order_id, int $product_id, $quantity ): void {
+ global $wpdb;
+
+ if ( ! $this->is_enabled() || $quantity <= 0 ) {
+ return;
+ }
+
+ $wpdb->query(
+ $wpdb->prepare(
+ "UPDATE {$wpdb->wc_reserved_stock} SET `stock_quantity` = GREATEST( 0, `stock_quantity` - %f ) WHERE `order_id` = %d AND `product_id` = %d",
+ $quantity,
+ $order_id,
+ $product_id
+ )
+ );
+ }
+
/**
* Reserve stock for a product by inserting rows into the DB.
*
@@ -298,14 +348,14 @@ final class ReserveStock {
private function get_query_for_reserved_stock( $product_id, $exclude_order_id ): string {
global $wpdb;
- $pending = OrderInternalStatus::PENDING;
if ( OrderUtil::custom_orders_table_usage_is_enabled() ) {
- $join = "{$wpdb->prefix}wc_orders orders ON stock_table.`order_id` = orders.id";
- $where_status = "orders.status IN ( 'wc-checkout-draft', '$pending' )";
+ $join = "{$wpdb->prefix}wc_orders orders ON stock_table.`order_id` = orders.id";
+ $status_column = 'orders.status';
} else {
- $join = "{$wpdb->posts} posts ON stock_table.`order_id` = posts.ID";
- $where_status = "posts.post_status IN ( 'wc-checkout-draft', '$pending' )";
+ $join = "{$wpdb->posts} posts ON stock_table.`order_id` = posts.ID";
+ $status_column = 'posts.post_status';
}
+ $where_status = $this->get_status_clause( $status_column, $this->get_counted_order_statuses() );
// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
$query = $wpdb->prepare(
@@ -322,13 +372,16 @@ final class ReserveStock {
);
// phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
- $query .= $this->get_stale_own_holds_exclusion_clause( $product_id, $exclude_order_id );
+ $query .= $this->get_stale_own_holds_exclusion_clause( $product_id, $exclude_order_id, $status_column );
/**
* Filter: woocommerce_query_for_reserved_stock
* Allows to filter the query for getting reserved stock of a product.
*
* @since 4.5.0
+ * @since 11.3.1 Holds are counted for failed, processing, on-hold and completed orders too, until
+ * the hold is released or expires. Use the woocommerce_reserved_stock_order_statuses
+ * filter to change the counted statuses instead of editing this query.
* @param string $query The query for getting reserved stock of a product.
* @param int $product_id Product ID.
* @param int $exclude_order_id Order to exclude from the results.
@@ -336,14 +389,95 @@ final class ReserveStock {
return apply_filters( 'woocommerce_query_for_reserved_stock', $query, $product_id, $exclude_order_id );
}
+ /**
+ * Builds the status condition of the reserved stock query.
+ *
+ * The two statuses counted before 11.3.1 are kept as the literal
+ * `IN ( 'wc-checkout-draft', 'wc-pending' )`, with any further statuses in a
+ * second IN list, because woocommerce_query_for_reserved_stock callbacks are
+ * known to string-replace that literal to add their own statuses.
+ *
+ * @param string $status_column Status column of the joined order table.
+ * @param string[] $statuses Internal order statuses to count.
+ * @return string SQL condition.
+ */
+ private function get_status_clause( string $status_column, array $statuses ): string {
+ $legacy_statuses = self::LEGACY_COUNTED_ORDER_STATUSES;
+ $extra_statuses = array_values( array_diff( $statuses, $legacy_statuses ) );
+
+ if ( count( array_intersect( $legacy_statuses, $statuses ) ) !== count( $legacy_statuses ) ) {
+ return "$status_column IN ( " . $this->quote_status_list( $statuses ) . ' )';
+ }
+
+ $clause = "$status_column IN ( " . $this->quote_status_list( $legacy_statuses ) . ' )';
+
+ if ( empty( $extra_statuses ) ) {
+ return $clause;
+ }
+
+ return "( $clause OR $status_column IN ( " . $this->quote_status_list( $extra_statuses ) . ' ) )';
+ }
+
+ /**
+ * Quotes and escapes a list of statuses for use inside an SQL IN list.
+ *
+ * @param string[] $statuses Statuses.
+ * @return string Comma-separated quoted statuses.
+ */
+ private function quote_status_list( array $statuses ): string {
+ return "'" . implode( "', '", array_map( 'esc_sql', $statuses ) ) . "'";
+ }
+
+ /**
+ * Returns the internal order statuses whose stock holds count as held stock.
+ *
+ * Payment writes the new status before stock is reduced, so holds on paid statuses
+ * stay counted until wc_reduce_stock_levels() releases them. Failed is counted because
+ * checkout resumes a failed order and reserves again without changing its status.
+ *
+ * @return string[] Internal (prefixed) order statuses.
+ */
+ private function get_counted_order_statuses(): array {
+ $default_statuses = array(
+ ...self::LEGACY_COUNTED_ORDER_STATUSES,
+ OrderInternalStatus::FAILED,
+ OrderInternalStatus::PROCESSING,
+ OrderInternalStatus::ON_HOLD,
+ OrderInternalStatus::COMPLETED,
+ );
+
+ /**
+ * Filters the internal order statuses whose stock holds count as held stock.
+ *
+ * A custom status that is paid before its stock is reduced should be added here so
+ * its hold keeps counting until wc_reduce_stock_levels() releases it. Statuses not
+ * listed stop counting as soon as the order enters them.
+ *
+ * @since 11.3.1
+ *
+ * @param string[] $statuses Internal order statuses, e.g. 'wc-processing'. Unprefixed slugs are accepted.
+ */
+ $statuses = apply_filters( 'woocommerce_reserved_stock_order_statuses', $default_statuses );
+
+ if ( ! is_array( $statuses ) ) {
+ return $default_statuses;
+ }
+
+ $statuses = array_filter( array_map( 'strval', array_filter( $statuses, 'is_scalar' ) ) );
+ $statuses = array_values( array_unique( array_map( fn( $status ) => 0 === strpos( $status, 'wc-' ) ? $status : 'wc-' . $status, $statuses ) ) );
+
+ return empty( $statuses ) ? $default_statuses : $statuses;
+ }
+
/**
* Builds a SQL clause excluding the current shopper's stale stock holds.
*
- * @param int $product_id Product whose reserved stock is being counted.
- * @param int $exclude_order_id Order already excluded by the caller.
+ * @param int $product_id Product whose reserved stock is being counted.
+ * @param int $exclude_order_id Order already excluded by the caller.
+ * @param string $status_column Status column of the order table joined by the caller.
* @return string SQL clause, or an empty string when no holds qualify.
*/
- private function get_stale_own_holds_exclusion_clause( $product_id, $exclude_order_id ): string {
+ private function get_stale_own_holds_exclusion_clause( $product_id, $exclude_order_id, string $status_column ): string {
global $wpdb;
/**
@@ -374,15 +508,21 @@ final class ReserveStock {
return '';
}
- $placeholders = implode( ',', array_fill( 0, count( $order_ids ), '%d' ) );
+ $placeholders = implode( ',', array_fill( 0, count( $order_ids ), '%d' ) );
+ $unpaid_statuses = $this->quote_status_list( self::UNPAID_ORDER_STATUSES );
// The `timestamp` column records when the hold was first placed, so it
// measures the age of the shopper's attempt rather than of the last write.
- // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- The interpolated value contains only generated %d placeholders.
+ // The status check is applied here rather than when collecting the ids:
+ // the session list and the per-request customer memo can still name an
+ // order after it has been paid, and its hold must keep counting until
+ // wc_reduce_stock_levels() releases it.
+ // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Interpolated values are generated %d placeholders, a column name and constant statuses.
return $wpdb->prepare(
"
AND NOT (
stock_table.`order_id` IN ( $placeholders )
+ AND $status_column IN ( $unpaid_statuses )
AND stock_table.`timestamp` < ( NOW() - INTERVAL %d MINUTE )
)
",
@@ -486,8 +626,8 @@ final class ReserveStock {
* Returns order ids of a signed-in customer that could be holding stock, newest first.
*
* Covers a shopper whose session pointers were lost (new device, cleared
- * cookies, lapsed session). The statuses match the ones the reserved stock
- * query counts.
+ * cookies, lapsed session). Only unpaid statuses are listed to keep the lookup
+ * small; get_stale_own_holds_exclusion_clause() enforces the same rule in SQL.
*
* @param int $customer_id Customer ID.
* @return int[]
@@ -501,7 +641,7 @@ final class ReserveStock {
$order_ids = wc_get_orders(
array(
'customer' => $customer_id,
- 'status' => array( OrderStatus::CHECKOUT_DRAFT, OrderStatus::PENDING ),
+ 'status' => array( OrderStatus::CHECKOUT_DRAFT, OrderStatus::PENDING, OrderStatus::FAILED ),
'limit' => self::MAX_OWN_ORDERS,
'orderby' => 'date',
'order' => 'DESC',
diff --git a/plugins/woocommerce/src/StoreApi/Routes/V1/Checkout.php b/plugins/woocommerce/src/StoreApi/Routes/V1/Checkout.php
index 899b1f1c097..431978fcb9b 100644
--- a/plugins/woocommerce/src/StoreApi/Routes/V1/Checkout.php
+++ b/plugins/woocommerce/src/StoreApi/Routes/V1/Checkout.php
@@ -673,8 +673,10 @@ class Checkout extends AbstractCartRoute {
* Via the block based checkout and Store API we already have a draft order, but when POSTing to the /checkout
* endpoint we do the same; reserve stock for the order to allow time to process payment.
*
- * Note, stock is only "held" while the order has the status wc-checkout-draft or pending. Stock is freed when
- * the order changes status, or there is an exception.
+ * Note, stock stays "held" while the order is in one of the statuses counted by the reserved stock
+ * query (see the woocommerce_reserved_stock_order_statuses filter) and until the hold expires or is
+ * released. The hold is released once the order's stock is reduced, on cancellation or failure, or
+ * on an exception.
*
* @see ReserveStock::get_query_for_reserved_stock()
*
diff --git a/plugins/woocommerce/src/StoreApi/Utilities/OrderController.php b/plugins/woocommerce/src/StoreApi/Utilities/OrderController.php
index 521a88f1e0c..a02576c0a04 100644
--- a/plugins/woocommerce/src/StoreApi/Utilities/OrderController.php
+++ b/plugins/woocommerce/src/StoreApi/Utilities/OrderController.php
@@ -1263,7 +1263,7 @@ class OrderController {
continue;
}
- // Check stock based on all items in the cart and consider any held stock within pending orders.
+ // Check stock based on all items in the cart and consider any stock held by other orders.
$held_stock = wc_get_held_stock_quantity( $product, $order->get_id() );
$required_stock = $quantities[ $product->get_stock_managed_by_id() ];
diff --git a/plugins/woocommerce/tests/php/includes/wc-stock-functions-tests.php b/plugins/woocommerce/tests/php/includes/wc-stock-functions-tests.php
index 97589c059f2..5d190f228a1 100644
--- a/plugins/woocommerce/tests/php/includes/wc-stock-functions-tests.php
+++ b/plugins/woocommerce/tests/php/includes/wc-stock-functions-tests.php
@@ -7,6 +7,7 @@
use Automattic\WooCommerce\Checkout\Helpers\ReserveStock;
use Automattic\WooCommerce\Enums\OrderInternalStatus;
+use Automattic\WooCommerce\Enums\OrderStatus;
/**
* Class WC_Stock_Functions_Tests.
@@ -401,6 +402,377 @@ class WC_Stock_Functions_Tests extends \WC_Unit_Test_Case {
);
}
+ /**
+ * @testdox Available stock stays constant while a paid order's hold is swapped for a stock reduction.
+ */
+ public function test_stock_hold_counts_until_stock_is_reduced_on_payment() {
+ $product = WC_Helper_Product::create_simple_product(
+ true,
+ array(
+ 'manage_stock' => true,
+ 'stock_quantity' => 10,
+ )
+ );
+
+ $this->assert_available_stock_constant_through_payment( $product, $product, 1, 9 );
+ }
+
+ /**
+ * @testdox Available parent stock stays constant while a parent-managed variation order is paid.
+ */
+ public function test_parent_managed_variation_hold_counts_until_stock_is_reduced_on_payment() {
+ $parent = WC_Helper_Product::create_variation_product();
+ $parent->set_manage_stock( true );
+ $parent->set_stock_quantity( 10 );
+ $parent->save();
+
+ // The cart needs every attribute chosen, so use a variation that sets all of them.
+ $variation = null;
+ foreach ( $parent->get_children() as $child_id ) {
+ $child = wc_get_product( $child_id );
+ if ( ! in_array( '', $child->get_variation_attributes(), true ) ) {
+ $variation = $child;
+ break;
+ }
+ }
+ $this->assertNotNull( $variation, 'The helper should create a fully specified variation.' );
+ $variation->set_manage_stock( false );
+ $variation->save();
+
+ $this->assertSame( $parent->get_id(), $variation->get_stock_managed_by_id(), 'The parent should manage the variation stock.' );
+
+ $this->assert_available_stock_constant_through_payment( $variation, $parent, 2, 8 );
+ }
+
+ /**
+ * @testdox Available parent stock stays constant after each item when two variations share one hold.
+ */
+ public function test_shared_hold_is_lowered_item_by_item_on_payment() {
+ $parent = WC_Helper_Product::create_variation_product();
+ $parent->set_manage_stock( true );
+ $parent->set_stock_quantity( 10 );
+ $parent->save();
+
+ // The cart needs every attribute chosen, so use variations that set all of them.
+ $variations = array();
+ foreach ( $parent->get_children() as $child_id ) {
+ $child = wc_get_product( $child_id );
+ if ( count( $variations ) < 2 && ! in_array( '', $child->get_variation_attributes(), true ) ) {
+ $child->set_manage_stock( false );
+ $child->save();
+ $variations[] = $child;
+ }
+ }
+ $this->assertCount( 2, $variations, 'The helper should create two fully specified variations.' );
+
+ // Two items of two units each share the parent's hold of four.
+ $this->assert_available_stock_constant_through_payment( $variations, $parent, 2, 6 );
+ }
+
+ /**
+ * Pay for an order of $quantity units of each product and check available stock never moves.
+ *
+ * @param WC_Product|WC_Product[] $products Product or products added to the cart.
+ * @param WC_Product $stock_product Product whose stock is managed.
+ * @param int $quantity Units ordered of each product.
+ * @param int $expected_available Stock minus the order's units.
+ */
+ private function assert_available_stock_constant_through_payment( $products, $stock_product, $quantity, $expected_available ) {
+ $products = is_array( $products ) ? $products : array( $products );
+ $observed = $this->with_stock_reservation_options(
+ '60',
+ function () use ( $products, $stock_product, $quantity, $expected_available ) {
+ WC()->cart->empty_cart();
+ foreach ( $products as $product ) {
+ if ( $product->is_type( 'variation' ) ) {
+ $cart_item_key = WC()->cart->add_to_cart( $product->get_parent_id(), $quantity, $product->get_id(), $product->get_variation_attributes() );
+ } else {
+ $cart_item_key = WC()->cart->add_to_cart( $product->get_id(), $quantity );
+ }
+ $this->assertNotFalse( $cart_item_key, 'The product should be added to the cart: ' . wc_print_notices( true ) );
+ }
+ WC()->cart->calculate_totals();
+
+ $checkout = WC_Checkout::instance();
+ $order = new WC_Order();
+ $checkout->set_data_from_cart( $order );
+ $order->set_status( OrderInternalStatus::PENDING );
+ $order->save();
+ wc_reserve_stock_for_order( $order );
+
+ $this->assertSame( $expected_available, $this->get_available_stock( $stock_product->get_id() ), 'The pending order should hold its units.' );
+
+ $observed = array();
+ foreach ( array( 9, 10, 11 ) as $priority ) {
+ add_action(
+ 'woocommerce_order_status_processing',
+ function () use ( &$observed, $stock_product, $priority ) {
+ $observed[ $priority ] = $this->get_available_stock( $stock_product->get_id() );
+ },
+ $priority
+ );
+ }
+
+ // Fires inside the reduction loop, once per item, after its stock is reduced and its share of the hold lowered.
+ add_action(
+ 'woocommerce_reduce_order_item_stock',
+ function () use ( &$observed, $stock_product ) {
+ $observed['item'][] = $this->get_available_stock( $stock_product->get_id() );
+ }
+ );
+
+ $order->update_status( OrderInternalStatus::PROCESSING );
+
+ return $observed;
+ }
+ );
+
+ $this->assertSame(
+ array(
+ 9 => $expected_available,
+ 'item' => array_fill( 0, count( $products ), $expected_available ),
+ 10 => $expected_available,
+ 11 => $expected_available,
+ ),
+ $observed,
+ 'Available stock should neither jump after the status is written nor drop while the hold and the reduction overlap.'
+ );
+ $this->assertSame( $expected_available, $this->get_available_stock( $stock_product->get_id() ), 'The reduced stock should be the only thing counted after the transition.' );
+ }
+
+ /**
+ * @testdox Stock holds count for orders in status $status: $expected.
+ *
+ * @dataProvider stock_hold_status_provider
+ *
+ * @param string $status Internal order status.
+ * @param bool $expected Whether the hold should count.
+ */
+ public function test_stock_hold_counts_by_order_status( $status, $expected ) {
+ $this->assertSame( $expected ? 2 : 0, $this->get_held_quantity_for_order_in_status( $status ), "A hold for a $status order should " . ( $expected ? '' : 'not ' ) . 'count.' );
+ }
+
+ /**
+ * Held stock as seen by wc_get_held_stock_quantity() for a two-unit hold on an order in $status.
+ *
+ * @param string $status Internal order status, registered on the fly if unknown.
+ * @return int
+ */
+ private function get_held_quantity_for_order_in_status( $status ) {
+ global $wpdb;
+
+ return (int) $this->with_stock_reservation_options(
+ '60',
+ function () use ( $status, $wpdb ) {
+ // Register the status the way an extension would, so it is stored with its prefix.
+ $is_custom_status = null === get_post_status_object( $status );
+ if ( $is_custom_status ) {
+ register_post_status( $status, array( 'label' => $status ) );
+ add_filter(
+ 'wc_order_statuses',
+ function ( $statuses ) use ( $status ) {
+ return $statuses + array( $status => $status );
+ }
+ );
+ }
+
+ try {
+ $order = $this->create_order_from_cart_with_status( $status );
+ $product = $this->stock_product;
+
+ $wpdb->delete( $wpdb->wc_reserved_stock, array( 'order_id' => $order->get_id() ) );
+ // Expiry is compared against the database's NOW(), so write it there too.
+ $wpdb->query(
+ $wpdb->prepare(
+ "INSERT INTO {$wpdb->wc_reserved_stock} ( `order_id`, `product_id`, `stock_quantity`, `timestamp`, `expires` ) VALUES ( %d, %d, 2, NOW(), NOW() + INTERVAL 1 HOUR )", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
+ $order->get_id(),
+ $product->get_id()
+ )
+ );
+
+ return wc_get_held_stock_quantity( $product );
+ } finally {
+ if ( $is_custom_status ) {
+ _unregister_post_status( $status );
+ }
+ }
+ }
+ );
+ }
+
+ /**
+ * @testdox Failing an order releases its stock hold.
+ */
+ public function test_failing_an_order_releases_its_hold() {
+ $held = $this->with_stock_reservation_options(
+ '60',
+ function () {
+ $order = $this->create_order_from_cart_with_status( OrderInternalStatus::PENDING );
+ wc_reserve_stock_for_order( $order );
+ $this->assertSame( 1, (int) wc_get_held_stock_quantity( $this->stock_product ), 'The pending order should hold its units.' );
+
+ $order->update_status( OrderStatus::FAILED );
+
+ return (int) wc_get_held_stock_quantity( $this->stock_product );
+ }
+ );
+
+ $this->assertSame( 0, $held );
+ }
+
+ /**
+ * @testdox Reducing an order's stock releases its hold even when woocommerce_hold_stock_for_checkout is false.
+ */
+ public function test_reducing_stock_releases_hold_regardless_of_hold_stock_filter() {
+ $held = $this->with_stock_reservation_options(
+ '60',
+ function () {
+ $order = $this->create_order_from_cart_with_status( OrderInternalStatus::PENDING );
+ wc_reserve_stock_for_order( $order );
+ $this->assertSame( 1, (int) wc_get_held_stock_quantity( $this->stock_product ), 'The pending order should hold its units.' );
+
+ add_filter( 'woocommerce_hold_stock_for_checkout', '__return_false' );
+ try {
+ wc_reduce_stock_levels( $order );
+ } finally {
+ remove_filter( 'woocommerce_hold_stock_for_checkout', '__return_false' );
+ }
+
+ return (int) wc_get_held_stock_quantity( $this->stock_product );
+ }
+ );
+
+ $this->assertSame( 0, $held );
+ }
+
+ /**
+ * @testdox A custom status added through woocommerce_reserved_stock_order_statuses counts its holds.
+ */
+ public function test_stock_hold_counts_for_status_added_by_filter() {
+ $add_status = function ( $statuses ) {
+ $statuses[] = 'wc-awaiting-shipment';
+ return $statuses;
+ };
+ add_filter( 'woocommerce_reserved_stock_order_statuses', $add_status );
+
+ try {
+ $held = $this->get_held_quantity_for_order_in_status( 'wc-awaiting-shipment' );
+ } finally {
+ remove_filter( 'woocommerce_reserved_stock_order_statuses', $add_status );
+ }
+
+ $this->assertSame( 2, $held, 'A status added through the filter should count its holds.' );
+ }
+
+ /**
+ * @testdox An unprefixed status added through woocommerce_reserved_stock_order_statuses counts its holds.
+ */
+ public function test_stock_hold_counts_for_unprefixed_status_added_by_filter() {
+ $add_status = function ( $statuses ) {
+ $statuses[] = 'awaiting-shipment';
+ return $statuses;
+ };
+ add_filter( 'woocommerce_reserved_stock_order_statuses', $add_status );
+
+ try {
+ $held = $this->get_held_quantity_for_order_in_status( 'wc-awaiting-shipment' );
+ } finally {
+ remove_filter( 'woocommerce_reserved_stock_order_statuses', $add_status );
+ }
+
+ $this->assertSame( 2, $held, 'An unprefixed status added through the filter should count its holds.' );
+ }
+
+ /**
+ * @testdox A woocommerce_query_for_reserved_stock callback that string-replaces the pre-11.3.1 status literal still works.
+ */
+ public function test_stock_hold_counts_for_status_added_by_replacing_legacy_query_literal() {
+ $replace_literal = function ( $query ) {
+ return str_replace(
+ "IN ( 'wc-checkout-draft', 'wc-pending' )",
+ "IN ( 'wc-checkout-draft', 'wc-pending', 'wc-quote-open' )",
+ $query
+ );
+ };
+ add_filter( 'woocommerce_query_for_reserved_stock', $replace_literal );
+
+ try {
+ $held = $this->get_held_quantity_for_order_in_status( 'wc-quote-open' );
+ } finally {
+ remove_filter( 'woocommerce_query_for_reserved_stock', $replace_literal );
+ }
+
+ $this->assertSame( 2, $held, 'A status added by replacing the legacy status literal should count its holds.' );
+ }
+
+ /**
+ * @testdox An unusable return from woocommerce_reserved_stock_order_statuses falls back to the default list.
+ *
+ * @dataProvider invalid_stock_hold_statuses_provider
+ *
+ * @param callable $callback Filter callback returning an unusable value.
+ */
+ public function test_stock_hold_statuses_filter_ignores_invalid_return( $callback ) {
+ add_filter( 'woocommerce_reserved_stock_order_statuses', $callback );
+
+ try {
+ $held = $this->get_held_quantity_for_order_in_status( OrderInternalStatus::PROCESSING );
+ } finally {
+ remove_filter( 'woocommerce_reserved_stock_order_statuses', $callback );
+ }
+
+ $this->assertSame( 2, $held, 'An unusable filter return should leave the default statuses counted.' );
+ }
+
+ /**
+ * Filter returns that must not change which holds are counted.
+ *
+ * @return array[]
+ */
+ public function invalid_stock_hold_statuses_provider() {
+ return array(
+ 'non-array' => array( '__return_false' ),
+ 'empty array' => array( '__return_empty_array' ),
+ 'non-scalars only' => array(
+ function () {
+ return array( array(), new stdClass() );
+ },
+ ),
+ );
+ }
+
+ /**
+ * Statuses whose holds must count, and those whose holds must not.
+ *
+ * @return array[]
+ */
+ public function stock_hold_status_provider() {
+ return array(
+ 'checkout-draft' => array( 'wc-checkout-draft', true ),
+ 'pending' => array( OrderInternalStatus::PENDING, true ),
+ 'processing' => array( OrderInternalStatus::PROCESSING, true ),
+ 'on-hold' => array( OrderInternalStatus::ON_HOLD, true ),
+ 'completed' => array( OrderInternalStatus::COMPLETED, true ),
+ 'cancelled' => array( OrderInternalStatus::CANCELLED, false ),
+ 'failed' => array( OrderInternalStatus::FAILED, true ),
+ 'refunded' => array( OrderInternalStatus::REFUNDED, false ),
+ 'trash' => array( OrderStatus::TRASH, false ),
+ 'custom' => array( 'wc-awaiting-shipment', false ),
+ );
+ }
+
+ /**
+ * Stock on hand minus held stock, read fresh from the database.
+ *
+ * @param int $product_id Product ID.
+ * @return int
+ */
+ private function get_available_stock( $product_id ) {
+ $product = wc_get_product( $product_id );
+
+ return (int) ( $product->get_stock_quantity() - wc_get_held_stock_quantity( $product ) );
+ }
+
/**
* Test wc_get_low_stock_amount with a simple product which has low stock amount set.
*/
diff --git a/plugins/woocommerce/tests/php/src/Checkout/Helpers/ReserveStockOwnHoldsTest.php b/plugins/woocommerce/tests/php/src/Checkout/Helpers/ReserveStockOwnHoldsTest.php
index 247c36b0a28..b4c47b5edb5 100644
--- a/plugins/woocommerce/tests/php/src/Checkout/Helpers/ReserveStockOwnHoldsTest.php
+++ b/plugins/woocommerce/tests/php/src/Checkout/Helpers/ReserveStockOwnHoldsTest.php
@@ -154,6 +154,56 @@ class ReserveStockOwnHoldsTest extends WC_Unit_Test_Case {
$this->assertSame( 1, wc_get_held_stock_quantity( $product, 0 ) );
}
+ /**
+ * @testdox The shopper's own stale hold on a failed order is excluded after an opted-in threshold.
+ */
+ public function test_own_stale_failed_hold_is_excluded(): void {
+ $product = $this->create_stock_managed_product( 1 );
+ $shopper = $this->create_signed_in_shopper();
+ $order = $this->create_unpaid_order_for( $shopper, $product, OrderStatus::FAILED );
+
+ $this->hold_stock( $order, $product->get_id(), 1, 11 );
+
+ $this->assertSame( 0, $this->get_held_stock_quantity_with_threshold( $product, 0, 10 ) );
+ }
+
+ /**
+ * @testdox A paid order found through the customer lookup keeps its hold counted until its stock is reduced.
+ */
+ public function test_own_stale_paid_hold_from_customer_lookup_still_blocks(): void {
+ $product = $this->create_stock_managed_product( 1 );
+ $shopper = $this->create_signed_in_shopper();
+ $order = $this->create_unpaid_order_for( $shopper, $product );
+
+ $this->hold_stock( $order, $product->get_id(), 1, 11 );
+
+ // Precondition: while unpaid, the customer lookup excludes the hold and memoises the order id.
+ $this->assertSame( 0, $this->get_held_stock_quantity_with_threshold( $product, 0, 10 ) );
+
+ $this->pay_without_reducing_stock( $order );
+
+ $this->assertSame( 1, $this->get_held_stock_quantity_with_threshold( $product, 0, 10 ) );
+ }
+
+ /**
+ * @testdox A paid order recorded in the session list keeps its hold counted until its stock is reduced.
+ */
+ public function test_own_stale_paid_hold_from_session_list_still_blocks(): void {
+ $product = $this->create_stock_managed_product( 1 );
+ $order = $this->create_unpaid_order_for( 0, $product );
+
+ // The real reservation path, which is what records the order in the session.
+ wc_reserve_stock_for_order( wc_get_order( $order ) );
+ $this->age_hold( $order, 11 );
+
+ // Precondition: while unpaid, the session list excludes the hold.
+ $this->assertSame( 0, $this->get_held_stock_quantity_with_threshold( $product, 0, 10 ) );
+
+ $this->pay_without_reducing_stock( $order );
+
+ $this->assertSame( 1, $this->get_held_stock_quantity_with_threshold( $product, 0, 10 ) );
+ }
+
/**
* @testdox An invalid threshold leaves the shopper's own hold counted.
*/
@@ -336,6 +386,7 @@ class ReserveStockOwnHoldsTest extends WC_Unit_Test_Case {
$this->assertSame( 4242, $seen['exclude_order_id'] );
$this->assertSame( $product->get_id(), $seen['product_id'] );
$this->assertStringContainsString( 'AND NOT (', $seen['query'], 'The filter sees the complete core query.' );
+ $this->assertStringContainsString( "IN ( 'wc-checkout-draft', 'wc-pending' )", $seen['query'], 'The pre-11.3.1 status literal is kept for callbacks that string-replace it.' );
}
// ---------------------------------------------------------------------
@@ -468,6 +519,22 @@ class ReserveStockOwnHoldsTest extends WC_Unit_Test_Case {
// phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
}
+ /**
+ * Move an order to processing without reducing its stock.
+ *
+ * @param int $order_id Order to pay.
+ */
+ private function pay_without_reducing_stock( int $order_id ): void {
+ remove_action( 'woocommerce_order_status_processing', 'wc_maybe_reduce_stock_levels' );
+ remove_action( 'woocommerce_order_status_processing', 'wc_release_stock_for_order', 11 );
+ try {
+ wc_get_order( $order_id )->update_status( OrderStatus::PROCESSING );
+ } finally {
+ add_action( 'woocommerce_order_status_processing', 'wc_maybe_reduce_stock_levels' );
+ add_action( 'woocommerce_order_status_processing', 'wc_release_stock_for_order', 11 );
+ }
+ }
+
/**
* Backdate a hold that was created by the real reservation path.
*