Commit cabb5255650 for woocommerce
commit cabb5255650b465ecc1d5bdfaaf22fe275a1b6a4
Author: Christopher Hertel <mail@christopher-hertel.de>
Date: Fri Nov 20 22:41:39 2026 +0100
Add tax rate create, update and delete abilities (#71065)
* Add tax rate create, update and delete abilities
Add woocommerce/tax-rate-create, woocommerce/tax-rate-update and
woocommerce/tax-rate-delete, mirroring the REST taxes controller's writes
through WC_Tax. They take the field names that tax-rates-query returns, so a
read round-trips into a write. Update changes only the sent fields, and an
empty postcodes or cities list clears it. Delete returns the rate as it was.
The rate formatting, output schema, location lookup and tax class check move
from TaxRatesQuery into TaxRateAbilityTrait, shared by all four abilities.
The tax-rates-query output does not change.
* Allow tax rate priority 0 and cover negative rate refusal
A stored rate can have priority 0, so the update schema accepts it and the rate can be sent back as read. Negative rates stay refused.
* Normalize tax rate postcodes as the settings screen does
A postcode saved with a space or hyphen only matched at checkout in
countries whose postcode format has that separator, so a rate for
"106 82" never applied to a Greek customer. Also tighten the
negative-rate test to check the error code and that nothing was saved.
* Refuse tax rate locations that would lift the restriction
An entry like "-" or "*" saved as nothing, and "Berlin;Paris" as two
entries, so an update could silently make a rate apply everywhere. Also
mark tax-rate-update as destructive like the other update abilities,
report a delete whose rate row was not removed, and make the append test
check the stored order.
* Check the tax rate row after a delete, not the query counter
A woocommerce_tax_rate_deleted callback that runs any query resets
$wpdb->rows_affected, so a successful delete was reported as failed.
* Treat a failed check of the deleted tax rate row as a failed delete
wpdb::get_row() returns null on a query error as well as on no row, so a
database failure after the delete was reported as a successful delete.
* Refresh cart shipping taxes after tax rate writes, and refuse locations that clean to nothing
Saved cart shipping rates carry their taxes and are keyed by the shipping
cache version, which the settings screen bumps but the abilities did not,
so carts kept charging the old rate on shipping.
sanitize_text_field runs after the schema pattern, so an entry such as
<br>, %20 or <b>*</b> passed it and cleaned to nothing or *, which WC_Tax
drops, lifting the restriction. Locations are now cleaned and checked
before any write.
* Refresh cart shipping taxes before checking a tax rate delete
A failed check after a delete that did happen returned before the refresh,
so saved carts kept the deleted rate's shipping taxes.
* Check tax rate regions, report unsaved locations, and accept rates such as .5
The settings screen orders rates with WC_Tax::sort_rates(), not by
tax_rate_order, so the create description no longer says a new rate comes
after the existing ones.
WC_Tax deletes a rate's postcodes or cities before it inserts the new ones,
so a failed insert left the rate applying everywhere while the ability
reported success. No hook or query runs between the insert and the check,
so $wpdb->last_error reliably tells, and the ability now returns a 500 with
the rate's id.
A country WooCommerce doesn't know, such as UK, or a state that isn't on
the country's list, such as California, saved a rate that never matches at
checkout. Both are now refused, as order address edits do. A state stays
free text for a country without a list.
The location error names the refused entry, and a rate without a leading
zero is accepted. Adds tests for a class change on update and an update of
only the cities.
* Quote the state as sent in the tax rate state error
The message quoted the stored form, so New York came back as NEWYORK.
diff --git a/plugins/woocommerce/changelog/add-tax-rate-write-abilities b/plugins/woocommerce/changelog/add-tax-rate-write-abilities
new file mode 100644
index 00000000000..38d1df95746
--- /dev/null
+++ b/plugins/woocommerce/changelog/add-tax-rate-write-abilities
@@ -0,0 +1,4 @@
+Significance: minor
+Type: add
+
+Let AI agents and other Abilities API clients add, change and remove tax rates.
diff --git a/plugins/woocommerce/src/Internal/Abilities/AbilitiesLoader.php b/plugins/woocommerce/src/Internal/Abilities/AbilitiesLoader.php
index d231069132c..2b0b805839d 100644
--- a/plugins/woocommerce/src/Internal/Abilities/AbilitiesLoader.php
+++ b/plugins/woocommerce/src/Internal/Abilities/AbilitiesLoader.php
@@ -44,7 +44,10 @@ use Automattic\WooCommerce\Internal\Abilities\Domain\ShippingZonesQuery;
use Automattic\WooCommerce\Internal\Abilities\Domain\SystemStatusGet;
use Automattic\WooCommerce\Internal\Abilities\Domain\SystemStatusToolRun;
use Automattic\WooCommerce\Internal\Abilities\Domain\SystemStatusToolsQuery;
+use Automattic\WooCommerce\Internal\Abilities\Domain\TaxRateCreate;
+use Automattic\WooCommerce\Internal\Abilities\Domain\TaxRateDelete;
use Automattic\WooCommerce\Internal\Abilities\Domain\TaxRatesQuery;
+use Automattic\WooCommerce\Internal\Abilities\Domain\TaxRateUpdate;
use Automattic\WooCommerce\Internal\AgentReadiness\ReportAbility;
use Automattic\WooCommerce\Internal\AgentReadiness\RunCheckAbility;
use Automattic\WooCommerce\Internal\Abilities\Domain\StoreSettingsGet;
@@ -107,6 +110,9 @@ class AbilitiesLoader {
ShippingZoneMethodCreate::class,
ShippingZoneMethodUpdate::class,
TaxRatesQuery::class,
+ TaxRateCreate::class,
+ TaxRateUpdate::class,
+ TaxRateDelete::class,
CustomersQuery::class,
StoreSettingsGet::class,
SettingsQuery::class,
diff --git a/plugins/woocommerce/src/Internal/Abilities/Domain/TaxRateCreate.php b/plugins/woocommerce/src/Internal/Abilities/Domain/TaxRateCreate.php
new file mode 100644
index 00000000000..351eeb3b8e0
--- /dev/null
+++ b/plugins/woocommerce/src/Internal/Abilities/Domain/TaxRateCreate.php
@@ -0,0 +1,136 @@
+<?php
+/**
+ * Tax rate 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\TaxRateAbilityTrait;
+
+defined( 'ABSPATH' ) || exit;
+
+/**
+ * Registers the ability that adds a tax rate. Tax rates are table rows with
+ * no object an extension could read or change, so they take no extension fields.
+ */
+class TaxRateCreate extends AbstractDomainAbility implements AbilityDefinition {
+
+ use TaxRateAbilityTrait;
+
+ /**
+ * Get the ability name.
+ *
+ * @return string
+ *
+ * @since 11.4.0
+ */
+ public static function get_name(): string {
+ return 'woocommerce/tax-rate-create';
+ }
+
+ /**
+ * Get the ability registration arguments.
+ *
+ * @return array
+ *
+ * @since 11.4.0
+ */
+ public static function get_registration_args(): array {
+ return array(
+ 'label' => __( 'Create tax rate', 'woocommerce' ),
+ 'description' => __( 'Add a tax rate to a tax class. Takes the fields that tax-rates-query returns, so check there first that no rate already covers the location.', 'woocommerce' ),
+ 'category' => 'woocommerce',
+ 'input_schema' => array(
+ 'type' => 'object',
+ 'properties' => self::get_rate_write_input_properties(),
+ 'required' => array( 'rate' ),
+ 'additionalProperties' => false,
+ ),
+ 'output_schema' => self::get_entity_output_schema( 'rate', self::get_rate_output_schema() ),
+ 'execute_callback' => array( __CLASS__, 'execute' ),
+ 'permission_callback' => array( __CLASS__, 'can_create_tax_rates' ),
+ 'meta' => array(
+ 'show_in_rest' => true,
+ 'mcp' => array(
+ 'public' => true,
+ 'type' => 'tool',
+ ),
+ 'annotations' => array(
+ 'readonly' => false,
+ 'idempotent' => false,
+ 'destructive' => false,
+ ),
+ ),
+ );
+ }
+
+ /**
+ * Add the rate. Unsent fields get the defaults of the tax settings screen.
+ *
+ * @param array $input Ability input.
+ * @return array|\WP_Error
+ *
+ * @since 11.4.0
+ */
+ public static function execute( array $input ) {
+ global $wpdb;
+
+ $columns = self::get_rate_columns( $input );
+ if ( is_wp_error( $columns ) ) {
+ return $columns;
+ }
+
+ $region_error = self::check_rate_region( $columns );
+ if ( $region_error ) {
+ return $region_error;
+ }
+
+ $locations = self::get_rate_locations( $input );
+ if ( is_wp_error( $locations ) ) {
+ return $locations;
+ }
+
+ $columns += array(
+ 'tax_rate_name' => '',
+ 'tax_rate_priority' => 1,
+ 'tax_rate_compound' => 0,
+ 'tax_rate_shipping' => 1,
+ 'tax_rate_class' => '',
+ );
+
+ $last_order = $wpdb->get_var( $wpdb->prepare( "SELECT MAX(tax_rate_order) FROM {$wpdb->prefix}woocommerce_tax_rates WHERE tax_rate_class = %s", $columns['tax_rate_class'] ) );
+ $columns['tax_rate_order'] = null === $last_order ? 0 : (int) $last_order + 1;
+
+ $rate_id = (int) \WC_Tax::_insert_tax_rate( $columns );
+ if ( ! $rate_id ) {
+ return new \WP_Error( 'woocommerce_ability_tax_rate_create_failed', __( 'The tax rate could not be saved.', 'woocommerce' ), array( 'status' => 500 ) );
+ }
+
+ $locations_error = self::write_rate_locations( $rate_id, $locations );
+ self::refresh_shipping_rates_cache();
+ if ( $locations_error ) {
+ return $locations_error;
+ }
+
+ $rate = self::get_rate_or_error( $rate_id );
+ if ( is_wp_error( $rate ) ) {
+ return $rate;
+ }
+
+ return array( 'rate' => $rate );
+ }
+
+ /**
+ * Check tax settings create access, as the REST taxes endpoint does.
+ *
+ * @return bool
+ *
+ * @since 11.4.0
+ */
+ public static function can_create_tax_rates(): bool {
+ return (bool) wc_rest_check_manager_permissions( 'settings', 'create' );
+ }
+}
diff --git a/plugins/woocommerce/src/Internal/Abilities/Domain/TaxRateDelete.php b/plugins/woocommerce/src/Internal/Abilities/Domain/TaxRateDelete.php
new file mode 100644
index 00000000000..e209e063dd2
--- /dev/null
+++ b/plugins/woocommerce/src/Internal/Abilities/Domain/TaxRateDelete.php
@@ -0,0 +1,113 @@
+<?php
+/**
+ * Tax rate delete 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\TaxRateAbilityTrait;
+
+defined( 'ABSPATH' ) || exit;
+
+/**
+ * Registers the ability that deletes a tax rate. Tax rates have no trash, so the delete is permanent.
+ */
+class TaxRateDelete extends AbstractDomainAbility implements AbilityDefinition {
+
+ use TaxRateAbilityTrait;
+
+ /**
+ * Get the ability name.
+ *
+ * @return string
+ *
+ * @since 11.4.0
+ */
+ public static function get_name(): string {
+ return 'woocommerce/tax-rate-delete';
+ }
+
+ /**
+ * Get the ability registration arguments.
+ *
+ * @return array
+ *
+ * @since 11.4.0
+ */
+ public static function get_registration_args(): array {
+ return array(
+ 'label' => __( 'Delete tax rate', 'woocommerce' ),
+ 'description' => __( 'Permanently delete a tax rate by its id from tax-rates-query. Returns the deleted rate; send its fields except id to tax-rate-create to add it back.', 'woocommerce' ),
+ 'category' => 'woocommerce',
+ 'input_schema' => array(
+ 'type' => 'object',
+ 'properties' => array(
+ 'id' => array(
+ 'type' => 'integer',
+ 'minimum' => 1,
+ ),
+ ),
+ 'required' => array( 'id' ),
+ 'additionalProperties' => false,
+ ),
+ 'output_schema' => self::get_entity_output_schema( 'rate', self::get_rate_output_schema() ),
+ 'execute_callback' => array( __CLASS__, 'execute' ),
+ 'permission_callback' => array( __CLASS__, 'can_delete_tax_rates' ),
+ 'meta' => array(
+ 'show_in_rest' => true,
+ 'mcp' => array(
+ 'public' => true,
+ 'type' => 'tool',
+ ),
+ 'annotations' => array(
+ 'readonly' => false,
+ 'idempotent' => true,
+ 'destructive' => true,
+ ),
+ ),
+ );
+ }
+
+ /**
+ * Delete the rate and its postcodes and cities.
+ *
+ * @param array $input Ability input.
+ * @return array|\WP_Error
+ *
+ * @since 11.4.0
+ */
+ public static function execute( array $input ) {
+ global $wpdb;
+
+ $rate = self::get_rate_or_error( $input['id'] );
+ if ( is_wp_error( $rate ) ) {
+ return $rate;
+ }
+
+ \WC_Tax::_delete_tax_rate( $input['id'] );
+ // Before the check, since a failed check can follow a delete that did happen.
+ self::refresh_shipping_rates_cache();
+
+ // The deleted hook may run queries of its own, so check the row rather than $wpdb->rows_affected.
+ // A failed check returns no row too, so its error counts as a failed delete.
+ if ( \WC_Tax::_get_tax_rate( $input['id'] ) || '' !== $wpdb->last_error ) {
+ return new \WP_Error( 'woocommerce_ability_tax_rate_delete_failed', __( 'The tax rate could not be deleted.', 'woocommerce' ), array( 'status' => 500 ) );
+ }
+
+ return array( 'rate' => $rate );
+ }
+
+ /**
+ * Check tax settings delete access, as the REST taxes endpoint does.
+ *
+ * @return bool
+ *
+ * @since 11.4.0
+ */
+ public static function can_delete_tax_rates(): bool {
+ return (bool) wc_rest_check_manager_permissions( 'settings', 'delete' );
+ }
+}
diff --git a/plugins/woocommerce/src/Internal/Abilities/Domain/TaxRateUpdate.php b/plugins/woocommerce/src/Internal/Abilities/Domain/TaxRateUpdate.php
new file mode 100644
index 00000000000..ec6d98d4235
--- /dev/null
+++ b/plugins/woocommerce/src/Internal/Abilities/Domain/TaxRateUpdate.php
@@ -0,0 +1,139 @@
+<?php
+/**
+ * Tax rate 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\TaxRateAbilityTrait;
+
+defined( 'ABSPATH' ) || exit;
+
+/**
+ * Registers the ability that changes a tax rate. Only the sent fields change.
+ */
+class TaxRateUpdate extends AbstractDomainAbility implements AbilityDefinition {
+
+ use TaxRateAbilityTrait;
+
+ /**
+ * Get the ability name.
+ *
+ * @return string
+ *
+ * @since 11.4.0
+ */
+ public static function get_name(): string {
+ return 'woocommerce/tax-rate-update';
+ }
+
+ /**
+ * Get the ability registration arguments.
+ *
+ * @return array
+ *
+ * @since 11.4.0
+ */
+ public static function get_registration_args(): array {
+ return array(
+ 'label' => __( 'Update tax rate', 'woocommerce' ),
+ 'description' => __( 'Change a tax rate. Send its id from tax-rates-query and only the fields to change. An empty postcodes or cities list makes the rate apply to every postcode or city.', 'woocommerce' ),
+ 'category' => 'woocommerce',
+ 'input_schema' => array(
+ 'type' => 'object',
+ 'properties' => array_merge(
+ array(
+ 'id' => array(
+ 'type' => 'integer',
+ 'minimum' => 1,
+ ),
+ ),
+ self::get_rate_write_input_properties()
+ ),
+ 'required' => array( 'id' ),
+ 'additionalProperties' => false,
+ ),
+ 'output_schema' => self::get_entity_output_schema( 'rate', self::get_rate_output_schema() ),
+ 'execute_callback' => array( __CLASS__, 'execute' ),
+ 'permission_callback' => array( __CLASS__, 'can_edit_tax_rates' ),
+ 'meta' => array(
+ 'show_in_rest' => true,
+ 'mcp' => array(
+ 'public' => true,
+ 'type' => 'tool',
+ ),
+ 'annotations' => array(
+ 'readonly' => false,
+ 'idempotent' => true,
+ 'destructive' => true,
+ ),
+ ),
+ );
+ }
+
+ /**
+ * Write the sent fields to the rate.
+ *
+ * @param array $input Ability input.
+ * @return array|\WP_Error
+ *
+ * @since 11.4.0
+ */
+ public static function execute( array $input ) {
+ $rate_id = $input['id'];
+
+ $current = self::get_rate_or_error( $rate_id );
+ if ( is_wp_error( $current ) ) {
+ return $current;
+ }
+
+ $columns = self::get_rate_columns( $input );
+ if ( is_wp_error( $columns ) ) {
+ return $columns;
+ }
+
+ $region_error = self::check_rate_region( $columns, $current );
+ if ( $region_error ) {
+ return $region_error;
+ }
+
+ $locations = self::get_rate_locations( $input );
+ if ( is_wp_error( $locations ) ) {
+ return $locations;
+ }
+
+ if ( empty( $columns ) && empty( $locations ) ) {
+ return array( 'rate' => $current );
+ }
+
+ if ( ! empty( $columns ) ) {
+ \WC_Tax::_update_tax_rate( $rate_id, $columns );
+ }
+ $locations_error = self::write_rate_locations( $rate_id, $locations );
+ self::refresh_shipping_rates_cache();
+ if ( $locations_error ) {
+ return $locations_error;
+ }
+
+ $rate = self::get_rate_or_error( $rate_id );
+ if ( is_wp_error( $rate ) ) {
+ return $rate;
+ }
+
+ return array( 'rate' => $rate );
+ }
+
+ /**
+ * Check tax settings edit access, as the REST taxes endpoint does.
+ *
+ * @return bool
+ *
+ * @since 11.4.0
+ */
+ public static function can_edit_tax_rates(): bool {
+ return (bool) wc_rest_check_manager_permissions( 'settings', 'edit' );
+ }
+}
diff --git a/plugins/woocommerce/src/Internal/Abilities/Domain/TaxRatesQuery.php b/plugins/woocommerce/src/Internal/Abilities/Domain/TaxRatesQuery.php
index 06c838b793e..fb246d5f489 100644
--- a/plugins/woocommerce/src/Internal/Abilities/Domain/TaxRatesQuery.php
+++ b/plugins/woocommerce/src/Internal/Abilities/Domain/TaxRatesQuery.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\TaxRateAbilityTrait;
defined( 'ABSPATH' ) || exit;
@@ -17,6 +18,8 @@ defined( 'ABSPATH' ) || exit;
*/
class TaxRatesQuery extends AbstractDomainAbility implements AbilityDefinition {
+ use TaxRateAbilityTrait;
+
/**
* Get the ability name.
*
@@ -122,8 +125,8 @@ class TaxRatesQuery extends AbstractDomainAbility implements AbilityDefinition {
$conditions[] = $wpdb->prepare( "tax_rate_id IN ({$placeholders})", $include );
}
if ( isset( $input['class'] ) ) {
- $tax_class = sanitize_title( $input['class'] );
- if ( 'standard' !== $tax_class && ! in_array( $tax_class, \WC_Tax::get_tax_class_slugs(), true ) ) {
+ $tax_class = self::get_stored_tax_class( $input['class'] );
+ if ( null === $tax_class ) {
return array(
'rates' => array(),
'total' => 0,
@@ -132,7 +135,7 @@ class TaxRatesQuery extends AbstractDomainAbility implements AbilityDefinition {
'per_page' => $per_page,
);
}
- $conditions[] = $wpdb->prepare( 'tax_rate_class = %s', 'standard' === $tax_class ? '' : $tax_class );
+ $conditions[] = $wpdb->prepare( 'tax_rate_class = %s', $tax_class );
}
if ( isset( $input['country'] ) ) {
$conditions[] = $wpdb->prepare( "tax_rate_country IN ( '', %s )", strtoupper( $input['country'] ) );
@@ -182,100 +185,4 @@ class TaxRatesQuery extends AbstractDomainAbility implements AbilityDefinition {
public static function can_query_taxes(): bool {
return (bool) wc_rest_check_manager_permissions( 'settings', 'read' );
}
-
- /**
- * Get the postcodes and cities of the given tax rates in one query.
- *
- * @param int[] $rate_ids Tax rate IDs.
- * @return array<int, array{postcodes?: string[], cities?: string[]}> Locations keyed by tax rate ID.
- */
- private static function get_locations( array $rate_ids ): array {
- global $wpdb;
-
- if ( empty( $rate_ids ) ) {
- return array();
- }
-
- $placeholders = implode( ', ', array_fill( 0, count( $rate_ids ), '%d' ) );
- // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare -- The placeholders are generated for each ID.
- $rows = $wpdb->get_results(
- $wpdb->prepare(
- "SELECT tax_rate_id, location_code, location_type FROM {$wpdb->prefix}woocommerce_tax_rate_locations WHERE tax_rate_id IN ({$placeholders}) ORDER BY location_id",
- $rate_ids
- )
- );
- // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
-
- $locations = array();
- foreach ( $rows as $row ) {
- $key = 'postcode' === $row->location_type ? 'postcodes' : ( 'city' === $row->location_type ? 'cities' : null );
- if ( null !== $key ) {
- $locations[ (int) $row->tax_rate_id ][ $key ][] = (string) $row->location_code;
- }
- }
-
- return $locations;
- }
-
- /**
- * Format a tax rate row.
- *
- * @param \stdClass $rate Row of the tax rates table.
- * @param array $locations Postcodes and cities of the rate.
- * @return array
- */
- private static function format_rate_for_response( \stdClass $rate, array $locations ): array {
- return array(
- 'id' => (int) $rate->tax_rate_id,
- 'country' => (string) $rate->tax_rate_country,
- 'state' => (string) $rate->tax_rate_state,
- 'postcodes' => $locations['postcodes'] ?? array(),
- 'cities' => $locations['cities'] ?? array(),
- 'rate' => (string) $rate->tax_rate,
- 'name' => (string) $rate->tax_rate_name,
- 'priority' => (int) $rate->tax_rate_priority,
- 'compound' => (bool) $rate->tax_rate_compound,
- 'shipping' => (bool) $rate->tax_rate_shipping,
- 'class' => '' === (string) $rate->tax_rate_class ? 'standard' : (string) $rate->tax_rate_class,
- );
- }
-
- /**
- * Get the schema of a tax rate in a response.
- *
- * @return array
- */
- private static function get_rate_output_schema(): array {
- $list = array(
- 'type' => 'array',
- 'items' => array( 'type' => 'string' ),
- );
-
- return array(
- 'type' => 'object',
- 'properties' => array(
- 'id' => array( 'type' => 'integer' ),
- 'country' => array(
- 'type' => 'string',
- 'description' => __( 'Empty for every country.', 'woocommerce' ),
- ),
- 'state' => array( 'type' => 'string' ),
- 'postcodes' => $list,
- 'cities' => $list,
- 'rate' => array(
- 'type' => 'string',
- 'description' => __( 'Percentage as a decimal string.', 'woocommerce' ),
- ),
- 'name' => array( 'type' => 'string' ),
- 'priority' => array( 'type' => 'integer' ),
- 'compound' => array( 'type' => 'boolean' ),
- 'shipping' => array(
- 'type' => 'boolean',
- 'description' => __( 'Whether the rate also applies to shipping.', 'woocommerce' ),
- ),
- 'class' => array( 'type' => 'string' ),
- ),
- 'additionalProperties' => false,
- );
- }
}
diff --git a/plugins/woocommerce/src/Internal/Abilities/Domain/Traits/TaxRateAbilityTrait.php b/plugins/woocommerce/src/Internal/Abilities/Domain/Traits/TaxRateAbilityTrait.php
new file mode 100644
index 00000000000..f6d817e2a68
--- /dev/null
+++ b/plugins/woocommerce/src/Internal/Abilities/Domain/Traits/TaxRateAbilityTrait.php
@@ -0,0 +1,398 @@
+<?php
+/**
+ * Tax rate ability trait file.
+ */
+
+declare( strict_types=1 );
+
+namespace Automattic\WooCommerce\Internal\Abilities\Domain\Traits;
+
+defined( 'ABSPATH' ) || exit;
+
+/**
+ * Reads, formats and writes tax rates for the tax abilities, with the field names of tax-rates-query.
+ */
+trait TaxRateAbilityTrait {
+
+ /**
+ * Get the stored value of a tax class slug.
+ *
+ * @param string $slug Tax class slug; standard for the standard rates.
+ * @return string|null Empty for the standard rates, or null when there is no such class.
+ */
+ private static function get_stored_tax_class( string $slug ): ?string {
+ $slug = sanitize_title( $slug );
+ if ( 'standard' === $slug ) {
+ return '';
+ }
+
+ return in_array( $slug, \WC_Tax::get_tax_class_slugs(), true ) ? $slug : null;
+ }
+
+ /**
+ * Get the error for a tax class slug that no class has.
+ *
+ * @param string $slug Tax class slug.
+ * @return \WP_Error
+ */
+ private static function get_tax_class_not_found_error( string $slug ): \WP_Error {
+ return new \WP_Error(
+ 'woocommerce_ability_tax_rate_class_not_found',
+ /* translators: 1: tax class slug, 2: comma-separated tax class slugs. */
+ sprintf( __( 'There is no tax class %1$s. Use one of: %2$s.', 'woocommerce' ), $slug, implode( ', ', array_merge( array( 'standard' ), \WC_Tax::get_tax_class_slugs() ) ) ),
+ array( 'status' => 400 )
+ );
+ }
+
+ /**
+ * Get a tax rate as the abilities return it.
+ *
+ * @param int $rate_id Tax rate ID.
+ * @return array|\WP_Error
+ */
+ private static function get_rate_or_error( int $rate_id ) {
+ $rate = \WC_Tax::_get_tax_rate( $rate_id, OBJECT );
+ if ( ! $rate instanceof \stdClass ) {
+ return new \WP_Error(
+ 'woocommerce_ability_tax_rate_not_found',
+ /* translators: %d: tax rate ID. */
+ sprintf( __( 'There is no tax rate with ID %d.', 'woocommerce' ), $rate_id ),
+ array( 'status' => 404 )
+ );
+ }
+
+ return self::format_rate_for_response( $rate, self::get_locations( array( $rate_id ) )[ $rate_id ] ?? array() );
+ }
+
+ /**
+ * Map the sent rate fields to tax rate table columns. Unsent fields are left out.
+ *
+ * @param array $input Ability input.
+ * @return array|\WP_Error
+ */
+ private static function get_rate_columns( array $input ) {
+ $columns = array();
+
+ if ( isset( $input['rate'] ) ) {
+ $columns['tax_rate'] = wc_format_decimal( $input['rate'] );
+ }
+ if ( isset( $input['country'] ) ) {
+ $columns['tax_rate_country'] = strtoupper( $input['country'] );
+ }
+ if ( isset( $input['state'] ) ) {
+ $columns['tax_rate_state'] = wc_clean( $input['state'] );
+ }
+ if ( isset( $input['name'] ) ) {
+ $columns['tax_rate_name'] = wc_clean( $input['name'] );
+ }
+ if ( isset( $input['priority'] ) ) {
+ $columns['tax_rate_priority'] = $input['priority'];
+ }
+ if ( isset( $input['compound'] ) ) {
+ $columns['tax_rate_compound'] = $input['compound'] ? 1 : 0;
+ }
+ if ( isset( $input['shipping'] ) ) {
+ $columns['tax_rate_shipping'] = $input['shipping'] ? 1 : 0;
+ }
+ if ( isset( $input['class'] ) ) {
+ $tax_class = self::get_stored_tax_class( $input['class'] );
+ if ( null === $tax_class ) {
+ return self::get_tax_class_not_found_error( $input['class'] );
+ }
+ $columns['tax_rate_class'] = $tax_class;
+ }
+
+ return $columns;
+ }
+
+ /**
+ * Check the country and state a rate will have once the sent columns are written. Only a sent
+ * country or state is checked, so a stored rate can still change its other fields. A state is
+ * free text for a country with no state list, since checkout matches what the customer typed.
+ *
+ * @param array $columns Columns from get_rate_columns().
+ * @param array $current The rate as stored, empty on create.
+ * @return \WP_Error|null
+ */
+ private static function check_rate_region( array $columns, array $current = array() ): ?\WP_Error {
+ if ( ! isset( $columns['tax_rate_country'] ) && ! isset( $columns['tax_rate_state'] ) ) {
+ return null;
+ }
+
+ $country = $columns['tax_rate_country'] ?? $current['country'] ?? '';
+ $sent_state = $columns['tax_rate_state'] ?? $current['state'] ?? '';
+ // WC_Tax stores the state in this form.
+ $state = strtoupper( sanitize_key( $sent_state ) );
+
+ if ( '' === $country ) {
+ return null;
+ }
+
+ if ( ! array_key_exists( $country, WC()->countries->get_countries() ) ) {
+ return new \WP_Error(
+ 'woocommerce_ability_tax_rate_country_invalid',
+ /* translators: %s: country code. */
+ sprintf( __( '"%s" is not a valid country. Send an ISO 3166-1 alpha-2 country code, such as GB, or empty for every country.', 'woocommerce' ), $country ),
+ array( 'status' => 400 )
+ );
+ }
+
+ $states = WC()->countries->get_states( $country );
+ if ( '' !== $state && ! empty( $states ) && ! array_key_exists( $state, $states ) ) {
+ return new \WP_Error(
+ 'woocommerce_ability_tax_rate_state_invalid',
+ /* translators: 1: state sent or kept from the rate, 2: country code, 3: comma-separated state codes. */
+ sprintf( __( '"%1$s" is not a state of %2$s. Send one of these codes, or empty for every state: %3$s.', 'woocommerce' ), $sent_state, $country, implode( ', ', array_keys( $states ) ) ),
+ array( 'status' => 400 )
+ );
+ }
+
+ return null;
+ }
+
+ /**
+ * Clean the sent postcodes and cities as the tax settings screen does; unsent lists are left out.
+ * Postcodes lose their spaces and hyphens, since checkout only matches a spaced postcode in
+ * countries whose format has the space. WC_Tax drops an entry that cleans to nothing or *,
+ * which would lift the whole restriction, so such an entry is refused.
+ *
+ * @param array $input Ability input.
+ * @return array{postcodes?: string[], cities?: string[]}|\WP_Error
+ */
+ private static function get_rate_locations( array $input ) {
+ $locations = array();
+ if ( isset( $input['postcodes'] ) ) {
+ $locations['postcodes'] = array_map( 'wc_normalize_postcode', array_map( 'sanitize_text_field', $input['postcodes'] ) );
+ }
+ if ( isset( $input['cities'] ) ) {
+ $locations['cities'] = array_map( 'sanitize_text_field', $input['cities'] );
+ }
+
+ foreach ( $locations as $field => $values ) {
+ $refused = array_intersect( $values, array( '', '*' ) );
+ if ( $refused ) {
+ return new \WP_Error(
+ 'woocommerce_ability_tax_rate_location_empty',
+ /* translators: 1: postcodes or cities, 2: zero-based position of the refused entry. */
+ sprintf( __( '%1$s[%2$d] needs a letter or number once HTML tags and percent-encoded characters are removed.', 'woocommerce' ), $field, key( $refused ) ),
+ array( 'status' => 400 )
+ );
+ }
+ }
+
+ return $locations;
+ }
+
+ /**
+ * Replace the postcodes and cities from get_rate_locations(). An empty list clears them.
+ * WC_Tax deletes the old entries before it inserts the new ones, so a failed write can lift the restriction.
+ *
+ * @param int $rate_id Tax rate ID.
+ * @param array $locations Cleaned postcodes and cities.
+ * @return \WP_Error|null
+ */
+ private static function write_rate_locations( int $rate_id, array $locations ): ?\WP_Error {
+ global $wpdb;
+
+ // No hook or other query runs between a location write and its check, so last_error is the write's.
+ if ( isset( $locations['postcodes'] ) ) {
+ \WC_Tax::_update_tax_rate_postcodes( $rate_id, implode( ';', $locations['postcodes'] ) );
+ if ( '' !== $wpdb->last_error ) {
+ return self::get_locations_failed_error( $rate_id, 'postcodes' );
+ }
+ }
+ if ( isset( $locations['cities'] ) ) {
+ \WC_Tax::_update_tax_rate_cities( $rate_id, implode( ';', $locations['cities'] ) );
+ if ( '' !== $wpdb->last_error ) {
+ return self::get_locations_failed_error( $rate_id, 'cities' );
+ }
+ }
+
+ return null;
+ }
+
+ /**
+ * Get the error for postcodes or cities that were not saved, after the rate itself was.
+ *
+ * @param int $rate_id Tax rate ID.
+ * @param string $field postcodes or cities.
+ * @return \WP_Error
+ */
+ private static function get_locations_failed_error( int $rate_id, string $field ): \WP_Error {
+ return new \WP_Error(
+ 'woocommerce_ability_tax_rate_locations_failed',
+ /* translators: 1: tax rate ID, 2: postcodes or cities. */
+ sprintf( __( 'Tax rate %1$d was saved, but its %2$s were not, so it may now apply everywhere. Send the %2$s again with tax-rate-update.', 'woocommerce' ), $rate_id, $field ),
+ array(
+ 'status' => 500,
+ 'rate_id' => $rate_id,
+ )
+ );
+ }
+
+ /**
+ * Saved cart shipping rates carry their taxes, so they must be recalculated after any rate change.
+ */
+ private static function refresh_shipping_rates_cache(): void {
+ \WC_Cache_Helper::get_transient_version( 'shipping', true );
+ }
+
+ /**
+ * Get the input schema of the fields that tax-rate-create and tax-rate-update write.
+ *
+ * @return array
+ */
+ private static function get_rate_write_input_properties(): array {
+ $list = array(
+ 'type' => 'array',
+ 'items' => array(
+ 'type' => 'string',
+ // WC_Tax drops an entry that is empty or * once trimmed, which would lift the whole restriction.
+ 'pattern' => '^[^;]*[^\s;*-][^;]*$',
+ 'maxLength' => 200,
+ ),
+ );
+
+ return array(
+ 'rate' => array(
+ 'type' => 'string',
+ 'description' => __( 'Percentage as a decimal string, such as "19" or "7.25".', 'woocommerce' ),
+ 'pattern' => '^([0-9]{1,3}|[0-9]{0,3}\.[0-9]{1,4})$',
+ ),
+ 'country' => array(
+ 'type' => 'string',
+ 'description' => __( 'Two-letter country code, or empty for every country.', 'woocommerce' ),
+ 'pattern' => '^([A-Za-z]{2})?$',
+ ),
+ 'state' => array(
+ 'type' => 'string',
+ 'description' => __( 'State code such as CA, or empty for every state. For a country with no state list, the state as customers enter it.', 'woocommerce' ),
+ 'maxLength' => 200,
+ ),
+ 'postcodes' => $list + array(
+ 'description' => __( 'Postcodes the rate is limited to. Takes ranges such as 10000...19999 and wildcards such as 10*. Empty for every postcode.', 'woocommerce' ),
+ ),
+ 'cities' => $list + array(
+ 'description' => __( 'Cities the rate is limited to. Empty for every city.', 'woocommerce' ),
+ ),
+ 'name' => array(
+ 'type' => 'string',
+ 'description' => __( 'Name shown on the cart, checkout and invoices. Empty saves the name Tax.', 'woocommerce' ),
+ 'maxLength' => 200,
+ ),
+ 'priority' => array(
+ 'type' => 'integer',
+ 'description' => __( 'Only one matching rate per priority applies. Use a different priority to stack rates.', 'woocommerce' ),
+ 'minimum' => 0,
+ ),
+ 'compound' => array(
+ 'type' => 'boolean',
+ 'description' => __( 'Whether the rate applies on top of the other taxes.', 'woocommerce' ),
+ ),
+ 'shipping' => array(
+ 'type' => 'boolean',
+ 'description' => __( 'Whether the rate also applies to shipping.', 'woocommerce' ),
+ ),
+ 'class' => array(
+ 'type' => 'string',
+ 'description' => __( 'Tax class slug; standard for the standard rates.', 'woocommerce' ),
+ ),
+ );
+ }
+
+ /**
+ * Get the postcodes and cities of the given tax rates in one query.
+ *
+ * @param int[] $rate_ids Tax rate IDs.
+ * @return array<int, array{postcodes?: string[], cities?: string[]}> Locations keyed by tax rate ID.
+ */
+ private static function get_locations( array $rate_ids ): array {
+ global $wpdb;
+
+ if ( empty( $rate_ids ) ) {
+ return array();
+ }
+
+ $placeholders = implode( ', ', array_fill( 0, count( $rate_ids ), '%d' ) );
+ // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare -- The placeholders are generated for each ID.
+ $rows = $wpdb->get_results(
+ $wpdb->prepare(
+ "SELECT tax_rate_id, location_code, location_type FROM {$wpdb->prefix}woocommerce_tax_rate_locations WHERE tax_rate_id IN ({$placeholders}) ORDER BY location_id",
+ $rate_ids
+ )
+ );
+ // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
+
+ $locations = array();
+ foreach ( $rows as $row ) {
+ $key = 'postcode' === $row->location_type ? 'postcodes' : ( 'city' === $row->location_type ? 'cities' : null );
+ if ( null !== $key ) {
+ $locations[ (int) $row->tax_rate_id ][ $key ][] = (string) $row->location_code;
+ }
+ }
+
+ return $locations;
+ }
+
+ /**
+ * Format a tax rate row.
+ *
+ * @param \stdClass $rate Row of the tax rates table.
+ * @param array $locations Postcodes and cities of the rate.
+ * @return array
+ */
+ private static function format_rate_for_response( \stdClass $rate, array $locations ): array {
+ return array(
+ 'id' => (int) $rate->tax_rate_id,
+ 'country' => (string) $rate->tax_rate_country,
+ 'state' => (string) $rate->tax_rate_state,
+ 'postcodes' => $locations['postcodes'] ?? array(),
+ 'cities' => $locations['cities'] ?? array(),
+ 'rate' => (string) $rate->tax_rate,
+ 'name' => (string) $rate->tax_rate_name,
+ 'priority' => (int) $rate->tax_rate_priority,
+ 'compound' => (bool) $rate->tax_rate_compound,
+ 'shipping' => (bool) $rate->tax_rate_shipping,
+ 'class' => '' === (string) $rate->tax_rate_class ? 'standard' : (string) $rate->tax_rate_class,
+ );
+ }
+
+ /**
+ * Get the schema of a tax rate in a response.
+ *
+ * @return array
+ */
+ private static function get_rate_output_schema(): array {
+ $list = array(
+ 'type' => 'array',
+ 'items' => array( 'type' => 'string' ),
+ );
+
+ return array(
+ 'type' => 'object',
+ 'properties' => array(
+ 'id' => array( 'type' => 'integer' ),
+ 'country' => array(
+ 'type' => 'string',
+ 'description' => __( 'Empty for every country.', 'woocommerce' ),
+ ),
+ 'state' => array( 'type' => 'string' ),
+ 'postcodes' => $list,
+ 'cities' => $list,
+ 'rate' => array(
+ 'type' => 'string',
+ 'description' => __( 'Percentage as a decimal string.', 'woocommerce' ),
+ ),
+ 'name' => array( 'type' => 'string' ),
+ 'priority' => array( 'type' => 'integer' ),
+ 'compound' => array( 'type' => 'boolean' ),
+ 'shipping' => array(
+ 'type' => 'boolean',
+ 'description' => __( 'Whether the rate also applies to shipping.', 'woocommerce' ),
+ ),
+ 'class' => 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 7b2f338a437..7ff64f857f3 100644
--- a/plugins/woocommerce/tests/php/src/Internal/Abilities/AbilitiesLoaderTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/Abilities/AbilitiesLoaderTest.php
@@ -70,6 +70,9 @@ class AbilitiesLoaderTest extends \WC_Unit_Test_Case {
'woocommerce/shipping-zone-method-update',
'woocommerce/system-status-get',
'woocommerce/tax-rates-query',
+ 'woocommerce/tax-rate-create',
+ 'woocommerce/tax-rate-update',
+ 'woocommerce/tax-rate-delete',
'woocommerce/system-status-tools-query',
'woocommerce/system-status-tool-run',
'woocommerce/payment-gateway-update',
@@ -285,6 +288,21 @@ class AbilitiesLoaderTest extends \WC_Unit_Test_Case {
'idempotent' => true,
'destructive' => false,
),
+ 'woocommerce/tax-rate-create' => array(
+ 'readonly' => false,
+ 'idempotent' => false,
+ 'destructive' => false,
+ ),
+ 'woocommerce/tax-rate-update' => array(
+ 'readonly' => false,
+ 'idempotent' => true,
+ 'destructive' => true,
+ ),
+ 'woocommerce/tax-rate-delete' => array(
+ 'readonly' => false,
+ 'idempotent' => true,
+ 'destructive' => true,
+ ),
'woocommerce/product-attributes-query' => array(
'readonly' => true,
'idempotent' => true,
@@ -1254,6 +1272,21 @@ class AbilitiesLoaderTest extends \WC_Unit_Test_Case {
'woocommerce/tax-rates-query',
array(),
),
+ 'tax-rate-create' => array(
+ 'woocommerce/tax-rate-create',
+ array( 'rate' => '19' ),
+ ),
+ 'tax-rate-update' => array(
+ 'woocommerce/tax-rate-update',
+ array(
+ 'id' => 1,
+ 'rate' => '19',
+ ),
+ ),
+ 'tax-rate-delete' => array(
+ 'woocommerce/tax-rate-delete',
+ array( 'id' => 1 ),
+ ),
'status-tools-query' => array(
'woocommerce/system-status-tools-query',
array(),
@@ -1340,6 +1373,9 @@ class AbilitiesLoaderTest extends \WC_Unit_Test_Case {
),
),
),
+ 'tax-rate-create' => array( 'woocommerce/tax-rate-create', array( 'rate' => '19' ) ),
+ 'tax-rate-update of missing' => array( 'woocommerce/tax-rate-update', $missing_id ),
+ 'tax-rate-delete of missing' => array( 'woocommerce/tax-rate-delete', $missing_id ),
'product-attributes-query' => array( 'woocommerce/product-attributes-query', array() ),
'product-attribute-create' => array( 'woocommerce/product-attribute-create', array( 'name' => 'Size' ) ),
'product-terms-query' => array( 'woocommerce/product-terms-query', array( 'taxonomy' => 'product_cat' ) ),
diff --git a/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/TaxRateAbilitiesTest.php b/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/TaxRateAbilitiesTest.php
new file mode 100644
index 00000000000..6c10b752b6a
--- /dev/null
+++ b/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/TaxRateAbilitiesTest.php
@@ -0,0 +1,850 @@
+<?php
+/**
+ * TaxRateAbilitiesTest class file.
+ */
+
+declare( strict_types=1 );
+
+namespace Automattic\WooCommerce\Tests\Internal\Abilities\Domain;
+
+use Automattic\WooCommerce\Internal\Abilities\AbilitiesLoader;
+
+/**
+ * Tests for the tax-rate-create, tax-rate-update and tax-rate-delete abilities.
+ */
+class TaxRateAbilitiesTest extends \WC_Unit_Test_Case {
+
+ /**
+ * 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 and no tax rates.
+ */
+ public function setUp(): void {
+ global $wp_actions, $wpdb;
+
+ 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();
+ $wpdb->query( "DELETE FROM {$wpdb->prefix}woocommerce_tax_rate_locations" );
+ $wpdb->query( "DELETE FROM {$wpdb->prefix}woocommerce_tax_rates" );
+
+ 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 rate through the ability.
+ *
+ * @param array $input Ability input.
+ * @return array The created rate.
+ */
+ private function create_rate( array $input ): array {
+ $result = $this->run_ability( 'woocommerce/tax-rate-create', $input );
+ $this->assertNotWPError( $result );
+
+ return $result['rate'];
+ }
+
+ /**
+ * @testdox Should create a rate that tax-rates-query returns as the create returned it.
+ */
+ public function test_create_reads_back_through_the_query(): void {
+ $rate = $this->create_rate(
+ array(
+ 'rate' => '7',
+ 'country' => 'de',
+ 'state' => '',
+ 'postcodes' => array( '10115', '10117' ),
+ 'cities' => array( 'Berlin' ),
+ 'name' => 'MwSt reduced',
+ 'priority' => 2,
+ 'compound' => true,
+ 'shipping' => false,
+ 'class' => 'reduced-rate',
+ )
+ );
+
+ $this->assertSame(
+ array(
+ 'id' => $rate['id'],
+ 'country' => 'DE',
+ 'state' => '',
+ 'postcodes' => array( '10115', '10117' ),
+ 'cities' => array( 'BERLIN' ),
+ 'rate' => '7.0000',
+ 'name' => 'MwSt reduced',
+ 'priority' => 2,
+ 'compound' => true,
+ 'shipping' => false,
+ 'class' => 'reduced-rate',
+ ),
+ $rate,
+ 'The create should return the stored rate.'
+ );
+
+ $query = $this->run_ability( 'woocommerce/tax-rates-query', array( 'include' => array( $rate['id'] ) ) );
+ $this->assertSame( array( $rate ), $query['rates'], 'tax-rates-query should return the rate as the create did.' );
+ }
+
+ /**
+ * @testdox Should give a created rate the defaults of the tax settings screen and place it after the rates of its class.
+ */
+ public function test_create_applies_defaults_and_appends(): void {
+ $first_id = \WC_Tax::_insert_tax_rate(
+ array(
+ 'tax_rate' => '19',
+ 'tax_rate_order' => 5,
+ )
+ );
+ $second = $this->create_rate( array( 'rate' => '20' ) );
+
+ $this->assertSame( 'standard', $second['class'] );
+ $this->assertSame( 1, $second['priority'] );
+ $this->assertFalse( $second['compound'] );
+ $this->assertTrue( $second['shipping'] );
+ $this->assertSame( '', $second['country'] );
+ $this->assertSame( 'Tax', $second['name'] );
+
+ $this->assertSame( '6', \WC_Tax::_get_tax_rate( $second['id'] )['tax_rate_order'], 'The new rate should come after the existing rates of its class.' );
+
+ $query = $this->run_ability( 'woocommerce/tax-rates-query' );
+ $this->assertSame( array( $first_id, $second['id'] ), array_column( $query['rates'], 'id' ) );
+ }
+
+ /**
+ * @testdox Should change only the sent fields of a rate.
+ */
+ public function test_partial_update_leaves_other_fields(): void {
+ $rate = $this->create_rate(
+ array(
+ 'rate' => '19',
+ 'country' => 'DE',
+ 'postcodes' => array( '10115' ),
+ 'name' => 'MwSt',
+ 'compound' => true,
+ )
+ );
+
+ $result = $this->run_ability(
+ 'woocommerce/tax-rate-update',
+ array(
+ 'id' => $rate['id'],
+ 'rate' => '16',
+ )
+ );
+
+ $this->assertNotWPError( $result );
+ $this->assertSame( array_merge( $rate, array( 'rate' => '16.0000' ) ), $result['rate'] );
+ }
+
+ /**
+ * @testdox Should accept priority 0, so a stored rate with that priority can be sent back.
+ */
+ public function test_update_accepts_priority_zero(): void {
+ $rate = $this->create_rate( array( 'rate' => '19' ) );
+
+ $result = $this->run_ability(
+ 'woocommerce/tax-rate-update',
+ array(
+ 'id' => $rate['id'],
+ 'priority' => 0,
+ )
+ );
+
+ $this->assertNotWPError( $result );
+ $this->assertSame( 0, $result['rate']['priority'] );
+ }
+
+ /**
+ * @testdox Should refuse a negative rate.
+ */
+ public function test_create_refuses_negative_rate(): void {
+ $result = $this->run_ability( 'woocommerce/tax-rate-create', array( 'rate' => '-5' ) );
+
+ $this->assertWPError( $result );
+ $this->assertSame( 'ability_invalid_input', $result->get_error_code() );
+ $this->assertSame( 0, $this->run_ability( 'woocommerce/tax-rates-query' )['total'], 'No rate should be created.' );
+ }
+
+ /**
+ * @testdox Should accept a rate without a leading zero, and refuse one that ends in a point.
+ */
+ public function test_create_accepts_a_rate_without_a_leading_zero(): void {
+ $this->assertSame( '0.5000', $this->create_rate( array( 'rate' => '.5' ) )['rate'] );
+
+ foreach ( array( '5.', '.' ) as $rate ) {
+ $result = $this->run_ability( 'woocommerce/tax-rate-create', array( 'rate' => $rate ) );
+
+ $this->assertWPError( $result, "Rate {$rate} should be refused." );
+ $this->assertSame( 'ability_invalid_input', $result->get_error_code() );
+ }
+ }
+
+ /**
+ * @testdox Should store postcodes without spaces or hyphens, as the tax settings screen does, keeping ranges and wildcards.
+ */
+ public function test_create_normalizes_postcodes(): void {
+ $rate = $this->create_rate(
+ array(
+ 'rate' => '24',
+ 'country' => 'GR',
+ 'postcodes' => array( '106 82', '107-01', '106 *', '106 00...106 99' ),
+ )
+ );
+
+ $this->assertSame( array( '10682', '10701', '106*', '10600...10699' ), $rate['postcodes'] );
+ }
+
+ /**
+ * @testdox Should refuse a postcode or city that would save as nothing or as two entries, and keep the stored ones.
+ */
+ public function test_update_refuses_locations_that_lift_the_restriction(): void {
+ $rate = $this->create_rate(
+ array(
+ 'rate' => '19',
+ 'postcodes' => array( '10115' ),
+ 'cities' => array( 'BERLIN' ),
+ )
+ );
+
+ foreach ( array( array( 'postcodes' => array( '-' ) ), array( 'postcodes' => array( '*' ) ), array( 'cities' => array( 'Berlin;Paris' ) ) ) as $locations ) {
+ $result = $this->run_ability( 'woocommerce/tax-rate-update', array( 'id' => $rate['id'] ) + $locations );
+
+ $this->assertWPError( $result );
+ $this->assertSame( 'ability_invalid_input', $result->get_error_code() );
+ }
+
+ $stored = $this->run_ability( 'woocommerce/tax-rates-query', array( 'include' => array( $rate['id'] ) ) )['rates'][0];
+ $this->assertSame( array( '10115' ), $stored['postcodes'] );
+ $this->assertSame( array( 'BERLIN' ), $stored['cities'] );
+ }
+
+ /**
+ * @testdox Should refuse a postcode or city that cleans to nothing or to *, and keep the stored ones.
+ */
+ public function test_update_refuses_locations_that_clean_to_nothing(): void {
+ $rate = $this->create_rate(
+ array(
+ 'rate' => '19',
+ 'postcodes' => array( '10115' ),
+ 'cities' => array( 'BERLIN' ),
+ )
+ );
+
+ $cases = array(
+ 'postcodes[0]' => array( 'postcodes' => array( '<br>' ) ),
+ 'postcodes[1]' => array( 'postcodes' => array( '10117', '%20' ) ),
+ 'postcodes[2]' => array( 'postcodes' => array( '10117', '10119', '<b>*</b>' ) ),
+ 'cities[0]' => array( 'cities' => array( '<b></b>' ) ),
+ );
+ foreach ( $cases as $position => $locations ) {
+ $result = $this->run_ability( 'woocommerce/tax-rate-update', array( 'id' => $rate['id'] ) + $locations );
+
+ $this->assertWPError( $result );
+ $this->assertSame( 'woocommerce_ability_tax_rate_location_empty', $result->get_error_code() );
+ $this->assertSame( 400, $result->get_error_data()['status'] );
+ $this->assertStringStartsWith( $position . ' ', $result->get_error_message(), 'The error should name the refused entry.' );
+ }
+
+ $stored = $this->run_ability( 'woocommerce/tax-rates-query', array( 'include' => array( $rate['id'] ) ) )['rates'][0];
+ $this->assertSame( array( '10115' ), $stored['postcodes'] );
+ $this->assertSame( array( 'BERLIN' ), $stored['cities'] );
+ }
+
+ /**
+ * @testdox Should refuse to create a rate whose city cleans to nothing, without saving the rate.
+ */
+ public function test_create_refuses_a_location_that_cleans_to_nothing(): void {
+ $result = $this->run_ability(
+ 'woocommerce/tax-rate-create',
+ array(
+ 'rate' => '19',
+ 'cities' => array( '<b></b>' ),
+ )
+ );
+
+ $this->assertWPError( $result );
+ $this->assertSame( 'woocommerce_ability_tax_rate_location_empty', $result->get_error_code() );
+ $this->assertStringStartsWith( 'cities[0] ', $result->get_error_message() );
+ $this->assertSame( 0, $this->run_ability( 'woocommerce/tax-rates-query' )['total'], 'No rate should be created.' );
+ }
+
+ /**
+ * @testdox Should match a customer postcode written with a space to a rate saved with that space.
+ */
+ public function test_spaced_postcode_matches_at_checkout(): void {
+ $rate = $this->create_rate(
+ array(
+ 'rate' => '24',
+ 'country' => 'GR',
+ 'postcodes' => array( '106 82' ),
+ )
+ );
+
+ $matched = \WC_Tax::find_rates(
+ array(
+ 'country' => 'GR',
+ 'postcode' => '106 82',
+ 'state' => '',
+ 'city' => '',
+ 'tax_class' => '',
+ )
+ );
+
+ $this->assertArrayHasKey( $rate['id'], $matched );
+ }
+
+ /**
+ * @testdox Should clear the postcodes of a rate when an empty list is sent, and keep its cities.
+ */
+ public function test_update_clears_postcodes(): void {
+ $rate = $this->create_rate(
+ array(
+ 'rate' => '19',
+ 'postcodes' => array( '10115', '10117' ),
+ 'cities' => array( 'BERLIN' ),
+ )
+ );
+
+ $result = $this->run_ability(
+ 'woocommerce/tax-rate-update',
+ array(
+ 'id' => $rate['id'],
+ 'postcodes' => array(),
+ )
+ );
+
+ $this->assertNotWPError( $result );
+ $this->assertSame( array(), $result['rate']['postcodes'] );
+ $this->assertSame( array( 'BERLIN' ), $result['rate']['cities'] );
+ }
+
+ /**
+ * @testdox Should replace only the cities of a rate when only cities are sent.
+ */
+ public function test_update_replaces_only_cities(): void {
+ $rate = $this->create_rate(
+ array(
+ 'rate' => '19',
+ 'country' => 'DE',
+ 'postcodes' => array( '10115' ),
+ 'cities' => array( 'Berlin' ),
+ 'name' => 'MwSt',
+ )
+ );
+ set_transient( 'shipping-transient-version', 'before-update' );
+
+ $result = $this->run_ability(
+ 'woocommerce/tax-rate-update',
+ array(
+ 'id' => $rate['id'],
+ 'cities' => array( 'Potsdam', 'Hamburg' ),
+ )
+ );
+
+ $this->assertNotWPError( $result );
+ $this->assertSame( array_merge( $rate, array( 'cities' => array( 'POTSDAM', 'HAMBURG' ) ) ), $result['rate'] );
+ $this->assertNotSame( 'before-update', get_transient( 'shipping-transient-version' ), 'An update of only the cities should refresh saved shipping rates.' );
+ }
+
+ /**
+ * @testdox Should return the rate unchanged, without a write, when only the id is sent.
+ */
+ public function test_update_with_only_id_returns_the_rate(): void {
+ $rate = $this->create_rate( array( 'rate' => '19' ) );
+ $updated = 0;
+ add_action(
+ 'woocommerce_tax_rate_updated',
+ static function () use ( &$updated ) {
+ ++$updated;
+ }
+ );
+
+ $result = $this->run_ability( 'woocommerce/tax-rate-update', array( 'id' => $rate['id'] ) );
+
+ $this->assertSame( array( 'rate' => $rate ), $result );
+ $this->assertSame( 0, $updated, 'No write should happen.' );
+ }
+
+ /**
+ * @testdox Should refuse a tax class that does not exist, on create and on update.
+ */
+ public function test_unknown_class_is_refused(): void {
+ $create = $this->run_ability(
+ 'woocommerce/tax-rate-create',
+ array(
+ 'rate' => '19',
+ 'class' => 'no-such-class',
+ )
+ );
+
+ $this->assertWPError( $create );
+ $this->assertSame( 'woocommerce_ability_tax_rate_class_not_found', $create->get_error_code() );
+ $this->assertSame( 400, $create->get_error_data()['status'] );
+ $this->assertSame( 0, $this->run_ability( 'woocommerce/tax-rates-query' )['total'], 'No rate should be created.' );
+
+ $rate = $this->create_rate( array( 'rate' => '19' ) );
+ $update = $this->run_ability(
+ 'woocommerce/tax-rate-update',
+ array(
+ 'id' => $rate['id'],
+ 'rate' => '7',
+ 'class' => 'no-such-class',
+ )
+ );
+
+ $this->assertWPError( $update );
+ $this->assertSame( 'woocommerce_ability_tax_rate_class_not_found', $update->get_error_code() );
+ $this->assertSame( '19.0000', $this->run_ability( 'woocommerce/tax-rates-query' )['rates'][0]['rate'], 'The rate should not change.' );
+ }
+
+ /**
+ * @testdox Should move a rate to another tax class, and back to the standard rates when standard is sent.
+ */
+ public function test_update_moves_a_rate_between_classes(): void {
+ $rate = $this->create_rate( array( 'rate' => '19' ) );
+
+ $reduced = $this->run_ability(
+ 'woocommerce/tax-rate-update',
+ array(
+ 'id' => $rate['id'],
+ 'class' => 'reduced-rate',
+ )
+ );
+ $this->assertNotWPError( $reduced );
+ $this->assertSame( 'reduced-rate', $reduced['rate']['class'] );
+
+ $standard = $this->run_ability(
+ 'woocommerce/tax-rate-update',
+ array(
+ 'id' => $rate['id'],
+ 'class' => 'standard',
+ )
+ );
+ $this->assertNotWPError( $standard );
+ $this->assertSame( $rate, $standard['rate'] );
+ $this->assertSame( '', \WC_Tax::_get_tax_rate( $rate['id'] )['tax_rate_class'], 'The standard rates should be stored as an empty class.' );
+ }
+
+ /**
+ * @testdox Should refuse country $country, which is not a valid country code.
+ *
+ * @testWith ["XX"]
+ * ["UK"]
+ *
+ * @param string $country Country code.
+ */
+ public function test_create_refuses_an_unknown_country( string $country ): void {
+ $result = $this->run_ability(
+ 'woocommerce/tax-rate-create',
+ array(
+ 'rate' => '20',
+ 'country' => $country,
+ )
+ );
+
+ $this->assertWPError( $result );
+ $this->assertSame( 'woocommerce_ability_tax_rate_country_invalid', $result->get_error_code() );
+ $this->assertSame( 400, $result->get_error_data()['status'] );
+ $this->assertSame( 0, $this->run_ability( 'woocommerce/tax-rates-query' )['total'], 'No rate should be created.' );
+ }
+
+ /**
+ * @testdox Should take a state from the country's list, and any state for a country without one.
+ */
+ public function test_create_checks_the_state_against_the_country(): void {
+ $refused = $this->run_ability(
+ 'woocommerce/tax-rate-create',
+ array(
+ 'rate' => '7.25',
+ 'country' => 'US',
+ 'state' => 'California',
+ )
+ );
+ $this->assertWPError( $refused );
+ $this->assertSame( 'woocommerce_ability_tax_rate_state_invalid', $refused->get_error_code() );
+ $this->assertStringStartsWith( '"California" is not a state of US.', $refused->get_error_message(), 'The error should quote the state as it was sent.' );
+ $this->assertStringContainsString( 'CA', $refused->get_error_message(), 'The error should list the valid codes.' );
+
+ $this->assertSame(
+ 'CA',
+ $this->create_rate(
+ array(
+ 'rate' => '7.25',
+ 'country' => 'US',
+ 'state' => 'ca',
+ )
+ )['state']
+ );
+ $this->assertSame(
+ 'TIROL',
+ $this->create_rate(
+ array(
+ 'rate' => '20',
+ 'country' => 'AT',
+ 'state' => 'Tirol',
+ )
+ )['state'],
+ 'A country without a state list should take any state.'
+ );
+ }
+
+ /**
+ * @testdox Should check the stored state against a new country, but not a stored region when other fields change.
+ */
+ public function test_update_checks_the_region_it_will_save(): void {
+ $rate = $this->create_rate(
+ array(
+ 'rate' => '7.25',
+ 'country' => 'US',
+ 'state' => 'CA',
+ )
+ );
+ $result = $this->run_ability(
+ 'woocommerce/tax-rate-update',
+ array(
+ 'id' => $rate['id'],
+ 'country' => 'DE',
+ )
+ );
+ $this->assertWPError( $result );
+ $this->assertSame( 'woocommerce_ability_tax_rate_state_invalid', $result->get_error_code() );
+ $this->assertSame( 'US', $this->run_ability( 'woocommerce/tax-rates-query', array( 'include' => array( $rate['id'] ) ) )['rates'][0]['country'], 'The rate should not change.' );
+
+ $stored_id = \WC_Tax::_insert_tax_rate(
+ array(
+ 'tax_rate' => '19',
+ 'tax_rate_country' => 'XX',
+ 'tax_rate_order' => 0,
+ )
+ );
+ $this->assertNotWPError(
+ $this->run_ability(
+ 'woocommerce/tax-rate-update',
+ array(
+ 'id' => $stored_id,
+ 'rate' => '7',
+ )
+ )
+ );
+ }
+
+ /**
+ * @testdox Should report the rate as saved without its locations when $ability fails to write them.
+ *
+ * @testWith ["woocommerce/tax-rate-create"]
+ * ["woocommerce/tax-rate-update"]
+ *
+ * @param string $ability Ability name.
+ */
+ public function test_failed_location_write_is_reported( string $ability ): void {
+ global $wpdb;
+
+ $input = array( 'postcodes' => array( '10117' ) );
+ if ( 'woocommerce/tax-rate-update' === $ability ) {
+ $input['id'] = $this->create_rate(
+ array(
+ 'rate' => '19',
+ 'postcodes' => array( '10115' ),
+ )
+ )['id'];
+ } else {
+ $input['rate'] = '19';
+ }
+ $locations_insert = "INSERT INTO {$wpdb->prefix}woocommerce_tax_rate_locations ";
+ add_filter(
+ 'query',
+ static function ( $query ) use ( $locations_insert ) {
+ return 0 === strpos( $query, $locations_insert ) ? 'INSERT INTO no_such_table_for_the_locations VALUES (1)' : $query;
+ }
+ );
+
+ $suppressed = $wpdb->suppress_errors( true );
+ try {
+ $result = $this->run_ability( $ability, $input );
+ } finally {
+ $wpdb->suppress_errors( $suppressed );
+ }
+
+ $this->assertWPError( $result );
+ $this->assertSame( 'woocommerce_ability_tax_rate_locations_failed', $result->get_error_code() );
+ $this->assertSame( 500, $result->get_error_data()['status'] );
+ $rate_id = $result->get_error_data()['rate_id'];
+ $this->assertSame( array(), $this->run_ability( 'woocommerce/tax-rates-query', array( 'include' => array( $rate_id ) ) )['rates'][0]['postcodes'], 'The error should name the rate that lost its postcodes.' );
+ }
+
+ /**
+ * @testdox Should report an unknown rate ID as not found on $ability.
+ *
+ * @testWith ["woocommerce/tax-rate-update"]
+ * ["woocommerce/tax-rate-delete"]
+ *
+ * @param string $ability Ability name.
+ */
+ public function test_unknown_id_is_not_found( string $ability ): void {
+ $result = $this->run_ability( $ability, array( 'id' => PHP_INT_MAX ) );
+
+ $this->assertWPError( $result );
+ $this->assertSame( 'woocommerce_ability_tax_rate_not_found', $result->get_error_code() );
+ $this->assertSame( 404, $result->get_error_data()['status'] );
+ }
+
+ /**
+ * @testdox Should delete a rate with its locations and return it as it was.
+ */
+ public function test_delete_returns_the_old_rate(): void {
+ global $wpdb;
+
+ $rate = $this->create_rate(
+ array(
+ 'rate' => '19',
+ 'country' => 'DE',
+ 'postcodes' => array( '10115' ),
+ 'cities' => array( 'BERLIN' ),
+ )
+ );
+
+ $result = $this->run_ability( 'woocommerce/tax-rate-delete', array( 'id' => $rate['id'] ) );
+
+ $this->assertSame( array( 'rate' => $rate ), $result );
+ $this->assertSame( 0, $this->run_ability( 'woocommerce/tax-rates-query' )['total'], 'The rate should be gone.' );
+ $this->assertSame(
+ '0',
+ $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->prefix}woocommerce_tax_rate_locations WHERE tax_rate_id = %d", $rate['id'] ) ),
+ 'The locations of the rate should be gone.'
+ );
+ }
+
+ /**
+ * @testdox Should make carts recalculate shipping taxes after a create, update or delete, but not after an update that changes nothing.
+ */
+ public function test_writes_refresh_saved_shipping_rates(): void {
+ set_transient( 'shipping-transient-version', 'before-create' );
+ $rate = $this->create_rate( array( 'rate' => '25' ) );
+ $this->assertNotSame( 'before-create', get_transient( 'shipping-transient-version' ), 'A create should refresh saved shipping rates.' );
+
+ set_transient( 'shipping-transient-version', 'before-noop' );
+ $this->run_ability( 'woocommerce/tax-rate-update', array( 'id' => $rate['id'] ) );
+ $this->assertSame( 'before-noop', get_transient( 'shipping-transient-version' ), 'An update that changes nothing should keep saved shipping rates.' );
+
+ set_transient( 'shipping-transient-version', 'before-update' );
+ $this->run_ability(
+ 'woocommerce/tax-rate-update',
+ array(
+ 'id' => $rate['id'],
+ 'postcodes' => array( '10115' ),
+ )
+ );
+ $this->assertNotSame( 'before-update', get_transient( 'shipping-transient-version' ), 'An update of only the postcodes should refresh saved shipping rates.' );
+
+ set_transient( 'shipping-transient-version', 'before-delete' );
+ $this->run_ability( 'woocommerce/tax-rate-delete', array( 'id' => $rate['id'] ) );
+ $this->assertNotSame( 'before-delete', get_transient( 'shipping-transient-version' ), 'A delete should refresh saved shipping rates.' );
+ }
+
+ /**
+ * @testdox Should report an error, not the deleted rate, when the rate row is not removed.
+ */
+ public function test_delete_reports_a_rate_row_that_was_not_removed(): void {
+ global $wpdb;
+
+ $rate = $this->create_rate( array( 'rate' => '19' ) );
+ $rates_delete = "DELETE FROM {$wpdb->prefix}woocommerce_tax_rates WHERE ";
+ add_filter(
+ 'query',
+ static function ( $query ) use ( $rates_delete ) {
+ return str_replace( $rates_delete, $rates_delete . '1 = 0 AND ', $query );
+ }
+ );
+
+ $result = $this->run_ability( 'woocommerce/tax-rate-delete', array( 'id' => $rate['id'] ) );
+
+ $this->assertWPError( $result );
+ $this->assertSame( 'woocommerce_ability_tax_rate_delete_failed', $result->get_error_code() );
+ $this->assertSame( 500, $result->get_error_data()['status'] );
+ }
+
+ /**
+ * @testdox Should report an error when the check for the rate row fails, and still make carts recalculate shipping taxes.
+ */
+ public function test_delete_reports_a_failed_check_of_the_rate_row(): void {
+ global $wpdb;
+
+ $rate = $this->create_rate( array( 'rate' => '19' ) );
+ $rates_table = "{$wpdb->prefix}woocommerce_tax_rates";
+ $hook_ran = false;
+ add_action(
+ 'woocommerce_tax_rate_deleted',
+ static function () use ( &$hook_ran ) {
+ $hook_ran = true;
+ }
+ );
+ add_filter(
+ 'query',
+ static function ( $query ) use ( &$hook_ran, $rates_table ) {
+ if ( $hook_ran && false !== strpos( $query, "FROM {$rates_table}" ) ) {
+ return 'SELECT * FROM no_such_table_for_the_check';
+ }
+ return $query;
+ }
+ );
+ set_transient( 'shipping-transient-version', 'before-delete' );
+
+ $suppressed = $wpdb->suppress_errors( true );
+ try {
+ $result = $this->run_ability( 'woocommerce/tax-rate-delete', array( 'id' => $rate['id'] ) );
+ } finally {
+ $wpdb->suppress_errors( $suppressed );
+ }
+
+ $this->assertWPError( $result );
+ $this->assertSame( 'woocommerce_ability_tax_rate_delete_failed', $result->get_error_code() );
+ $this->assertNotSame( 'before-delete', get_transient( 'shipping-transient-version' ), 'Saved shipping rates should be refreshed even when the check fails.' );
+ }
+
+ /**
+ * @testdox Should report a delete as done when a deleted-hook callback runs a query of its own.
+ */
+ public function test_delete_succeeds_when_the_deleted_hook_runs_a_query(): void {
+ global $wpdb;
+
+ $rate = $this->create_rate( array( 'rate' => '19' ) );
+ add_action(
+ 'woocommerce_tax_rate_deleted',
+ static function () use ( $wpdb ) {
+ $wpdb->get_var( 'SELECT 1' );
+ }
+ );
+
+ $result = $this->run_ability( 'woocommerce/tax-rate-delete', array( 'id' => $rate['id'] ) );
+
+ $this->assertSame( array( 'rate' => $rate ), $result );
+ }
+
+ /**
+ * @testdox Should let a shop manager create, update and delete rates.
+ */
+ public function test_shop_manager_can_write(): void {
+ wp_set_current_user( self::factory()->user->create( array( 'role' => 'shop_manager' ) ) );
+
+ $rate = $this->create_rate( array( 'rate' => '19' ) );
+ $this->assertNotWPError(
+ $this->run_ability(
+ 'woocommerce/tax-rate-update',
+ array(
+ 'id' => $rate['id'],
+ 'rate' => '7',
+ )
+ )
+ );
+ $this->assertNotWPError( $this->run_ability( 'woocommerce/tax-rate-delete', array( 'id' => $rate['id'] ) ) );
+ }
+
+ /**
+ * @testdox Should refuse tax rate writes to a customer.
+ */
+ public function test_customer_is_refused(): void {
+ $rate_id = \WC_Tax::_insert_tax_rate(
+ array(
+ 'tax_rate' => '19.0000',
+ 'tax_rate_order' => 0,
+ )
+ );
+ wp_set_current_user( self::factory()->user->create( array( 'role' => 'customer' ) ) );
+
+ $results = array(
+ $this->run_ability( 'woocommerce/tax-rate-create', array( 'rate' => '7' ) ),
+ $this->run_ability(
+ 'woocommerce/tax-rate-update',
+ array(
+ 'id' => $rate_id,
+ 'rate' => '7',
+ )
+ ),
+ $this->run_ability( 'woocommerce/tax-rate-delete', array( 'id' => $rate_id ) ),
+ );
+
+ foreach ( $results as $result ) {
+ $this->assertWPError( $result );
+ $this->assertSame( 'ability_invalid_permissions', $result->get_error_code() );
+ }
+ $this->assertSame( '19.0000', \WC_Tax::_get_tax_rate( $rate_id )['tax_rate'], 'The rate should not change.' );
+ }
+}