I have simple product A which is made from two components X and Y. Both X and Y are stock managed simple products but not for sale on the website.
Programmatically when A is placed in the cart or removed, the stock levels of X and Y are altered using the action hooks.
add_action( 'woocommerce_add_to_cart', custom_parts_deduct', 10, 4 );
add_action( 'woocommerce_cart_item_removed', 'after_remove_product_from_cart', 10, 2 );
Updating the quantity of the product in the cart also works using the hook
add_action('woocommerce_after_cart_item_quantity_update', custom_quantity_update', 10, 4);
THE PROBLEM I have encountered is that due to the changed availability (stock) of parts the stock levels of other simple products which could be added to the cart are incorrect and need updating.
I have used the following hooks to successfully alter the stock of A, or any other product (with parts) before adding to cart.
add_filter('woocommerce_add_to_cart_validation', 'custom_add_to_cart_validation', 10, 5);
add_action('woocommerce_before_single_product', 'custom_before_product_view');
In doing so product A stock levels screw up; meaning, for example, that the cart level could be ‘3’ when the simple product stock has changed to ‘2’.
I need to alter stock levels of simple products with parts as they are moved in and out of the cart or if the cart is updated in real time but avoid adding products where parts are unavailable. Doing it on order completion is not an option.
If I treated the parts as invisible cart items the stock levels of parts could easily be exceed for all the simple products in the cart.
Could I keep a running total of parts as meta data?
FYI I make use of a DB table to calculate the stock level of A based on X and Y
CREATE TABLE IF NOT EXISTS wp_parts
(
id SMALLINT UNIQUE AUTO_INCREMENT ,
parts_id SMALLINT NOT NULL ,
parts_idp SMALLINT NOT NULL ,
parts_quantp SMALLINT DEFAULT 1 NOT NULL
);
ALTER TABLE wp_parts
ADD CONSTRAINT UC_wp_parts UNIQUE (parts_id , parts_idp);