Commit afd06bf1c4d for woocommerce

commit afd06bf1c4d36630c65d2db966a686aa3b272f08
Author: Aarón Fas <yo@aaron.com.es>
Date:   Wed Nov 18 13:39:44 2026 +0100

    Add coupon query, create and update abilities to Core (#70618)

    * Add coupon query and write abilities

    Build on Rodolfo Melogli’s coupon contribution so Core clients can find scheduled coupons and create or update coupon data. Use the current write lifecycle, omit customer email restrictions, and expose restrictions, availability, expiry and paginated totals.

    Co-authored-by: Rodolfo Melogli <16014385+BusinessBloomer@users.noreply.github.com>

    * Protect coupon publication and remove email inputs

    Require coupon creation permission before updates publish, schedule or privatize a coupon. Reject customer email inputs while Core customer-data controls are deferred, and verify these boundaries through the registered ability schema.

    * Validate coupon mutations before saving

    Reject scheduling without a future publication date and invalid expiry strings instead of silently publishing or removing limits. Revalidate amounts after type changes and reserve coupon codes across supported statuses. Regression tests verify rejected updates preserve stored data.

    * Allow coupon editors to retain publication status

    Only require publication permission when the requested status differs from the stored status. An amount update with an explicit unchanged status should have the same permissions as one that omits status.

    * Normalize coupon expiry before calling the date setter

    Pass validated expiry values as timestamps so fractional ISO dates retain their offset and compact dates are not treated as Unix timestamps. Verify stored values in Europe/Madrid.

    * Reset the publication date when publishing a scheduled coupon

    WordPress retains future status when the post date is still ahead of now. Move that date to now on an explicit publish request and verify the persisted status matches the response.

    * Preserve coupon totals on out-of-range pages

    WordPress skips found-row counting when a page has no results. Fetch the count from the first page with the same filters so an empty later page still reports the true total and page count.

    * Allow supplied coupon email restrictions in write abilities

    Restore targeted-coupon creation and updates without exposing stored customer emails in responses. Validate each supplied address before the WooCommerce setter can sanitize or drop it, and reject invalid lists without saving other changes. Cover replacement, omission, clearing, and response privacy through the abilities API.

    * Match coupon email responses to authenticated REST

    Return email restrictions in the shared coupon schema and response while preserving input validation. Reload updated coupons so replacement and clearing responses reflect storage instead of retained in-memory array entries. Shared PII policy will govern future withholding.

    * Validate coupon spending limits as a final pair

    Clear the old maximum in memory when both bounds are supplied, then let the coupon setters validate the final range before saving. This permits valid upward and downward range updates while preserving rejection and atomicity for invalid pairs and single-bound updates.

    * Preserve exact coupon query constraints

    Treat the search string zero as a real term and reject exact codes that normalize to empty. These inputs must not silently drop their predicates and return unrelated coupons.

    * Allow unrelated edits to overdue scheduled coupons

    Validate the future publication date only when scheduling is explicitly requested. A delayed WP-Cron publication must not block amount or email changes that leave the stored schedule intact.

    Cover persisted updates without publication capability and atomic rejection of an explicit invalid scheduling request.

    * Cover coupon abilities in the shared permission contract

    List all three coupon abilities and supply minimal valid inputs for denial tests. This satisfies the canonical ability completeness check added on trunk and exercises the shared negative permission cases.

    * Authorize implicit coupon publication before saving

    Evaluate publication against the loaded coupon and its actual changes. WordPress publishes scheduled posts less than a minute from their publication time when post fields are saved, so description and code updates need publication permission in that case.

    Keep metadata-only and unchanged-field edits available to editors. Cover explicit transitions, changed loaded status, atomic refusal, and saved state for authorized and unauthorized scheduled-coupon edits.

    * Clarify supported coupon creation and expiry inputs

    Remove future from creation because no publication date can be supplied. Explain REST-parity draft creation permission and midnight expiry rather than adding new behavior. Assert schema rejection and the existing draft permission requirement.

    * Return stored coupon fields after creation

    Reload the created coupon before formatting its response so changes made by insertion filters are reflected in status and availability. Cover a filter that stores a draft while the in-memory object remains published.

    * Normalize filtered coupon permissions to booleans

    REST permission filters can return truthy non-boolean values. Cast create and query results to avoid strict return-type errors, and include both abilities in the existing shared truthy-permission regression.

    * Reload saved coupon responses without virtual code lookup

    Pass the saved coupon object to the constructor so response reloads read its database ID directly. Integer constructor inputs pass through the virtual-coupon filter and can otherwise return an unrelated coupon with ID zero.

    Cover both create and update responses with a virtual numeric code matching the saved coupon ID, and verify response fields against storage.

    ---------

    Co-authored-by: Rodolfo Melogli <16014385+BusinessBloomer@users.noreply.github.com>

diff --git a/plugins/woocommerce/changelog/add-coupon-domain-abilities b/plugins/woocommerce/changelog/add-coupon-domain-abilities
new file mode 100644
index 00000000000..4f410d628fa
--- /dev/null
+++ b/plugins/woocommerce/changelog/add-coupon-domain-abilities
@@ -0,0 +1,4 @@
+Significance: minor
+Type: add
+
+Add coupon abilities so AI assistants and other tools can find, create and update coupons.
diff --git a/plugins/woocommerce/src/Internal/Abilities/AbilitiesLoader.php b/plugins/woocommerce/src/Internal/Abilities/AbilitiesLoader.php
index 51e24f76e6c..b757236a6d4 100644
--- a/plugins/woocommerce/src/Internal/Abilities/AbilitiesLoader.php
+++ b/plugins/woocommerce/src/Internal/Abilities/AbilitiesLoader.php
@@ -19,6 +19,9 @@ use Automattic\WooCommerce\Internal\Abilities\Domain\OrderUpdate;
 use Automattic\WooCommerce\Internal\Abilities\Domain\OrderUpdateStatus;
 use Automattic\WooCommerce\Internal\Abilities\Domain\CustomersQuery;
 use Automattic\WooCommerce\Internal\Abilities\Domain\OrdersQuery;
+use Automattic\WooCommerce\Internal\Abilities\Domain\CouponsQuery;
+use Automattic\WooCommerce\Internal\Abilities\Domain\CouponCreate;
+use Automattic\WooCommerce\Internal\Abilities\Domain\CouponUpdate;
 use Automattic\WooCommerce\Internal\Abilities\Domain\PaymentGatewayUpdate;
 use Automattic\WooCommerce\Internal\Abilities\Domain\PaymentGatewaysQuery;
 use Automattic\WooCommerce\Internal\Abilities\Domain\ProductAttributeCreate;
@@ -67,6 +70,9 @@ class AbilitiesLoader {
 	 */
 	private const CORE_ABILITY_DEFINITION_CLASSES = array(
 		OrdersQuery::class,
+		CouponsQuery::class,
+		CouponCreate::class,
+		CouponUpdate::class,
 		OrderAddNote::class,
 		OrderCreate::class,
 		OrderNotesQuery::class,
diff --git a/plugins/woocommerce/src/Internal/Abilities/Domain/CouponCreate.php b/plugins/woocommerce/src/Internal/Abilities/Domain/CouponCreate.php
new file mode 100644
index 00000000000..285970f832f
--- /dev/null
+++ b/plugins/woocommerce/src/Internal/Abilities/Domain/CouponCreate.php
@@ -0,0 +1,129 @@
+<?php
+/**
+ * Coupon create ability definition file.
+ */
+
+declare( strict_types=1 );
+
+namespace Automattic\WooCommerce\Internal\Abilities\Domain;
+
+use Automattic\WooCommerce\Abilities\ActionableAbility;
+use Automattic\WooCommerce\Internal\Abilities\Domain\Traits\DomainAbilityHelpers;
+use Automattic\WooCommerce\Internal\Abilities\Domain\Traits\CouponAbilityTrait;
+
+defined( 'ABSPATH' ) || exit;
+
+/**
+ * Registers the WooCommerce coupon create ability.
+ */
+class CouponCreate extends ActionableAbility {
+
+	use CouponAbilityTrait;
+	use DomainAbilityHelpers;
+
+	/** Ability name. */
+	public const ABILITY_NAME = 'woocommerce/coupon-create';
+
+	/**
+	 * Get the ability registration arguments.
+	 *
+	 * @return array
+	 *
+	 * @since 11.4.0
+	 */
+	public static function get_registration_args(): array {
+		return array(
+			'label'               => __( 'Create coupon', 'woocommerce' ),
+			'description'         => __(
+				'Create a coupon. Defaults to a published fixed cart discount. Requires publication permission even for drafts, matching WooCommerce REST.',
+				'woocommerce'
+			),
+			'category'            => 'woocommerce',
+			'input_schema'        => self::build_input_schema(),
+			'output_schema'       => self::get_entity_output_schema( 'coupon', self::get_coupon_output_schema() ),
+			'permission_callback' => array( __CLASS__, 'can_create_coupon' ),
+			'meta'                => array(
+				'show_in_rest' => true,
+				'mcp'          => array(
+					'public' => true,
+					'type'   => 'tool',
+				),
+				'annotations'  => array(
+					'readonly'    => false,
+					'idempotent'  => false,
+					'destructive' => false,
+				),
+			),
+		);
+	}
+
+	/**
+	 * Resource being changed.
+	 *
+	 * @return string
+	 */
+	public function get_resource(): string {
+		return 'coupon';
+	}
+
+	/**
+	 * Load the coupon without saving.
+	 *
+	 * @param array $input Ability input.
+	 * @return \WC_Coupon|\WP_Error
+	 */
+	protected function load( array $input ) {
+		return new \WC_Coupon();
+	}
+
+	/**
+	 * Change coupon fields in memory.
+	 *
+	 * @param \WC_Coupon $subject Coupon.
+	 * @param array      $input Ability input.
+	 * @return null|\WP_Error
+	 */
+	protected function change( $subject, array $input ) {
+		$subject->set_status( $input['status'] ?? 'publish' );
+		$result = self::set_coupon_props_from_input( $subject, $input );
+		return is_wp_error( $result ) ? $result : null;
+	}
+
+	/**
+	 * Return saved coupon fields.
+	 *
+	 * @param \WC_Coupon $subject Coupon.
+	 * @return array
+	 */
+	protected function prepare_response( $subject ): array {
+		return array( 'coupon' => self::format_coupon_for_response( new \WC_Coupon( $subject ) ) );
+	}
+
+	/**
+	 * Check coupon create access.
+	 *
+	 * @return bool
+	 *
+	 * @since 11.4.0
+	 */
+	public static function can_create_coupon(): bool {
+		return (bool) wc_rest_check_post_permissions( 'shop_coupon', 'create' );
+	}
+
+	/**
+	 * Get the ability input schema.
+	 *
+	 * @return array
+	 */
+	private static function build_input_schema(): array {
+		$properties                   = self::get_coupon_writable_properties_schema();
+		$properties['status']['enum'] = array_values( array_diff( $properties['status']['enum'], array( 'future' ) ) );
+
+		return array(
+			'type'                 => 'object',
+			'properties'           => $properties,
+			'required'             => array( 'code' ),
+			'additionalProperties' => false,
+		);
+	}
+}
diff --git a/plugins/woocommerce/src/Internal/Abilities/Domain/CouponUpdate.php b/plugins/woocommerce/src/Internal/Abilities/Domain/CouponUpdate.php
new file mode 100644
index 00000000000..3547706946c
--- /dev/null
+++ b/plugins/woocommerce/src/Internal/Abilities/Domain/CouponUpdate.php
@@ -0,0 +1,161 @@
+<?php
+/**
+ * Coupon update ability definition file.
+ */
+
+declare( strict_types=1 );
+
+namespace Automattic\WooCommerce\Internal\Abilities\Domain;
+
+use Automattic\WooCommerce\Abilities\ActionableAbility;
+use Automattic\WooCommerce\Internal\Abilities\Domain\Traits\DomainAbilityHelpers;
+use Automattic\WooCommerce\Internal\Abilities\Domain\Traits\CouponAbilityTrait;
+
+defined( 'ABSPATH' ) || exit;
+
+/**
+ * Registers the WooCommerce coupon update ability.
+ */
+class CouponUpdate extends ActionableAbility {
+
+	use CouponAbilityTrait;
+	use DomainAbilityHelpers;
+
+	/** Ability name. */
+	public const ABILITY_NAME = 'woocommerce/coupon-update';
+
+	/**
+	 * Get the ability registration arguments.
+	 *
+	 * @return array
+	 *
+	 * @since 11.4.0
+	 */
+	public static function get_registration_args(): array {
+		return array(
+			'label'               => __( 'Update coupon', 'woocommerce' ),
+			'description'         => __(
+				'Update an existing coupon, such as its amount, expiry date or usage limits.',
+				'woocommerce'
+			),
+			'category'            => 'woocommerce',
+			'input_schema'        => self::build_input_schema(),
+			'output_schema'       => self::get_entity_output_schema( 'coupon', self::get_coupon_output_schema() ),
+			'permission_callback' => array( __CLASS__, 'can_update_coupon' ),
+			'meta'                => array(
+				'show_in_rest' => true,
+				'mcp'          => array(
+					'public' => true,
+					'type'   => 'tool',
+				),
+				'annotations'  => array(
+					'readonly'    => false,
+					'idempotent'  => false,
+					'destructive' => true,
+				),
+			),
+		);
+	}
+
+	/**
+	 * Resource being changed.
+	 *
+	 * @return string
+	 */
+	public function get_resource(): string {
+		return 'coupon';
+	}
+
+	/**
+	 * Load the coupon without saving.
+	 *
+	 * @param array $input Ability input.
+	 * @return \WC_Coupon|\WP_Error
+	 */
+	protected function load( array $input ) {
+		return self::get_coupon_from_input( $input );
+	}
+
+	/**
+	 * Change coupon fields in memory.
+	 *
+	 * @param \WC_Coupon $subject Coupon.
+	 * @param array      $input Ability input.
+	 * @return null|\WP_Error
+	 */
+	protected function change( $subject, array $input ) {
+		$previous_status = $subject->get_status();
+		if ( isset( $input['status'] ) ) {
+			if ( 'publish' === $input['status'] && $subject->get_date_created() && $subject->get_date_created()->getTimestamp() > time() ) {
+				$subject->set_date_created( time() );
+			}
+			$subject->set_status( $input['status'] );
+		}
+		$result = self::set_coupon_props_from_input( $subject, $input );
+		if ( is_wp_error( $result ) ) {
+			return $result;
+		}
+
+		$status = $subject->get_status();
+		// WordPress can publish a scheduled coupon when post fields are saved near or after its publication time.
+		if (
+			'future' === $status
+			&& $subject->get_date_created()
+			&& $subject->get_date_created()->getTimestamp() < time() + MINUTE_IN_SECONDS
+			&& array_intersect( array( 'code', 'description', 'date_created', 'date_modified', 'status' ), array_keys( $subject->get_changes() ) )
+		) {
+			$status = 'publish';
+		}
+		if ( $status !== $previous_status && in_array( $status, array( 'publish', 'future', 'private' ), true ) && ! wc_rest_check_post_permissions( 'shop_coupon', 'create' ) ) {
+			return new \WP_Error( 'woocommerce_ability_coupon_publish_forbidden', __( 'You are not allowed to publish coupons.', 'woocommerce' ), array( 'status' => rest_authorization_required_code() ) );
+		}
+		return null;
+	}
+
+	/**
+	 * Return saved coupon fields.
+	 *
+	 * @param \WC_Coupon $subject Coupon.
+	 * @return array
+	 */
+	protected function prepare_response( $subject ): array {
+		// Reload because saving can retain removed array entries in the in-memory object.
+		return array( 'coupon' => self::format_coupon_for_response( new \WC_Coupon( $subject ) ) );
+	}
+
+	/**
+	 * Check coupon update access.
+	 *
+	 * @param mixed $input Ability input.
+	 * @return bool
+	 *
+	 * @since 11.4.0
+	 */
+	public static function can_update_coupon( $input = array() ): bool {
+		$coupon_id = self::get_id_from_input( $input );
+
+		return $coupon_id > 0 && wc_rest_check_post_permissions( 'shop_coupon', 'edit', $coupon_id );
+	}
+
+	/**
+	 * Get the ability input schema.
+	 *
+	 * @return array
+	 */
+	private static function build_input_schema(): array {
+		return array(
+			'type'                 => 'object',
+			'properties'           => array_merge(
+				array(
+					'id' => array(
+						'type'    => 'integer',
+						'minimum' => 1,
+					),
+				),
+				self::get_coupon_writable_properties_schema()
+			),
+			'required'             => array( 'id' ),
+			'additionalProperties' => false,
+		);
+	}
+}
diff --git a/plugins/woocommerce/src/Internal/Abilities/Domain/CouponsQuery.php b/plugins/woocommerce/src/Internal/Abilities/Domain/CouponsQuery.php
new file mode 100644
index 00000000000..241f7dc41d6
--- /dev/null
+++ b/plugins/woocommerce/src/Internal/Abilities/Domain/CouponsQuery.php
@@ -0,0 +1,200 @@
+<?php
+/**
+ * Coupons query ability definition file.
+ */
+
+declare( strict_types=1 );
+
+namespace Automattic\WooCommerce\Internal\Abilities\Domain;
+
+use Automattic\WooCommerce\Abilities\AbilityDefinition;
+use Automattic\WooCommerce\Internal\Abilities\Domain\Traits\CouponAbilityTrait;
+
+defined( 'ABSPATH' ) || exit;
+
+/**
+ * Registers the WooCommerce coupons query ability.
+ */
+class CouponsQuery extends AbstractDomainAbility implements AbilityDefinition {
+
+	use CouponAbilityTrait;
+
+	/**
+	 * Get the ability name.
+	 *
+	 * @return string
+	 *
+	 * @since 11.4.0
+	 */
+	public static function get_name(): string {
+		return 'woocommerce/coupons-query';
+	}
+
+	/**
+	 * Get the ability registration arguments.
+	 *
+	 * @return array
+	 *
+	 * @since 11.4.0
+	 */
+	public static function get_registration_args(): array {
+		$output_schema                        = self::get_collection_output_schema( 'coupons', self::get_coupon_output_schema() );
+		$output_schema['properties']['total'] = array( 'type' => 'integer' );
+		return array(
+			'label'               => __( 'Query coupons', 'woocommerce' ),
+			'description'         => __(
+				'Find coupons by ID, exact code, or search term.',
+				'woocommerce'
+			),
+			'category'            => 'woocommerce',
+			'input_schema'        => self::get_input_schema(),
+			'output_schema'       => $output_schema,
+			'execute_callback'    => array( __CLASS__, 'execute' ),
+			'permission_callback' => array( __CLASS__, 'can_query_coupons' ),
+			'meta'                => array(
+				'show_in_rest' => true,
+				'mcp'          => array(
+					'public' => true,
+					'type'   => 'tool',
+				),
+				'annotations'  => array(
+					'readonly'    => true,
+					'idempotent'  => true,
+					'destructive' => false,
+				),
+			),
+		);
+	}
+
+	/**
+	 * Query coupons.
+	 *
+	 * @param array $input Ability input.
+	 * @return array|\WP_Error
+	 *
+	 * @since 11.4.0
+	 */
+	public static function execute( array $input ) {
+		$page     = (int) ( $input['page'] ?? 1 );
+		$per_page = (int) ( $input['per_page'] ?? 10 );
+		$args     = array(
+			'post_type'      => 'shop_coupon',
+			'post_status'    => ! empty( $input['status'] ) ? $input['status'] : self::get_coupon_status_slugs(),
+			'posts_per_page' => $per_page,
+			'paged'          => $page,
+			'orderby'        => 'date',
+			'order'          => 'DESC',
+		);
+
+		if ( isset( $input['search'] ) && '' !== $input['search'] ) {
+			$args['s'] = wc_clean( $input['search'] );
+		}
+
+		if ( isset( $input['include'] ) ) {
+			$args['post__in'] = $input['include'];
+		}
+		if ( isset( $input['code'] ) ) {
+			$args['title'] = wc_format_coupon_code( $input['code'] );
+			if ( '' === $args['title'] ) {
+				return new \WP_Error( 'woocommerce_ability_coupon_code_required', __( 'Coupon code is required.', 'woocommerce' ), array( 'status' => 400 ) );
+			}
+		}
+		if ( isset( $input['discount_type'] ) ) {
+			$args['meta_query'] = array( // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- Coupon discount types are stored only in post meta.
+				array(
+					'key'   => 'discount_type',
+					'value' => $input['discount_type'],
+				),
+			);
+		}
+		$args['orderby'] = array(
+			'date' => 'DESC',
+			'ID'   => 'DESC',
+		);
+		$query           = new \WP_Query( $args );
+		$total           = (int) $query->found_posts;
+		if ( empty( $query->posts ) && $page > 1 ) {
+			$args['paged']          = 1;
+			$args['posts_per_page'] = 1;
+			$args['fields']         = 'ids';
+			$count_query            = new \WP_Query( $args );
+			$total                  = (int) $count_query->found_posts;
+		}
+
+		return array(
+			'coupons'     => array_map(
+				static function ( $coupon_id ) {
+					return self::format_coupon_for_response( new \WC_Coupon( $coupon_id instanceof \WP_Post ? $coupon_id->ID : $coupon_id ) );
+				},
+				$query->posts
+			),
+			'total'       => $total,
+			'total_pages' => (int) ceil( $total / $per_page ),
+			'page'        => $page,
+			'per_page'    => $per_page,
+		);
+	}
+
+	/**
+	 * Check coupon read access.
+	 *
+	 * @param mixed $input Ability input.
+	 * @return bool
+	 *
+	 * @since 11.4.0
+	 */
+	public static function can_query_coupons( $input = array() ): bool {
+		return (bool) wc_rest_check_post_permissions( 'shop_coupon', 'read', self::get_id_from_input( $input ) );
+	}
+
+	/**
+	 * Get the ability input schema.
+	 *
+	 * @return array
+	 */
+	private static function get_input_schema(): array {
+		return array(
+			'type'                 => 'object',
+			'properties'           => array(
+				'include'       => array(
+					'type'     => 'array',
+					'minItems' => 1,
+					'items'    => array(
+						'type'    => 'integer',
+						'minimum' => 1,
+					),
+				),
+				'discount_type' => array(
+					'type' => 'string',
+					'enum' => array_keys( wc_get_coupon_types() ),
+				),
+				'code'          => array(
+					'type'        => 'string',
+					'description' => __( 'Exact coupon code. Matches coupons in any supported status.', 'woocommerce' ),
+				),
+				'search'        => array( 'type' => 'string' ),
+				'status'        => array(
+					'type'     => 'array',
+					'items'    => array(
+						'type' => 'string',
+						'enum' => self::get_coupon_status_slugs(),
+					),
+					'minItems' => 1,
+				),
+				'page'          => array(
+					'type'    => 'integer',
+					'default' => 1,
+					'minimum' => 1,
+				),
+				'per_page'      => array(
+					'type'    => 'integer',
+					'default' => 10,
+					'minimum' => 1,
+					'maximum' => 100,
+				),
+			),
+			'additionalProperties' => false,
+			'default'              => array(),
+		);
+	}
+}
diff --git a/plugins/woocommerce/src/Internal/Abilities/Domain/Traits/CouponAbilityTrait.php b/plugins/woocommerce/src/Internal/Abilities/Domain/Traits/CouponAbilityTrait.php
new file mode 100644
index 00000000000..156c68e841b
--- /dev/null
+++ b/plugins/woocommerce/src/Internal/Abilities/Domain/Traits/CouponAbilityTrait.php
@@ -0,0 +1,380 @@
+<?php
+/**
+ * Coupon ability trait file.
+ */
+
+declare( strict_types=1 );
+
+namespace Automattic\WooCommerce\Internal\Abilities\Domain\Traits;
+
+defined( 'ABSPATH' ) || exit;
+
+/**
+ * Shared coupon helpers for WooCommerce domain ability definitions.
+ */
+trait CouponAbilityTrait {
+
+	/**
+	 * Coupon post statuses supported by the coupon abilities.
+	 *
+	 * @return array<int, string>
+	 */
+	protected static function get_coupon_status_slugs(): array {
+		return array( 'publish', 'draft', 'pending', 'private', 'future' );
+	}
+
+	/**
+	 * Get the schema for a single coupon in a response.
+	 *
+	 * @return array
+	 */
+	protected static function get_coupon_output_schema(): array {
+		return array(
+			'type'                 => 'object',
+			'properties'           => array(
+				'id'                          => array( 'type' => 'integer' ),
+				'code'                        => array( 'type' => 'string' ),
+				'status'                      => array( 'type' => 'string' ),
+				'discount_type'               => array(
+					'type' => 'string',
+					'enum' => array_keys( wc_get_coupon_types() ),
+				),
+				'amount'                      => array( 'type' => 'string' ),
+				'description'                 => array( 'type' => 'string' ),
+				'date_expires'                => array(
+					'type'   => 'string',
+					'format' => 'date-time',
+				),
+				'date_expires_gmt'            => array(
+					'type'   => 'string',
+					'format' => 'date-time',
+				),
+				'product_ids'                 => array(
+					'type'  => 'array',
+					'items' => array( 'type' => 'integer' ),
+				),
+				'excluded_product_ids'        => array(
+					'type'  => 'array',
+					'items' => array( 'type' => 'integer' ),
+				),
+				'product_categories'          => array(
+					'type'  => 'array',
+					'items' => array( 'type' => 'integer' ),
+				),
+				'excluded_product_categories' => array(
+					'type'  => 'array',
+					'items' => array( 'type' => 'integer' ),
+				),
+				'email_restrictions'          => array(
+					'type'  => 'array',
+					'items' => array( 'type' => 'string' ),
+				),
+				'exclude_sale_items'          => array( 'type' => 'boolean' ),
+				'redeemable'                  => array( 'type' => 'boolean' ),
+				'expired'                     => array( 'type' => 'boolean' ),
+				'scheduled'                   => array( 'type' => 'boolean' ),
+				'not_redeemable_reason'       => array( 'type' => 'string' ),
+				'starts_at'                   => array(
+					'type'   => 'string',
+					'format' => 'date-time',
+				),
+				'expiry'                      => array(
+					'type'                 => 'object',
+					'properties'           => array(
+						'expires_at'     => array( 'type' => 'string' ),
+						'last_valid_day' => array( 'type' => 'string' ),
+						'timezone'       => array( 'type' => 'string' ),
+					),
+					'additionalProperties' => false,
+				),
+				'usage_count'                 => array( 'type' => 'integer' ),
+				'usage_limit'                 => array( 'type' => 'integer' ),
+				'usage_limit_per_user'        => array( 'type' => 'integer' ),
+				'individual_use'              => array( 'type' => 'boolean' ),
+				'free_shipping'               => array( 'type' => 'boolean' ),
+				'minimum_amount'              => array( 'type' => 'string' ),
+				'maximum_amount'              => array( 'type' => 'string' ),
+				'date_created'                => array(
+					'type'   => 'string',
+					'format' => 'date-time',
+				),
+				'date_modified'               => array(
+					'type'   => 'string',
+					'format' => 'date-time',
+				),
+			),
+			'additionalProperties' => false,
+		);
+	}
+
+	/**
+	 * Get the writable coupon field schemas shared by create and update.
+	 *
+	 * @return array
+	 */
+	protected static function get_coupon_writable_properties_schema(): array {
+		return array(
+			'code'                 => array(
+				'type'        => 'string',
+				'minLength'   => 1,
+				'description' => __( 'Coupon code. Must be unique.', 'woocommerce' ),
+			),
+			'status'               => array(
+				'type' => 'string',
+				'enum' => self::get_coupon_status_slugs(),
+			),
+			'discount_type'        => array(
+				'type' => 'string',
+				'enum' => array_keys( wc_get_coupon_types() ),
+			),
+			'amount'               => array(
+				'type'        => 'string',
+				'description' => __( 'Discount amount as a decimal string, without a currency symbol.', 'woocommerce' ),
+				'pattern'     => '^[0-9]+(\.[0-9]+)?$',
+			),
+			'description'          => array( 'type' => 'string' ),
+			'date_expires'         => array(
+				'type'        => 'string',
+				'description' => __( 'Expiry date in the store timezone (Y-m-d or ISO 8601). A date without a time expires at 00:00 on that day; use the day after the last valid day. An empty string removes the expiry date.', 'woocommerce' ),
+			),
+			'usage_limit'          => array(
+				'type'        => 'integer',
+				'minimum'     => 0,
+				'description' => __( 'How many times the coupon can be used in total. 0 means unlimited.', 'woocommerce' ),
+			),
+			'usage_limit_per_user' => array(
+				'type'        => 'integer',
+				'minimum'     => 0,
+				'description' => __( 'How many times each customer can use the coupon. 0 means unlimited.', 'woocommerce' ),
+			),
+			'individual_use'       => array( 'type' => 'boolean' ),
+			'free_shipping'        => array( 'type' => 'boolean' ),
+			'minimum_amount'       => array(
+				'type'    => 'string',
+				'pattern' => '^([0-9]+(\.[0-9]+)?)?$',
+			),
+			'maximum_amount'       => array(
+				'type'    => 'string',
+				'pattern' => '^([0-9]+(\.[0-9]+)?)?$',
+			),
+			'email_restrictions'   => array(
+				'type'        => 'array',
+				'description' => __( 'Allowed billing emails supplied by the user. Replaces existing restrictions; an empty array clears them. Omit to keep them.', 'woocommerce' ),
+				'items'       => array( 'type' => 'string' ),
+			),
+		);
+	}
+
+	/**
+	 * Get a coupon from ability input.
+	 *
+	 * @param array $input Ability input.
+	 * @return \WC_Coupon|\WP_Error
+	 */
+	protected static function get_coupon_from_input( array $input ) {
+		$coupon_id = isset( $input['id'] ) ? (int) $input['id'] : 0;
+
+		if ( $coupon_id < 1 ) {
+			return new \WP_Error(
+				'woocommerce_ability_coupon_id_required',
+				__( 'Coupon ID is required.', 'woocommerce' ),
+				array( 'status' => 400 )
+			);
+		}
+
+		if ( 'shop_coupon' !== get_post_type( $coupon_id ) ) {
+			return new \WP_Error(
+				'woocommerce_ability_coupon_not_found',
+				__( 'Coupon not found.', 'woocommerce' ),
+				array( 'status' => 404 )
+			);
+		}
+
+		return new \WC_Coupon( $coupon_id );
+	}
+
+	/**
+	 * Check whether a coupon code is already used by another coupon.
+	 *
+	 * @param string $code      Coupon code.
+	 * @param int    $coupon_id Coupon being saved, 0 for a new coupon.
+	 * @return bool
+	 */
+	protected static function is_coupon_code_taken( string $code, int $coupon_id = 0 ): bool {
+		$query = new \WP_Query(
+			array(
+				'post_type'      => 'shop_coupon',
+				'post_status'    => self::get_coupon_status_slugs(),
+				'title'          => $code,
+				'post__not_in'   => array( $coupon_id ),
+				'posts_per_page' => 1,
+				'fields'         => 'ids',
+				'no_found_rows'  => true,
+			)
+		);
+		return ! empty( $query->posts );
+	}
+
+	/**
+	 * Apply writable fields from ability input to a coupon.
+	 *
+	 * @param \WC_Coupon $coupon Coupon object.
+	 * @param array      $input  Ability input.
+	 * @return true|\WP_Error
+	 */
+	protected static function set_coupon_props_from_input( \WC_Coupon $coupon, array $input ) {
+		if ( 'future' === ( $input['status'] ?? null ) && ( ! $coupon->get_date_created() || $coupon->get_date_created()->getTimestamp() <= time() ) ) {
+			return new \WP_Error( 'woocommerce_ability_coupon_invalid_schedule', __( 'Scheduling requires an existing future publication date.', 'woocommerce' ), array( 'status' => 400 ) );
+		}
+		if ( isset( $input['date_expires'] ) && '' !== $input['date_expires'] ) {
+			$date = date_parse( $input['date_expires'] );
+			if ( $date['error_count'] || $date['warning_count'] || ! $date['year'] || ! $date['month'] || ! $date['day'] ) {
+				return new \WP_Error( 'woocommerce_ability_coupon_invalid_expiry', __( 'Expiry must be a valid date or datetime.', 'woocommerce' ), array( 'status' => 400 ) );
+			}
+			$input['date_expires'] = ( new \DateTimeImmutable( $input['date_expires'], wp_timezone() ) )->getTimestamp();
+		}
+
+		if ( isset( $input['code'] ) ) {
+			$code = wc_format_coupon_code( (string) $input['code'] );
+
+			if ( '' === $code ) {
+				return new \WP_Error(
+					'woocommerce_ability_coupon_code_required',
+					__( 'Coupon code is required.', 'woocommerce' ),
+					array( 'status' => 400 )
+				);
+			}
+
+			if ( self::is_coupon_code_taken( $code, $coupon->get_id() ) ) {
+				return new \WP_Error(
+					'woocommerce_ability_coupon_code_exists',
+					__( 'A coupon with this code already exists.', 'woocommerce' ),
+					array( 'status' => 400 )
+				);
+			}
+
+			$coupon->set_code( $code );
+		}
+
+		if ( isset( $input['email_restrictions'] ) ) {
+			$input['email_restrictions'] = array_map( 'trim', $input['email_restrictions'] );
+			foreach ( $input['email_restrictions'] as $email ) {
+				if ( ! is_email( $email ) ) {
+					return new \WP_Error( 'woocommerce_ability_coupon_email_invalid', __( 'Email restrictions must be valid email addresses.', 'woocommerce' ), array( 'status' => 400 ) );
+				}
+			}
+		}
+
+		$setters = array(
+			'discount_type'        => 'set_discount_type',
+			'amount'               => 'set_amount',
+			'date_expires'         => 'set_date_expires',
+			'usage_limit'          => 'set_usage_limit',
+			'usage_limit_per_user' => 'set_usage_limit_per_user',
+			'individual_use'       => 'set_individual_use',
+			'free_shipping'        => 'set_free_shipping',
+			'minimum_amount'       => 'set_minimum_amount',
+			'maximum_amount'       => 'set_maximum_amount',
+			'email_restrictions'   => 'set_email_restrictions',
+		);
+
+		try {
+			if ( isset( $input['minimum_amount'], $input['maximum_amount'] ) ) {
+				// Validate the new bounds together instead of against the stored maximum.
+				$coupon->set_maximum_amount( '' );
+			}
+			foreach ( $setters as $field => $setter ) {
+				if ( array_key_exists( $field, $input ) ) {
+					$coupon->$setter( $input[ $field ] ?? null );
+				}
+			}
+			if ( isset( $input['discount_type'] ) && ! isset( $input['amount'] ) ) {
+				$coupon->set_amount( $coupon->get_amount( 'edit' ) );
+			}
+		} catch ( \WC_Data_Exception $exception ) {
+			return new \WP_Error(
+				'woocommerce_ability_coupon_invalid_data',
+				$exception->getMessage(),
+				array( 'status' => 400 )
+			);
+		}
+
+		if ( isset( $input['description'] ) ) {
+			$coupon->set_description( wp_kses_post( (string) $input['description'] ) );
+		}
+
+		return true;
+	}
+
+	/**
+	 * Format a coupon for ability output.
+	 *
+	 * @param \WC_Coupon $coupon Coupon object.
+	 * @return array
+	 */
+	protected static function format_coupon_for_response( \WC_Coupon $coupon ): array {
+		$usage_limit          = $coupon->get_usage_limit();
+		$usage_limit_per_user = $coupon->get_usage_limit_per_user();
+
+		$output              = array(
+			'id'                          => $coupon->get_id(),
+			'code'                        => $coupon->get_code(),
+			'status'                      => (string) $coupon->get_status(),
+			'discount_type'               => $coupon->get_discount_type(),
+			'amount'                      => wc_format_decimal( $coupon->get_amount() ),
+			'description'                 => $coupon->get_description(),
+			'date_expires'                => self::format_date_for_response( $coupon->get_date_expires(), false ),
+			'date_expires_gmt'            => self::format_date_for_response( $coupon->get_date_expires() ),
+			'product_ids'                 => array_values( $coupon->get_product_ids() ),
+			'excluded_product_ids'        => array_values( $coupon->get_excluded_product_ids() ),
+			'product_categories'          => array_values( $coupon->get_product_categories() ),
+			'excluded_product_categories' => array_values( $coupon->get_excluded_product_categories() ),
+			'exclude_sale_items'          => $coupon->get_exclude_sale_items(),
+			'email_restrictions'          => array_values( $coupon->get_email_restrictions() ),
+			'usage_count'                 => $coupon->get_usage_count(),
+			'usage_limit'                 => (int) $usage_limit,
+			'usage_limit_per_user'        => (int) $usage_limit_per_user,
+			'individual_use'              => $coupon->get_individual_use(),
+			'free_shipping'               => $coupon->get_free_shipping(),
+			'minimum_amount'              => wc_format_decimal( $coupon->get_minimum_amount() ),
+			'maximum_amount'              => wc_format_decimal( $coupon->get_maximum_amount() ),
+			'date_created'                => self::format_date_for_response( $coupon->get_date_created(), false ),
+			'date_modified'               => self::format_date_for_response( $coupon->get_date_modified(), false ),
+		);
+		$date                = $coupon->get_date_expires();
+		$output['expired']   = $date && time() > $date->getTimestamp();
+		$output['scheduled'] = 'future' === $coupon->get_status();
+		$reason              = '';
+		if ( $output['expired'] ) {
+			$reason = 'expired';
+		} elseif ( $usage_limit && $coupon->get_usage_count() >= $usage_limit ) {
+			$reason = 'usage_limit_reached';
+		} elseif ( $output['scheduled'] ) {
+			$reason = 'scheduled';
+		} elseif ( 'publish' !== $coupon->get_status() ) {
+			$reason = 'not_published';
+		}
+		$output['redeemable'] = '' === $reason;
+		if ( '' !== $reason ) {
+			$output['not_redeemable_reason'] = $reason;
+		}
+		if ( $output['scheduled'] ) {
+			$output['starts_at'] = self::format_date_for_response( $coupon->get_date_created(), false );
+		}
+		$output['expiry'] = array( 'timezone' => wp_timezone_string() );
+		if ( $date ) {
+			$local = clone $date;
+			$local->setTimezone( wp_timezone() );
+			$output['expiry']['expires_at'] = $local->format( DATE_ATOM );
+			if ( '00:00:00' === $local->format( 'H:i:s' ) ) {
+				$output['expiry']['last_valid_day'] = $local->modify( '-1 day' )->format( 'Y-m-d' );
+			}
+		}
+		return array_filter(
+			$output,
+			static function ( $value ) {
+				return null !== $value;
+			}
+		);
+	}
+}
diff --git a/plugins/woocommerce/tests/php/src/Internal/Abilities/AbilitiesLoaderTest.php b/plugins/woocommerce/tests/php/src/Internal/Abilities/AbilitiesLoaderTest.php
index 1864effaeb7..e8c00d3843c 100644
--- a/plugins/woocommerce/tests/php/src/Internal/Abilities/AbilitiesLoaderTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/Abilities/AbilitiesLoaderTest.php
@@ -34,6 +34,9 @@ class AbilitiesLoaderTest extends \WC_Unit_Test_Case {
 	private static $administrator_id;

 	private const CANONICAL_ABILITY_IDS = array(
+		'woocommerce/coupons-query',
+		'woocommerce/coupon-create',
+		'woocommerce/coupon-update',
 		'woocommerce/store-settings-get',
 		'woocommerce/settings-groups-query',
 		'woocommerce/settings-query',
@@ -1039,6 +1042,15 @@ class AbilitiesLoaderTest extends \WC_Unit_Test_Case {
 	public function provider_canonical_abilities_with_minimal_input(): array {
 		// Valid-shape input only — permission check should fire before execute.
 		return array(
+			'coupons-query'               => array( 'woocommerce/coupons-query', array() ),
+			'coupon-create'               => array( 'woocommerce/coupon-create', array( 'code' => 'forbidden' ) ),
+			'coupon-update'               => array(
+				'woocommerce/coupon-update',
+				array(
+					'id'     => 1,
+					'amount' => '10',
+				),
+			),
 			'store-settings-get'          => array( 'woocommerce/store-settings-get', array() ),
 			'settings-groups-query'       => array( 'woocommerce/settings-groups-query', array() ),
 			'settings-query'              => array( 'woocommerce/settings-query', array( 'group' => 'general' ) ),
@@ -1250,6 +1262,8 @@ class AbilitiesLoaderTest extends \WC_Unit_Test_Case {
 		$missing_id = array( 'id' => PHP_INT_MAX );

 		return array(
+			'coupon-create'                  => array( 'woocommerce/coupon-create', array( 'code' => 'granted' ) ),
+			'coupons-query'                  => array( 'woocommerce/coupons-query', array() ),
 			'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 ),
diff --git a/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/CouponsQueryTest.php b/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/CouponsQueryTest.php
new file mode 100644
index 00000000000..e3be840eb80
--- /dev/null
+++ b/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/CouponsQueryTest.php
@@ -0,0 +1,625 @@
+<?php
+/**
+ * Coupon query ability tests.
+ */
+
+declare( strict_types=1 );
+
+namespace Automattic\WooCommerce\Tests\Internal\Abilities\Domain;
+
+use Automattic\WooCommerce\Internal\Abilities\Domain\CouponsQuery;
+
+/**
+ * Tests coupon reads through the ability API.
+ */
+class CouponsQueryTest extends \WC_Unit_Test_Case {
+	/**
+	 * @testdox Should find scheduled coupons by code with their email restrictions.
+	 */
+	public function test_scheduled_coupon_lookup(): void {
+		wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) );
+		$coupon = new \WC_Coupon();
+		$coupon->set_code( 'scheduled-code' );
+		$coupon->set_date_created( time() + DAY_IN_SECONDS );
+		$coupon->set_status( 'future' );
+		$coupon->set_email_restrictions( array( 'customer@example.test' ) );
+		$coupon->save();
+
+		$ability = new \WP_Ability( CouponsQuery::get_name(), CouponsQuery::get_registration_args() );
+		$result  = $ability->execute( array( 'code' => 'scheduled-code' ) );
+
+		$this->assertNotWPError( $result );
+		$this->assertSame( 1, $result['total'] );
+		$this->assertSame( $coupon->get_id(), $result['coupons'][0]['id'] );
+		$this->assertTrue( $result['coupons'][0]['scheduled'] );
+		$this->assertFalse( $result['coupons'][0]['redeemable'] );
+		$this->assertArrayHasKey( 'starts_at', $result['coupons'][0] );
+		$this->assertSame( array( 'customer@example.test' ), $result['coupons'][0]['email_restrictions'] );
+	}
+
+	/**
+	 * @testdox Should create and update a coupon while preserving its usage count.
+	 */
+	public function test_writes_preserve_usage(): void {
+		wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) );
+		$class   = \Automattic\WooCommerce\Internal\Abilities\Domain\CouponCreate::class;
+		$ability = new $class( $class::ABILITY_NAME, $class::get_registration_args() );
+		$result  = $ability->execute(
+			array(
+				'code'   => 'write-test',
+				'amount' => '10',
+			)
+		);
+		$this->assertNotWPError( $result );
+		$coupon = new \WC_Coupon( $result['coupon']['id'] );
+		$coupon->set_usage_count( 2 );
+		$coupon->save();
+		$class   = \Automattic\WooCommerce\Internal\Abilities\Domain\CouponUpdate::class;
+		$ability = new $class( $class::ABILITY_NAME, $class::get_registration_args() );
+		$result  = $ability->execute(
+			array(
+				'id'     => $coupon->get_id(),
+				'amount' => '20',
+			)
+		);
+		$this->assertNotWPError( $result );
+		$this->assertSame( '20', $result['coupon']['amount'] );
+		$this->assertSame( 2, $result['coupon']['usage_count'] );
+	}
+
+	/**
+	 * @testdox Should return saved email restrictions on create, update and query.
+	 */
+	public function test_email_restriction_writes(): void {
+		wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) );
+		$class  = \Automattic\WooCommerce\Internal\Abilities\Domain\CouponCreate::class;
+		$create = new $class( $class::ABILITY_NAME, $class::get_registration_args() );
+		$result = $create->execute(
+			array(
+				'code'               => 'restricted-emails',
+				'email_restrictions' => array( ' Customer@example.test ', 'other@example.test' ),
+			)
+		);
+		$this->assertNotWPError( $result );
+		$this->assertSame( array( 'customer@example.test', 'other@example.test' ), $result['coupon']['email_restrictions'] );
+		$id = $result['coupon']['id'];
+		$this->assertSame( array( 'customer@example.test', 'other@example.test' ), ( new \WC_Coupon( $id ) )->get_email_restrictions() );
+
+		$class  = \Automattic\WooCommerce\Internal\Abilities\Domain\CouponUpdate::class;
+		$update = new $class( $class::ABILITY_NAME, $class::get_registration_args() );
+		$result = $update->execute(
+			array(
+				'id'                 => $id,
+				'email_restrictions' => array( 'replacement@example.test' ),
+			)
+		);
+		$this->assertNotWPError( $result );
+		$this->assertSame( array( 'replacement@example.test' ), $result['coupon']['email_restrictions'] );
+		$this->assertSame( array( 'replacement@example.test' ), ( new \WC_Coupon( $id ) )->get_email_restrictions() );
+
+		$result = $update->execute(
+			array(
+				'id'     => $id,
+				'amount' => '15',
+			)
+		);
+		$this->assertNotWPError( $result );
+		$this->assertSame( array( 'replacement@example.test' ), ( new \WC_Coupon( $id ) )->get_email_restrictions() );
+		$query  = new \WP_Ability( CouponsQuery::get_name(), CouponsQuery::get_registration_args() );
+		$result = $query->execute( array( 'include' => array( $id ) ) );
+		$this->assertNotWPError( $result );
+		$this->assertSame( array( 'replacement@example.test' ), $result['coupons'][0]['email_restrictions'] );
+
+		$result = $update->execute(
+			array(
+				'id'                 => $id,
+				'email_restrictions' => array(),
+			)
+		);
+		$this->assertNotWPError( $result );
+		$this->assertSame( array(), $result['coupon']['email_restrictions'] );
+		$this->assertSame( array(), ( new \WC_Coupon( $id ) )->get_email_restrictions() );
+	}
+
+	/**
+	 * @testdox Should reject invalid emails before saving any coupon changes.
+	 * @testWith [["not-an-email"]]
+	 *           [["customer name@example.test"]]
+	 *           [[""]]
+	 *           [["valid@example.test", "invalid"]]
+	 * @param array $emails Supplied restrictions.
+	 */
+	public function test_invalid_email_restrictions( array $emails ): void {
+		wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) );
+		$class  = \Automattic\WooCommerce\Internal\Abilities\Domain\CouponCreate::class;
+		$create = new $class( $class::ABILITY_NAME, $class::get_registration_args() );
+		$result = $create->execute(
+			array(
+				'code'               => 'invalid-email-create',
+				'email_restrictions' => $emails,
+			)
+		);
+		$this->assertWPError( $result );
+		$this->assertSame( 'woocommerce_ability_coupon_email_invalid', $result->get_error_code() );
+		$this->assertSame( 0, wc_get_coupon_id_by_code( 'invalid-email-create' ) );
+
+		$coupon = new \WC_Coupon();
+		$coupon->set_code( 'invalid-email-update' );
+		$coupon->set_amount( '10' );
+		$coupon->set_email_restrictions( array( 'original@example.test' ) );
+		$coupon->save();
+		$before = ( new \WC_Coupon( $coupon->get_id() ) )->get_data();
+		$class  = \Automattic\WooCommerce\Internal\Abilities\Domain\CouponUpdate::class;
+		$update = new $class( $class::ABILITY_NAME, $class::get_registration_args() );
+		$result = $update->execute(
+			array(
+				'id'                 => $coupon->get_id(),
+				'amount'             => '20',
+				'email_restrictions' => $emails,
+			)
+		);
+		$this->assertWPError( $result );
+		$this->assertSame( 'woocommerce_ability_coupon_email_invalid', $result->get_error_code() );
+		$this->assertEquals( $before, ( new \WC_Coupon( $coupon->get_id() ) )->get_data() );
+	}
+
+	/**
+	 * @testdox Should page included coupons and filter by discount type.
+	 */
+	public function test_pagination_and_filters(): void {
+		wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) );
+		$ids = array();
+		foreach ( array( 'percent', 'percent', 'fixed_cart' ) as $index => $type ) {
+			$coupon = new \WC_Coupon();
+			$coupon->set_code( 'page-' . $index );
+			$coupon->set_discount_type( $type );
+			$coupon->save();
+			$ids[] = $coupon->get_id();
+		}
+		$ability = new \WP_Ability( CouponsQuery::get_name(), CouponsQuery::get_registration_args() );
+		$input   = array(
+			'include'       => $ids,
+			'discount_type' => 'percent',
+			'per_page'      => 1,
+		);
+		$first   = $ability->execute( $input );
+		$second  = $ability->execute( $input + array( 'page' => 2 ) );
+		$this->assertSame( 2, $first['total'] );
+		$this->assertSame( 2, $first['total_pages'] );
+		$this->assertCount( 1, $first['coupons'] );
+		$this->assertNotSame( $first['coupons'][0]['id'], $second['coupons'][0]['id'] );
+	}
+
+	/**
+	 * @testdox Should refuse coupon access to customers.
+	 */
+	public function test_permissions(): void {
+		wp_set_current_user( self::factory()->user->create( array( 'role' => 'customer' ) ) );
+		$ability = new \WP_Ability( CouponsQuery::get_name(), CouponsQuery::get_registration_args() );
+		$this->assertWPError( $ability->execute( array() ) );
+	}
+
+	/**
+	 * @testdox Should require publication permission for published, scheduled and private coupons.
+	 * @testWith ["publish"]
+	 *           ["future"]
+	 *           ["private"]
+	 * @param string $status Requested status.
+	 */
+	public function test_publication_permission( string $status ): void {
+		$user = self::factory()->user->create( array( 'role' => 'administrator' ) );
+		wp_set_current_user( $user );
+		wp_get_current_user()->add_cap( 'publish_shop_coupons', false );
+		$coupon = new \WC_Coupon();
+		$coupon->set_code( 'restricted-status' );
+		$coupon->set_status( 'draft' );
+		$coupon->set_date_created( time() + DAY_IN_SECONDS );
+		$coupon->save();
+		$class   = \Automattic\WooCommerce\Internal\Abilities\Domain\CouponUpdate::class;
+		$ability = new $class( $class::ABILITY_NAME, $class::get_registration_args() );
+		$before  = ( new \WC_Coupon( $coupon->get_id() ) )->get_data();
+		$result  = $ability->execute(
+			array(
+				'id'     => $coupon->get_id(),
+				'status' => $status,
+				'amount' => '20',
+			)
+		);
+		$this->assertWPError( $result );
+		$this->assertSame( 'woocommerce_ability_coupon_publish_forbidden', $result->get_error_code() );
+		$this->assertEquals( $before, ( new \WC_Coupon( $coupon->get_id() ) )->get_data() );
+	}
+
+	/**
+	 * @testdox Should authorize publication against the coupon loaded after the permission callback.
+	 */
+	public function test_publication_permission_after_status_change(): void {
+		wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) );
+		wp_get_current_user()->add_cap( 'publish_shop_coupons', false );
+		$coupon = new \WC_Coupon();
+		$coupon->set_code( 'publication-status-change' );
+		$coupon->save();
+		$class = \Automattic\WooCommerce\Internal\Abilities\Domain\CouponUpdate::class;
+		$input = array(
+			'id'     => $coupon->get_id(),
+			'status' => 'publish',
+		);
+		$this->assertTrue( $class::can_update_coupon( $input ) );
+		$coupon->set_status( 'draft' );
+		$coupon->save();
+		$before  = ( new \WC_Coupon( $coupon->get_id() ) )->get_data();
+		$ability = new $class( $class::ABILITY_NAME, $class::get_registration_args() );
+		$result  = $ability->execute_change( $input );
+		$this->assertWPError( $result );
+		$this->assertSame( 'woocommerce_ability_coupon_publish_forbidden', $result->get_error_code() );
+		$this->assertEquals( $before, ( new \WC_Coupon( $coupon->get_id() ) )->get_data() );
+	}
+
+	/**
+	 * @testdox Should require REST creation permission even for a draft coupon.
+	 */
+	public function test_draft_creation_permission(): void {
+		wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) );
+		wp_get_current_user()->add_cap( 'publish_shop_coupons', false );
+		$class   = \Automattic\WooCommerce\Internal\Abilities\Domain\CouponCreate::class;
+		$ability = new $class( $class::ABILITY_NAME, $class::get_registration_args() );
+		$result  = $ability->execute(
+			array(
+				'code'   => 'forbidden-draft',
+				'status' => 'draft',
+			)
+		);
+		$this->assertWPError( $result );
+		$this->assertSame( 'ability_invalid_permissions', $result->get_error_code() );
+		$this->assertSame( 0, wc_get_coupon_id_by_code( 'forbidden-draft' ) );
+	}
+
+	/**
+	 * @testdox Should reject invalid mutations without changing stored coupon data.
+	 * @testWith [{"status":"future"}]
+	 *           [{"date_expires":"not-a-date"}]
+	 *           [{"discount_type":"percent"}]
+	 * @param array $input Mutation.
+	 */
+	public function test_invalid_mutations( array $input ): void {
+		wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) );
+		$coupon = new \WC_Coupon();
+		$coupon->set_code( 'invalid-mutation' );
+		$coupon->set_amount( '150' );
+		$coupon->set_date_expires( '2030-01-01' );
+		$coupon->save();
+		$before  = ( new \WC_Coupon( $coupon->get_id() ) )->get_data();
+		$class   = \Automattic\WooCommerce\Internal\Abilities\Domain\CouponUpdate::class;
+		$ability = new $class( $class::ABILITY_NAME, $class::get_registration_args() );
+		$this->assertWPError( $ability->execute( $input + array( 'id' => $coupon->get_id() ) ) );
+		$this->assertEquals( $before, ( new \WC_Coupon( $coupon->get_id() ) )->get_data() );
+	}
+
+	/**
+	 * @testdox Should reject duplicate draft codes and unscheduled future creation.
+	 * @testWith [{"code":"existing-draft"}, "woocommerce_ability_coupon_code_exists"]
+	 *           [{"code":"new-future","status":"future"}, "ability_invalid_input"]
+	 * @param array  $input Creation input.
+	 * @param string $error_code Expected rejection.
+	 */
+	public function test_invalid_creation( array $input, string $error_code ): void {
+		wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) );
+		$coupon = new \WC_Coupon();
+		$coupon->set_code( 'existing-draft' );
+		$coupon->set_status( 'draft' );
+		$coupon->save();
+		$class   = \Automattic\WooCommerce\Internal\Abilities\Domain\CouponCreate::class;
+		$ability = new $class( $class::ABILITY_NAME, $class::get_registration_args() );
+		$result  = $ability->execute( $input );
+		$this->assertWPError( $result );
+		$this->assertSame( $error_code, $result->get_error_code() );
+	}
+
+	/**
+	 * @testdox Should let an editor retain the existing publication status.
+	 */
+	public function test_unchanged_status(): void {
+		wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) );
+		wp_get_current_user()->add_cap( 'publish_shop_coupons', false );
+		$coupon = new \WC_Coupon();
+		$coupon->set_code( 'unchanged-status' );
+		$coupon->save();
+		$class   = \Automattic\WooCommerce\Internal\Abilities\Domain\CouponUpdate::class;
+		$ability = new $class( $class::ABILITY_NAME, $class::get_registration_args() );
+		$result  = $ability->execute(
+			array(
+				'id'     => $coupon->get_id(),
+				'status' => 'publish',
+				'amount' => '20',
+			)
+		);
+		$this->assertNotWPError( $result );
+		$this->assertSame( '20', ( new \WC_Coupon( $coupon->get_id() ) )->get_amount() );
+	}
+
+	/**
+	 * @testdox Should preserve expiry instants when the store uses a non-UTC timezone.
+	 * @testWith ["2030-01-01T12:00:00.123+01:00", 1893495600]
+	 *           ["20300101", 1893452400]
+	 * @param string $expiry Expiry input.
+	 * @param int    $timestamp Expected stored instant.
+	 */
+	public function test_expiry_normalization( string $expiry, int $timestamp ): void {
+		update_option( 'timezone_string', 'Europe/Madrid' );
+		wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) );
+		$class   = \Automattic\WooCommerce\Internal\Abilities\Domain\CouponCreate::class;
+		$ability = new $class( $class::ABILITY_NAME, $class::get_registration_args() );
+		$result  = $ability->execute(
+			array(
+				'code'         => 'normalized-expiry',
+				'date_expires' => $expiry,
+			)
+		);
+		$this->assertNotWPError( $result );
+		$coupon = new \WC_Coupon( $result['coupon']['id'] );
+		$this->assertSame( $timestamp, $coupon->get_date_expires()->getTimestamp() );
+	}
+
+	/**
+	 * @testdox Should authorize implicit publication while allowing unrelated overdue coupon edits.
+	 * @testWith [{"amount":"15","email_restrictions":["customer@example.com"]}, false, "future"]
+	 *           [{"description":"changed","amount":"15"}, false, null]
+	 *           [{"code":"changed-code","amount":"15"}, false, null]
+	 *           [{"description":"changed"}, true, "publish"]
+	 *           [{"code":"changed-code"}, true, "publish"]
+	 *           [{"description":"","code":"overdue-scheduled","amount":"15"}, false, "future"]
+	 *           [{"description":"changed","status":"draft"}, false, "draft"]
+	 *           [{"description":"changed"}, false, null, 30]
+	 * @param array       $input Update fields.
+	 * @param bool        $can_publish Whether publication is allowed.
+	 * @param string|null $expected_status Saved status, or null for a rejected update.
+	 * @param int         $publication_offset Seconds until the publication date.
+	 */
+	public function test_update_overdue_scheduled_coupon( array $input, bool $can_publish, ?string $expected_status, int $publication_offset = -DAY_IN_SECONDS ): void {
+		global $wpdb;
+
+		wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) );
+		wp_get_current_user()->add_cap( 'publish_shop_coupons', $can_publish );
+		$coupon = new \WC_Coupon();
+		$coupon->set_code( 'overdue-scheduled' );
+		$coupon->set_amount( '10' );
+		$coupon->set_date_created( time() + DAY_IN_SECONDS );
+		$coupon->set_status( 'future' );
+		$coupon->save();
+		$overdue = time() + $publication_offset;
+		// Simulate a publication that WP-Cron has not processed yet.
+		$wpdb->update(
+			$wpdb->posts,
+			array(
+				'post_date'     => wp_date( 'Y-m-d H:i:s', $overdue ),
+				'post_date_gmt' => gmdate( 'Y-m-d H:i:s', $overdue ),
+			),
+			array( 'ID' => $coupon->get_id() )
+		);
+		clean_post_cache( $coupon->get_id() );
+		$class   = \Automattic\WooCommerce\Internal\Abilities\Domain\CouponUpdate::class;
+		$ability = new $class( $class::ABILITY_NAME, $class::get_registration_args() );
+		$before  = ( new \WC_Coupon( $coupon->get_id() ) )->get_data();
+		$result  = $ability->execute( $input + array( 'id' => $coupon->get_id() ) );
+		$stored  = new \WC_Coupon( $coupon->get_id() );
+		if ( null === $expected_status ) {
+			$this->assertWPError( $result );
+			$this->assertSame( 'woocommerce_ability_coupon_publish_forbidden', $result->get_error_code() );
+			$this->assertEquals( $before, $stored->get_data() );
+			return;
+		}
+		$this->assertNotWPError( $result );
+		$this->assertSame( $expected_status, $stored->get_status() );
+		$this->assertSame( $expected_status, $result['coupon']['status'] );
+		$this->assertSame( $overdue, $stored->get_date_created()->getTimestamp() );
+		foreach ( $input as $field => $value ) {
+			$this->assertSame( $value, $stored->{ 'get_' . $field }() );
+		}
+		if ( 'future' === $expected_status ) {
+			$before = $stored->get_data();
+			$result = $ability->execute(
+				array(
+					'id'     => $coupon->get_id(),
+					'status' => 'future',
+					'amount' => '20',
+				)
+			);
+			$this->assertWPError( $result );
+			$this->assertSame( 'woocommerce_ability_coupon_invalid_schedule', $result->get_error_code() );
+			$this->assertEquals( $before, ( new \WC_Coupon( $coupon->get_id() ) )->get_data() );
+		}
+	}
+
+	/**
+	 * @testdox Should publish a scheduled coupon in storage as well as in its response.
+	 */
+	public function test_publish_scheduled_coupon(): void {
+		wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) );
+		$coupon = new \WC_Coupon();
+		$coupon->set_code( 'publish-scheduled' );
+		$coupon->set_date_created( time() + DAY_IN_SECONDS );
+		$coupon->set_status( 'future' );
+		$coupon->save();
+		$class   = \Automattic\WooCommerce\Internal\Abilities\Domain\CouponUpdate::class;
+		$ability = new $class( $class::ABILITY_NAME, $class::get_registration_args() );
+		$result  = $ability->execute(
+			array(
+				'id'     => $coupon->get_id(),
+				'status' => 'publish',
+			)
+		);
+		$this->assertNotWPError( $result );
+		$this->assertSame( 'publish', $result['coupon']['status'] );
+		$this->assertSame( 'publish', ( new \WC_Coupon( $coupon->get_id() ) )->get_status() );
+	}
+
+	/**
+	 * @testdox Should retain totals when the requested page is beyond the last match.
+	 */
+	public function test_out_of_range_totals(): void {
+		wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) );
+		$coupon = new \WC_Coupon();
+		$coupon->set_code( 'one-match' );
+		$coupon->save();
+		$ability = new \WP_Ability( CouponsQuery::get_name(), CouponsQuery::get_registration_args() );
+		$result  = $ability->execute(
+			array(
+				'include'  => array( $coupon->get_id() ),
+				'page'     => 2,
+				'per_page' => 1,
+			)
+		);
+		$this->assertSame( array(), $result['coupons'] );
+		$this->assertSame( 1, $result['total'] );
+		$this->assertSame( 1, $result['total_pages'] );
+	}
+	/**
+	 * @testdox Should validate spending limits against their final values without partial saves.
+	 * @testWith [{"minimum_amount":"30","maximum_amount":"40"}, "30", "40", true]
+	 *           [{"minimum_amount":"1","maximum_amount":"5"}, "1", "5", true]
+	 *           [{"minimum_amount":"30","maximum_amount":"0"}, "30", "0", true]
+	 *           [{"minimum_amount":"30","maximum_amount":""}, "30", "0", true]
+	 *           [{"minimum_amount":"","maximum_amount":"5"}, "0", "5", true]
+	 *           [{"minimum_amount":"30","maximum_amount":"25"}, "10", "20", false]
+	 *           [{"minimum_amount":"30"}, "10", "20", false]
+	 *           [{"maximum_amount":"5"}, "10", "20", false]
+	 * @param array  $input Requested limits.
+	 * @param string $minimum Expected minimum.
+	 * @param string $maximum Expected maximum.
+	 * @param bool   $valid Whether the final pair is valid.
+	 */
+	public function test_spending_limit_updates( array $input, string $minimum, string $maximum, bool $valid ): void {
+		wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) );
+		$coupon = new \WC_Coupon();
+		$coupon->set_code( 'spending-limit-update' );
+		$coupon->set_minimum_amount( '10' );
+		$coupon->set_maximum_amount( '20' );
+		$coupon->save();
+		$before = ( new \WC_Coupon( $coupon->get_id() ) )->get_data();
+		$class  = \Automattic\WooCommerce\Internal\Abilities\Domain\CouponUpdate::class;
+		$update = new $class( $class::ABILITY_NAME, $class::get_registration_args() );
+		$result = $update->execute( $input + array( 'id' => $coupon->get_id() ) );
+		if ( $valid ) {
+			$this->assertNotWPError( $result );
+		} else {
+			$this->assertWPError( $result );
+			$this->assertSame( 'woocommerce_ability_coupon_invalid_data', $result->get_error_code() );
+			$this->assertEquals( $before, ( new \WC_Coupon( $coupon->get_id() ) )->get_data() );
+		}
+		$stored = new \WC_Coupon( $coupon->get_id() );
+		$this->assertSame( $minimum, $stored->get_minimum_amount() );
+		$this->assertSame( $maximum, $stored->get_maximum_amount() );
+	}
+
+	/**
+	 * @testdox Should retain a zero search term instead of returning every included coupon.
+	 */
+	public function test_zero_search(): void {
+		wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) );
+		$ids = array();
+		foreach ( array( 'no-match', 'match-0' ) as $code ) {
+			$coupon = new \WC_Coupon();
+			$coupon->set_code( $code );
+			$coupon->save();
+			$ids[] = $coupon->get_id();
+		}
+		$ability = new \WP_Ability( CouponsQuery::get_name(), CouponsQuery::get_registration_args() );
+		$result  = $ability->execute(
+			array(
+				'include' => $ids,
+				'search'  => '0',
+			)
+		);
+		$this->assertNotWPError( $result );
+		$this->assertSame( 1, $result['total'] );
+		$this->assertSame( array( $ids[1] ), array_column( $result['coupons'], 'id' ) );
+	}
+
+	/**
+	 * @testdox Should reject exact codes that normalize to empty instead of listing unrelated coupons.
+	 * @testWith [""]
+	 *           ["   "]
+	 *           ["\u0000"]
+	 * @param string $code Exact code input.
+	 */
+	public function test_empty_exact_code( string $code ): void {
+		wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) );
+		$coupon = new \WC_Coupon();
+		$coupon->set_code( 'unrelated-coupon' );
+		$coupon->save();
+		$ability = new \WP_Ability( CouponsQuery::get_name(), CouponsQuery::get_registration_args() );
+		$result  = $ability->execute(
+			array(
+				'include' => array( $coupon->get_id() ),
+				'code'    => $code,
+			)
+		);
+		$this->assertWPError( $result );
+		$this->assertSame( 'woocommerce_ability_coupon_code_required', $result->get_error_code() );
+	}
+	/**
+	 * @testdox Should report the stored status when a creation filter changes it.
+	 */
+	public function test_create_response_uses_saved_coupon(): void {
+		wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) );
+		add_filter(
+			'woocommerce_new_coupon_data',
+			static function ( $data ) {
+				$data['post_status'] = 'draft';
+				return $data;
+			}
+		);
+		$class   = \Automattic\WooCommerce\Internal\Abilities\Domain\CouponCreate::class;
+		$ability = new $class( $class::ABILITY_NAME, $class::get_registration_args() );
+		$result  = $ability->execute( array( 'code' => 'filtered-creation' ) );
+		$this->assertNotWPError( $result );
+		$this->assertSame( 'draft', ( new \WC_Coupon( $result['coupon']['id'] ) )->get_status() );
+		$this->assertSame( 'draft', $result['coupon']['status'] );
+		$this->assertFalse( $result['coupon']['redeemable'] );
+	}
+
+	/**
+	 * @testdox Should reload saved coupon responses without treating their IDs as virtual codes.
+	 * @testWith ["create"]
+	 *           ["update"]
+	 * @param string $operation Mutation to execute.
+	 */
+	public function test_saved_response_bypasses_virtual_coupon_filter( string $operation ): void {
+		wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) );
+		$input = array( 'amount' => '15' );
+		if ( 'update' === $operation ) {
+			$coupon = new \WC_Coupon();
+			$coupon->set_code( 'saved-real-coupon' );
+			$coupon->save();
+			$input['id'] = $coupon->get_id();
+			$class       = \Automattic\WooCommerce\Internal\Abilities\Domain\CouponUpdate::class;
+		} else {
+			$input['code'] = 'saved-real-coupon';
+			$class         = \Automattic\WooCommerce\Internal\Abilities\Domain\CouponCreate::class;
+		}
+		$saved_id = 0;
+		add_action(
+			'create' === $operation ? 'woocommerce_new_coupon' : 'woocommerce_update_coupon',
+			static function ( $id ) use ( &$saved_id ) {
+				$saved_id = $id;
+				add_filter(
+					'woocommerce_get_shop_coupon_data',
+					static function ( $data, $code ) use ( $id ) {
+						return (string) $id === (string) $code ? array( 'amount' => '99' ) : $data;
+					},
+					10,
+					2
+				);
+			}
+		);
+		$ability = new $class( $class::ABILITY_NAME, $class::get_registration_args() );
+		$result  = $ability->execute( $input );
+		$this->assertNotWPError( $result );
+		$this->assertGreaterThan( 0, $saved_id );
+		$this->assertSame( $saved_id, $result['coupon']['id'] );
+		$this->assertSame( 'saved-real-coupon', $result['coupon']['code'] );
+		$this->assertSame( '15', $result['coupon']['amount'] );
+		$this->assertSame( 'saved-real-coupon', get_post_field( 'post_title', $saved_id ) );
+		$this->assertSame( '15', get_post_meta( $saved_id, 'coupon_amount', true ) );
+	}
+}