Commit 0494549f197 for woocommerce
commit 0494549f197288ef84df7e49f13acce4c8505300
Author: Luis Felipe Zaguini <26530524+zaguiini@users.noreply.github.com>
Date: Thu Nov 19 14:22:21 2026 -0300
Let product-update change products to and from variable types (#71077)
* Let product-update turn a non-variable product into a variable one
The guard refused every type change into or out of a variable product, but
only the change out of one loses data: WooCommerce deletes the variations of
a variable product that changes type. Any product that is not variable and
not a variation can now become a variable product, with its attributes and
variations in the same call, and it keeps its ID. Variable products and
variations still cannot change their type, and no product can become a
variation.
After the change the product runs the same sync as a variable product with
new variations, so the old price meta and the meta lookup price of the
simple product do not stay in force. The old sale dates are cleared, as the
REST API does for a variable product.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
* Let the product abilities set the stock of a variable product
A variable product can track stock for the variations that do not track
their own, but the abilities refused manage_stock and stock_quantity on it.
So an agent could not change that stock, and after a product became variable
its old stock stayed in force. Both fields are now accepted on create and
update. stock_status stays refused, because WooCommerce computes it from the
quantity or from the variations on every save.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
* Let product-update change a variable product into another type
The REST API and the product screen let a variable product change type,
and WooCommerce then deletes its variations. product-update now allows it
too, and treats the deletion like a variations item with delete: the call
needs the delete permission, the validators see each variation with
deleting set, the syncs get them as deleted, and a failed save rolls the
delete back.
The ability asks the same filter as WooCommerce,
woocommerce_delete_variations_on_product_type_change, to know whether the
change deletes the variations. When the filter keeps them, the new type
must be variable, otherwise the variations would stay without a variable
parent. A variation still cannot change its type, and no product can
become a variation.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
* Delete the variations of any variable type that becomes non-variable
WooCommerce deletes the variations only when the old type is exactly
variable and its filter agrees. A product of another variable class, such
as variable-subscription, that became simple kept its variations without
a variable parent, so the ability refused that change. Now the ability
decides by class: a product of a variable class that becomes a product of
a class that is not variable always loses its variations. When WooCommerce
does not delete them in the save, the ability deletes them after the save
with the same data store call. The list of variations to delete now uses
the same query, so trashed variations are reported to validators and syncs
too.
A rolled back type change left the old type in the product type cache, so
the rollback cleanup now clears that cache too.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
* Drop the variation prices when a variable product changes type
A variable product that became simple or external kept one _price row per
old variation price, and the price lookup table kept the old minimum and
maximum, because WooCommerce does not refresh the lookup row for a type
change. So a product without a price still showed in the price filter
and in price sorting. After the variations are deleted, the ability now
keeps one _price row with the price of the new product and refreshes the
lookup row. A grouped product already gets its price from its children.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
* Check type changes that delete variations with the same data as WooCommerce
- Pass the product with its new class to
woocommerce_delete_variations_on_product_type_change, as WooCommerce
does in the save. A filter that looks at the product class could answer
differently for the ability and for WooCommerce before.
- In the permission check, read the type only when it is a string, and
use the product that the ID names. A variation ID no longer asks for
the delete permission of its parent, and a bad type no longer throws.
- Load the variations to delete with primed caches, and refuse the call
when one cannot be loaded, so the validators see every variation that
is deleted.
- Refuse the call with 409 when the variations changed between the
validators and the save, so no variation is deleted without a check.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
* Refuse a type change when other fields change the variation delete decision
Between two variable types, the woocommerce_delete_variations_on_product_type_change
filter decides whether the variations are deleted. The ability asked it
before the call changed the other fields, and WooCommerce asks it again in
the save with the changed product. A filter that reads such a field could
then delete variations that skipped the delete permission and the
validators. The save now asks the filter again with the changed product
and refuses the call when the answer differs. The lookup test now checks
each price on its own.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
* Sync grouped prices from the children when a variable product becomes grouped
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Let the checked decision control variation deletes on a type change
A type change now saves without the WooCommerce handler that deletes
variations. The ability deletes only the variations that the permission
check and the validators saw, and refuses the call when a save hook
added or removed one.
Also drop the cached lookup row on a rollback, give the syncs the new
price of a product that becomes grouped, and check edit access before
the permission callback loads the product.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Check the saved variation ID after deleting it on a type change
delete( true ) resets the variation ID to 0, so the check after the
delete looked up post 0 and never saw a refused delete. The type change
then reported success while the variation stayed in the database.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
diff --git a/plugins/woocommerce/changelog/wooai-1669-simple-to-variable-product-update b/plugins/woocommerce/changelog/wooai-1669-simple-to-variable-product-update
new file mode 100644
index 00000000000..37d3032554c
--- /dev/null
+++ b/plugins/woocommerce/changelog/wooai-1669-simple-to-variable-product-update
@@ -0,0 +1,4 @@
+Significance: minor
+Type: add
+
+Let the product-update ability change a product into a variable product and back, keeping its ID. A variable product loses its variations.
diff --git a/plugins/woocommerce/changelog/wooai-1669-variable-product-stock-fields b/plugins/woocommerce/changelog/wooai-1669-variable-product-stock-fields
new file mode 100644
index 00000000000..110053f54ed
--- /dev/null
+++ b/plugins/woocommerce/changelog/wooai-1669-variable-product-stock-fields
@@ -0,0 +1,4 @@
+Significance: minor
+Type: add
+
+Let the product abilities set the stock of a variable product, which its variations use when they do not track their own stock.
diff --git a/plugins/woocommerce/src/Abilities/ActionableAbility.php b/plugins/woocommerce/src/Abilities/ActionableAbility.php
index 05f2ce7b3b6..2c181da6477 100644
--- a/plugins/woocommerce/src/Abilities/ActionableAbility.php
+++ b/plugins/woocommerce/src/Abilities/ActionableAbility.php
@@ -352,8 +352,8 @@ abstract class ActionableAbility extends Ability {
/**
* Drop the object caches of the objects a rolled back save() touched. The
* saves filled the caches with rows the rollback removed, so a read in the
- * same request would still see them. The `WC_Data` meta cache and the
- * product instance cache are separate from the post cache.
+ * same request would still see them. The `WC_Data` meta cache, the product type cache, the
+ * product instance cache and the price lookup cache are separate from the post cache.
*
* @param array<int, array{0: \WC_Data, 1: array, 2: string}> $objects The primary object and the secondary objects.
* @param \WC_Data[] $deleted The objects the call deleted.
@@ -367,10 +367,13 @@ abstract class ActionableAbility extends Ability {
}
if ( $id > 0 && $object instanceof \WC_Product ) {
clean_post_cache( $id );
+ wp_cache_delete( 'lookup_table', 'object_' . $id );
+ \WC_Cache_Helper::invalidate_cache_group( 'product_' . $id );
wc_delete_product_transients( $id );
$product_cache->remove( $id );
if ( $object->get_parent_id() > 0 ) {
clean_post_cache( $object->get_parent_id() );
+ wp_cache_delete( 'lookup_table', 'object_' . $object->get_parent_id() );
wc_delete_product_transients( $object->get_parent_id() );
$product_cache->remove( $object->get_parent_id() );
}
diff --git a/plugins/woocommerce/src/Internal/Abilities/Domain/ProductUpdate.php b/plugins/woocommerce/src/Internal/Abilities/Domain/ProductUpdate.php
index 472edcbf5db..b58529e3cd5 100644
--- a/plugins/woocommerce/src/Internal/Abilities/Domain/ProductUpdate.php
+++ b/plugins/woocommerce/src/Internal/Abilities/Domain/ProductUpdate.php
@@ -8,6 +8,8 @@ declare( strict_types=1 );
namespace Automattic\WooCommerce\Internal\Abilities\Domain;
use Automattic\WooCommerce\Abilities\ActionableAbility;
+use Automattic\WooCommerce\Enums\ProductStatus;
+use Automattic\WooCommerce\Enums\ProductType;
use Automattic\WooCommerce\Internal\Abilities\Domain\Traits\DomainAbilityHelpers;
use Automattic\WooCommerce\Internal\Abilities\Domain\Traits\ProductAbilityTrait;
use Automattic\WooCommerce\Internal\Abilities\Domain\Traits\ProductFieldRefusalsTrait;
@@ -87,12 +89,15 @@ class ProductUpdate extends ActionableAbility {
* @return \WC_Product|\WP_Error
*/
protected function load( array $input ) {
- $this->variations = array(
+ $this->variations = array(
'save' => array(),
'delete' => array(),
);
- $this->deleted = array();
- $this->parent = null;
+ $this->deleted = array();
+ $this->parent = null;
+ $this->changes_type = false;
+ $this->type_deletes = false;
+ $this->variable_old = '';
$product = self::get_product_from_input( $input );
@@ -114,16 +119,36 @@ class ProductUpdate extends ActionableAbility {
}
if ( isset( $input['type'] ) && $input['type'] !== $product->get_type() ) {
- $is_variable = static function ( $class_or_object ): bool {
- return is_a( $class_or_object, \WC_Product_Variable::class, true ) || is_a( $class_or_object, \WC_Product_Variation::class, true );
- };
- if ( $is_variable( \WC_Product_Factory::get_product_classname( $product->get_id(), $input['type'] ) ) || $is_variable( $product ) ) {
+ $target_class = \WC_Product_Factory::get_product_classname( $product->get_id(), $input['type'] );
+ if ( $product instanceof \WC_Product_Variation || is_a( $target_class, \WC_Product_Variation::class, true ) ) {
return new \WP_Error(
'woocommerce_product_type_unsupported',
- __( 'A product cannot change into or out of a variable product or a variation through this ability. WooCommerce would delete its variations.', 'woocommerce' ),
+ __( 'A variation cannot change its type, and a product cannot become a variation.', 'woocommerce' ),
array( 'status' => 400 )
);
}
+ $this->type_deletes = self::type_change_deletes_variations( $product, $input['type'] );
+ $this->variable_old = $product instanceof \WC_Product_Variable ? $product->get_type() : '';
+ if ( $this->type_deletes && isset( $input['variations'] ) ) {
+ return new \WP_Error(
+ 'woocommerce_product_type_unsupported',
+ __( 'This type change deletes every variation of the product, so the call cannot also send variations.', 'woocommerce' ),
+ array( 'status' => 400 )
+ );
+ }
+ if ( $this->type_deletes ) {
+ $children = self::get_variation_ids( $product->get_id() );
+ _prime_post_caches( $children );
+ $this->variations['delete'] = array_values( array_filter( array_map( 'wc_get_product', $children ), static fn( $child ) => $child instanceof \WC_Product_Variation ) );
+ if ( count( $this->variations['delete'] ) !== count( $children ) ) {
+ return new \WP_Error(
+ 'woocommerce_product_type_unsupported',
+ __( 'A variation of this product cannot be loaded, so the ability cannot check it before it deletes it.', 'woocommerce' ),
+ array( 'status' => 400 )
+ );
+ }
+ }
+ $this->changes_type = true;
return self::get_product_object_for_type( $input['type'], $product->get_id() );
}
@@ -187,7 +212,28 @@ class ProductUpdate extends ActionableAbility {
private ?\WC_Product_Variable $parent = null;
/**
- * The variations that the `variations` input marked for deletion.
+ * Whether the input changes the product type.
+ *
+ * @var bool
+ */
+ private bool $changes_type = false;
+
+ /**
+ * Whether the type change deletes the variations of the product.
+ *
+ * @var bool
+ */
+ private bool $type_deletes = false;
+
+ /**
+ * The old type of a variable product whose type the input changes, else an empty string.
+ *
+ * @var string
+ */
+ private string $variable_old = '';
+
+ /**
+ * The variations that the `variations` input or the type change deleted.
*
* @return \WC_Product_Variation[]
*/
@@ -196,7 +242,7 @@ class ProductUpdate extends ActionableAbility {
}
/**
- * The variations that the `variations` input marked for deletion, for the validators.
+ * The variations that the `variations` input or the type change will delete, for the validators.
*
* @return \WC_Product_Variation[]
*/
@@ -205,20 +251,64 @@ class ProductUpdate extends ActionableAbility {
}
/**
- * Save the product, then the variations that the input names.
+ * Save the product, then the variations that the input names. A type change
+ * saves without the WooCommerce handler that deletes variations, so the
+ * decision that the permission check and the validators saw is the one that
+ * runs. When it deletes, the ability deletes only the checked variations,
+ * and refuses the call when the save hooks added or removed one.
*
* @param \WC_Product $subject Changed product.
* @return null|\WP_Error
*/
protected function save( $subject ) {
- $error = self::save_product( $subject, 'woocommerce_product_update_failed' );
+ $this->deleted = array_map( static fn( \WC_Product_Variation $variation ) => clone $variation, $this->variations['delete'] );
+
+ if ( '' !== $this->variable_old && $subject instanceof \WC_Product_Variable && self::filter_deletes_variations( $subject, $this->variable_old ) !== $this->type_deletes ) {
+ return new \WP_Error(
+ 'woocommerce_product_type_unsupported',
+ __( 'The other fields of this call change whether the type change deletes the variations. Change the type in a call of its own.', 'woocommerce' ),
+ array( 'status' => 400 )
+ );
+ }
+
+ $error = $this->get_changed_variations_error( $subject->get_id() );
+ if ( null !== $error ) {
+ return $error;
+ }
+
+ $error = $this->changes_type ? self::save_product_keeping_variations( $subject ) : self::save_product( $subject, 'woocommerce_product_update_failed' );
if ( is_wp_error( $error ) ) {
return $error;
}
+ if ( $this->type_deletes ) {
+ $error = $this->get_changed_variations_error( $subject->get_id() );
+ if ( null !== $error ) {
+ return $error;
+ }
+ foreach ( $this->variations['delete'] as $variation ) {
+ $variation_id = $variation->get_id();
+ if ( ! $variation->delete( true ) || null !== get_post( $variation_id ) ) {
+ return new \WP_Error( 'woocommerce_product_update_failed', __( 'Failed to delete a variation.', 'woocommerce' ), array( 'status' => 500 ) );
+ }
+ }
+ $this->variations['delete'] = array();
+ if ( $subject instanceof \WC_Product_Grouped ) {
+ $subject->get_data_store()->sync_price( $subject ); // @phpstan-ignore method.notFound (WC_Data_Store forwards the call to the grouped product data store)
+ $subject->set_price( (string) get_post_meta( $subject->get_id(), '_price', true ) );
+ } elseif ( ! $subject instanceof \WC_Product_Variable ) {
+ delete_post_meta( $subject->get_id(), '_price' );
+ add_post_meta( $subject->get_id(), '_price', $subject->get_price( 'edit' ) );
+ $subject->get_data_store()->refresh_product_lookup_table( $subject->get_id() ); // @phpstan-ignore method.notFound (WC_Data_Store forwards the call to the product data store)
+ }
+ }
+
if ( $subject instanceof \WC_Product_Variable ) {
- $this->deleted = array_map( static fn( \WC_Product_Variation $variation ) => clone $variation, $this->variations['delete'] );
- return self::save_variations( $subject, $this->variations, 'woocommerce_product_update_failed' );
+ $error = self::save_variations( $subject, $this->variations, 'woocommerce_product_update_failed' );
+ if ( null === $error && $this->changes_type && empty( $this->variations['save'] ) && empty( $this->variations['delete'] ) ) {
+ self::sync_variable_parent( $subject );
+ }
+ return $error;
}
if ( null !== $this->parent ) {
@@ -228,6 +318,50 @@ class ProductUpdate extends ActionableAbility {
return null;
}
+ /**
+ * A conflict error when the variations of a product differ from the ones
+ * that the type change deletes, else null.
+ *
+ * @param int $product_id Product ID.
+ * @return \WP_Error|null
+ */
+ private function get_changed_variations_error( int $product_id ): ?\WP_Error {
+ if ( ! $this->type_deletes ) {
+ return null;
+ }
+ $planned = array_map( static fn( \WC_Product_Variation $variation ) => $variation->get_id(), $this->variations['delete'] );
+ $current = self::get_variation_ids( $product_id );
+ sort( $planned );
+ sort( $current );
+ if ( $planned === $current ) {
+ return null;
+ }
+
+ return new \WP_Error( 'woocommerce_product_update_conflict', __( 'The variations of the product changed during the call. Try again.', 'woocommerce' ), array( 'status' => 409 ) );
+ }
+
+ /**
+ * Save a product whose type changes without the WooCommerce handler that
+ * deletes the variations in the save. The ability deletes them itself.
+ *
+ * @param \WC_Product $product Changed product.
+ * @return null|\WP_Error
+ */
+ private static function save_product_keeping_variations( \WC_Product $product ) {
+ $handler = array( \WC_Post_Data::class, 'product_type_changed' );
+ $priority = has_action( 'woocommerce_product_type_changed', $handler );
+ if ( false !== $priority ) {
+ remove_action( 'woocommerce_product_type_changed', $handler, $priority );
+ }
+ try {
+ return self::save_product( $product, 'woocommerce_product_update_failed' );
+ } finally {
+ if ( false !== $priority ) {
+ add_action( 'woocommerce_product_type_changed', $handler, $priority, 3 );
+ }
+ }
+ }
+
/**
* The ability output for the saved product.
*
@@ -248,10 +382,89 @@ class ProductUpdate extends ActionableAbility {
*/
public static function can_update_product( $input = array() ): bool {
$product_id = self::get_id_from_input( $input );
- $deletes = ! empty( array_filter( array_column( $input['variations'] ?? array(), 'delete' ) ) );
+ if ( ! self::check_product_permission( $product_id, 'edit' ) ) {
+ return false;
+ }
+ $product = is_string( $input['type'] ?? null ) ? wc_get_product( $product_id ) : null;
+ $deletes = ! empty( array_filter( array_column( $input['variations'] ?? array(), 'delete' ) ) )
+ || ( $product instanceof \WC_Product && self::type_change_deletes_variations( $product, $input['type'] ) );
- return self::check_product_permission( $product_id, 'edit' )
- && ( ! $deletes || self::check_product_permission( $product_id, 'delete' ) );
+ return ! $deletes || self::check_product_permission( $product_id, 'delete' );
+ }
+
+ /**
+ * Whether a type change deletes the variations of a product. A product of
+ * a variable class that becomes a product of a class that is not variable
+ * always loses its variations. Here the ability differs from WooCommerce on
+ * purpose: WooCommerce keeps them when the old type is not exactly
+ * `variable` or when the filter returns false, and they stay without a
+ * variable parent. Between two variable classes the filter decides. It gets
+ * the product with its new class, as WooCommerce passes it in the save.
+ *
+ * @param \WC_Product $product Product before the change.
+ * @param string $type New product type.
+ * @return bool
+ */
+ private static function type_change_deletes_variations( \WC_Product $product, string $type ): bool {
+ $from = $product->get_type();
+ if ( ! $product instanceof \WC_Product_Variable || $type === $from || is_a( \WC_Product_Factory::get_product_classname( $product->get_id(), $type ), \WC_Product_Variation::class, true ) ) {
+ return false;
+ }
+ $target = self::get_product_object_for_type( $type, $product->get_id() );
+ if ( is_wp_error( $target ) ) {
+ return false;
+ }
+ if ( ! $target instanceof \WC_Product_Variable ) {
+ return true;
+ }
+
+ return self::filter_deletes_variations( $target, $from );
+ }
+
+ /**
+ * Whether the WooCommerce filter deletes the variations of a variable
+ * product that changes into another variable type. The save asks again
+ * with the changed product, to refuse a call whose other fields change the answer.
+ *
+ * @param \WC_Product $target Product with its new type.
+ * @param string $from Old product type.
+ * @return bool
+ */
+ private static function filter_deletes_variations( \WC_Product $target, string $from ): bool {
+ $type = $target->get_type();
+
+ /**
+ * Filter whether WooCommerce deletes the variations of a variable product when its type changes.
+ *
+ * @since 5.0.0
+ *
+ * @param bool $delete Whether to delete the variations.
+ * @param \WC_Product $product Product with its new type.
+ * @param string $from Old product type.
+ * @param string $to New product type.
+ */
+ return (bool) apply_filters( 'woocommerce_delete_variations_on_product_type_change', ProductType::VARIABLE === $from && ProductType::VARIABLE !== $type, $target, $from, $type );
+ }
+
+ /**
+ * The IDs of every variation of a product, with the query that the
+ * variable product data store uses to delete them, trashed ones included.
+ *
+ * @param int $product_id Product ID.
+ * @return int[]
+ */
+ private static function get_variation_ids( int $product_id ): array {
+ return wp_parse_id_list(
+ get_posts(
+ array(
+ 'post_parent' => $product_id,
+ 'post_type' => 'product_variation',
+ 'fields' => 'ids',
+ 'post_status' => array( 'any', ProductStatus::TRASH, ProductStatus::AUTO_DRAFT ),
+ 'numberposts' => -1,
+ )
+ )
+ );
}
/**
diff --git a/plugins/woocommerce/src/Internal/Abilities/Domain/Traits/ProductAbilityTrait.php b/plugins/woocommerce/src/Internal/Abilities/Domain/Traits/ProductAbilityTrait.php
index 90fbd757bc1..410a8e3e730 100644
--- a/plugins/woocommerce/src/Internal/Abilities/Domain/Traits/ProductAbilityTrait.php
+++ b/plugins/woocommerce/src/Internal/Abilities/Domain/Traits/ProductAbilityTrait.php
@@ -64,6 +64,8 @@ trait ProductAbilityTrait {
if ( $creating ) {
$type_schema['default'] = ProductType::SIMPLE;
$type_schema['description'] .= ' ' . __( 'A product without a type is simple.', 'woocommerce' );
+ } else {
+ $type_schema['description'] .= ' ' . __( 'Changing the type of a variable product deletes all its variations for good. Only a change between two variable types can keep them, when the extension that owns one of the types says so. A variation cannot change its type.', 'woocommerce' );
}
$properties = $creating ? array() : array(
@@ -323,7 +325,10 @@ trait ProductAbilityTrait {
'type' => 'boolean',
'description' => __( 'Whether the product gives the customer files to download.', 'woocommerce' ),
),
- 'manage_stock' => array( 'type' => 'boolean' ),
+ 'manage_stock' => array(
+ 'type' => 'boolean',
+ 'description' => __( 'Whether the product tracks its stock quantity. On a variable product, a variation that does not track its own stock uses the stock of the product.', 'woocommerce' ),
+ ),
'stock_quantity' => array(
'type' => self::get_product_stock_quantity_schema_type(),
'description' => __( 'Available stock quantity when product-level stock management is used.', 'woocommerce' ),
@@ -517,7 +522,11 @@ trait ProductAbilityTrait {
$fields = array_values( array_diff( $fields, array( 'attributes' ) ) );
}
} elseif ( is_a( $classname, \WC_Product_Variable::class, true ) ) {
- $fields = array_merge( $fields, array( 'attributes', 'variations', 'tax_status', 'sold_individually', 'weight', 'dimensions', 'shipping_class' ) );
+ $fields = array_merge( $fields, array( 'attributes', 'variations', 'tax_status', 'sold_individually', 'weight', 'dimensions', 'shipping_class', 'manage_stock', 'stock_quantity' ) );
+ $product_props = array(
+ 'date_on_sale_from' => null,
+ 'date_on_sale_to' => null,
+ );
} elseif ( is_a( $classname, \WC_Product_External::class, true ) ) {
$fields = array_merge( $fields, $price_fields, array( 'external_url', 'button_text' ) );
$product_props = array(
@@ -1455,11 +1464,13 @@ trait ProductAbilityTrait {
*/
protected static function apply_product_type_config( \WC_Product $product, array $product_config ): void {
$prop_setters = array(
- 'virtual' => 'set_virtual',
- 'downloadable' => 'set_downloadable',
- 'manage_stock' => 'set_manage_stock',
- 'stock_quantity' => 'set_stock_quantity',
- 'stock_status' => 'set_stock_status',
+ 'virtual' => 'set_virtual',
+ 'downloadable' => 'set_downloadable',
+ 'manage_stock' => 'set_manage_stock',
+ 'stock_quantity' => 'set_stock_quantity',
+ 'stock_status' => 'set_stock_status',
+ 'date_on_sale_from' => 'set_date_on_sale_from',
+ 'date_on_sale_to' => 'set_date_on_sale_to',
);
foreach ( $product_config['product_props'] as $prop => $value ) {
diff --git a/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/ProductWritesTest.php b/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/ProductWritesTest.php
index 49c74af581c..efe31a5f3fe 100644
--- a/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/ProductWritesTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/ProductWritesTest.php
@@ -4,6 +4,7 @@ declare( strict_types = 1 );
namespace Automattic\WooCommerce\Tests\Internal\Abilities\Domain;
use Automattic\WooCommerce\Enums\ProductTaxStatus;
+use Automattic\WooCommerce\Internal\Abilities\Domain\ProductUpdate;
use WC_Helper_Product;
use WC_Unit_Test_Case;
@@ -414,6 +415,474 @@ class ProductWritesTest extends WC_Unit_Test_Case {
$this->assertSame( 'woocommerce_product_variation_global_unique_id_duplicate', $mixed_case->get_error_code() );
}
+ /**
+ * @testdox Should turn a simple product into a variable one with global attributes and priced variations, and keep its ID.
+ */
+ public function test_update_turns_a_simple_product_into_a_variable_one(): void {
+ $product = WC_Helper_Product::create_simple_product( true, array( 'sku' => 'tee' ) );
+ $size = WC_Helper_Product::create_attribute( 'size', array( 'small', 'large' ) );
+ $color = WC_Helper_Product::create_attribute( 'color', array( 'red', 'blue' ) );
+ $items = array();
+ $prices = array( '11.00', '12.00', '13.00', '14.00' );
+ foreach ( array( 'small', 'large' ) as $size_slug ) {
+ foreach ( array( 'red', 'blue' ) as $color_slug ) {
+ $items[] = array(
+ 'attributes' => array(
+ array(
+ 'id' => $size['attribute_id'],
+ 'option' => $size_slug,
+ ),
+ array(
+ 'id' => $color['attribute_id'],
+ 'option' => $color_slug,
+ ),
+ ),
+ 'regular_price' => $prices[ count( $items ) ],
+ );
+ }
+ }
+
+ $updated = $this->execute(
+ 'woocommerce/product-update',
+ array(
+ 'id' => $product->get_id(),
+ 'type' => 'variable',
+ 'attributes' => array(
+ array(
+ 'id' => $size['attribute_id'],
+ 'options' => array( 'small', 'large' ),
+ ),
+ array(
+ 'id' => $color['attribute_id'],
+ 'options' => array( 'red', 'blue' ),
+ ),
+ ),
+ 'variations' => $items,
+ )
+ )['product'];
+
+ $this->assertSame( $product->get_id(), $updated['id'] );
+ $this->assertSame( 'variable', $updated['type'] );
+ $this->assertCount( 4, $updated['variation_ids'] );
+ $this->assertSame( 'tee', $updated['sku'] );
+
+ $variable = wc_get_product( $product->get_id() );
+ $this->assertInstanceOf( \WC_Product_Variable::class, $variable );
+ $this->assertSame( array( '11.00', '12.00', '13.00', '14.00' ), array_values( $variable->get_variation_prices()['regular_price'] ) );
+ $this->assertSame( '', get_post_meta( $product->get_id(), '_regular_price', true ), 'The old price of the simple product should be gone.' );
+ $this->assertSame( array( '11.00', '12.00', '13.00', '14.00' ), get_post_meta( $product->get_id(), '_price', false ) );
+ }
+
+ /**
+ * @testdox Should turn a $source product into a variable one with a variation, and keep its ID.
+ *
+ * @testWith ["grouped"]
+ * ["external"]
+ *
+ * @param string $source Product type before the change.
+ */
+ public function test_update_turns_a_grouped_or_external_product_into_a_variable_one( string $source ): void {
+ $product = 'grouped' === $source ? WC_Helper_Product::create_grouped_product() : WC_Helper_Product::create_external_product();
+
+ $updated = $this->execute(
+ 'woocommerce/product-update',
+ array(
+ 'id' => $product->get_id(),
+ 'type' => 'variable',
+ 'attributes' => array(
+ array(
+ 'name' => 'Size',
+ 'options' => array( 'S', 'M' ),
+ ),
+ ),
+ 'variations' => array(
+ array(
+ 'attributes' => array(
+ array(
+ 'name' => 'Size',
+ 'option' => 'S',
+ ),
+ ),
+ 'regular_price' => '20',
+ ),
+ ),
+ )
+ )['product'];
+
+ $this->assertSame( $product->get_id(), $updated['id'] );
+ $this->assertSame( 'variable', $updated['type'] );
+ $this->assertCount( 1, $updated['variation_ids'] );
+ $this->assertSame( array( '20' ), get_post_meta( $product->get_id(), '_price', false ) );
+ }
+
+ /**
+ * @testdox Should clear the old price and sale dates when a simple product becomes variable without variations.
+ */
+ public function test_update_to_variable_without_variations_clears_the_old_price(): void {
+ global $wpdb;
+
+ $product = WC_Helper_Product::create_simple_product(
+ true,
+ array(
+ 'regular_price' => '10',
+ 'sale_price' => '8',
+ 'date_on_sale_from' => '2020-01-01',
+ 'date_on_sale_to' => '2040-01-01',
+ )
+ );
+
+ $updated = $this->execute(
+ 'woocommerce/product-update',
+ array(
+ 'id' => $product->get_id(),
+ 'type' => 'variable',
+ )
+ )['product'];
+
+ $this->assertSame( 'variable', $updated['type'] );
+ foreach ( array( '_price', '_regular_price', '_sale_price' ) as $meta_key ) {
+ $this->assertFalse( metadata_exists( 'post', $product->get_id(), $meta_key ), "$meta_key should be gone." );
+ }
+ $this->assertEmpty( get_post_meta( $product->get_id(), '_sale_price_dates_from', true ) );
+ $this->assertEmpty( get_post_meta( $product->get_id(), '_sale_price_dates_to', true ) );
+ $lookup = $wpdb->get_row( $wpdb->prepare( "SELECT min_price, max_price FROM {$wpdb->wc_product_meta_lookup} WHERE product_id = %d", $product->get_id() ), ARRAY_A );
+ $this->assertArrayHasKey( 'min_price', $lookup );
+ $this->assertArrayHasKey( 'max_price', $lookup );
+ $this->assertSame( '0.0000', $lookup['min_price'] );
+ $this->assertSame( '0.0000', $lookup['max_price'] );
+ }
+
+ /**
+ * @testdox Should turn a variable product into a simple one, keep its ID and delete its variations.
+ */
+ public function test_update_turns_a_variable_product_into_a_simple_one(): void {
+ $variable = WC_Helper_Product::create_variation_product();
+ $variations = $variable->get_children();
+
+ $updated = $this->execute(
+ 'woocommerce/product-update',
+ array(
+ 'id' => $variable->get_id(),
+ 'type' => 'simple',
+ 'regular_price' => '15',
+ )
+ );
+
+ $this->assertGreaterThanOrEqual( 2, count( $variations ) );
+ $this->assertSame( $variable->get_id(), $updated['product']['id'] );
+ $this->assertSame( 'simple', $updated['product']['type'] );
+ $this->assertSame( '15', $updated['product']['regular_price'] );
+ $this->assertSame( array(), $updated['product']['variation_ids'] );
+ $this->assertSame( array(), $updated['variations'] );
+ foreach ( $variations as $variation_id ) {
+ $this->assertNull( get_post( $variation_id ), "Variation $variation_id should be deleted." );
+ }
+ }
+
+ /**
+ * @testdox Should drop the variation prices from the price lookup when a variable product becomes $type without a price.
+ *
+ * @testWith ["simple"]
+ * ["external"]
+ * ["grouped"]
+ *
+ * @param string $type New product type.
+ */
+ public function test_change_out_of_variable_drops_the_variation_prices( string $type ): void {
+ global $wpdb;
+
+ $items = array();
+ $prices = array(
+ 'S' => '11',
+ 'M' => '12',
+ );
+ foreach ( $prices as $option => $price ) {
+ $items[] = array(
+ 'attributes' => array(
+ array(
+ 'name' => 'Size',
+ 'option' => $option,
+ ),
+ ),
+ 'regular_price' => $price,
+ );
+ }
+ $created = $this->execute(
+ 'woocommerce/product-create',
+ array(
+ 'name' => 'Shirt',
+ 'type' => 'variable',
+ 'attributes' => array(
+ array(
+ 'name' => 'Size',
+ 'options' => array( 'S', 'M' ),
+ ),
+ ),
+ 'variations' => $items,
+ )
+ );
+ $variable = wc_get_product( $created['product']['id'] );
+
+ $this->execute(
+ 'woocommerce/product-update',
+ array(
+ 'id' => $variable->get_id(),
+ 'type' => $type,
+ )
+ );
+
+ $this->assertEmpty( array_filter( get_post_meta( $variable->get_id(), '_price', false ), 'strlen' ) );
+ $this->assertLessThanOrEqual( 1, count( get_post_meta( $variable->get_id(), '_price', false ) ) );
+ $lookup = $wpdb->get_row( $wpdb->prepare( "SELECT min_price, max_price FROM {$wpdb->wc_product_meta_lookup} WHERE product_id = %d", $variable->get_id() ), ARRAY_A );
+ $this->assertEmpty( (float) $lookup['min_price'] );
+ $this->assertEmpty( (float) $lookup['max_price'] );
+ }
+
+ /**
+ * @testdox Should take the grouped prices from the children when a grouped product goes to variable and back.
+ */
+ public function test_grouped_to_variable_and_back_syncs_the_grouped_prices(): void {
+ global $wpdb;
+
+ $grouped = WC_Helper_Product::create_grouped_product();
+ $prices = array_map( static fn( int $id ) => (float) wc_get_product( $id )->get_price(), $grouped->get_children() );
+
+ $this->execute(
+ 'woocommerce/product-update',
+ array(
+ 'id' => $grouped->get_id(),
+ 'type' => 'variable',
+ 'attributes' => array(
+ array(
+ 'name' => 'Size',
+ 'options' => array( 'S' ),
+ ),
+ ),
+ 'variations' => array(
+ array(
+ 'attributes' => array(
+ array(
+ 'name' => 'Size',
+ 'option' => 'S',
+ ),
+ ),
+ 'regular_price' => '99',
+ ),
+ ),
+ )
+ );
+ $this->execute(
+ 'woocommerce/product-update',
+ array(
+ 'id' => $grouped->get_id(),
+ 'type' => 'grouped',
+ )
+ );
+
+ $lookup = $wpdb->get_row( $wpdb->prepare( "SELECT min_price, max_price FROM {$wpdb->wc_product_meta_lookup} WHERE product_id = %d", $grouped->get_id() ), ARRAY_A );
+ $this->assertSame( min( $prices ), (float) $lookup['min_price'] );
+ $this->assertSame( max( $prices ), (float) $lookup['max_price'] );
+ }
+
+ /**
+ * @testdox Should answer the permission check without an error for a variation ID or a type that is not a string.
+ */
+ public function test_permission_check_with_a_variation_id_or_a_bad_type(): void {
+ $variable = WC_Helper_Product::create_variation_product();
+ $variation = $variable->get_children()[0];
+ $deny = static fn( $caps, $cap ) => 'delete_post' === $cap ? array( 'do_not_allow' ) : $caps;
+
+ add_filter( 'map_meta_cap', $deny, 10, 2 );
+ $from_variation = ProductUpdate::can_update_product(
+ array(
+ 'id' => $variation,
+ 'type' => 'simple',
+ )
+ );
+ $bad_type = ProductUpdate::can_update_product(
+ array(
+ 'id' => $variable->get_id(),
+ 'type' => array( 'simple' ),
+ )
+ );
+ remove_filter( 'map_meta_cap', $deny, 10 );
+
+ $this->assertTrue( $from_variation, 'load() refuses the type change of a variation, so the check needs no delete permission.' );
+ $this->assertTrue( $bad_type, 'The schema refuses a type that is not a string.' );
+ }
+
+ /**
+ * @testdox Should require the delete permission for a type change that deletes variations.
+ */
+ public function test_type_change_that_deletes_variations_requires_the_delete_permission(): void {
+ $variable = WC_Helper_Product::create_variation_product();
+ $simple = WC_Helper_Product::create_simple_product();
+ $deny = static fn( $caps, $cap ) => 'delete_post' === $cap ? array( 'do_not_allow' ) : $caps;
+
+ add_filter( 'map_meta_cap', $deny, 10, 2 );
+ $refused = wp_get_ability( 'woocommerce/product-update' )->execute(
+ array(
+ 'id' => $variable->get_id(),
+ 'type' => 'simple',
+ )
+ );
+ $allowed = ProductUpdate::can_update_product(
+ array(
+ 'id' => $simple->get_id(),
+ 'type' => 'external',
+ )
+ );
+ remove_filter( 'map_meta_cap', $deny, 10 );
+
+ $this->assertWPError( $refused );
+ $this->assertSame( 'ability_invalid_permissions', $refused->get_error_code() );
+ $this->assertTrue( $allowed, 'A type change that deletes nothing needs only the edit permission.' );
+ $this->assertSame( 'variable', wc_get_product( $variable->get_id() )->get_type() );
+ $this->assertNotEmpty( wc_get_product( $variable->get_id() )->get_children() );
+ }
+
+ /**
+ * @testdox Should keep the variations when the save of a type change fails.
+ */
+ public function test_failed_type_change_keeps_the_variations(): void {
+ $variable = WC_Helper_Product::create_variation_product();
+ $variations = $variable->get_children();
+ $fail = static function () {
+ throw new \Exception( 'Save failed.' );
+ };
+
+ add_action( 'woocommerce_product_type_changed', $fail, 20 );
+ $failed = wp_get_ability( 'woocommerce/product-update' )->execute(
+ array(
+ 'id' => $variable->get_id(),
+ 'type' => 'simple',
+ )
+ );
+ remove_action( 'woocommerce_product_type_changed', $fail, 20 );
+
+ $this->assertWPError( $failed );
+ $this->assertSame( 'woocommerce_product_update_failed', $failed->get_error_code() );
+ $this->assertSame( 'variable', wc_get_product( $variable->get_id() )->get_type() );
+ foreach ( $variations as $variation_id ) {
+ $this->assertInstanceOf( \WC_Product_Variation::class, wc_get_product( $variation_id ) );
+ }
+ }
+
+ /**
+ * @testdox Should roll back a type change when WordPress refuses to delete a variation.
+ */
+ public function test_type_change_rolls_back_when_a_variation_delete_is_refused(): void {
+ $variable = WC_Helper_Product::create_variation_product();
+ $variations = $variable->get_children();
+ add_filter( 'pre_delete_post', '__return_false' );
+
+ $failed = wp_get_ability( 'woocommerce/product-update' )->execute(
+ array(
+ 'id' => $variable->get_id(),
+ 'type' => 'simple',
+ )
+ );
+
+ $this->assertWPError( $failed );
+ $this->assertSame( 'woocommerce_product_update_failed', $failed->get_error_code() );
+ $this->assertSame( 'variable', wc_get_product( $variable->get_id() )->get_type() );
+ $this->assertSame( $variations, wc_get_product( $variable->get_id() )->get_children() );
+ }
+
+ /**
+ * @testdox Should refuse a type change of a variation, variations sent with a change that deletes them, and a simple-product price on a variable product.
+ */
+ public function test_update_refuses_type_changes_that_cannot_work(): void {
+ $variable = WC_Helper_Product::create_variation_product();
+ $simple = WC_Helper_Product::create_simple_product();
+ $ability = wp_get_ability( 'woocommerce/product-update' );
+
+ $from_variation = $ability->execute(
+ array(
+ 'id' => $variable->get_children()[0],
+ 'type' => 'simple',
+ )
+ );
+ $with_items = $ability->execute(
+ array(
+ 'id' => $variable->get_id(),
+ 'type' => 'simple',
+ 'variations' => array( array( 'regular_price' => '1' ) ),
+ )
+ );
+ $price = $ability->execute(
+ array(
+ 'id' => $simple->get_id(),
+ 'type' => 'variable',
+ 'regular_price' => '20',
+ )
+ );
+
+ $this->assertSame( 'woocommerce_product_type_unsupported', $from_variation->get_error_code() );
+ $this->assertSame( 'woocommerce_product_type_unsupported', $with_items->get_error_code() );
+ $this->assertSame( 'woocommerce_product_field_unsupported', $price->get_error_code() );
+ $this->assertSame( 'simple', wc_get_product( $simple->get_id() )->get_type() );
+ $this->assertNotEmpty( wc_get_product( $variable->get_id() )->get_children() );
+ }
+
+ /**
+ * @testdox Should set the stock of a variable product, which its variations use, and refuse a stock status for it.
+ */
+ public function test_variable_product_stock_fields(): void {
+ $created = $this->execute(
+ 'woocommerce/product-create',
+ array(
+ 'name' => 'Shirt',
+ 'type' => 'variable',
+ 'manage_stock' => true,
+ 'stock_quantity' => 5,
+ 'attributes' => array(
+ array(
+ 'name' => 'Size',
+ 'options' => array( 'S' ),
+ ),
+ ),
+ 'variations' => array(
+ array(
+ 'attributes' => array(
+ array(
+ 'name' => 'Size',
+ 'option' => 'S',
+ ),
+ ),
+ 'regular_price' => '10',
+ ),
+ ),
+ )
+ )['product'];
+
+ $this->assertTrue( $created['manage_stock'] );
+ $this->assertSame( 5, $created['stock_quantity'] );
+
+ $updated = $this->execute(
+ 'woocommerce/product-update',
+ array(
+ 'id' => $created['id'],
+ 'stock_quantity' => 0,
+ )
+ )['product'];
+
+ $variation = wc_get_product( $created['variation_ids'][0] );
+ $this->assertSame( 0, $updated['stock_quantity'] );
+ $this->assertSame( 'outofstock', $updated['stock_status'] );
+ $this->assertSame( 0, $variation->get_stock_quantity(), 'A variation without its own stock uses the stock of the product.' );
+ $this->assertFalse( $variation->is_in_stock() );
+
+ $status = wp_get_ability( 'woocommerce/product-update' )->execute(
+ array(
+ 'id' => $created['id'],
+ 'stock_status' => 'instock',
+ )
+ );
+ $this->assertWPError( $status );
+ $this->assertSame( 'woocommerce_product_field_unsupported', $status->get_error_code() );
+ }
+
/**
* @testdox Should accept sale dates and the tax status on external products, but not sold individually.
*/
diff --git a/plugins/woocommerce/tests/php/src/Internal/AbilitiesApi/ExtensibleAbilitiesTest.php b/plugins/woocommerce/tests/php/src/Internal/AbilitiesApi/ExtensibleAbilitiesTest.php
index b57c52d435b..0edea741b86 100644
--- a/plugins/woocommerce/tests/php/src/Internal/AbilitiesApi/ExtensibleAbilitiesTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/AbilitiesApi/ExtensibleAbilitiesTest.php
@@ -3756,6 +3756,55 @@ class ExtensibleAbilitiesTest extends \WC_REST_Unit_Test_Case {
$this->assertNull( get_post( $other ) );
}
+ /**
+ * @testdox Should run validators on the variations that a type change deletes, and give them to the syncs as deleted.
+ */
+ public function test_a_type_change_reports_the_variations_it_deletes(): void {
+ $created = $this->run_ability( 'woocommerce/product-create', $this->get_shirt_input() );
+ $ids = $created['product']['variation_ids'];
+ $refuse = true;
+ $seen = array();
+ $deleted = array();
+ $this->register_validator(
+ 'product',
+ 'test-ext',
+ static function ( \WC_Product $product, ActionableAbility $ability, array $context ) use ( &$seen, &$refuse ) {
+ unset( $ability );
+ $seen[ $product->get_id() ] = $context['deleting'];
+ return $refuse && $context['deleting'] ? new \WP_Error( 'test_keep', 'Keep them.' ) : null;
+ }
+ );
+ $this->register_sync(
+ 'product',
+ 'test-ext',
+ static function ( array $saved, ActionableAbility $ability, array $context ) use ( &$deleted ) {
+ unset( $saved, $ability );
+ $deleted = array_map( static fn( \WC_Data $item ) => $item->get_id(), $context['deleted'] );
+ return null;
+ }
+ );
+ $this->reset_registries();
+ AbilitiesLoader::init_extensions();
+ $input = array(
+ 'id' => $created['product']['id'],
+ 'type' => 'simple',
+ );
+
+ $refused = $this->run_ability_response( 'woocommerce/product-update', $input );
+ $kept = wc_get_product( $created['product']['id'] )->get_children();
+ $refuse = false;
+ $changed = $this->run_ability( 'woocommerce/product-update', $input );
+
+ $this->assertSame( 400, $refused->get_status() );
+ $this->assertEqualsCanonicalizing( $ids, $kept );
+ $this->assertSame( 'simple', $changed['product']['type'] );
+ $this->assertTrue( $seen[ $ids[0] ] );
+ $this->assertTrue( $seen[ $ids[1] ] );
+ $this->assertFalse( $seen[ $created['product']['id'] ] );
+ $this->assertEqualsCanonicalizing( $ids, $deleted );
+ $this->assertNull( get_post( $ids[0] ) );
+ }
+
/**
* @testdox Should run validators on the variations of a deleted parent, and delete nothing when one refuses.
*/
@@ -4994,85 +5043,355 @@ class ExtensibleAbilitiesTest extends \WC_REST_Unit_Test_Case {
}
/**
- * @testdox Should refuse a type change into or out of a variable product type that an extension registers.
+ * @testdox Should change a simple product into a variable product type that an extension registers.
*/
- public function test_refuses_a_type_change_into_or_out_of_a_variable_subclass(): void {
+ public function test_a_simple_product_becomes_a_variable_subclass(): void {
$this->register_variation_subclass();
+ $simple = \WC_Helper_Product::create_simple_product();
+
+ $into = $this->run_ability(
+ 'woocommerce/product-update',
+ array(
+ 'id' => $simple->get_id(),
+ 'type' => 'test-variable',
+ )
+ );
+
+ $this->assertSame( 'test-variable', $into['product']['type'] );
+ $this->assertInstanceOf( TestVariableProduct::class, wc_get_product( $simple->get_id() ) );
+ }
+
+ /**
+ * @testdox Should delete every variation, trashed ones too, when a $type product of an extension becomes simple, with the delete permission and a rollback on refusal.
+ *
+ * @testWith ["test-variable"]
+ * ["test-plan"]
+ *
+ * @param string $type Variable product type that an extension registers.
+ */
+ public function test_a_variable_subclass_becomes_simple_and_loses_its_variations( string $type ): void {
+ $this->register_variation_subclass();
+ $plan_class = get_class(
+ new class() extends \WC_Product_Variable {
+ /**
+ * Get the product type.
+ *
+ * @return string
+ */
+ public function get_type() {
+ return 'test-plan';
+ }
+ }
+ );
+ $this->add_test_action( 'product_type_selector', static fn( array $types ): array => $types + array( 'test-plan' => 'Test plan' ) );
+ $this->add_test_action( 'woocommerce_data_stores', static fn( array $stores ): array => $stores + array( 'product-test-plan' => 'WC_Product_Variable_Data_Store_CPT' ) );
+ $this->add_test_action( 'woocommerce_product_class', static fn( $classname, $product_type ) => 'test-plan' === $product_type ? $plan_class : $classname, 10, 2 );
+ $refuse = false;
+ $deleted = array();
+ $this->register_sync(
+ 'product',
+ 'test-ext',
+ static function ( array $saved, ActionableAbility $ability, array $context ) use ( &$deleted, &$refuse ) {
+ unset( $saved, $ability );
+ $deleted = array_map( static fn( \WC_Data $item ) => $item->get_id(), $context['deleted'] );
+ return $refuse ? new \WP_Error( 'test_refused', 'Refused.' ) : null;
+ }
+ );
+ $this->reset_registries();
+ AbilitiesLoader::init_extensions();
$input = $this->get_shirt_input();
- $input['type'] = 'test-variable';
+ $input['type'] = $type;
$created = $this->run_ability( 'woocommerce/product-create', $input );
- $simple = \WC_Helper_Product::create_simple_product();
+ $id = $created['product']['id'];
+ $ids = $created['product']['variation_ids'];
+ wc_get_product( $ids[0] )->delete();
+ $change = array(
+ 'id' => $id,
+ 'type' => 'simple',
+ );
+
+ $deny = static fn( $caps, $cap ) => 'delete_post' === $cap ? array( 'do_not_allow' ) : $caps;
+ add_filter( 'map_meta_cap', $deny, 10, 2 );
+ $forbidden = $this->run_ability_response( 'woocommerce/product-update', $change );
+ remove_filter( 'map_meta_cap', $deny, 10 );
+ $refuse = true;
+ $refused = $this->run_ability_response( 'woocommerce/product-update', $change );
+ $kept = array_map( 'get_post_status', $ids );
+ $type = wc_get_product( $id )->get_type();
+ $refuse = false;
+ $changed = $this->run_ability( 'woocommerce/product-update', $change );
- $out_of = $this->run_ability_response(
+ $this->assertSame( 403, $forbidden->get_status() );
+ $this->assertSame( 400, $refused->get_status() );
+ $this->assertSame( array( 'trash', 'publish' ), $kept );
+ $this->assertSame( $input['type'], $type, 'A rolled back call keeps the old type.' );
+ $this->assertSame( $id, $changed['product']['id'] );
+ $this->assertSame( 'simple', $changed['product']['type'] );
+ $this->assertSame( array(), $changed['product']['variation_ids'] );
+ $this->assertEqualsCanonicalizing( $ids, $deleted );
+ foreach ( $ids as $variation_id ) {
+ $this->assertNull( get_post( $variation_id ) );
+ }
+ }
+
+ /**
+ * @testdox Should delete the variations on a change from variable to a variable type of an extension, unless the filter keeps them for the new product.
+ */
+ public function test_a_change_between_two_variable_types_follows_the_filter(): void {
+ $this->register_variation_subclass();
+ $input = $this->get_shirt_input();
+ $deleted = $this->run_ability( 'woocommerce/product-create', $input );
+
+ $input['variations'][0]['sku'] = 'other-s';
+ $input['variations'][1]['sku'] = 'other-m';
+
+ $kept = $this->run_ability( 'woocommerce/product-create', $input );
+
+ $with_items = $this->run_ability_response(
'woocommerce/product-update',
array(
- 'id' => $created['product']['id'],
- 'type' => 'simple',
+ 'id' => $deleted['product']['id'],
+ 'type' => 'test-variable',
+ 'variations' => array(
+ array(
+ 'id' => $deleted['product']['variation_ids'][0],
+ 'regular_price' => '9.00',
+ ),
+ ),
)
);
- $into = $this->run_ability_response(
+ $changed = $this->run_ability(
'woocommerce/product-update',
array(
- 'id' => $simple->get_id(),
+ 'id' => $deleted['product']['id'],
'type' => 'test-variable',
)
);
+ $this->add_test_action(
+ 'woocommerce_delete_variations_on_product_type_change',
+ static fn( $delete, $product ) => $product instanceof TestVariableProduct ? false : $delete,
+ 10,
+ 2
+ );
+ $kept_change = $this->run_ability(
+ 'woocommerce/product-update',
+ array(
+ 'id' => $kept['product']['id'],
+ 'type' => 'test-variable',
+ 'variations' => array(
+ array(
+ 'id' => $kept['product']['variation_ids'][0],
+ 'regular_price' => '9.00',
+ ),
+ ),
+ )
+ );
- $this->assertSame( 'woocommerce_product_type_unsupported', $out_of->get_data()['code'] );
- $this->assertSame( 'woocommerce_product_type_unsupported', $into->get_data()['code'] );
- $this->assertInstanceOf( TestVariableProduct::class, wc_get_product( $created['product']['id'] ) );
- $this->assertCount( 2, wc_get_product( $created['product']['id'] )->get_children() );
- $this->assertSame( 'simple', wc_get_product( $simple->get_id() )->get_type() );
+ $this->assertSame( 400, $with_items->get_status() );
+ $this->assertSame( 'test-variable', $changed['product']['type'] );
+ $this->assertSame( array(), $changed['product']['variation_ids'] );
+ $this->assertNull( get_post( $deleted['product']['variation_ids'][0] ) );
+ $this->assertSame( 'test-variable', $kept_change['product']['type'] );
+ $this->assertEqualsCanonicalizing( $kept['product']['variation_ids'], $kept_change['product']['variation_ids'] );
+ $this->assertSame( '9.00', $kept_change['variations'][0]['regular_price'] );
}
/**
- * @testdox Should refuse a type change into a variable class that a class filter returns only for a saved product.
+ * @testdox Should refuse a type change when the other fields of the call change whether the filter deletes the variations.
*/
- public function test_refuses_a_type_change_when_the_class_filter_depends_on_the_product_id(): void {
+ public function test_a_type_change_refuses_fields_that_change_the_delete_decision(): void {
+ $this->register_variation_subclass();
$this->add_test_action(
- 'product_type_selector',
- static fn( array $types ): array => $types + array( 'test-variable' => 'Test variable' )
+ 'woocommerce_delete_variations_on_product_type_change',
+ static fn( $delete, $product ) => 'Delete' === $product->get_name(),
+ 10,
+ 2
);
- $this->add_test_action(
- 'woocommerce_data_stores',
- static fn( array $stores ): array => $stores + array( 'product-test-variable' => 'WC_Product_Variable_Data_Store_CPT' )
+ $created = $this->run_ability( 'woocommerce/product-create', $this->get_shirt_input() );
+
+ $refused = $this->run_ability_response(
+ 'woocommerce/product-update',
+ array(
+ 'id' => $created['product']['id'],
+ 'type' => 'test-variable',
+ 'name' => 'Delete',
+ )
);
- $unsaved_class = get_class(
- new class() extends \WC_Product_Simple {
- /**
- * Get the product type.
- *
- * @return string
- */
- public function get_type() {
- return 'test-variable';
+
+ $this->assertSame( 400, $refused->get_status() );
+ $this->assertSame( 'variable', wc_get_product( $created['product']['id'] )->get_type() );
+ $this->assertEqualsCanonicalizing( $created['product']['variation_ids'], wc_get_product( $created['product']['id'] )->get_children() );
+ }
+
+ /**
+ * @testdox Should refuse a type change that deletes the variations when a variation appears after the validators ran.
+ */
+ public function test_a_type_change_refuses_a_variation_added_during_the_call(): void {
+ $created = $this->run_ability( 'woocommerce/product-create', $this->get_shirt_input() );
+ $id = $created['product']['id'];
+ $added = 0;
+ $this->register_validator(
+ 'product',
+ 'test-ext',
+ static function ( \WC_Product $product ) use ( $id, &$added ) {
+ if ( $id === $product->get_id() && ! $added ) {
+ $variation = new \WC_Product_Variation();
+ $variation->set_parent_id( $id );
+ $variation->save();
+ $added = $variation->get_id();
}
+ return null;
}
);
+ $this->reset_registries();
+ AbilitiesLoader::init_extensions();
+
+ $refused = $this->run_ability_response(
+ 'woocommerce/product-update',
+ array(
+ 'id' => $id,
+ 'type' => 'simple',
+ )
+ );
+
+ $this->assertSame( 409, $refused->get_status() );
+ $this->assertSame( 'variable', wc_get_product( $id )->get_type() );
+ $this->assertInstanceOf( \WC_Product_Variation::class, wc_get_product( $added ) );
+ $this->assertInstanceOf( \WC_Product_Variation::class, wc_get_product( $created['product']['variation_ids'][0] ) );
+ }
+
+ /**
+ * @testdox Should refuse a type change that deletes the variations when a save hook adds a variation, and roll it back.
+ */
+ public function test_a_type_change_refuses_a_variation_added_during_the_save(): void {
+ $created = $this->run_ability( 'woocommerce/product-create', $this->get_shirt_input() );
+ $id = $created['product']['id'];
$this->add_test_action(
- 'woocommerce_product_class',
- static function ( $classname, $product_type, $post_type, $product_id ) use ( $unsaved_class ) {
- if ( 'test-variable' !== $product_type ) {
- return $classname;
+ 'woocommerce_product_type_changed',
+ static function ( \WC_Product $product ) use ( $id ) {
+ if ( $id === $product->get_id() ) {
+ $variation = new \WC_Product_Variation();
+ $variation->set_parent_id( $id );
+ $variation->save();
}
- return $product_id > 0 ? TestVariableProduct::class : $unsaved_class;
- },
+ }
+ );
+
+ $refused = $this->run_ability_response(
+ 'woocommerce/product-update',
+ array(
+ 'id' => $id,
+ 'type' => 'simple',
+ )
+ );
+ $children = get_posts(
+ array(
+ 'post_parent' => $id,
+ 'post_type' => 'product_variation',
+ 'fields' => 'ids',
+ 'post_status' => 'any',
+ 'numberposts' => -1,
+ )
+ );
+
+ $this->assertSame( 409, $refused->get_status() );
+ $this->assertSame( 'variable', wc_get_product( $id )->get_type() );
+ $this->assertEqualsCanonicalizing( $created['product']['variation_ids'], $children );
+ }
+
+ /**
+ * @testdox Should keep the variations that the permission check kept, even when the filter answers otherwise during the save.
+ */
+ public function test_a_type_change_keeps_the_variations_that_the_permission_check_kept(): void {
+ $this->register_variation_subclass();
+ $created = $this->run_ability( 'woocommerce/product-create', $this->get_shirt_input() );
+ $id = $created['product']['id'];
+ $this->add_test_action(
+ 'woocommerce_delete_variations_on_product_type_change',
+ static fn( $delete, $product ) => has_term( 'test-variable', 'product_type', $product->get_id() ),
10,
- 4
+ 2
);
- $simple = \WC_Helper_Product::create_simple_product();
+ $deny = static fn( $caps, $cap ) => 'delete_post' === $cap ? array( 'do_not_allow' ) : $caps;
- $refused = $this->run_ability_response(
+ add_filter( 'map_meta_cap', $deny, 10, 2 );
+ $changed = $this->run_ability(
'woocommerce/product-update',
array(
- 'id' => $simple->get_id(),
+ 'id' => $id,
'type' => 'test-variable',
)
);
+ remove_filter( 'map_meta_cap', $deny, 10 );
+
+ $this->assertSame( 'test-variable', $changed['product']['type'] );
+ $this->assertEqualsCanonicalizing( $created['product']['variation_ids'], $changed['product']['variation_ids'] );
+ foreach ( $created['product']['variation_ids'] as $variation_id ) {
+ $this->assertInstanceOf( \WC_Product_Variation::class, wc_get_product( $variation_id ) );
+ }
+ }
+
+ /**
+ * @testdox Should write the cleared price to the price lookup when a type change runs again after a sync refused it.
+ */
+ public function test_a_type_change_after_a_rollback_clears_the_lookup_price(): void {
+ global $wpdb;
+
+ $refuse = true;
+ $this->register_sync(
+ 'product',
+ 'test-ext',
+ static function () use ( &$refuse ) {
+ return $refuse ? new \WP_Error( 'test_refused', 'Refused.' ) : null;
+ }
+ );
+ $this->reset_registries();
+ AbilitiesLoader::init_extensions();
+ $product = \WC_Helper_Product::create_simple_product( true, array( 'regular_price' => '17' ) );
+ $input = array(
+ 'id' => $product->get_id(),
+ 'type' => 'variable',
+ );
+
+ $refused = $this->run_ability_response( 'woocommerce/product-update', $input );
+ $cached = wp_cache_get( 'lookup_table', 'object_' . $product->get_id() );
+ $refuse = false;
+ $this->run_ability( 'woocommerce/product-update', $input );
+
+ $this->assertSame( 400, $refused->get_status() );
+ $this->assertFalse( $cached, 'The rollback should drop the cached lookup row that the refused call wrote.' );
+ $lookup = $wpdb->get_row( $wpdb->prepare( "SELECT min_price, max_price FROM {$wpdb->wc_product_meta_lookup} WHERE product_id = %d", $product->get_id() ), ARRAY_A );
+ $this->assertSame( '0.0000', $lookup['min_price'] );
+ $this->assertSame( '0.0000', $lookup['max_price'] );
+ }
+
+ /**
+ * @testdox Should give the syncs a grouped product without the variation price when a variable product becomes grouped.
+ */
+ public function test_a_variable_product_that_becomes_grouped_gives_the_syncs_its_new_price(): void {
+ $price = null;
+ $this->register_sync(
+ 'product',
+ 'test-ext',
+ static function ( array $saved ) use ( &$price ) {
+ $price = $saved[0]->get_price( 'edit' );
+ return null;
+ }
+ );
+ $this->reset_registries();
+ AbilitiesLoader::init_extensions();
+ $created = $this->run_ability( 'woocommerce/product-create', $this->get_shirt_input() );
+
+ $this->run_ability(
+ 'woocommerce/product-update',
+ array(
+ 'id' => $created['product']['id'],
+ 'type' => 'grouped',
+ )
+ );
- $this->assertSame( 'woocommerce_product_type_unsupported', $refused->get_data()['code'] ?? null );
- $this->assertSame( 'simple', wc_get_product( $simple->get_id() )->get_type() );
+ $this->assertSame( '', $price );
}
/**