step 1:
open template.php in the theme you have decided to use in /sites/all/themes/xxx/template.php
add the following code at the bottom
function get_user_purchased_products(){
// Assuming we have $user populated with the user's ID:
global $user;
$query = db_select('commerce_order', 'cord');
$query->join('commerce_line_item', 'li', 'cord.order_id = li.order_id');
$query->join('field_data_commerce_product', 'prod', 'li.line_item_id = prod.entity_id');
$query->condition('cord.uid', $user->uid, '=')->condition('cord.status', 'completed', '=')->fields('prod', array('commerce_product_product_id'));
$result = $query->execute();
$purchased_products = array();
foreach($result as $oneResult){
array_push($purchased_products, $oneResult->commerce_product_product_id);
}
return $purchased_products;
}
step2:
import this rule and enjoy.
{ "rules_prevent_buying_an_already_purchased_product" : {
"LABEL" : "Prevent buying an already purchased product",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "php", "rules", "commerce_cart" ],
"ON" : { "commerce_cart_product_add" : [] },
"DO" : [
{ "php_eval" : { "code" : "global $pProducts;\r\n$pProducts = get_user_purchased_products();" } },
{ "LOOP" : {
"USING" : { "list" : [ "commerce-order:commerce-line-items" ] },
"ITEM" : { "list_item" : "Current list item" },
"DO" : [
{ "component_rules_check_if_cart_products_are_in_purchase_list" : { "line_item" : [ "list-item" ], "product" : [ "commerce-product" ] } }
]
}
}
]
}
}
what happens here is:
1- the rules gets called after adding the product to the shopping cart list.
2- it calls the function that loads all previously purchased product by the user and puts their ids in an array.
3- it loops in the shopping cart, extracting the product id from every line item and checking to see if this product is in the previously purchased product list.
4- if found, a message is fired and the product is removed from the list.
The idea is to come up with a solution that doesn't require you write a lot of php code so that if you want to update your modules later on or drupal core, you can do so without having to worry what will break.
i am building an online audio store and i have the same issue mentioned here and i have been googling for a way to do this for a few days now. a user buys an unlimited license for an audio track once in his life. no need to buy the same product again.
this worked for me, i hope it works for you as well.
i also hope drupal_commerce adds support for this later on, since it doesn't require much work, a simple function and a rule to be implemented :)
Comments
Unfortunately your solution doesn't work for me. It goes: "Integrity check for the imported configuration failed. Error message: Unknown action component_rules_check_if_cart_products_are_in_purchase_list.." while I am trying to import it. Anybody knows what's happening?