Commit 205e7f276b5 for woocommerce
commit 205e7f276b57090de4436ec61a89f1cf1f07fa83
Author: Christopher Hertel <mail@christopher-hertel.de>
Date: Mon Nov 16 21:57:00 2026 +0100
Add shipping zone and method write abilities (#70878)
* Add shipping zone and method write abilities
Add shipping-zone-create, shipping-zone-method-create and
shipping-zone-method-update, so an agent can set up a zone with a flat
rate and free shipping over a minimum.
The method writes go through ShippingZoneMethodService, so the setting
validators and the instance settings filter run as on the settings
screen. Settings are slashed first, since those validators unslash, and
the shipping cache version is bumped after every write: the service only
bumps it for enabled or order changes, which left stale rates in carts.
Sending min_amount to a free shipping method without a requirement sets
requires to min_amount, since the minimum is ignored otherwise.
The zone and method formatting moves into ShippingZoneAbilityTrait,
shared with shipping-zones-query.
* Refuse shipping writes while shipping is turned off
With shipping disabled, the zone and methods were saved and the ability
reported success, but checkout offered none of them. The REST endpoints
refuse in that case, so the abilities now do too.
Also note in the method create docblock that a refused create fires the
method added and deleted hooks back to back.
* Require zone locations and tighten shipping write input
A zone without locations matches every address no earlier zone covers,
so a create without locations would hide zone 0 behind a zone with no
methods. Locations are now required, and codes are capped at the
200 characters their column holds.
A method that can't be read back after it was added is removed again,
and a negative free shipping minimum is refused.
* Cover shipping writes in the ability permission refusal tests
* Accept truthy REST permission grants in shipping writes
A woocommerce_rest_check_permissions callback that returns 1 grants
access in REST, but made the bool return of the shared permission
callback throw a TypeError under strict types.
* Refuse unreadable free shipping minimums and refresh rates after partial writes
The price validator turns a minimum without digits, such as a lone comma,
into an empty value that every cart meets, so it is now refused with
negative ones.
The method service saves the settings before the enabled state and
order, and returns without bumping the shipping cache when that second
write fails, which left the new cost out of carts.
diff --git a/plugins/woocommerce/changelog/wooai-1548-shipping-writes b/plugins/woocommerce/changelog/wooai-1548-shipping-writes
new file mode 100644
index 00000000000..f82f36f3c59
--- /dev/null
+++ b/plugins/woocommerce/changelog/wooai-1548-shipping-writes
@@ -0,0 +1,4 @@
+Significance: minor
+Type: add
+
+Add abilities that create shipping zones and add or change their flat rate, free shipping and local pickup methods.
diff --git a/plugins/woocommerce/src/Internal/Abilities/AbilitiesLoader.php b/plugins/woocommerce/src/Internal/Abilities/AbilitiesLoader.php
index 5caa24951be..bab61f2fd16 100644
--- a/plugins/woocommerce/src/Internal/Abilities/AbilitiesLoader.php
+++ b/plugins/woocommerce/src/Internal/Abilities/AbilitiesLoader.php
@@ -33,6 +33,9 @@ use Automattic\WooCommerce\Internal\Abilities\Domain\ProductReviewReply;
use Automattic\WooCommerce\Internal\Abilities\Domain\ProductTermUpdate;
use Automattic\WooCommerce\Internal\Abilities\Domain\ProductReviewsQuery;
use Automattic\WooCommerce\Internal\Abilities\Domain\ProductReviewUpdate;
+use Automattic\WooCommerce\Internal\Abilities\Domain\ShippingZoneCreate;
+use Automattic\WooCommerce\Internal\Abilities\Domain\ShippingZoneMethodCreate;
+use Automattic\WooCommerce\Internal\Abilities\Domain\ShippingZoneMethodUpdate;
use Automattic\WooCommerce\Internal\Abilities\Domain\ShippingZonesQuery;
use Automattic\WooCommerce\Internal\Abilities\Domain\SystemStatusToolRun;
use Automattic\WooCommerce\Internal\Abilities\Domain\SystemStatusToolsQuery;
@@ -87,6 +90,9 @@ class AbilitiesLoader {
ShippingZonesQuery::class,
SystemStatusToolsQuery::class,
SystemStatusToolRun::class,
+ ShippingZoneCreate::class,
+ ShippingZoneMethodCreate::class,
+ ShippingZoneMethodUpdate::class,
TaxRatesQuery::class,
CustomersQuery::class,
);
diff --git a/plugins/woocommerce/src/Internal/Abilities/Domain/ShippingZoneCreate.php b/plugins/woocommerce/src/Internal/Abilities/Domain/ShippingZoneCreate.php
new file mode 100644
index 00000000000..9b00c764d6b
--- /dev/null
+++ b/plugins/woocommerce/src/Internal/Abilities/Domain/ShippingZoneCreate.php
@@ -0,0 +1,144 @@
+<?php
+/**
+ * Shipping zone create 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\ShippingZoneAbilityTrait;
+
+defined( 'ABSPATH' ) || exit;
+
+/**
+ * Creates a shipping zone without methods.
+ *
+ * Not an ActionableAbility, which would make the zone a resource that extensions add fields to.
+ */
+class ShippingZoneCreate extends AbstractDomainAbility implements AbilityDefinition {
+
+ use ShippingZoneAbilityTrait;
+
+ /**
+ * Get the ability name.
+ *
+ * @return string
+ *
+ * @since 11.4.0
+ */
+ public static function get_name(): string {
+ return 'woocommerce/shipping-zone-create';
+ }
+
+ /**
+ * Get the ability registration arguments.
+ *
+ * @return array
+ *
+ * @since 11.4.0
+ */
+ public static function get_registration_args(): array {
+ return array(
+ 'label' => __( 'Create shipping zone', 'woocommerce' ),
+ 'description' => __( 'Create a shipping zone for a set of regions. It has no methods yet; add them with shipping-zone-method-create. A customer gets the first zone in order that matches their address.', 'woocommerce' ),
+ 'category' => 'woocommerce',
+ 'input_schema' => array(
+ 'type' => 'object',
+ 'properties' => array(
+ 'name' => array(
+ 'type' => 'string',
+ 'description' => __( 'Zone name, shown only to the store team.', 'woocommerce' ),
+ ),
+ 'locations' => array(
+ 'type' => 'array',
+ 'description' => __( 'Regions the zone covers.', 'woocommerce' ),
+ 'minItems' => 1,
+ 'items' => array(
+ 'type' => 'object',
+ 'properties' => array(
+ 'code' => array(
+ 'type' => 'string',
+ 'description' => __( 'ISO country code such as DE, COUNTRY:STATE such as US:CA, continent code such as EU, or a postcode, a range such as 10000...19999, or a wildcard such as 10*.', 'woocommerce' ),
+ 'minLength' => 1,
+ 'maxLength' => 200,
+ ),
+ 'type' => array(
+ 'type' => 'string',
+ 'enum' => array( 'country', 'state', 'postcode', 'continent' ),
+ ),
+ ),
+ 'required' => array( 'code', 'type' ),
+ 'additionalProperties' => false,
+ ),
+ ),
+ 'order' => array(
+ 'type' => 'integer',
+ 'description' => __( 'Position among the zones. Lower is matched first.', 'woocommerce' ),
+ 'minimum' => 0,
+ ),
+ ),
+ 'required' => array( 'name', 'locations' ),
+ 'additionalProperties' => false,
+ ),
+ 'output_schema' => self::get_entity_output_schema( 'zone', self::get_zone_output_schema() ),
+ 'execute_callback' => array( __CLASS__, 'execute' ),
+ 'permission_callback' => array( __CLASS__, 'can_edit_shipping' ),
+ 'meta' => array(
+ 'show_in_rest' => true,
+ 'mcp' => array(
+ 'public' => true,
+ 'type' => 'tool',
+ ),
+ 'annotations' => array(
+ 'readonly' => false,
+ 'idempotent' => false,
+ 'destructive' => false,
+ ),
+ ),
+ );
+ }
+
+ /**
+ * Create the zone.
+ *
+ * @param array $input Ability input.
+ * @return array|\WP_Error
+ *
+ * @since 11.4.0
+ */
+ public static function execute( array $input ) {
+ $disabled = self::get_shipping_disabled_error();
+ if ( null !== $disabled ) {
+ return $disabled;
+ }
+
+ $name = sanitize_text_field( $input['name'] );
+ if ( '' === $name ) {
+ return new \WP_Error( 'woocommerce_ability_shipping_zone_name_empty', __( 'The zone name is empty.', 'woocommerce' ), array( 'status' => 400 ) );
+ }
+
+ $zone = new \WC_Shipping_Zone( null );
+ $zone->set_zone_name( $name );
+ $zone->set_zone_order( $input['order'] ?? 0 );
+ $zone->set_locations(
+ array_map(
+ static function ( array $location ): array {
+ return array(
+ 'code' => sanitize_text_field( $location['code'] ),
+ 'type' => $location['type'],
+ );
+ },
+ $input['locations'] ?? array()
+ )
+ );
+ $zone->save();
+
+ if ( ! $zone->get_id() ) {
+ return new \WP_Error( 'woocommerce_ability_shipping_zone_create_failed', __( 'The shipping zone could not be saved.', 'woocommerce' ), array( 'status' => 500 ) );
+ }
+
+ return array( 'zone' => self::format_zone_for_response( new \WC_Shipping_Zone( $zone->get_id() ) ) );
+ }
+}
diff --git a/plugins/woocommerce/src/Internal/Abilities/Domain/ShippingZoneMethodCreate.php b/plugins/woocommerce/src/Internal/Abilities/Domain/ShippingZoneMethodCreate.php
new file mode 100644
index 00000000000..575bea8031e
--- /dev/null
+++ b/plugins/woocommerce/src/Internal/Abilities/Domain/ShippingZoneMethodCreate.php
@@ -0,0 +1,127 @@
+<?php
+/**
+ * Shipping zone method create 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\ShippingZoneAbilityTrait;
+
+defined( 'ABSPATH' ) || exit;
+
+/**
+ * Adds a flat rate, free shipping or local pickup method to a zone.
+ *
+ * A method is a table row plus an option, not a WC_Data object, so a failed settings write removes the method again instead of rolling back.
+ * Listeners then see woocommerce_shipping_zone_method_added and, right after, woocommerce_shipping_zone_method_deleted.
+ */
+class ShippingZoneMethodCreate extends AbstractDomainAbility implements AbilityDefinition {
+
+ use ShippingZoneAbilityTrait;
+
+ /**
+ * Get the ability name.
+ *
+ * @return string
+ *
+ * @since 11.4.0
+ */
+ public static function get_name(): string {
+ return 'woocommerce/shipping-zone-method-create';
+ }
+
+ /**
+ * Get the ability registration arguments.
+ *
+ * @return array
+ *
+ * @since 11.4.0
+ */
+ public static function get_registration_args(): array {
+ return array(
+ 'label' => __( 'Add shipping method to zone', 'woocommerce' ),
+ 'description' => __( 'Add a flat rate, free shipping or local pickup method to a shipping zone, with its settings. Zone 0 covers every location no other zone matches.', 'woocommerce' ),
+ 'category' => 'woocommerce',
+ 'input_schema' => array(
+ 'type' => 'object',
+ 'properties' => array_merge(
+ array(
+ 'zone_id' => array(
+ 'type' => 'integer',
+ 'minimum' => 0,
+ ),
+ 'method_id' => array(
+ 'type' => 'string',
+ 'enum' => array_keys( self::$writable_method_settings ),
+ ),
+ ),
+ self::get_method_write_input_properties()
+ ),
+ 'required' => array( 'zone_id', 'method_id' ),
+ 'additionalProperties' => false,
+ ),
+ 'output_schema' => self::get_entity_output_schema( 'method', self::get_method_output_schema() ),
+ 'execute_callback' => array( __CLASS__, 'execute' ),
+ 'permission_callback' => array( __CLASS__, 'can_edit_shipping' ),
+ 'meta' => array(
+ 'show_in_rest' => true,
+ 'mcp' => array(
+ 'public' => true,
+ 'type' => 'tool',
+ ),
+ 'annotations' => array(
+ 'readonly' => false,
+ 'idempotent' => false,
+ 'destructive' => false,
+ ),
+ ),
+ );
+ }
+
+ /**
+ * Add the method to the zone and write its settings.
+ *
+ * @param array $input Ability input.
+ * @return array|\WP_Error
+ *
+ * @since 11.4.0
+ */
+ public static function execute( array $input ) {
+ $disabled = self::get_shipping_disabled_error();
+ if ( null !== $disabled ) {
+ return $disabled;
+ }
+
+ $zone = self::get_zone_or_error( $input['zone_id'] );
+ if ( is_wp_error( $zone ) ) {
+ return $zone;
+ }
+
+ // A woocommerce_shipping_methods callback can remove a Core method or replace its class.
+ $available = WC()->shipping()->get_shipping_methods();
+ $prototype = $available[ $input['method_id'] ] ?? null;
+ if ( ! $prototype instanceof \WC_Shipping_Method || ! self::is_core_method( $prototype ) ) {
+ return self::get_unsupported_method_error( $input['method_id'] );
+ }
+
+ $instance_id = $zone->add_shipping_method( $input['method_id'] );
+ $method = $instance_id ? \WC_Shipping_Zones::get_shipping_method( $instance_id ) : false;
+ if ( ! $method instanceof \WC_Shipping_Method ) {
+ if ( $instance_id ) {
+ $zone->delete_shipping_method( $instance_id );
+ }
+ return new \WP_Error( 'woocommerce_ability_shipping_method_create_failed', __( 'The shipping method could not be added to the zone.', 'woocommerce' ), array( 'status' => 500 ) );
+ }
+
+ $error = self::write_method_changes( $method, $zone, $input );
+ if ( is_wp_error( $error ) ) {
+ $zone->delete_shipping_method( $instance_id );
+ return $error;
+ }
+
+ return self::get_saved_method_response( $instance_id );
+ }
+}
diff --git a/plugins/woocommerce/src/Internal/Abilities/Domain/ShippingZoneMethodUpdate.php b/plugins/woocommerce/src/Internal/Abilities/Domain/ShippingZoneMethodUpdate.php
new file mode 100644
index 00000000000..8fc48548d43
--- /dev/null
+++ b/plugins/woocommerce/src/Internal/Abilities/Domain/ShippingZoneMethodUpdate.php
@@ -0,0 +1,114 @@
+<?php
+/**
+ * Shipping zone method update 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\ShippingZoneAbilityTrait;
+
+defined( 'ABSPATH' ) || exit;
+
+/**
+ * Changes a flat rate, free shipping or local pickup method of a zone. Extension methods are refused.
+ */
+class ShippingZoneMethodUpdate extends AbstractDomainAbility implements AbilityDefinition {
+
+ use ShippingZoneAbilityTrait;
+
+ /**
+ * Get the ability name.
+ *
+ * @return string
+ *
+ * @since 11.4.0
+ */
+ public static function get_name(): string {
+ return 'woocommerce/shipping-zone-method-update';
+ }
+
+ /**
+ * Get the ability registration arguments.
+ *
+ * @return array
+ *
+ * @since 11.4.0
+ */
+ public static function get_registration_args(): array {
+ return array(
+ 'label' => __( 'Update shipping method', 'woocommerce' ),
+ 'description' => __( 'Turn a flat rate, free shipping or local pickup method of a zone on or off, move it, or change its settings, such as the cost or the free shipping minimum. Get the instance_id from shipping-zones-query.', 'woocommerce' ),
+ 'category' => 'woocommerce',
+ 'input_schema' => array(
+ 'type' => 'object',
+ 'properties' => array_merge(
+ array(
+ 'instance_id' => array(
+ 'type' => 'integer',
+ 'minimum' => 1,
+ ),
+ ),
+ self::get_method_write_input_properties()
+ ),
+ 'required' => array( 'instance_id' ),
+ 'additionalProperties' => false,
+ ),
+ 'output_schema' => self::get_entity_output_schema( 'method', self::get_method_output_schema() ),
+ 'execute_callback' => array( __CLASS__, 'execute' ),
+ 'permission_callback' => array( __CLASS__, 'can_edit_shipping' ),
+ 'meta' => array(
+ 'show_in_rest' => true,
+ 'mcp' => array(
+ 'public' => true,
+ 'type' => 'tool',
+ ),
+ 'annotations' => array(
+ 'readonly' => false,
+ 'idempotent' => true,
+ 'destructive' => true,
+ ),
+ ),
+ );
+ }
+
+ /**
+ * Write the changes to the method.
+ *
+ * @param array $input Ability input.
+ * @return array|\WP_Error
+ *
+ * @since 11.4.0
+ */
+ public static function execute( array $input ) {
+ $disabled = self::get_shipping_disabled_error();
+ if ( null !== $disabled ) {
+ return $disabled;
+ }
+
+ $instance_id = $input['instance_id'];
+ $method = \WC_Shipping_Zones::get_shipping_method( $instance_id );
+ $zone = $method ? \WC_Shipping_Zones::get_zone_by( 'instance_id', $instance_id ) : false;
+ if ( ! $method instanceof \WC_Shipping_Method || ! $zone instanceof \WC_Shipping_Zone ) {
+ return new \WP_Error(
+ 'woocommerce_ability_shipping_method_not_found',
+ /* translators: %d: shipping method instance ID. */
+ sprintf( __( 'There is no shipping method with instance ID %d.', 'woocommerce' ), $instance_id ),
+ array( 'status' => 404 )
+ );
+ }
+
+ if ( ! self::is_core_method( $method ) ) {
+ return self::get_unsupported_method_error( $method->id );
+ }
+
+ $error = self::write_method_changes( $method, $zone, $input );
+ if ( is_wp_error( $error ) ) {
+ return $error;
+ }
+
+ return self::get_saved_method_response( $instance_id );
+ }
+}
diff --git a/plugins/woocommerce/src/Internal/Abilities/Domain/ShippingZonesQuery.php b/plugins/woocommerce/src/Internal/Abilities/Domain/ShippingZonesQuery.php
index 146aa76d572..1667258f463 100644
--- a/plugins/woocommerce/src/Internal/Abilities/Domain/ShippingZonesQuery.php
+++ b/plugins/woocommerce/src/Internal/Abilities/Domain/ShippingZonesQuery.php
@@ -8,6 +8,7 @@ declare( strict_types=1 );
namespace Automattic\WooCommerce\Internal\Abilities\Domain;
use Automattic\WooCommerce\Abilities\AbilityDefinition;
+use Automattic\WooCommerce\Internal\Abilities\Domain\Traits\ShippingZoneAbilityTrait;
defined( 'ABSPATH' ) || exit;
@@ -16,10 +17,7 @@ defined( 'ABSPATH' ) || exit;
*/
class ShippingZonesQuery extends AbstractDomainAbility implements AbilityDefinition {
- /**
- * Methods whose settings are returned. Extensions keep credentials in method settings under any name.
- */
- private const CORE_METHOD_CLASSES = array( \WC_Shipping_Flat_Rate::class, \WC_Shipping_Free_Shipping::class, \WC_Shipping_Local_Pickup::class );
+ use ShippingZoneAbilityTrait;
/**
* Get the ability name.
@@ -121,124 +119,4 @@ class ShippingZonesQuery extends AbstractDomainAbility implements AbilityDefinit
public static function can_query_shipping(): bool {
return (bool) wc_rest_check_manager_permissions( 'settings', 'read' );
}
-
- /**
- * Format a zone for ability output.
- *
- * @param \WC_Shipping_Zone $zone Zone.
- * @return array
- */
- private static function format_zone_for_response( \WC_Shipping_Zone $zone ): array {
- return array(
- 'id' => $zone->get_id(),
- 'name' => $zone->get_zone_name(),
- 'order' => $zone->get_zone_order(),
- 'locations' => array_map(
- static function ( $location ): array {
- return array(
- 'code' => (string) $location->code,
- 'type' => (string) $location->type,
- );
- },
- array_values( $zone->get_zone_locations() )
- ),
- 'methods' => array_map( array( __CLASS__, 'format_method' ), array_values( $zone->get_shipping_methods() ) ),
- );
- }
-
- /**
- * Format a shipping method of a zone. Only Core methods get settings, limited to the
- * fields Core declares, since extensions can add fields to them through filters.
- *
- * @param \WC_Shipping_Method $method Method.
- * @return array
- */
- private static function format_method( \WC_Shipping_Method $method ): array {
- $data = array(
- 'instance_id' => (int) $method->get_instance_id(),
- 'method_id' => (string) $method->id,
- 'title' => (string) $method->get_title(),
- 'enabled' => 'yes' === $method->enabled,
- 'order' => (int) $method->method_order,
- );
-
- $class = get_class( $method );
- if ( in_array( $class, self::CORE_METHOD_CLASSES, true ) ) {
- // A fresh instance, since a woocommerce_shipping_zone_shipping_methods callback can change the zone's one.
- $core = new $class( $method->get_instance_id() );
- $core->init_instance_settings();
- $settings = array();
- foreach ( array_keys( $core->instance_form_fields ) as $key ) {
- $value = $core->instance_settings[ $key ] ?? null;
- if ( 'title' !== $key && is_scalar( $value ) ) {
- $settings[ $key ] = (string) $value;
- }
- }
- $data['settings'] = (object) $settings;
- }
-
- return $data;
- }
-
- /**
- * Get the schema of a zone in a response.
- *
- * @return array
- */
- private static function get_zone_output_schema(): array {
- return array(
- 'type' => 'object',
- 'properties' => array(
- 'id' => array( 'type' => 'integer' ),
- 'name' => array( 'type' => 'string' ),
- 'order' => array( 'type' => 'integer' ),
- 'locations' => array(
- 'type' => 'array',
- 'items' => array(
- 'type' => 'object',
- 'properties' => array(
- 'code' => array(
- 'type' => 'string',
- 'description' => __( 'Country code, COUNTRY:STATE, postcode pattern or continent code, by type.', 'woocommerce' ),
- ),
- 'type' => array(
- 'type' => 'string',
- 'enum' => array( 'country', 'state', 'postcode', 'continent' ),
- ),
- ),
- 'additionalProperties' => false,
- ),
- ),
- 'methods' => array(
- 'type' => 'array',
- 'items' => self::get_method_output_schema(),
- ),
- ),
- 'additionalProperties' => false,
- );
- }
-
- /**
- * Get the schema of a shipping method in a response.
- *
- * @return array
- */
- private static function get_method_output_schema(): array {
- return array(
- 'type' => 'object',
- 'properties' => array(
- 'instance_id' => array( 'type' => 'integer' ),
- 'method_id' => array( 'type' => 'string' ),
- 'title' => array( 'type' => 'string' ),
- 'enabled' => array( 'type' => 'boolean' ),
- 'order' => array( 'type' => 'integer' ),
- 'settings' => array(
- 'type' => 'object',
- 'description' => __( 'Settings such as cost or min_amount, as stored. Only for the flat rate, free shipping and local pickup methods.', 'woocommerce' ),
- 'additionalProperties' => array( 'type' => 'string' ),
- ),
- ),
- 'additionalProperties' => false,
- );
- }
}
diff --git a/plugins/woocommerce/src/Internal/Abilities/Domain/Traits/ShippingZoneAbilityTrait.php b/plugins/woocommerce/src/Internal/Abilities/Domain/Traits/ShippingZoneAbilityTrait.php
new file mode 100644
index 00000000000..0b521d48f02
--- /dev/null
+++ b/plugins/woocommerce/src/Internal/Abilities/Domain/Traits/ShippingZoneAbilityTrait.php
@@ -0,0 +1,365 @@
+<?php
+/**
+ * Shipping zone ability trait file.
+ */
+
+declare( strict_types=1 );
+
+namespace Automattic\WooCommerce\Internal\Abilities\Domain\Traits;
+
+use Automattic\WooCommerce\Internal\RestApi\Routes\V4\ShippingZoneMethod\ShippingZoneMethodService;
+
+defined( 'ABSPATH' ) || exit;
+
+/**
+ * Formats zones and methods for the shipping abilities, and writes method changes.
+ */
+trait ShippingZoneAbilityTrait {
+
+ /**
+ * Settings that the write abilities accept, keyed by method ID. Each list is a subset of the method's instance form fields.
+ *
+ * @var array<string, string[]>
+ */
+ private static array $writable_method_settings = array(
+ 'flat_rate' => array( 'title', 'tax_status', 'cost' ),
+ 'free_shipping' => array( 'title', 'requires', 'min_amount', 'ignore_discounts' ),
+ 'local_pickup' => array( 'title', 'tax_status', 'cost' ),
+ );
+
+ /**
+ * Whether the method is one of Core's own. Extensions keep credentials in method settings under any name, so only these get settings.
+ *
+ * @param \WC_Shipping_Method $method Method.
+ * @return bool
+ */
+ private static function is_core_method( \WC_Shipping_Method $method ): bool {
+ return in_array( get_class( $method ), array( \WC_Shipping_Flat_Rate::class, \WC_Shipping_Free_Shipping::class, \WC_Shipping_Local_Pickup::class ), true );
+ }
+
+ /**
+ * Check shipping settings edit access.
+ *
+ * @return bool
+ *
+ * @since 11.4.0
+ */
+ public static function can_edit_shipping(): bool {
+ return (bool) wc_rest_check_manager_permissions( 'settings', 'edit' );
+ }
+
+ /**
+ * Get the error for a write while shipping is turned off, when checkout would offer none of what it saves.
+ *
+ * @return \WP_Error|null
+ */
+ private static function get_shipping_disabled_error(): ?\WP_Error {
+ if ( wc_shipping_enabled() ) {
+ return null;
+ }
+
+ return new \WP_Error(
+ 'woocommerce_ability_shipping_disabled',
+ __( 'Shipping is turned off, so checkout would offer no shipping method. Turn it on under WooCommerce > Settings > General > Shipping location(s) first.', 'woocommerce' ),
+ array( 'status' => 400 )
+ );
+ }
+
+ /**
+ * Format a zone for ability output.
+ *
+ * @param \WC_Shipping_Zone $zone Zone.
+ * @return array
+ */
+ private static function format_zone_for_response( \WC_Shipping_Zone $zone ): array {
+ return array(
+ 'id' => $zone->get_id(),
+ 'name' => $zone->get_zone_name(),
+ 'order' => $zone->get_zone_order(),
+ 'locations' => array_map(
+ static function ( $location ): array {
+ return array(
+ 'code' => (string) $location->code,
+ 'type' => (string) $location->type,
+ );
+ },
+ array_values( $zone->get_zone_locations() )
+ ),
+ 'methods' => array_map( static fn( \WC_Shipping_Method $method ): array => self::format_method( $method ), array_values( $zone->get_shipping_methods() ) ),
+ );
+ }
+
+ /**
+ * Format a shipping method of a zone. Only Core methods get settings, limited to the
+ * fields Core declares, since extensions can add fields to them through filters.
+ *
+ * @param \WC_Shipping_Method $method Method.
+ * @return array
+ */
+ private static function format_method( \WC_Shipping_Method $method ): array {
+ $data = array(
+ 'instance_id' => (int) $method->get_instance_id(),
+ 'method_id' => (string) $method->id,
+ 'title' => (string) $method->get_title(),
+ 'enabled' => 'yes' === $method->enabled,
+ 'order' => (int) $method->method_order,
+ );
+
+ if ( self::is_core_method( $method ) ) {
+ $class = get_class( $method );
+ // A fresh instance, since a woocommerce_shipping_zone_shipping_methods callback can change the zone's one.
+ $core = new $class( $method->get_instance_id() );
+ $core->init_instance_settings();
+ $settings = array();
+ foreach ( array_keys( $core->instance_form_fields ) as $key ) {
+ $value = $core->instance_settings[ $key ] ?? null;
+ if ( 'title' !== $key && is_scalar( $value ) ) {
+ $settings[ $key ] = (string) $value;
+ }
+ }
+ $data['settings'] = (object) $settings;
+ }
+
+ return $data;
+ }
+
+ /**
+ * Read the method back after a write, so the response shows what was stored.
+ *
+ * @param int $instance_id Method instance ID.
+ * @return array|\WP_Error
+ */
+ private static function get_saved_method_response( int $instance_id ) {
+ $method = \WC_Shipping_Zones::get_shipping_method( $instance_id );
+ if ( ! $method instanceof \WC_Shipping_Method ) {
+ return new \WP_Error( 'woocommerce_ability_shipping_method_not_found', __( 'The shipping method was saved but could not be read back.', 'woocommerce' ), array( 'status' => 500 ) );
+ }
+
+ return array( 'method' => self::format_method( $method ) );
+ }
+
+ /**
+ * Write the enabled state, order and settings of a Core method, the way the shipping settings screen saves them.
+ *
+ * @param \WC_Shipping_Method $method Method of the zone.
+ * @param \WC_Shipping_Zone $zone Zone of the method.
+ * @param array $input Ability input with optional `enabled`, `order` and `settings`.
+ * @return null|\WP_Error
+ */
+ private static function write_method_changes( \WC_Shipping_Method $method, \WC_Shipping_Zone $zone, array $input ): ?\WP_Error {
+ $data = array_intersect_key( $input, array_flip( array( 'enabled', 'order' ) ) );
+
+ if ( isset( $input['settings'] ) ) {
+ $settings = self::prepare_method_settings( $method, $input['settings'] );
+ if ( is_wp_error( $settings ) ) {
+ return $settings;
+ }
+ // The setting validators unslash, as they expect the slashed form data of the settings screen.
+ $data['settings'] = wp_slash( $settings );
+ }
+
+ if ( empty( $data ) ) {
+ return null;
+ }
+
+ $result = wc_get_container()->get( ShippingZoneMethodService::class )->update_shipping_zone_method( $method, $method->get_instance_id(), $data, $zone->get_id() );
+
+ // The service bumps the cache version only when the enabled state or order changes, and not when that fails after the settings were saved.
+ \WC_Cache_Helper::get_transient_version( 'shipping', true );
+
+ if ( is_wp_error( $result ) ) {
+ $code = 'woocommerce_rest_shipping_method_invalid_setting' === $result->get_error_code() ? 'woocommerce_ability_shipping_method_setting_invalid' : 'woocommerce_ability_shipping_method_update_failed';
+ return new \WP_Error( $code, $result->get_error_message(), array( 'status' => 'woocommerce_ability_shipping_method_setting_invalid' === $code ? 400 : 500 ) );
+ }
+
+ return null;
+ }
+
+ /**
+ * Check the settings against the method, and convert them to the values its settings form posts.
+ *
+ * @param \WC_Shipping_Method $method Method.
+ * @param array $settings Settings input.
+ * @return array|\WP_Error
+ */
+ private static function prepare_method_settings( \WC_Shipping_Method $method, array $settings ) {
+ $writable = self::$writable_method_settings[ $method->id ] ?? array();
+ $unknown = array_diff( array_keys( $settings ), $writable );
+ if ( ! empty( $unknown ) ) {
+ return new \WP_Error(
+ 'woocommerce_ability_shipping_method_setting_unknown',
+ /* translators: 1: setting names, 2: shipping method ID, 3: setting names the method accepts. */
+ sprintf( __( 'The %2$s method has no setting %1$s. It accepts: %3$s.', 'woocommerce' ), implode( ', ', $unknown ), $method->id, implode( ', ', $writable ) ),
+ array( 'status' => 400 )
+ );
+ }
+
+ // The price validator turns text without digits into an empty minimum, which every cart meets.
+ if ( isset( $settings['min_amount'] ) ) {
+ $min_amount = wc_format_decimal( $settings['min_amount'] );
+ if ( ! is_numeric( $min_amount ) || (float) $min_amount < 0 ) {
+ return new \WP_Error( 'woocommerce_ability_shipping_method_setting_invalid', __( 'The minimum order amount must be a number of 0 or more.', 'woocommerce' ), array( 'status' => 400 ) );
+ }
+ }
+
+ // Free shipping ignores the minimum unless it is required, and an agent that sets one means it to apply.
+ if ( 'free_shipping' === $method->id && isset( $settings['min_amount'] ) && ! isset( $settings['requires'] ) && '' === (string) $method->get_option( 'requires' ) ) {
+ $settings['requires'] = 'min_amount';
+ }
+
+ // The checkbox validator reads any posted value as checked, and a missing one as unchecked.
+ if ( array_key_exists( 'ignore_discounts', $settings ) ) {
+ $settings['ignore_discounts'] = $settings['ignore_discounts'] ? 'yes' : null;
+ }
+
+ return $settings;
+ }
+
+ /**
+ * Get the zone, or an error when there is none with that ID.
+ *
+ * @param int $zone_id Zone ID. Zero is the zone for locations no other zone covers.
+ * @return \WC_Shipping_Zone|\WP_Error
+ */
+ private static function get_zone_or_error( int $zone_id ) {
+ $zone = \WC_Shipping_Zones::get_zone( $zone_id );
+ if ( ! $zone instanceof \WC_Shipping_Zone || ( 0 !== $zone->get_id() && '' === $zone->get_zone_name() ) ) {
+ return new \WP_Error(
+ 'woocommerce_ability_shipping_zone_not_found',
+ /* translators: %d: shipping zone ID. */
+ sprintf( __( 'There is no shipping zone with ID %d.', 'woocommerce' ), $zone_id ),
+ array( 'status' => 404 )
+ );
+ }
+
+ return $zone;
+ }
+
+ /**
+ * Get the error for a method that the write abilities do not change.
+ *
+ * @param string $method_id Shipping method ID.
+ * @return \WP_Error
+ */
+ private static function get_unsupported_method_error( string $method_id ): \WP_Error {
+ return new \WP_Error(
+ 'woocommerce_ability_shipping_method_unsupported',
+ /* translators: %s: shipping method ID. */
+ sprintf( __( 'The %s method is not supported. Only the flat rate, free shipping and local pickup methods can be added or changed here.', 'woocommerce' ), $method_id ),
+ array( 'status' => 400 )
+ );
+ }
+
+ /**
+ * Get the input schema of the method writes.
+ *
+ * @return array
+ */
+ private static function get_method_write_input_properties(): array {
+ return array(
+ 'enabled' => array(
+ 'type' => 'boolean',
+ 'description' => __( 'Whether customers can choose the method at checkout.', 'woocommerce' ),
+ ),
+ 'order' => array(
+ 'type' => 'integer',
+ 'description' => __( 'Position of the method in its zone. Lower comes first.', 'woocommerce' ),
+ 'minimum' => 0,
+ ),
+ 'settings' => array(
+ 'type' => 'object',
+ 'description' => __( 'Settings to change. Flat rate and local pickup take title, tax_status and cost. Free shipping takes title, requires, min_amount and ignore_discounts.', 'woocommerce' ),
+ 'properties' => array(
+ 'title' => array(
+ 'type' => 'string',
+ 'description' => __( 'Name customers see at checkout.', 'woocommerce' ),
+ ),
+ 'tax_status' => array(
+ 'type' => 'string',
+ 'enum' => array( 'taxable', 'none' ),
+ ),
+ 'cost' => array(
+ 'type' => 'string',
+ 'description' => __( 'Cost before tax, such as "5" or a formula like "10 + [qty] * 2". [qty] is the number of items, [cost] the order cost, and [fee percent="10" min_fee="2"] a percentage fee.', 'woocommerce' ),
+ ),
+ 'requires' => array(
+ 'type' => 'string',
+ 'description' => __( 'What earns free shipping: nothing, a free shipping coupon, the minimum amount, either one, or both. Sending min_amount alone on a method with no requirement sets this to min_amount.', 'woocommerce' ),
+ 'enum' => array( '', 'coupon', 'min_amount', 'either', 'both' ),
+ ),
+ 'min_amount' => array(
+ 'type' => 'string',
+ 'description' => __( 'Order amount that earns free shipping, as a decimal string without a currency symbol.', 'woocommerce' ),
+ ),
+ 'ignore_discounts' => array(
+ 'type' => 'boolean',
+ 'description' => __( 'Whether the minimum applies to the order amount before coupon discounts.', 'woocommerce' ),
+ ),
+ ),
+ 'additionalProperties' => false,
+ ),
+ );
+ }
+
+ /**
+ * Get the schema of a zone in a response.
+ *
+ * @return array
+ */
+ private static function get_zone_output_schema(): array {
+ return array(
+ 'type' => 'object',
+ 'properties' => array(
+ 'id' => array( 'type' => 'integer' ),
+ 'name' => array( 'type' => 'string' ),
+ 'order' => array( 'type' => 'integer' ),
+ 'locations' => array(
+ 'type' => 'array',
+ 'items' => array(
+ 'type' => 'object',
+ 'properties' => array(
+ 'code' => array(
+ 'type' => 'string',
+ 'description' => __( 'Country code, COUNTRY:STATE, postcode pattern or continent code, by type.', 'woocommerce' ),
+ ),
+ 'type' => array(
+ 'type' => 'string',
+ 'enum' => array( 'country', 'state', 'postcode', 'continent' ),
+ ),
+ ),
+ 'additionalProperties' => false,
+ ),
+ ),
+ 'methods' => array(
+ 'type' => 'array',
+ 'items' => self::get_method_output_schema(),
+ ),
+ ),
+ 'additionalProperties' => false,
+ );
+ }
+
+ /**
+ * Get the schema of a shipping method in a response.
+ *
+ * @return array
+ */
+ private static function get_method_output_schema(): array {
+ return array(
+ 'type' => 'object',
+ 'properties' => array(
+ 'instance_id' => array( 'type' => 'integer' ),
+ 'method_id' => array( 'type' => 'string' ),
+ 'title' => array( 'type' => 'string' ),
+ 'enabled' => array( 'type' => 'boolean' ),
+ 'order' => array( 'type' => 'integer' ),
+ 'settings' => array(
+ 'type' => 'object',
+ 'description' => __( 'Settings such as cost or min_amount, as stored. Only for the flat rate, free shipping and local pickup methods.', 'woocommerce' ),
+ 'additionalProperties' => array( 'type' => 'string' ),
+ ),
+ ),
+ 'additionalProperties' => false,
+ );
+ }
+}
diff --git a/plugins/woocommerce/tests/php/src/Internal/Abilities/AbilitiesLoaderTest.php b/plugins/woocommerce/tests/php/src/Internal/Abilities/AbilitiesLoaderTest.php
index 4e507baa82c..2c74ae07767 100644
--- a/plugins/woocommerce/tests/php/src/Internal/Abilities/AbilitiesLoaderTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/Abilities/AbilitiesLoaderTest.php
@@ -57,6 +57,9 @@ class AbilitiesLoaderTest extends \WC_Unit_Test_Case {
'woocommerce/product-review-reply',
'woocommerce/product-reviews-query',
'woocommerce/shipping-zones-query',
+ 'woocommerce/shipping-zone-create',
+ 'woocommerce/shipping-zone-method-create',
+ 'woocommerce/shipping-zone-method-update',
'woocommerce/tax-rates-query',
'woocommerce/system-status-tools-query',
'woocommerce/system-status-tool-run',
@@ -253,136 +256,151 @@ class AbilitiesLoaderTest extends \WC_Unit_Test_Case {
*/
public function test_canonical_ability_annotations_match_intent(): void {
$expectations = array(
- 'woocommerce/products-query' => array(
+ 'woocommerce/products-query' => array(
'readonly' => true,
'idempotent' => true,
'destructive' => false,
),
- 'woocommerce/product-reviews-query' => array(
+ 'woocommerce/product-reviews-query' => array(
'readonly' => true,
'idempotent' => true,
'destructive' => false,
),
- 'woocommerce/shipping-zones-query' => array(
+ 'woocommerce/shipping-zones-query' => array(
'readonly' => true,
'idempotent' => true,
'destructive' => false,
),
- 'woocommerce/tax-rates-query' => array(
+ 'woocommerce/tax-rates-query' => array(
'readonly' => true,
'idempotent' => true,
'destructive' => false,
),
- 'woocommerce/product-attributes-query' => array(
+ 'woocommerce/product-attributes-query' => array(
'readonly' => true,
'idempotent' => true,
'destructive' => false,
),
- 'woocommerce/product-attribute-create' => array(
+ 'woocommerce/product-attribute-create' => array(
'readonly' => false,
'idempotent' => false,
'destructive' => false,
),
- 'woocommerce/product-term-create' => array(
+ 'woocommerce/product-term-create' => array(
'readonly' => false,
'idempotent' => false,
'destructive' => false,
),
- 'woocommerce/product-term-update' => array(
+ 'woocommerce/product-term-update' => array(
'readonly' => false,
'idempotent' => false,
'destructive' => true,
),
- 'woocommerce/product-create' => array(
+ 'woocommerce/product-create' => array(
'readonly' => false,
'idempotent' => false,
'destructive' => false,
),
- 'woocommerce/product-update' => array(
+ 'woocommerce/product-update' => array(
'readonly' => false,
'idempotent' => false,
'destructive' => true,
),
- 'woocommerce/product-delete' => array(
+ 'woocommerce/product-delete' => array(
'readonly' => false,
'idempotent' => true,
'destructive' => true,
),
- 'woocommerce/orders-query' => array(
+ 'woocommerce/orders-query' => array(
'readonly' => true,
'idempotent' => true,
'destructive' => false,
),
- 'woocommerce/order-send-email' => array(
+ 'woocommerce/order-send-email' => array(
'readonly' => false,
'idempotent' => false,
'destructive' => false,
),
- 'woocommerce/order-create' => array(
+ 'woocommerce/order-create' => array(
'readonly' => false,
'idempotent' => false,
'destructive' => false,
),
- 'woocommerce/order-delete' => array(
+ 'woocommerce/order-delete' => array(
'readonly' => false,
'idempotent' => true,
'destructive' => true,
),
- 'woocommerce/order-update' => array(
+ 'woocommerce/order-update' => array(
'readonly' => false,
'idempotent' => false,
'destructive' => true,
),
- 'woocommerce/order-update-status' => array(
+ 'woocommerce/order-update-status' => array(
'readonly' => false,
'idempotent' => false,
'destructive' => true,
),
- 'woocommerce/order-add-note' => array(
+ 'woocommerce/order-add-note' => array(
'readonly' => false,
'idempotent' => false,
'destructive' => false,
),
- 'woocommerce/order-notes-query' => array(
+ 'woocommerce/order-notes-query' => array(
'readonly' => true,
'idempotent' => true,
'destructive' => false,
),
- 'woocommerce/payment-gateways-query' => array(
+ 'woocommerce/payment-gateways-query' => array(
'readonly' => true,
'idempotent' => true,
'destructive' => false,
),
- 'woocommerce/customers-query' => array(
+ 'woocommerce/customers-query' => array(
'readonly' => true,
'idempotent' => true,
'destructive' => false,
),
- 'woocommerce/product-review-update' => array(
+ 'woocommerce/product-review-update' => array(
'readonly' => false,
'idempotent' => false,
'destructive' => true,
),
- 'woocommerce/product-review-reply' => array(
+ 'woocommerce/product-review-reply' => array(
'readonly' => false,
'idempotent' => false,
'destructive' => false,
),
- 'woocommerce/system-status-tools-query' => array(
+ 'woocommerce/system-status-tools-query' => array(
'readonly' => true,
'idempotent' => true,
'destructive' => false,
),
- 'woocommerce/system-status-tool-run' => array(
+ 'woocommerce/system-status-tool-run' => array(
'readonly' => false,
'idempotent' => true,
'destructive' => false,
),
- 'woocommerce/payment-gateway-update' => array(
+ 'woocommerce/payment-gateway-update' => array(
'readonly' => false,
'idempotent' => true,
'destructive' => false,
),
+ 'woocommerce/shipping-zone-create' => array(
+ 'readonly' => false,
+ 'idempotent' => false,
+ 'destructive' => false,
+ ),
+ 'woocommerce/shipping-zone-method-create' => array(
+ 'readonly' => false,
+ 'idempotent' => false,
+ 'destructive' => false,
+ ),
+ 'woocommerce/shipping-zone-method-update' => array(
+ 'readonly' => false,
+ 'idempotent' => true,
+ 'destructive' => true,
+ ),
);
foreach ( $expectations as $ability_id => $annotations ) {
@@ -1017,20 +1035,20 @@ 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(
- 'product-terms-query' => array(
+ 'product-terms-query' => array(
'woocommerce/product-terms-query',
array(
'taxonomy' => 'product_cat',
),
),
- 'product-term-create' => array(
+ 'product-term-create' => array(
'woocommerce/product-term-create',
array(
'taxonomy' => 'product_cat',
'name' => 'Forbidden',
),
),
- 'product-term-update' => array(
+ 'product-term-update' => array(
'woocommerce/product-term-update',
array(
'taxonomy' => 'product_cat',
@@ -1038,134 +1056,160 @@ class AbilitiesLoaderTest extends \WC_Unit_Test_Case {
'name' => 'Forbidden',
),
),
- 'product-attributes-query' => array(
+ 'product-attributes-query' => array(
'woocommerce/product-attributes-query',
array(),
),
- 'product-attribute-create' => array(
+ 'product-attribute-create' => array(
'woocommerce/product-attribute-create',
array(
'name' => 'Forbidden',
),
),
- 'products-query' => array(
+ 'products-query' => array(
'woocommerce/products-query',
array(
'id' => 1,
),
),
- 'product-create' => array(
+ 'product-create' => array(
'woocommerce/product-create',
array(
'name' => 'Forbidden',
),
),
- 'product-update' => array(
+ 'product-update' => array(
'woocommerce/product-update',
array(
'id' => 1,
'name' => 'Forbidden',
),
),
- 'product-delete' => array(
+ 'product-delete' => array(
'woocommerce/product-delete',
array(
'id' => 1,
),
),
- 'orders-query' => array(
+ 'orders-query' => array(
'woocommerce/orders-query',
array(
'id' => 1,
),
),
- 'order-send-email' => array(
+ 'order-send-email' => array(
'woocommerce/order-send-email',
array(
'id' => 1,
'email' => 'invoice',
),
),
- 'order-create' => array(
+ 'order-create' => array(
'woocommerce/order-create',
array( 'line_items' => array( array( 'product_id' => 1 ) ) ),
),
- 'order-delete' => array(
+ 'order-delete' => array(
'woocommerce/order-delete',
array(
'id' => 1,
),
),
- 'order-update' => array(
+ 'order-update' => array(
'woocommerce/order-update',
array(
'id' => 1,
'shipping' => array( 'city' => 'Denied' ),
),
),
- 'order-update-status' => array(
+ 'order-update-status' => array(
'woocommerce/order-update-status',
array(
'id' => 1,
'status' => 'processing',
),
),
- 'product-review-update' => array(
+ 'product-review-update' => array(
'woocommerce/product-review-update',
array(
'id' => 1,
'status' => 'approved',
),
),
- 'product-review-reply' => array(
+ 'product-review-reply' => array(
'woocommerce/product-review-reply',
array(
'id' => 1,
'content' => 'denied',
),
),
- 'order-add-note' => array(
+ 'order-add-note' => array(
'woocommerce/order-add-note',
array(
'id' => 1,
'note' => 'denied',
),
),
- 'order-notes-query' => array(
+ 'order-notes-query' => array(
'woocommerce/order-notes-query',
array(
'id' => 1,
),
),
- 'payment-gateways-query' => array(
+ 'payment-gateways-query' => array(
'woocommerce/payment-gateways-query',
array(),
),
- 'customers-query' => array(
+ 'customers-query' => array(
'woocommerce/customers-query',
array(),
),
- 'product-reviews-query' => array(
+ 'product-reviews-query' => array(
'woocommerce/product-reviews-query',
array(),
),
- 'shipping-zones-query' => array(
+ 'shipping-zones-query' => array(
'woocommerce/shipping-zones-query',
array(),
),
- 'tax-rates-query' => array(
+ 'shipping-zone-create' => array(
+ 'woocommerce/shipping-zone-create',
+ array(
+ 'name' => 'Germany',
+ 'locations' => array(
+ array(
+ 'code' => 'DE',
+ 'type' => 'country',
+ ),
+ ),
+ ),
+ ),
+ 'shipping-zone-method-create' => array(
+ 'woocommerce/shipping-zone-method-create',
+ array(
+ 'zone_id' => 0,
+ 'method_id' => 'flat_rate',
+ ),
+ ),
+ 'shipping-zone-method-update' => array(
+ 'woocommerce/shipping-zone-method-update',
+ array(
+ 'instance_id' => 1,
+ 'enabled' => false,
+ ),
+ ),
+ 'tax-rates-query' => array(
'woocommerce/tax-rates-query',
array(),
),
- 'status-tools-query' => array(
+ 'status-tools-query' => array(
'woocommerce/system-status-tools-query',
array(),
),
- 'status-tool-run' => array(
+ 'status-tool-run' => array(
'woocommerce/system-status-tool-run',
array( 'id' => 'recount_terms' ),
),
- 'payment-gateway-update' => array(
+ 'payment-gateway-update' => array(
'woocommerce/payment-gateway-update',
array(
'id' => 'bacs',
@@ -1213,6 +1257,13 @@ class AbilitiesLoaderTest extends \WC_Unit_Test_Case {
),
'customers-query' => array( 'woocommerce/customers-query', array() ),
'shipping-zones-query' => array( 'woocommerce/shipping-zones-query', array() ),
+ 'shipping-zone-method-update' => array(
+ 'woocommerce/shipping-zone-method-update',
+ array(
+ 'instance_id' => 1,
+ 'enabled' => false,
+ ),
+ ),
'tax-rates-query' => array( 'woocommerce/tax-rates-query', array() ),
'product-attributes-query' => array( 'woocommerce/product-attributes-query', array() ),
'product-attribute-create' => array( 'woocommerce/product-attribute-create', array( 'name' => 'Size' ) ),
diff --git a/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/ShippingWritesTest.php b/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/ShippingWritesTest.php
new file mode 100644
index 00000000000..40a2b111e64
--- /dev/null
+++ b/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/ShippingWritesTest.php
@@ -0,0 +1,593 @@
+<?php
+/**
+ * ShippingWritesTest class file.
+ */
+
+declare( strict_types=1 );
+
+namespace Automattic\WooCommerce\Tests\Internal\Abilities\Domain;
+
+use Automattic\WooCommerce\Internal\Abilities\AbilitiesLoader;
+
+/**
+ * Tests for the shipping-zone-create, shipping-zone-method-create and shipping-zone-method-update abilities.
+ */
+class ShippingWritesTest extends \WC_Unit_Test_Case {
+
+ private const GERMANY = array(
+ array(
+ 'code' => 'DE',
+ 'type' => 'country',
+ ),
+ );
+
+ /**
+ * Administrator used as the current user.
+ *
+ * @var int
+ */
+ private static $administrator_id;
+
+ /**
+ * Init action count restored in tearDown.
+ *
+ * @var int|null
+ */
+ private $original_init_count;
+
+ /**
+ * Create the administrator once for the class.
+ *
+ * @param \WP_UnitTest_Factory $factory WordPress unit test factory.
+ */
+ public static function wpSetUpBeforeClass( $factory ): void {
+ self::$administrator_id = $factory->user->create( array( 'role' => 'administrator' ) );
+ }
+
+ /**
+ * Start each test from an empty abilities registry, so the abilities register again.
+ */
+ public function setUp(): void {
+ global $wp_actions;
+
+ if ( ! function_exists( 'wp_register_ability' ) ) {
+ require_once WC_ABSPATH . 'vendor/wordpress/abilities-api/includes/bootstrap.php';
+ }
+
+ // The Abilities API registry refuses to initialize before `init` has fired.
+ $this->original_init_count = $wp_actions['init'] ?? null;
+ $wp_actions['init'] = max( 1, (int) ( $wp_actions['init'] ?? 0 ) ); // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
+
+ parent::setUp();
+
+ wc_get_container()->get( AbilitiesLoader::class )->init();
+ self::reset_registries();
+ wp_set_current_user( self::$administrator_id );
+ }
+
+ /**
+ * Leave the registries and the init count as the next test expects them.
+ */
+ public function tearDown(): void {
+ global $wp_actions;
+
+ try {
+ self::reset_registries();
+ } finally {
+ parent::tearDown();
+ }
+
+ if ( null !== $this->original_init_count ) {
+ $wp_actions['init'] = $this->original_init_count; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
+ } else {
+ unset( $wp_actions['init'] ); // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
+ }
+ }
+
+ /**
+ * Run an ability as the current user, with its permission check.
+ *
+ * @param string $name Ability name.
+ * @param array $input Ability input.
+ * @return mixed|\WP_Error
+ */
+ private function run_ability( string $name, array $input = array() ) {
+ $ability = wp_get_ability( $name );
+ $this->assertNotNull( $ability, "Ability {$name} should be registered." );
+
+ return $ability->execute( $input );
+ }
+
+ /**
+ * Drop every registered ability, so the next read registers them again.
+ */
+ private static function reset_registries(): void {
+ global $wp_actions;
+
+ foreach ( array( 'WP_Abilities_Registry', 'WP_Ability_Categories_Registry' ) as $registry ) {
+ if ( class_exists( $registry ) ) {
+ $instance = new \ReflectionProperty( $registry, 'instance' );
+ $instance->setAccessible( true );
+ $instance->setValue( null, null );
+ }
+ }
+ unset( $wp_actions['wp_abilities_api_init'], $wp_actions['wp_abilities_api_categories_init'] );
+ }
+
+ /**
+ * Create a zone for Germany through the ability.
+ *
+ * @return int Zone ID.
+ */
+ private function create_germany_zone(): int {
+ $result = $this->run_ability(
+ 'woocommerce/shipping-zone-create',
+ array(
+ 'name' => 'Germany',
+ 'locations' => array(
+ array(
+ 'code' => 'DE',
+ 'type' => 'country',
+ ),
+ ),
+ )
+ );
+ $this->assertNotWPError( $result );
+
+ return $result['zone']['id'];
+ }
+
+ /**
+ * Put one product at the price in a fresh cart shipping to Germany, and return the offered rates.
+ *
+ * @param float $price Product price.
+ * @return array<string, string> Cost by method ID.
+ */
+ private function rates_for_cart_of( float $price ): array {
+ WC()->cart->empty_cart();
+ WC()->customer->set_shipping_country( 'DE' );
+ WC()->customer->set_billing_country( 'DE' );
+
+ $product = new \WC_Product_Simple();
+ $product->set_regular_price( (string) $price );
+ $product->save();
+ $this->assertNotFalse( WC()->cart->add_to_cart( $product->get_id(), 1 ), 'The fixture product should reach the cart.' );
+ WC()->cart->calculate_totals();
+
+ $rates = array();
+ foreach ( WC()->shipping()->get_packages()[0]['rates'] ?? array() as $rate ) {
+ $rates[ $rate->get_method_id() ] = $rate->get_cost();
+ }
+ ksort( $rates );
+
+ return $rates;
+ }
+
+ /**
+ * @testdox Should let an agent set up a zone with a flat rate and free shipping over a minimum.
+ */
+ public function test_sets_up_a_zone_with_flat_rate_and_free_shipping_over_a_minimum(): void {
+ $zone_id = $this->create_germany_zone();
+
+ $flat_rate = $this->run_ability(
+ 'woocommerce/shipping-zone-method-create',
+ array(
+ 'zone_id' => $zone_id,
+ 'method_id' => 'flat_rate',
+ 'settings' => array( 'cost' => '5' ),
+ )
+ );
+ $free = $this->run_ability(
+ 'woocommerce/shipping-zone-method-create',
+ array(
+ 'zone_id' => $zone_id,
+ 'method_id' => 'free_shipping',
+ 'settings' => array( 'min_amount' => '50' ),
+ )
+ );
+
+ $this->assertNotWPError( $flat_rate );
+ $this->assertNotWPError( $free );
+ $this->assertSame( 'min_amount', ( (array) $free['method']['settings'] )['requires'], 'A minimum sent alone should become the free shipping requirement.' );
+ $this->assertSame( array( 'flat_rate' => '5' ), $this->rates_for_cart_of( 40 ), 'Below the minimum only the flat rate applies.' );
+ $this->assertSame(
+ array(
+ 'flat_rate' => '5',
+ 'free_shipping' => '0',
+ ),
+ $this->rates_for_cart_of( 60 ),
+ 'Above the minimum free shipping is offered too.'
+ );
+
+ $zones = $this->run_ability( 'woocommerce/shipping-zones-query', array( 'include' => array( $zone_id ) ) );
+ $this->assertSame( array( 'flat_rate', 'free_shipping' ), array_column( $zones['zones'][0]['methods'], 'method_id' ) );
+ }
+
+ /**
+ * @testdox Should charge the new cost in a cart whose rates were already calculated.
+ */
+ public function test_cost_change_reaches_a_cart_with_calculated_rates(): void {
+ $zone_id = $this->create_germany_zone();
+ $created = $this->run_ability(
+ 'woocommerce/shipping-zone-method-create',
+ array(
+ 'zone_id' => $zone_id,
+ 'method_id' => 'flat_rate',
+ 'settings' => array( 'cost' => '5' ),
+ )
+ );
+ $this->assertSame( array( 'flat_rate' => '5' ), $this->rates_for_cart_of( 40 ) );
+
+ $updated = $this->run_ability(
+ 'woocommerce/shipping-zone-method-update',
+ array(
+ 'instance_id' => $created['method']['instance_id'],
+ 'settings' => array( 'cost' => '10 + [qty] * 2' ),
+ )
+ );
+
+ $this->assertNotWPError( $updated );
+ $this->assertSame( '10 + [qty] * 2', ( (array) $updated['method']['settings'] )['cost'] );
+ WC()->cart->calculate_totals();
+ $this->assertSame( '12', WC()->shipping()->get_packages()[0]['rates'][ 'flat_rate:' . $created['method']['instance_id'] ]->get_cost() );
+ }
+
+ /**
+ * @testdox Should refresh cart rates when the settings are saved but the enabled state is not.
+ */
+ public function test_saved_settings_reach_the_cart_when_the_rest_of_the_write_fails(): void {
+ global $wpdb;
+
+ $zone_id = $this->create_germany_zone();
+ $created = $this->run_ability(
+ 'woocommerce/shipping-zone-method-create',
+ array(
+ 'zone_id' => $zone_id,
+ 'method_id' => 'flat_rate',
+ 'settings' => array( 'cost' => '5' ),
+ )
+ );
+ $this->rates_for_cart_of( 40 );
+
+ $break_method_update = static function ( string $query ) use ( $wpdb ): string {
+ return 0 === strpos( $query, "UPDATE `{$wpdb->prefix}woocommerce_shipping_zone_methods`" ) ? 'UPDATE no_such_table SET x = 1' : $query;
+ };
+ add_filter( 'query', $break_method_update );
+ $suppress = $wpdb->suppress_errors( true );
+ $updated = $this->run_ability(
+ 'woocommerce/shipping-zone-method-update',
+ array(
+ 'instance_id' => $created['method']['instance_id'],
+ 'enabled' => true,
+ 'settings' => array( 'cost' => '7' ),
+ )
+ );
+ $wpdb->suppress_errors( $suppress );
+ remove_filter( 'query', $break_method_update );
+
+ $this->assertWPError( $updated );
+ $this->assertSame( 'woocommerce_ability_shipping_method_update_failed', $updated->get_error_code() );
+ WC()->cart->calculate_totals();
+ $this->assertSame( '7', WC()->shipping()->get_packages()[0]['rates'][ 'flat_rate:' . $created['method']['instance_id'] ]->get_cost() );
+ }
+
+ /**
+ * @testdox Should keep the free shipping requirement already stored when only the minimum changes.
+ */
+ public function test_minimum_keeps_a_stored_requirement(): void {
+ $created = $this->run_ability(
+ 'woocommerce/shipping-zone-method-create',
+ array(
+ 'zone_id' => 0,
+ 'method_id' => 'free_shipping',
+ 'settings' => array( 'requires' => 'coupon' ),
+ )
+ );
+
+ $updated = $this->run_ability(
+ 'woocommerce/shipping-zone-method-update',
+ array(
+ 'instance_id' => $created['method']['instance_id'],
+ 'settings' => array( 'min_amount' => '75' ),
+ )
+ );
+
+ $settings = (array) $updated['method']['settings'];
+ $this->assertSame( 'coupon', $settings['requires'] );
+ $this->assertSame( '75', $settings['min_amount'] );
+ }
+
+ /**
+ * @testdox Should store free text as sent and the coupon rule checkbox as yes or no.
+ */
+ public function test_writes_text_and_checkbox_settings(): void {
+ $created = $this->run_ability(
+ 'woocommerce/shipping-zone-method-create',
+ array(
+ 'zone_id' => 0,
+ 'method_id' => 'free_shipping',
+ 'settings' => array(
+ 'title' => 'Free \\ fast',
+ 'ignore_discounts' => true,
+ ),
+ )
+ );
+ $this->assertSame( 'Free \\ fast', $created['method']['title'] );
+ $this->assertSame( 'yes', ( (array) $created['method']['settings'] )['ignore_discounts'] );
+
+ $updated = $this->run_ability(
+ 'woocommerce/shipping-zone-method-update',
+ array(
+ 'instance_id' => $created['method']['instance_id'],
+ 'enabled' => false,
+ 'settings' => array( 'ignore_discounts' => false ),
+ )
+ );
+
+ $this->assertFalse( $updated['method']['enabled'] );
+ $this->assertSame( 'no', ( (array) $updated['method']['settings'] )['ignore_discounts'] );
+ }
+
+ /**
+ * @testdox Should refuse settings the method rejects, and leave no method behind.
+ * @testWith ["flat_rate", {"min_amount": "50"}, "woocommerce_ability_shipping_method_setting_unknown"]
+ * ["flat_rate", {"cost": "10 +"}, "woocommerce_ability_shipping_method_setting_invalid"]
+ * ["free_shipping", {"min_amount": "-5"}, "woocommerce_ability_shipping_method_setting_invalid"]
+ * ["free_shipping", {"min_amount": ","}, "woocommerce_ability_shipping_method_setting_invalid"]
+ * ["free_shipping", {"min_amount": ""}, "woocommerce_ability_shipping_method_setting_invalid"]
+ *
+ * @param string $method_id Method to add.
+ * @param array $settings Settings to send.
+ * @param string $code Expected error code.
+ */
+ public function test_refuses_bad_settings_without_adding_the_method( string $method_id, array $settings, string $code ): void {
+ $zone_id = $this->create_germany_zone();
+
+ $result = $this->run_ability(
+ 'woocommerce/shipping-zone-method-create',
+ array(
+ 'zone_id' => $zone_id,
+ 'method_id' => $method_id,
+ 'settings' => $settings,
+ )
+ );
+
+ $this->assertWPError( $result );
+ $this->assertSame( $code, $result->get_error_code() );
+ $this->assertSame( array(), ( new \WC_Shipping_Zone( $zone_id ) )->get_shipping_methods(), 'The method should be removed again.' );
+ }
+
+ /**
+ * @testdox Should remove the method again when it cannot be read back after adding it.
+ */
+ public function test_removes_a_method_it_cannot_read_back(): void {
+ $zone_id = $this->create_germany_zone();
+ $unregister = static function ( array $methods ): array {
+ unset( $methods['flat_rate'] );
+ return $methods;
+ };
+ add_action(
+ 'woocommerce_shipping_zone_method_added',
+ static function () use ( $unregister ): void {
+ add_filter( 'woocommerce_shipping_methods', $unregister );
+ }
+ );
+
+ $result = $this->run_ability(
+ 'woocommerce/shipping-zone-method-create',
+ array(
+ 'zone_id' => $zone_id,
+ 'method_id' => 'flat_rate',
+ )
+ );
+ remove_filter( 'woocommerce_shipping_methods', $unregister );
+
+ $this->assertWPError( $result );
+ $this->assertSame( 'woocommerce_ability_shipping_method_create_failed', $result->get_error_code() );
+ $this->assertSame( array(), ( new \WC_Shipping_Zone( $zone_id ) )->get_shipping_methods( false, 'admin' ), 'The method should be removed again.' );
+ }
+
+ /**
+ * @testdox Should refuse a zone or method that does not exist.
+ * @testWith ["woocommerce/shipping-zone-method-create", {"zone_id": 999999, "method_id": "flat_rate"}, "woocommerce_ability_shipping_zone_not_found"]
+ * ["woocommerce/shipping-zone-method-update", {"instance_id": 999999, "enabled": true}, "woocommerce_ability_shipping_method_not_found"]
+ *
+ * @param string $ability Ability name.
+ * @param array $input Ability input.
+ * @param string $code Expected error code.
+ */
+ public function test_refuses_missing_targets( string $ability, array $input, string $code ): void {
+ $result = $this->run_ability( $ability, $input );
+
+ $this->assertWPError( $result );
+ $this->assertSame( $code, $result->get_error_code() );
+ }
+
+ /**
+ * @testdox Should refuse to change a method from an extension, even one that extends a Core method.
+ */
+ public function test_refuses_extension_methods(): void {
+ $carrier = new class() extends \WC_Shipping_Flat_Rate {
+ /**
+ * Give the subclass its own method ID.
+ *
+ * @param int $instance_id Instance ID.
+ */
+ public function __construct( $instance_id = 0 ) {
+ parent::__construct( $instance_id );
+ $this->id = 'test_carrier';
+ }
+ };
+ $register = static function ( array $methods ) use ( $carrier ): array {
+ $methods['test_carrier'] = $carrier;
+ return $methods;
+ };
+ add_filter( 'woocommerce_shipping_methods', $register );
+ $instance_id = ( new \WC_Shipping_Zone( 0 ) )->add_shipping_method( 'test_carrier' );
+
+ $result = $this->run_ability(
+ 'woocommerce/shipping-zone-method-update',
+ array(
+ 'instance_id' => $instance_id,
+ 'settings' => array( 'cost' => '1' ),
+ )
+ );
+
+ $this->assertWPError( $result );
+ $this->assertSame( 'woocommerce_ability_shipping_method_unsupported', $result->get_error_code() );
+ $this->assertFalse( get_option( "woocommerce_test_carrier_{$instance_id}_settings" ), 'Nothing should be written for the extension method.' );
+ }
+
+ /**
+ * @testdox Should create a zone with state and postcode locations in the given order.
+ */
+ public function test_creates_a_zone_with_locations(): void {
+ $result = $this->run_ability(
+ 'woocommerce/shipping-zone-create',
+ array(
+ 'name' => 'California <b>metro</b>',
+ 'order' => 3,
+ 'locations' => array(
+ array(
+ 'code' => 'US:CA',
+ 'type' => 'state',
+ ),
+ array(
+ 'code' => '90*',
+ 'type' => 'postcode',
+ ),
+ ),
+ )
+ );
+
+ $this->assertNotWPError( $result );
+ $this->assertSame( 'California metro', $result['zone']['name'] );
+ $this->assertSame( 3, $result['zone']['order'] );
+ $this->assertSame(
+ array(
+ array(
+ 'code' => 'US:CA',
+ 'type' => 'state',
+ ),
+ array(
+ 'code' => '90*',
+ 'type' => 'postcode',
+ ),
+ ),
+ $result['zone']['locations']
+ );
+ $this->assertSame( array(), $result['zone']['methods'] );
+ }
+
+ /**
+ * @testdox Should refuse a zone without locations, which would match every address, or with a code longer than the column.
+ * @testWith [[]]
+ * [[{"code": "%s", "type": "postcode"}]]
+ *
+ * @param array $locations Locations to send.
+ */
+ public function test_refuses_zone_locations_that_cannot_be_saved( array $locations ): void {
+ $zone_count = count( \WC_Shipping_Zones::get_zones() );
+ if ( isset( $locations[0]['code'] ) ) {
+ $locations[0]['code'] = str_repeat( '1', 201 );
+ }
+
+ $result = $this->run_ability(
+ 'woocommerce/shipping-zone-create',
+ array(
+ 'name' => 'Everywhere',
+ 'locations' => $locations,
+ )
+ );
+
+ $this->assertWPError( $result );
+ $this->assertSame( 'ability_invalid_input', $result->get_error_code() );
+ $this->assertCount( $zone_count, \WC_Shipping_Zones::get_zones(), 'No zone should be created.' );
+ }
+
+ /**
+ * @testdox Should refuse a zone name with nothing left after cleaning.
+ */
+ public function test_refuses_an_empty_zone_name(): void {
+ $result = $this->run_ability(
+ 'woocommerce/shipping-zone-create',
+ array(
+ 'name' => ' <b></b> ',
+ 'locations' => self::GERMANY,
+ )
+ );
+
+ $this->assertWPError( $result );
+ $this->assertSame( 'woocommerce_ability_shipping_zone_name_empty', $result->get_error_code() );
+ }
+
+ /**
+ * @testdox Should refuse every shipping write while shipping is turned off, and save nothing.
+ */
+ public function test_refuses_writes_while_shipping_is_disabled(): void {
+ $instance_id = ( new \WC_Shipping_Zone( 0 ) )->add_shipping_method( 'flat_rate' );
+ $zone_count = count( \WC_Shipping_Zones::get_zones() );
+ update_option( 'woocommerce_ship_to_countries', 'disabled' );
+
+ $results = array(
+ $this->run_ability(
+ 'woocommerce/shipping-zone-create',
+ array(
+ 'name' => 'Refused',
+ 'locations' => self::GERMANY,
+ )
+ ),
+ $this->run_ability(
+ 'woocommerce/shipping-zone-method-create',
+ array(
+ 'zone_id' => 0,
+ 'method_id' => 'free_shipping',
+ )
+ ),
+ $this->run_ability(
+ 'woocommerce/shipping-zone-method-update',
+ array(
+ 'instance_id' => $instance_id,
+ 'settings' => array( 'cost' => '9' ),
+ )
+ ),
+ );
+
+ foreach ( $results as $result ) {
+ $this->assertWPError( $result );
+ $this->assertSame( 'woocommerce_ability_shipping_disabled', $result->get_error_code() );
+ }
+ $this->assertCount( $zone_count, \WC_Shipping_Zones::get_zones(), 'No zone should be created.' );
+ $this->assertCount( 1, ( new \WC_Shipping_Zone( 0 ) )->get_shipping_methods(), 'No method should be added.' );
+ $this->assertFalse( get_option( "woocommerce_flat_rate_{$instance_id}_settings" ), 'The flat rate settings should stay untouched.' );
+ }
+
+ /**
+ * @testdox Should let a shop manager write shipping, and refuse a user who cannot manage WooCommerce.
+ */
+ public function test_requires_settings_permission(): void {
+ wp_set_current_user( self::factory()->user->create( array( 'role' => 'editor' ) ) );
+ $this->assertWPError(
+ $this->run_ability(
+ 'woocommerce/shipping-zone-create',
+ array(
+ 'name' => 'Refused',
+ 'locations' => self::GERMANY,
+ )
+ )
+ );
+ $this->assertWPError(
+ $this->run_ability(
+ 'woocommerce/shipping-zone-method-create',
+ array(
+ 'zone_id' => 0,
+ 'method_id' => 'flat_rate',
+ )
+ )
+ );
+ $this->assertSame( array(), ( new \WC_Shipping_Zone( 0 ) )->get_shipping_methods() );
+
+ wp_set_current_user( self::factory()->user->create( array( 'role' => 'shop_manager' ) ) );
+ $this->assertGreaterThan( 0, $this->create_germany_zone() );
+ }
+}