Commit d75f2c3bb03 for woocommerce

commit d75f2c3bb0368134971013eabfd8948ba8db604b
Author: Christopher Hertel <mail@christopher-hertel.de>
Date:   Mon Nov 16 20:42:03 2026 +0100

    Add an order-delete ability (#70877)

    * Add an order-delete ability

    Agents could trash or delete products through the Core abilities but had
    no way to remove an order, so merchants had to do it in wp-admin. The new
    woocommerce/order-delete ability trashes an order by default, or deletes
    it for good with force, and reports which one happened.

    It runs on ActionableAbility, so order validators see the order with
    deleting set and can refuse, and syncs receive the trashed or deleted
    order. Permissions check the delete capability of the order's own type.

    * Test that a refused sync restores a removed order

    Cover the rollback of a trash and a forced delete in every storage and
    sync mode, run the blocked-delete test on both storages, and scope the
    save() docblock: only a forced delete removes the refunds under HPOS.

    * Grant the delete caps to the current user object in the custom order type test

    get_userdata() returns a separate WP_User, so the caps it added never
    reached the object current_user_can() reads, and the trash was refused.

    * Check the refunds of a force-deleted order

    A forced delete removes the order's refunds too. List them with the order, so
    the validators can refuse the cascade and the syncs see what was deleted. Fail
    the call when a refund survives, since the order store ignores a plugin that
    stops a refund delete. Assert the response fields one by one in the tests.

    * Test that order-delete honours a truthy REST grant for an unknown order

    * Check every child order that a forced order delete removes

    Under HPOS, the order store deletes every child of the order, not just its
    refunds, and a subscription is a child of its parent order. List the same
    children the store deletes, so the validators can refuse them and the syncs
    see them. Look them up again just before the delete and fail when they
    changed, so a refund or child added after the validators ran is not deleted
    unchecked.

    * Check delete-others access for an unknown order ID in order-delete

    The fallback for an ID with no order checked edit-others access. A user who
    may edit but not delete other users' orders then got a not-found error for a
    free ID and a permission error for a taken one, which tells which IDs exist.
    Check delete-others access instead, through the same REST permission filter.

    * Check the descendants that a forced order delete removes under HPOS

    Each child that HPOS deletes deletes its own children the same way, so a
    refund of a child order went unchecked. Collect the descendants the store
    deletes, going into a child only when its type is not hierarchical.

    * Share the administrator across the order-delete tests

diff --git a/plugins/woocommerce/changelog/wooai-1663-order-delete b/plugins/woocommerce/changelog/wooai-1663-order-delete
new file mode 100644
index 00000000000..cf3afd03f17
--- /dev/null
+++ b/plugins/woocommerce/changelog/wooai-1663-order-delete
@@ -0,0 +1,4 @@
+Significance: minor
+Type: add
+
+Add an ability that lets AI agents move an order to the trash or delete it permanently.
diff --git a/plugins/woocommerce/src/Internal/Abilities/AbilitiesLoader.php b/plugins/woocommerce/src/Internal/Abilities/AbilitiesLoader.php
index d42f82a698e..5caa24951be 100644
--- a/plugins/woocommerce/src/Internal/Abilities/AbilitiesLoader.php
+++ b/plugins/woocommerce/src/Internal/Abilities/AbilitiesLoader.php
@@ -14,6 +14,7 @@ use Automattic\WooCommerce\Internal\Abilities\Domain\OrderAddNote;
 use Automattic\WooCommerce\Internal\Abilities\Domain\OrderCreate;
 use Automattic\WooCommerce\Internal\Abilities\Domain\OrderNotesQuery;
 use Automattic\WooCommerce\Internal\Abilities\Domain\OrderSendEmail;
+use Automattic\WooCommerce\Internal\Abilities\Domain\OrderDelete;
 use Automattic\WooCommerce\Internal\Abilities\Domain\OrderUpdate;
 use Automattic\WooCommerce\Internal\Abilities\Domain\OrderUpdateStatus;
 use Automattic\WooCommerce\Internal\Abilities\Domain\CustomersQuery;
@@ -64,6 +65,7 @@ class AbilitiesLoader {
 		OrderCreate::class,
 		OrderNotesQuery::class,
 		OrderSendEmail::class,
+		OrderDelete::class,
 		OrderUpdate::class,
 		OrderUpdateStatus::class,
 		PaymentGatewaysQuery::class,
diff --git a/plugins/woocommerce/src/Internal/Abilities/Domain/OrderDelete.php b/plugins/woocommerce/src/Internal/Abilities/Domain/OrderDelete.php
new file mode 100644
index 00000000000..bf994bd478b
--- /dev/null
+++ b/plugins/woocommerce/src/Internal/Abilities/Domain/OrderDelete.php
@@ -0,0 +1,369 @@
+<?php
+/**
+ * Order delete ability definition file.
+ */
+
+declare( strict_types=1 );
+
+namespace Automattic\WooCommerce\Internal\Abilities\Domain;
+
+use Automattic\WooCommerce\Abilities\ActionableAbility;
+use Automattic\WooCommerce\Enums\OrderStatus;
+use Automattic\WooCommerce\Internal\Abilities\Domain\Traits\DomainAbilityHelpers;
+use Automattic\WooCommerce\Internal\Abilities\Domain\Traits\OrderAbilityTrait;
+use Automattic\WooCommerce\Internal\DataStores\Orders\OrdersTableDataStore;
+use Automattic\WooCommerce\Utilities\OrderUtil;
+
+defined( 'ABSPATH' ) || exit;
+
+/**
+ * Registers the WooCommerce order delete ability.
+ *
+ * The delete runs on the write pipeline of ActionableAbility, so the
+ * validators of the order resource can refuse it, the syncs see the deleted
+ * or trashed order, and a failure rolls everything back. A forced delete
+ * also deletes the orders that the order store deletes with it, such as
+ * refunds and, with HPOS, subscriptions, so they go through the same checks.
+ */
+class OrderDelete extends ActionableAbility {
+
+	use DomainAbilityHelpers;
+	use OrderAbilityTrait;
+
+	/**
+	 * Ability name.
+	 */
+	public const ABILITY_NAME = 'woocommerce/order-delete';
+
+	/**
+	 * The result status of a forced delete, which leaves nothing to restore.
+	 */
+	private const STATUS_DELETED = 'deleted';
+
+	/**
+	 * ID of the order the call deletes, kept because the delete clears the object's ID.
+	 *
+	 * @var int
+	 */
+	private int $order_id = 0;
+
+	/**
+	 * Whether the call deletes for good instead of trashing.
+	 *
+	 * @var bool
+	 */
+	private bool $force = false;
+
+	/**
+	 * IDs of the orders that the order store deletes with a forced delete, as the validators saw them.
+	 *
+	 * @var int[]
+	 */
+	private array $child_ids = array();
+
+	/**
+	 * The order the call will delete or trash, and the orders that a forced delete takes with it.
+	 *
+	 * @var \WC_Abstract_Order[]
+	 */
+	private array $deleting = array();
+
+	/**
+	 * The order and the orders deleted with it, as they were before a forced delete.
+	 *
+	 * @var \WC_Abstract_Order[]
+	 */
+	private array $deleted = array();
+
+	/**
+	 * The order the call moved to the trash.
+	 *
+	 * @var \WC_Order[]
+	 */
+	private array $trashed = array();
+
+	/**
+	 * Get the ability registration arguments.
+	 *
+	 * @return array
+	 *
+	 * @since 11.4.0
+	 */
+	public static function get_registration_args(): array {
+		return array(
+			'label'               => __( 'Delete order', 'woocommerce' ),
+			'description'         => __(
+				'Move an order to the trash, or delete it permanently.',
+				'woocommerce'
+			),
+			'category'            => 'woocommerce',
+			'input_schema'        => self::build_input_schema(),
+			'output_schema'       => self::build_output_schema(),
+			'permission_callback' => array( __CLASS__, 'can_delete_order' ),
+			'meta'                => array(
+				'show_in_rest' => true,
+				'mcp'          => array(
+					'public' => true,
+					'type'   => 'tool',
+				),
+				'annotations'  => array(
+					'readonly'    => false,
+					'idempotent'  => true,
+					'destructive' => true,
+				),
+			),
+		);
+	}
+
+	/**
+	 * The resource the ability changes.
+	 *
+	 * @return string
+	 */
+	public function get_resource(): string {
+		return 'order';
+	}
+
+	/**
+	 * A delete writes no extension fields.
+	 *
+	 * @return bool
+	 */
+	protected function writes_extension_fields(): bool {
+		return false;
+	}
+
+	/**
+	 * Load the order and check that it can be trashed when the call does not force a delete.
+	 *
+	 * @param array $input Ability input.
+	 * @return \WC_Order|\WP_Error
+	 */
+	protected function load( array $input ) {
+		$this->order_id  = 0;
+		$this->force     = $input['force'] ?? false;
+		$this->child_ids = array();
+		$this->deleting  = array();
+		$this->deleted   = array();
+		$this->trashed   = array();
+
+		$order = self::get_order_from_input( $input );
+
+		if ( is_wp_error( $order ) ) {
+			return $order;
+		}
+
+		/**
+		 * Filter whether an order supports trashing in WooCommerce domain abilities.
+		 *
+		 * @param bool      $supports_trash Whether the order supports trashing.
+		 * @param \WC_Order $order          The order being considered for trashing.
+		 *
+		 * @since 11.4.0
+		 */
+		$supports_trash = apply_filters( 'woocommerce_order_object_trashable', EMPTY_TRASH_DAYS > 0, $order );
+
+		if ( ! $this->force && ! $supports_trash ) {
+			return new \WP_Error(
+				'woocommerce_ability_order_trash_not_supported',
+				__( 'Trash is disabled on this site. Pass force: true to permanently delete.', 'woocommerce' ),
+				array( 'status' => 501 )
+			);
+		}
+
+		$this->order_id = $order->get_id();
+
+		return $order;
+	}
+
+	/**
+	 * Nothing changes in memory, and the delete saves no other object.
+	 *
+	 * @param \WC_Order $subject Order to delete.
+	 * @param array     $input   Ability input.
+	 * @return null
+	 */
+	protected function change( $subject, array $input ) {
+		unset( $input );
+
+		$this->child_ids = $this->force ? self::get_child_ids( $subject ) : array();
+		$this->deleting  = array_merge( array( $subject ), array_values( array_filter( array_map( 'wc_get_order', $this->child_ids ) ) ) );
+
+		return null;
+	}
+
+	/**
+	 * Delete or trash the order. A child order that appeared after the validators
+	 * ran, or that survives the delete because a plugin stopped it, fails the call.
+	 *
+	 * @param \WC_Order $subject Order to delete.
+	 * @return null|\WP_Error
+	 */
+	protected function save( $subject ) {
+		if ( $this->force && self::get_child_ids( $subject ) !== $this->child_ids ) {
+			return new \WP_Error(
+				'woocommerce_ability_order_children_changed',
+				__( 'The refunds or child orders of this order changed during the delete. Try again.', 'woocommerce' ),
+				array( 'status' => 409 )
+			);
+		}
+
+		if ( $this->force ) {
+			$this->deleted = array_map( static fn( \WC_Abstract_Order $order ) => clone $order, $this->deleting );
+		} else {
+			$this->trashed = array( clone $subject );
+		}
+
+		$deleted = $subject->delete( $this->force );
+		$stored  = wc_get_order( $this->order_id );
+
+		if (
+			! $deleted
+			|| ( $this->force && false !== $stored )
+			|| ( ! $this->force && ( ! $stored instanceof \WC_Order || OrderStatus::TRASH !== $stored->get_status( 'edit' ) ) )
+			|| array_filter( $this->child_ids, static fn( int $child_id ) => false !== wc_get_order( $child_id ) )
+		) {
+			return new \WP_Error(
+				'woocommerce_ability_order_delete_failed',
+				__( 'Failed to delete order.', 'woocommerce' ),
+				array( 'status' => 500 )
+			);
+		}
+
+		return null;
+	}
+
+	/**
+	 * IDs of the orders that the order store deletes with a forced delete of the order, sorted.
+	 *
+	 * The queries match what the order store does. HPOS deletes every child of
+	 * an order type that is not hierarchical, and each deleted child deletes its
+	 * own children the same way. The posts storage deletes the refunds of a shop order.
+	 *
+	 * @param \WC_Order $order Order to delete.
+	 * @return int[]
+	 */
+	private static function get_child_ids( \WC_Order $order ): array {
+		global $wpdb;
+
+		$ids = array();
+		if ( OrderUtil::custom_orders_table_usage_is_enabled() ) {
+			$orders_table = OrdersTableDataStore::get_orders_table_name();
+			$parents      = is_post_type_hierarchical( $order->get_type() ) ? array() : array( $order->get_id() );
+			while ( ! empty( $parents ) ) {
+				$placeholders = implode( ',', array_fill( 0, count( $parents ), '%d' ) );
+				// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare -- The table name comes from the data store, and the placeholders match the IDs.
+				$children = $wpdb->get_results( $wpdb->prepare( "SELECT id, type FROM $orders_table WHERE parent_order_id IN ( $placeholders )", $parents ) );
+				$parents  = array();
+				foreach ( $children as $child ) {
+					$child_id = (int) $child->id;
+					if ( in_array( $child_id, $ids, true ) || $order->get_id() === $child_id ) {
+						continue;
+					}
+					$ids[] = $child_id;
+					if ( ! is_post_type_hierarchical( $child->type ) ) {
+						$parents[] = $child_id;
+					}
+				}
+			}
+		} elseif ( 'shop_order' === $order->get_type() ) {
+			$ids = array_map( 'intval', $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_type = 'shop_order_refund' AND post_parent = %d", $order->get_id() ) ) );
+		}
+
+		sort( $ids );
+
+		return $ids;
+	}
+
+	/**
+	 * The order and, for a forced delete, the orders deleted with it, for the validators.
+	 *
+	 * @return \WC_Abstract_Order[]
+	 */
+	protected function get_objects_to_delete(): array {
+		return $this->deleting;
+	}
+
+	/**
+	 * The order and the orders deleted with it, as they were before a forced delete, which clears the ID of the live objects.
+	 *
+	 * @return \WC_Abstract_Order[]
+	 */
+	protected function get_deleted_objects(): array {
+		return $this->deleted;
+	}
+
+	/**
+	 * The order, when the call trashed it.
+	 *
+	 * @return \WC_Order[]
+	 */
+	protected function get_trashed_objects(): array {
+		return $this->trashed;
+	}
+
+	/**
+	 * The response of a delete.
+	 *
+	 * @param \WC_Order $subject Deleted order.
+	 * @return array
+	 */
+	protected function prepare_response( $subject ): array {
+		unset( $subject );
+
+		return array(
+			'id'     => $this->order_id,
+			'status' => $this->force ? self::STATUS_DELETED : OrderStatus::TRASH,
+		);
+	}
+
+	/**
+	 * Get the input schema.
+	 *
+	 * @return array
+	 */
+	private static function build_input_schema(): array {
+		return array(
+			'type'                 => 'object',
+			'properties'           => array(
+				'id'    => array(
+					'type'    => 'integer',
+					'minimum' => 1,
+				),
+				'force' => array(
+					'type'        => 'boolean',
+					'description' => __(
+						'Permanently delete the order. Defaults to false, which moves the order to trash.',
+						'woocommerce'
+					),
+					'default'     => false,
+				),
+			),
+			'required'             => array( 'id' ),
+			'additionalProperties' => false,
+		);
+	}
+
+	/**
+	 * Get the output schema.
+	 *
+	 * @return array
+	 */
+	private static function build_output_schema(): array {
+		return array(
+			'type'                 => 'object',
+			'properties'           => array(
+				'id'     => array(
+					'type'        => 'integer',
+					'description' => __( 'ID of the order.', 'woocommerce' ),
+				),
+				'status' => array(
+					'type'        => 'string',
+					'enum'        => array( OrderStatus::TRASH, self::STATUS_DELETED ),
+					'description' => __( 'What happened to the order. "trash": the order was moved to the trash, and can be restored. "deleted": the order was permanently deleted, and cannot be restored.', 'woocommerce' ),
+				),
+			),
+			'additionalProperties' => false,
+		);
+	}
+}
diff --git a/plugins/woocommerce/src/Internal/Abilities/Domain/Traits/OrderAbilityTrait.php b/plugins/woocommerce/src/Internal/Abilities/Domain/Traits/OrderAbilityTrait.php
index 1dd93332377..6c282973bc7 100644
--- a/plugins/woocommerce/src/Internal/Abilities/Domain/Traits/OrderAbilityTrait.php
+++ b/plugins/woocommerce/src/Internal/Abilities/Domain/Traits/OrderAbilityTrait.php
@@ -354,6 +354,20 @@ trait OrderAbilityTrait {
 		return $order_id > 0 && self::check_order_permission( $order_id, 'read' );
 	}

+	/**
+	 * Check order delete access for an ability input payload.
+	 *
+	 * @param mixed $input Ability input.
+	 * @return bool
+	 *
+	 * @since 11.4.0
+	 */
+	public static function can_delete_order( $input = array() ): bool {
+		$order_id = self::get_id_from_input( $input );
+
+		return $order_id > 0 && self::check_order_permission( $order_id, 'delete' );
+	}
+
 	/**
 	 * Check a permission against the actual type of an order. An order whose
 	 * type the abilities do not support fails. An ID that wc_get_order() has no
@@ -367,8 +381,25 @@ trait OrderAbilityTrait {
 	protected static function check_order_permission( int $order_id, string $context ): bool {
 		$class_names = \WC_Order_Factory::get_class_names_for_order_ids( array( $order_id ) );

+		if ( empty( $class_names[ $order_id ] ) && 'delete' === $context ) {
+			$type_object = get_post_type_object( 'shop_order' );
+			$permission  = $type_object instanceof \WP_Post_Type && current_user_can( $type_object->cap->delete_others_posts );
+
+			/**
+			 * Filter a REST API permission check, as wc_rest_check_post_permissions() does.
+			 *
+			 * @since 2.6.0
+			 *
+			 * @param bool   $permission Whether the current user has the permission.
+			 * @param string $context    Permission context.
+			 * @param int    $object_id  Object ID, 0 for no object.
+			 * @param string $post_type  Post type.
+			 */
+			return (bool) apply_filters( 'woocommerce_rest_check_permissions', $permission, 'delete', 0, 'shop_order' );
+		}
+
 		if ( empty( $class_names[ $order_id ] ) ) {
-			return (bool) wc_rest_check_post_permissions( 'shop_order', 'edit' === $context ? 'batch' : $context );
+			return (bool) wc_rest_check_post_permissions( 'shop_order', 'read' === $context ? 'read' : 'batch' );
 		}

 		$type = OrderUtil::get_order_type( $order_id );
diff --git a/plugins/woocommerce/tests/php/src/Internal/Abilities/AbilitiesLoaderTest.php b/plugins/woocommerce/tests/php/src/Internal/Abilities/AbilitiesLoaderTest.php
index 1780ec303af..4e507baa82c 100644
--- a/plugins/woocommerce/tests/php/src/Internal/Abilities/AbilitiesLoaderTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/Abilities/AbilitiesLoaderTest.php
@@ -46,6 +46,7 @@ class AbilitiesLoaderTest extends \WC_Unit_Test_Case {
 		'woocommerce/orders-query',
 		'woocommerce/order-send-email',
 		'woocommerce/order-create',
+		'woocommerce/order-delete',
 		'woocommerce/order-update',
 		'woocommerce/order-update-status',
 		'woocommerce/order-add-note',
@@ -322,6 +323,11 @@ class AbilitiesLoaderTest extends \WC_Unit_Test_Case {
 				'idempotent'  => false,
 				'destructive' => false,
 			),
+			'woocommerce/order-delete'              => array(
+				'readonly'    => false,
+				'idempotent'  => true,
+				'destructive' => true,
+			),
 			'woocommerce/order-update'              => array(
 				'readonly'    => false,
 				'idempotent'  => false,
@@ -1084,6 +1090,12 @@ class AbilitiesLoaderTest extends \WC_Unit_Test_Case {
 				'woocommerce/order-create',
 				array( 'line_items' => array( array( 'product_id' => 1 ) ) ),
 			),
+			'order-delete'             => array(
+				'woocommerce/order-delete',
+				array(
+					'id' => 1,
+				),
+			),
 			'order-update'             => array(
 				'woocommerce/order-update',
 				array(
@@ -1190,6 +1202,7 @@ class AbilitiesLoaderTest extends \WC_Unit_Test_Case {
 			'products-query'                 => array( 'woocommerce/products-query', $missing_id ),
 			'orders-query by type'           => array( 'woocommerce/orders-query', array() ),
 			'orders-query by missing order'  => array( 'woocommerce/orders-query', $missing_id ),
+			'order-delete by missing order'  => array( 'woocommerce/order-delete', $missing_id ),
 			'payment-gateways-query'         => array( 'woocommerce/payment-gateways-query', array() ),
 			'payment-gateway-update'         => array(
 				'woocommerce/payment-gateway-update',
@@ -1281,6 +1294,9 @@ class AbilitiesLoaderTest extends \WC_Unit_Test_Case {
 				'id'    => $order->get_id(),
 				'email' => 'invoice',
 			),
+			'woocommerce/order-delete'        => array(
+				'id' => $order->get_id(),
+			),
 			'woocommerce/order-update'        => array(
 				'id'       => $order->get_id(),
 				'shipping' => array( 'city' => 'Unauthorized city' ),
@@ -1455,6 +1471,9 @@ class AbilitiesLoaderTest extends \WC_Unit_Test_Case {
 				'id'    => $order_id,
 				'email' => 'invoice',
 			),
+			'woocommerce/order-delete'        => array(
+				'id' => $order_id,
+			),
 			'woocommerce/order-update'        => array(
 				'id'       => $order_id,
 				'shipping' => array( 'city' => 'Springfield' ),
@@ -1803,6 +1822,10 @@ class AbilitiesLoaderTest extends \WC_Unit_Test_Case {
 					'email' => 'invoice',
 				),
 			),
+			'order-delete'          => array(
+				'woocommerce/order-delete',
+				array( 'id' => -123 ),
+			),
 			'order-update'          => array(
 				'woocommerce/order-update',
 				array(
diff --git a/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/OrderDeleteTest.php b/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/OrderDeleteTest.php
new file mode 100644
index 00000000000..5be85e16719
--- /dev/null
+++ b/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/OrderDeleteTest.php
@@ -0,0 +1,290 @@
+<?php
+declare( strict_types = 1 );
+
+namespace Automattic\WooCommerce\Tests\Internal\Abilities\Domain;
+
+use Automattic\WooCommerce\Enums\OrderStatus;
+use Automattic\WooCommerce\RestApi\UnitTests\HPOSToggleTrait;
+use Automattic\WooCommerce\RestApi\UnitTests\Helpers\OrderHelper;
+use Automattic\WooCommerce\Utilities\OrderUtil;
+use WC_Unit_Test_Case;
+
+/**
+ * Tests for the order-delete ability.
+ */
+class OrderDeleteTest extends WC_Unit_Test_Case {
+	use HPOSToggleTrait;
+
+	/**
+	 * The order storage that was active before the test.
+	 *
+	 * @var bool|null
+	 */
+	private ?bool $original_hpos = null;
+
+	/**
+	 * An administrator, who may delete any order, that every test starts as.
+	 *
+	 * @var int
+	 */
+	private static $administrator_id;
+
+	/**
+	 * Create the HPOS tables outside the test transaction, since DDL commits implicitly.
+	 *
+	 * @param \WP_UnitTest_Factory $factory WordPress unit test factory.
+	 */
+	public static function wpSetUpBeforeClass( $factory ): void {
+		self::$administrator_id = $factory->user->create( array( 'role' => 'administrator' ) );
+
+		$previous_hpos = 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 ) {
+				OrderHelper::toggle_cot_feature_and_usage( $previous_hpos );
+			}
+		} finally {
+			remove_filter( 'wc_allow_changing_orders_storage_while_sync_is_pending', '__return_true' );
+		}
+	}
+
+	/**
+	 * Log in as the shared administrator.
+	 */
+	public function setUp(): void {
+		parent::setUp();
+
+		wp_set_current_user( self::$administrator_id );
+	}
+
+	/**
+	 * Restore the order storage a test switched.
+	 */
+	public function tearDown(): void {
+		try {
+			if ( null !== $this->original_hpos ) {
+				$this->toggle_cot_feature_and_usage( $this->original_hpos );
+				$this->original_hpos = null;
+			}
+		} finally {
+			remove_filter( 'wc_allow_changing_orders_storage_while_sync_is_pending', '__return_true' );
+			parent::tearDown();
+		}
+	}
+
+	/**
+	 * Storage modes.
+	 *
+	 * @return array<string, array{0: bool}>
+	 */
+	public function storage_modes(): array {
+		return array(
+			'posts storage' => array( false ),
+			'HPOS storage'  => array( true ),
+		);
+	}
+
+	/**
+	 * @testdox Should move an order to the trash by default, and report it as trashed, also when it is already there.
+	 *
+	 * @dataProvider storage_modes
+	 * @param bool $hpos Whether to use the custom orders table.
+	 */
+	public function test_trashes_an_order_by_default( bool $hpos ): void {
+		$this->use_storage( $hpos );
+		$order = OrderHelper::create_order();
+
+		$first  = $this->execute( array( 'id' => $order->get_id() ) );
+		$second = $this->execute( array( 'id' => $order->get_id() ) );
+
+		$this->assertArrayHasKey( 'id', $first );
+		$this->assertSame( $order->get_id(), $first['id'] );
+		$this->assertArrayHasKey( 'status', $first );
+		$this->assertSame( 'trash', $first['status'] );
+		$this->assertSame( 'trash', $second['status'], 'Trashing a trashed order should succeed again.' );
+		$this->assertSame( OrderStatus::TRASH, wc_get_order( $order->get_id() )->get_status() );
+	}
+
+	/**
+	 * @testdox Should delete an order and its refunds for good when force is true.
+	 *
+	 * @dataProvider storage_modes
+	 * @param bool $hpos Whether to use the custom orders table.
+	 */
+	public function test_force_deletes_an_order_and_its_refunds( bool $hpos ): void {
+		$this->use_storage( $hpos );
+		$order  = OrderHelper::create_order();
+		$refund = wc_create_refund(
+			array(
+				'order_id' => $order->get_id(),
+				'amount'   => 1,
+			)
+		);
+
+		$result = $this->execute(
+			array(
+				'id'    => $order->get_id(),
+				'force' => true,
+			)
+		);
+
+		$this->assertArrayHasKey( 'id', $result );
+		$this->assertSame( $order->get_id(), $result['id'] );
+		$this->assertArrayHasKey( 'status', $result );
+		$this->assertSame( 'deleted', $result['status'] );
+		$this->assertFalse( wc_get_order( $order->get_id() ) );
+		$this->assertFalse( wc_get_order( $refund->get_id() ), 'The refund of a deleted order should go with it.' );
+	}
+
+	/**
+	 * @testdox Should fail and keep the order when another plugin stops the delete of one of its refunds.
+	 */
+	public function test_fails_when_a_refund_survives_a_forced_delete(): void {
+		$this->use_storage( true );
+		$order  = OrderHelper::create_order();
+		$refund = wc_create_refund(
+			array(
+				'order_id' => $order->get_id(),
+				'amount'   => 1,
+			)
+		);
+		add_filter( 'woocommerce_pre_delete_order_refund', '__return_false' );
+
+		$result = wp_get_ability( 'woocommerce/order-delete' )->execute(
+			array(
+				'id'    => $order->get_id(),
+				'force' => true,
+			)
+		);
+
+		$this->assertWPError( $result );
+		$this->assertSame( 'woocommerce_ability_order_delete_failed', $result->get_error_code() );
+		$this->assertInstanceOf( \WC_Order::class, wc_get_order( $order->get_id() ), 'The rollback should restore the order.' );
+		$this->assertInstanceOf( \WC_Order_Refund::class, wc_get_order( $refund->get_id() ) );
+	}
+
+	/**
+	 * @testdox Should refuse to trash an order when the trash is disabled, and still delete it with force.
+	 */
+	public function test_refuses_trash_when_trash_is_disabled(): void {
+		$order = OrderHelper::create_order();
+		add_filter( 'woocommerce_order_object_trashable', '__return_false' );
+
+		$refused = wp_get_ability( 'woocommerce/order-delete' )->execute( array( 'id' => $order->get_id() ) );
+		$deleted = $this->execute(
+			array(
+				'id'    => $order->get_id(),
+				'force' => true,
+			)
+		);
+
+		$this->assertWPError( $refused );
+		$this->assertSame( 'woocommerce_ability_order_trash_not_supported', $refused->get_error_code() );
+		$this->assertSame( 'deleted', $deleted['status'] );
+	}
+
+	/**
+	 * @testdox Should report a failure when another plugin stops the delete.
+	 *
+	 * @dataProvider storage_modes
+	 * @param bool $hpos Whether to use the custom orders table.
+	 */
+	public function test_reports_a_delete_that_did_not_happen( bool $hpos ): void {
+		$this->use_storage( $hpos );
+		$order = OrderHelper::create_order();
+		add_filter( 'woocommerce_pre_delete_order', '__return_false' );
+
+		$result = wp_get_ability( 'woocommerce/order-delete' )->execute( array( 'id' => $order->get_id() ) );
+
+		$this->assertWPError( $result );
+		$this->assertSame( 'woocommerce_ability_order_delete_failed', $result->get_error_code() );
+		$this->assertNotSame( OrderStatus::TRASH, wc_get_order( $order->get_id() )->get_status() );
+	}
+
+	/**
+	 * @testdox Should trash an order of another order type, checking the delete capability of that type.
+	 */
+	public function test_trashes_an_order_of_another_type(): void {
+		global $wc_order_types, $post_type_meta_caps, $wpdb;
+
+		$this->use_storage( true );
+		$meta_caps = $post_type_meta_caps;
+		wc_register_order_type(
+			'shop_test_custom',
+			array(
+				'capability_type'          => 'shop_test_custom',
+				'map_meta_cap'             => true,
+				'exclude_from_order_views' => true,
+				'add_order_meta_boxes'     => false,
+			)
+		);
+		$order = OrderHelper::create_order();
+		$wpdb->update( $wpdb->posts, array( 'post_type' => 'shop_test_custom' ), array( 'ID' => $order->get_id() ) );
+		$wpdb->update( \Automattic\WooCommerce\Internal\DataStores\Orders\OrdersTableDataStore::get_orders_table_name(), array( 'type' => 'shop_test_custom' ), array( 'id' => $order->get_id() ) );
+		clean_post_cache( $order->get_id() );
+		wp_cache_flush();
+		$manager = self::factory()->user->create( array( 'role' => 'shop_manager' ) );
+		wp_set_current_user( $manager );
+
+		try {
+			$refused = wp_get_ability( 'woocommerce/order-delete' )->execute( array( 'id' => $order->get_id() ) );
+			wp_get_current_user()->add_cap( 'delete_others_shop_test_customs' );
+			wp_get_current_user()->add_cap( 'delete_published_shop_test_customs' );
+			$trashed = $this->execute( array( 'id' => $order->get_id() ) );
+		} finally {
+			unset( $wc_order_types['shop_test_custom'] );
+			unregister_post_type( 'shop_test_custom' );
+			$post_type_meta_caps = $meta_caps; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- unregister_post_type() removes the shop_order meta caps too.
+		}
+
+		$this->assertWPError( $refused );
+		$this->assertSame( 'ability_invalid_permissions', $refused->get_error_code(), 'Shop order caps should not cover another order type.' );
+		$this->assertSame( 'trash', $trashed['status'] );
+	}
+
+	/**
+	 * @testdox Should treat an unknown order ID like another user's order, so a user who may edit but not delete orders gets no hint that the ID is free.
+	 */
+	public function test_checks_delete_access_for_an_unknown_order_id(): void {
+		$order   = OrderHelper::create_order();
+		$ability = wp_get_ability( 'woocommerce/order-delete' );
+		wp_set_current_user( self::factory()->user->create( array( 'role' => 'subscriber' ) ) );
+		wp_get_current_user()->add_cap( 'edit_shop_orders' );
+		wp_get_current_user()->add_cap( 'edit_others_shop_orders' );
+
+		$existing = $ability->check_permissions( array( 'id' => $order->get_id() ) );
+		$unknown  = $ability->check_permissions( array( 'id' => PHP_INT_MAX ) );
+		wp_get_current_user()->add_cap( 'delete_others_shop_orders' );
+		$unknown_with_delete = $ability->check_permissions( array( 'id' => PHP_INT_MAX ) );
+
+		$this->assertFalse( $existing );
+		$this->assertFalse( $unknown, 'Edit access alone should not pass for an unknown ID.' );
+		$this->assertTrue( $unknown_with_delete );
+	}
+
+	/**
+	 * Execute the ability and check it succeeded.
+	 *
+	 * @param array $input Ability input.
+	 * @return array
+	 */
+	private function execute( array $input ): array {
+		$result = wp_get_ability( 'woocommerce/order-delete' )->execute( $input );
+
+		$this->assertIsArray( $result, is_wp_error( $result ) ? $result->get_error_message() : '' );
+
+		return $result;
+	}
+
+	/**
+	 * Switch the order storage for the test.
+	 *
+	 * @param bool $hpos Whether to use the custom orders table.
+	 */
+	private function use_storage( bool $hpos ): void {
+		$this->original_hpos = OrderUtil::custom_orders_table_usage_is_enabled();
+		add_filter( 'wc_allow_changing_orders_storage_while_sync_is_pending', '__return_true' );
+		$this->toggle_cot_feature_and_usage( $hpos );
+	}
+}
diff --git a/plugins/woocommerce/tests/php/src/Internal/AbilitiesApi/ExtensibleAbilitiesTest.php b/plugins/woocommerce/tests/php/src/Internal/AbilitiesApi/ExtensibleAbilitiesTest.php
index 1a27f92373b..ff40c3b899b 100644
--- a/plugins/woocommerce/tests/php/src/Internal/AbilitiesApi/ExtensibleAbilitiesTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/AbilitiesApi/ExtensibleAbilitiesTest.php
@@ -3160,6 +3160,320 @@ class ExtensibleAbilitiesTest extends \WC_REST_Unit_Test_Case {
 		$this->assertSame( array( 'woocommerce/product-delete', true ), $seen[ $created['product']['id'] ] );
 	}

+	/**
+	 * @testdox Should let an order validator refuse a trash and a permanent delete, and give the syncs the removed order.
+	 */
+	public function test_a_validator_can_refuse_deleting_an_order(): void {
+		$order    = \WC_Helper_Order::create_order();
+		$order_id = $order->get_id();
+		$refuse   = true;
+		$seen     = array();
+		$synced   = array();
+		$this->register_validator(
+			'order',
+			'test-ext',
+			static function ( \WC_Order $order, ActionableAbility $ability, array $context ) use ( &$seen, &$refuse ) {
+				$seen[] = array( $order->get_id(), $ability->get_name(), $context['deleting'] );
+				return $refuse ? new \WP_Error( 'test_cancel_first', 'Cancel it first.' ) : null;
+			}
+		);
+		$this->register_sync(
+			'order',
+			'test-ext',
+			static function ( array $saved, ActionableAbility $ability, array $context ) use ( &$synced ) {
+				unset( $ability );
+				$synced[] = array(
+					count( $saved ),
+					array_map( static fn( \WC_Order $order ) => $order->get_id(), $context['trashed'] ),
+					array_map( static fn( \WC_Order $order ) => $order->get_id(), $context['deleted'] ),
+				);
+			}
+		);
+		$this->reset_registries();
+		AbilitiesLoader::init_extensions();
+
+		$refused_trash  = $this->run_ability_response( 'woocommerce/order-delete', array( 'id' => $order_id ) );
+		$refused_delete = $this->run_ability_response(
+			'woocommerce/order-delete',
+			array(
+				'id'    => $order_id,
+				'force' => true,
+			)
+		);
+		$after_refusals = wc_get_order( $order_id )->get_status();
+		$refuse         = false;
+		$trashed        = $this->run_ability( 'woocommerce/order-delete', array( 'id' => $order_id ) );
+		$deleted        = $this->run_ability(
+			'woocommerce/order-delete',
+			array(
+				'id'    => $order_id,
+				'force' => true,
+			)
+		);
+
+		foreach ( array( $refused_trash, $refused_delete ) as $refused ) {
+			$this->assertSame( 400, $refused->get_status() );
+			$this->assertSame( 'test-ext:test_cancel_first', $refused->get_data()['code'] );
+		}
+		$this->assertNotSame( 'trash', $after_refusals, 'A refused call should leave the order where it was.' );
+		$this->assertSame( array( $order_id, 'woocommerce/order-delete', true ), $seen[0] );
+		$this->assertSame( 'trash', $trashed['status'] );
+		$this->assertSame( 'deleted', $deleted['status'] );
+		$this->assertFalse( wc_get_order( $order_id ) );
+		$this->assertSame(
+			array(
+				array( 0, array( $order_id ), array() ),
+				array( 0, array(), array( $order_id ) ),
+			),
+			$synced,
+			'The syncs should see the removed order, with its ID, and no saved object.'
+		);
+	}
+
+	/**
+	 * @testdox Should run validators on the refunds of a force-deleted order, delete nothing when one refuses, and give the syncs the deleted refunds.
+	 */
+	public function test_a_validator_can_refuse_deleting_the_refunds_of_an_order(): void {
+		$order     = \WC_Helper_Order::create_order();
+		$order_id  = $order->get_id();
+		$refund_id = wc_create_refund(
+			array(
+				'order_id' => $order_id,
+				'amount'   => 1,
+			)
+		)->get_id();
+		$refuse    = true;
+		$seen      = array();
+		$deleted   = array();
+		$this->register_validator(
+			'order',
+			'test-ext',
+			static function ( \WC_Abstract_Order $order, ActionableAbility $ability, array $context ) use ( &$seen, &$refuse, $refund_id ) {
+				unset( $ability );
+				$seen[ $order->get_id() ] = $context['deleting'];
+				return $refuse && $refund_id === $order->get_id() ? new \WP_Error( 'test_keep_refund', 'Keep the refund.' ) : null;
+			}
+		);
+		$this->register_sync(
+			'order',
+			'test-ext',
+			static function ( array $saved, ActionableAbility $ability, array $context ) use ( &$deleted ) {
+				unset( $saved, $ability );
+				$deleted = array_map( static fn( \WC_Abstract_Order $order ) => $order->get_id(), $context['deleted'] );
+			}
+		);
+		$this->reset_registries();
+		AbilitiesLoader::init_extensions();
+		$input = array(
+			'id'    => $order_id,
+			'force' => true,
+		);
+
+		$refused = $this->run_ability_response( 'woocommerce/order-delete', $input );
+		$kept    = array( wc_get_order( $order_id ), wc_get_order( $refund_id ) );
+		$refuse  = false;
+		$result  = $this->run_ability( 'woocommerce/order-delete', $input );
+
+		$this->assertSame( 400, $refused->get_status() );
+		$this->assertSame( 'test-ext:test_keep_refund', $refused->get_data()['code'] );
+		$this->assertInstanceOf( \WC_Order::class, $kept[0], 'A refused refund should keep the order.' );
+		$this->assertInstanceOf( \WC_Order_Refund::class, $kept[1] );
+		$this->assertTrue( $seen[ $refund_id ], 'The validators should see the refund as deleted.' );
+		$this->assertSame( 'deleted', $result['status'] );
+		$this->assertSame( array( $order_id, $refund_id ), $deleted );
+	}
+
+	/**
+	 * @testdox Should run validators on a child order and its refund that HPOS deletes with the parent, and delete nothing when one refuses.
+	 */
+	public function test_a_validator_can_refuse_deleting_a_child_order(): void {
+		$original = OrderUtil::custom_orders_table_usage_is_enabled();
+		add_filter( 'wc_allow_changing_orders_storage_while_sync_is_pending', '__return_true' );
+		$this->toggle_cot_feature_and_usage( true );
+
+		try {
+			$order_id = \WC_Helper_Order::create_order()->get_id();
+			$child    = \WC_Helper_Order::create_order();
+			$child->set_parent_id( $order_id );
+			$child->save();
+			$child_id      = $child->get_id();
+			$grandchild_id = wc_create_refund(
+				array(
+					'order_id' => $child_id,
+					'amount'   => 1,
+				)
+			)->get_id();
+			$refuse        = true;
+			$seen          = array();
+			$deleted       = array();
+			$this->register_validator(
+				'order',
+				'test-ext',
+				static function ( \WC_Abstract_Order $order, ActionableAbility $ability, array $context ) use ( &$seen, &$refuse, $grandchild_id ) {
+					unset( $ability );
+					$seen[ $order->get_id() ] = $context['deleting'];
+					return $refuse && $grandchild_id === $order->get_id() ? new \WP_Error( 'test_keep_child', 'Keep the refund of the child.' ) : null;
+				}
+			);
+			$this->register_sync(
+				'order',
+				'test-ext',
+				static function ( array $saved, ActionableAbility $ability, array $context ) use ( &$deleted ) {
+					unset( $saved, $ability );
+					$deleted = array_map( static fn( \WC_Abstract_Order $order ) => $order->get_id(), $context['deleted'] );
+				}
+			);
+			$this->reset_registries();
+			AbilitiesLoader::init_extensions();
+			$input = array(
+				'id'    => $order_id,
+				'force' => true,
+			);
+
+			$refused = $this->run_ability_response( 'woocommerce/order-delete', $input );
+			$kept    = array( wc_get_order( $order_id ), wc_get_order( $child_id ), wc_get_order( $grandchild_id ) );
+			$refuse  = false;
+			$result  = $this->run_ability( 'woocommerce/order-delete', $input );
+
+			$this->assertSame( 400, $refused->get_status() );
+			$this->assertSame( 'test-ext:test_keep_child', $refused->get_data()['code'] );
+			$this->assertInstanceOf( \WC_Order::class, $kept[0], 'A refused refund of the child should keep the parent.' );
+			$this->assertInstanceOf( \WC_Order::class, $kept[1] );
+			$this->assertInstanceOf( \WC_Order_Refund::class, $kept[2] );
+			$this->assertTrue( $seen[ $child_id ], 'The validators should see the child as deleted.' );
+			$this->assertTrue( $seen[ $grandchild_id ], 'The validators should see the refund of the child as deleted.' );
+			$this->assertSame( 'deleted', $result['status'] );
+			$this->assertFalse( wc_get_order( $child_id ), 'HPOS should delete the child with its parent.' );
+			$this->assertFalse( wc_get_order( $grandchild_id ), 'HPOS should delete the refund of the child too.' );
+			$this->assertSame( array( $order_id, $child_id, $grandchild_id ), $deleted );
+		} finally {
+			$this->toggle_cot_feature_and_usage( $original );
+			remove_filter( 'wc_allow_changing_orders_storage_while_sync_is_pending', '__return_true' );
+		}
+	}
+
+	/**
+	 * @testdox Should refuse a forced delete and keep everything when a refund appears after the validators ran.
+	 *
+	 * @dataProvider provider_order_storage
+	 *
+	 * @param bool $hpos Whether to use the custom orders table.
+	 */
+	public function test_a_refund_added_after_validation_stops_a_forced_delete( bool $hpos ): void {
+		$original = OrderUtil::custom_orders_table_usage_is_enabled();
+		add_filter( 'wc_allow_changing_orders_storage_while_sync_is_pending', '__return_true' );
+		$this->toggle_cot_feature_and_usage( $hpos );
+
+		try {
+			$order_id  = \WC_Helper_Order::create_order()->get_id();
+			$refund_id = 0;
+			$this->register_validator(
+				'order',
+				'test-ext',
+				static function ( \WC_Abstract_Order $order ) use ( &$refund_id, $order_id ) {
+					if ( 0 === $refund_id && $order_id === $order->get_id() ) {
+						$refund_id = wc_create_refund(
+							array(
+								'order_id' => $order_id,
+								'amount'   => 1,
+							)
+						)->get_id();
+					}
+					return null;
+				}
+			);
+			$this->reset_registries();
+			AbilitiesLoader::init_extensions();
+
+			$result = $this->run_ability_response(
+				'woocommerce/order-delete',
+				array(
+					'id'    => $order_id,
+					'force' => true,
+				)
+			);
+
+			$this->assertSame( 409, $result->get_status() );
+			$this->assertSame( 'woocommerce_ability_order_children_changed', $result->get_data()['code'] );
+			$this->assertInstanceOf( \WC_Order::class, wc_get_order( $order_id ) );
+			$this->assertInstanceOf( \WC_Order_Refund::class, wc_get_order( $refund_id ) );
+		} finally {
+			$this->toggle_cot_feature_and_usage( $original );
+			remove_filter( 'wc_allow_changing_orders_storage_while_sync_is_pending', '__return_true' );
+		}
+	}
+
+	/**
+	 * Order storage modes.
+	 *
+	 * @return array<string, array{0: bool}>
+	 */
+	public function provider_order_storage(): array {
+		return array(
+			'posts storage' => array( false ),
+			'HPOS storage'  => array( true ),
+		);
+	}
+
+	/**
+	 * @testdox Should restore a trashed or deleted order and its refund when a sync refuses, with HPOS and with posts storage, with and without sync.
+	 * @testWith [true, false]
+	 *           [true, true]
+	 *           [false, false]
+	 *           [false, true]
+	 *
+	 * @param bool $hpos Whether HPOS is on.
+	 * @param bool $sync Whether HPOS and posts storage sync.
+	 */
+	public function test_a_sync_refusal_restores_a_removed_order( bool $hpos, bool $sync ): void {
+		$original = OrderUtil::custom_orders_table_usage_is_enabled();
+		add_filter( 'wc_allow_changing_orders_storage_while_sync_is_pending', '__return_true' );
+		$this->toggle_cot_feature_and_usage( $hpos );
+		if ( $sync ) {
+			$this->enable_cot_sync();
+		} else {
+			$this->disable_cot_sync();
+		}
+
+		try {
+			$order  = \WC_Helper_Order::create_order();
+			$status = $order->get_status();
+			$refund = wc_create_refund(
+				array(
+					'order_id' => $order->get_id(),
+					'amount'   => 1,
+				)
+			);
+			$this->register_sync(
+				'order',
+				'test-ext',
+				static fn() => new \WP_Error( 'test_ledger_down', 'Ledger is down.' )
+			);
+			$this->reset_registries();
+			AbilitiesLoader::init_extensions();
+
+			$trash = $this->run_ability_response( 'woocommerce/order-delete', array( 'id' => $order->get_id() ) );
+			$after = wc_get_order( $order->get_id() );
+			$force = $this->run_ability_response(
+				'woocommerce/order-delete',
+				array(
+					'id'    => $order->get_id(),
+					'force' => true,
+				)
+			);
+
+			$this->assertSame( 400, $trash->get_status() );
+			$this->assertSame( $status, $after->get_status(), 'A refused trash should leave the order out of the trash.' );
+			$this->assertSame( 400, $force->get_status() );
+			$this->assertInstanceOf( \WC_Order::class, wc_get_order( $order->get_id() ), 'A refused delete should keep the order.' );
+			$this->assertInstanceOf( \WC_Order_Refund::class, wc_get_order( $refund->get_id() ), 'A refused delete should keep the refund.' );
+		} finally {
+			remove_all_filters( 'pre_option_' . DataSynchronizer::ORDERS_DATA_SYNC_ENABLED_OPTION );
+			$this->toggle_cot_feature_and_usage( $original );
+			remove_filter( 'wc_allow_changing_orders_storage_while_sync_is_pending', '__return_true' );
+		}
+	}
+
 	/**
 	 * @testdox Should return the stored slug from product-create, for the product and its variations.
 	 */