Jump to content

Creating a cart rule via php code


mitsos1os

Recommended Posts

Hi guys, I have a problem with creating a cart rule from module code. I cannot see any documentation anywhere so I gather information from different modules' code.

So far I have found the following code in order to create a cart rule.

 

$coupon = new Discount();
  $coupon->quantity = 1;
  $coupon->quantity_per_user = 1;
  @$coupon->id_discount_type = (int)$id_discount_type;
  @$coupon->value = $value;

  $start_date = date('Y-m-d H:i:s');
  $coupon->date_from = $start_date;

  $end_date = //some end date
  $coupon->date_to = $end_date;

  $gen_pass = strtoupper(Tools::passwdGen(8));
  $vouchercode = 'somecode';
  $name_v = $vouchercode.'-'.$gen_pass;
  $coupon->name = $name_v;

  $current_language = (int)$cookie->id_lang;

  $coupon->id_customer = $uid;

	 // for ps 1.5
	 if(substr(_PS_VERSION_,0,3) == '1.5'){

	  // fixed bug for currency
	  if($id_discount_type == 2){
	   $coupon->reduction_currency = 1;
	   $coupon->minimum_amount_currency = 1;
	  }
	  $code_v = $vouchercode.'-'.$gen_pass;
	  $coupon->code = $code_v;

	  //$coupon->minimal = $coupon->value;
	  $coupon->active = 1;
   //$coupon->cart_display = 1;
   $coupon->cart_rule_restriction = 0;
   $coupon->description = //description
   $coupon->highlight = 1;
	 } else {
	  // for ps 1.3, 1.4

	  if($id_currency)
 $coupon->id_currency = $id_currency;
	  $coupon->cumulable = 1;
   $coupon->cumulable_reduction = 1;
	 }


	 $coupon->add();

 

However with the above code my problem is that the cart rule is created, but unfortunately with blank name. There has to be something with multiple language function where names for different languages are created. Please if you have any suggestions they are welcome!

  • Like 1
Link to comment
Share on other sites

Thank you very much for your reply. Unfortunately I didn't clearly understand the structure that I must use with name array. Could you provide a single line example?

 

PS: Is there some place where I can find such info as the one you told me about the name specifications so I could search myself and not bother everyone here? Thanks again!

Link to comment
Share on other sites

the answer is very simple: read the code.

really, it's important part of developing extensions for prestashop.

 

if you want to use default core classes / functions - for any object you've got object definition like fields and validation informations for them. In this case you're talking about cartRule class.

 

by object definition I mean a piece of code with something like:

/**
 * @see ObjectModel::$definition
 */
public static $definition = array();

 

so, in cartRule object definition we have got:

 

public static $definition = array(
 'table' => 'cart_rule',
 'primary' => 'id_cart_rule',
 'multilang' => true,
 'fields' => array(
  'id_customer' =>    array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId'),
  'date_from' =>	 array('type' => self::TYPE_DATE, 'validate' => 'isDate', 'required' => true),
  'date_to' =>	 array('type' => self::TYPE_DATE, 'validate' => 'isDate', 'required' => true),
  'description' =>    array('type' => self::TYPE_STRING, 'validate' => 'isCleanHtml', 'size' => 65534),
  'quantity' =>	 array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'),
  'quantity_per_user' =>   array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'),
  'priority' =>	 array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'),
  'partial_use' =>    array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
  'code' =>	  array('type' => self::TYPE_STRING, 'validate' => 'isCleanHtml', 'size' => 254),
  'minimum_amount' =>   array('type' => self::TYPE_FLOAT, 'validate' => 'isFloat'),
  'minimum_amount_tax' =>  array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
  'minimum_amount_currency' =>array('type' => self::TYPE_INT, 'validate' => 'isInt'),
  'minimum_amount_shipping' =>array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
  'country_restriction' => array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
  'carrier_restriction' =>  array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
  'group_restriction' =>   array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
  'cart_rule_restriction' =>  array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
  'product_restriction' =>  array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
  'shop_restriction' =>   array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
  'free_shipping' =>    array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
  'reduction_percent' =>   array('type' => self::TYPE_FLOAT, 'validate' => 'isPercentage'),
  'reduction_amount' =>   array('type' => self::TYPE_FLOAT, 'validate' => 'isFloat'),
  'reduction_tax' =>    array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
  'reduction_currency' =>  array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId'),
  'reduction_product' =>   array('type' => self::TYPE_INT, 'validate' => 'isInt'),
  'gift_product' =>    array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId'),
  'gift_product_attribute' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId'),
  'highlight' =>	 array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
  'active' =>	 array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
  'date_add' =>	 array('type' => self::TYPE_DATE, 'validate' => 'isDate'),
  'date_upd' =>	 array('type' => self::TYPE_DATE, 'validate' => 'isDate'),
  // Lang fields
  'name' =>	  array('type' => self::TYPE_STRING, 'lang' => true, 'validate' => 'isCleanHtml', 'required' => true, 'size' => 254),
 ),
);

 

 

as you can see above, the 'name' field has got 'lang' true - which mean that you have to create array with language ID => value

(create foreach loop for languages, extrude the id_lang - create array $name[$id_lang]="value" and use $name variable in object definition:

 

$cartrule->name=$name

 

voila ;-)

  • Like 1
Link to comment
Share on other sites

hi, trouble again....

I changed my code to the name part as you suggested like this...

 

$languages = Language::getLanguages(true,false);


$namelang = array();
foreach ($languages as $language){
$namelang[$language['id_lang']] = 'text';  
}
//Even tried setting the language ids that i use manually
$namelang = array();
  $namelang[1] = 'greek';
  $namelang[7] = 'english';


//Add Name array
$coupon->name = $namelang;

 

But unfortunately it still isn't working

Edited by mitsos1os (see edit history)
Link to comment
Share on other sites

  • 3 months later...

Hello there,

 

I am looking for information to how set some "cart_rule_restriction" to the cartRules generated by "referralprogram".

 

I know that I have to set "cart_rule_restriction" = 1, but I dont find the way to set the compatibility with the others existing cartRules, by code...

 

 

any idea ? thanks a lot

Link to comment
Share on other sites

  • 5 months later...

Hello there,

 

I am looking for information to how set some "cart_rule_restriction" to the cartRules generated by "referralprogram".

 

I know that I have to set "cart_rule_restriction" = 1, but I dont find the way to set the compatibility with the others existing cartRules, by code...

 

 

any idea ? thanks a lot

 

Same question. Any help?

Link to comment
Share on other sites

  • 3 months later...

Hi!

 

anyone knows how to create an automatic discount?

 

I mean, if you do not enter any code name in BO, the discount will be applied automaticaly, right? So how to do it with php code?

 

I tried this:

 

$coupon->code = ''; (empty content within quotes)  but nothing happens.

 

Thanks for helping!

Link to comment
Share on other sites

you can generate code for example with function passwdGen:

 

$coupon->code = Tools::passwdGen(5);

where 5 is the length of code

Thanks, but I needed that customer get the discount in the next cart, so the coupon should have not code, right?

 

Apart from this, how I get the attribute id_customer? I need the coupon was just valid for the logged user.

 

$coupon->id_customer = ??

Link to comment
Share on other sites

 

 

 so the coupon should have not code, right?

i don't understand

coupon without code = it's not possible in prestashop. coupon = code.

you can use $cart->id_customer variable to get ID of cart owner.

Link to comment
Share on other sites

i don't understand

coupon without code = it's not possible in prestashop. coupon = code.

you can use $cart->id_customer variable to get ID of cart owner.

I meant a cart rule without code.  Sorry, bad translation I guess.

 

Thanks, I will try to do that.

Link to comment
Share on other sites

  • 2 months later...

silentRun, on 02 Sept 2013 - 1:07 PM, said:snapback.png

Hello there,

 

I am looking for information to how set some "cart_rule_restriction" to the cartRules generated by "referralprogram".

 

I know that I have to set "cart_rule_restriction" = 1, but I dont find the way to set the compatibility with the others existing cartRules, by code...

 

 

any idea ? thanks a lot

 

Same question. Any help????

Link to comment
Share on other sites

  • 1 year later...
  • 2 months later...

I want create a cart_rule via api, but i have this problem:

 

Warning: It is not yet possible to assign complex types to properties in C:\wamp\www\cajondesastre\referido\apis\api_create_cart_rules.php on line 44

Line44 - $resources->name->language = array(1 => 'Hola', 2 => 'Hello');

 

Error: 
This call to PrestaShop Web Services failed and returned an HTTP status of 400. That means: Bad Request.

 

 

This its my code:

<?php
    session_start();
    include_once("api_conf.php");
    //extract($_POST);

    require_once( './PSWebServiceLibrary.php' );

    try {		
            $webService = new PrestaShopWebservice(PS_SHOP_PATH, PS_WS_AUTH_KEY, DEBUG);
            $opt = array('resource' => 'cart_rules');
            $xml = $webService->get(array('url' => PS_SHOP_PATH.'/api/cart_rules?schema=blank'));
            $resources = $xml->children()->children();
			
            $resources->date_from = date('Y-m-d H:i:s');
			$resources->date_to = date('Y-m-d H:i:s', strtotime ( '+1 year' , strtotime (date('Y-m-d H:i:s')) ));
			$resources->description = "Mi descr. cupon";
			//$resources->quantity = 9999;
			//$resources->quantity_per_user = 1;
			//$resources->priority = 1;
			//$resources->partial_use = 1;
			$resources->code = "kazpacio";
			$resources->minimum_amount = "100";
			$resources->minimum_amount_tax ="1";
			//$resources->minimum_amount_currency = 2;
			$resources->minimum_amount_shipping = "0";
			//$resources->country_restriction = 0;
			//$resources->carrier_restriction = 0;
			//$resources->group_restriction = 0;
			//$resources->cart_rule_restriction = 0;
			//$resources->product_restriction = 0;
			//$resources->shop_restriction = 0;
			//$resources->free_shipping = 0;
			$resources->reduction_percent = "35.00";
			//$resources->reduction_amount = 0.00;
			//$resources->reduction_tax = 0;
			//$resources->reduction_currency = 2;
			//$resources->reduction_product = 0;
			//$resources->gift_product = 0;
			//$resources->gift_product_attribute = 0;
			//$resources->highlight = 0;
			//$resources->active = 1;
			//$resources->date_add = date('Y-m-d H:i:s');
			//$resources->date_upd = date('Y-m-d H:i:s');
			$resources->name->language = array(1 => 'Hola', 2 => 'Hello');

            $opt = array('resource' => 'cart_rules');
            $opt['postXml'] = $xml->asXML();
            $xml = $webService->add($opt);
			
    }
    catch (PrestaShopWebserviceException $ex) {
        echo 'Error: <br/>'.$ex->getMessage();
    }
?>

api_conf.php

<?php
    ini_set('display_errors',1);
    ini_set('display_startup_errors',1);
    error_reporting(-1);
    define('DEBUG', true);
    define('_PS_DEBUG_SQL', true);
    define('PS_SHOP_PATH', 'http://mitienda.com/tienda');
    define('PS_WS_AUTH_KEY', 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA');
?>
Link to comment
Share on other sites

C:\wamp\www\cajondesastre\referido\apis\api_create_cart_rules.php

require_once( './PSWebServiceLibrary.php' );

Are these files that you have created, or perhaps you downloaded some API?  These files do not exist in the PS v1.6.1.2 code base.

 

 

I also searched the PS v1.6.1.2 code base for the message "It is not yet possible to assign complex types to properties", and nothing comes up.  So I suspect this has nothing to do with Prestashop, but rather the code you have developed or downloaded, which you don't specify

 

I would suggest that you create your own topic related to creating cart rules via the webservice API that you are using, as the original topic was not about this

Link to comment
Share on other sites

  • 1 year later...

Hi guys, I have a problem with creating a cart rule from module code. I cannot see any documentation anywhere so I gather information from different modules' code.

So far I have found the following code in order to create a cart rule.

 

As mentionned on first post by mitsos1os, i dont find any real core developper doc either.. is there somthing i missed too ? maybe there should be a pinned post about this

 

For exemple, where is the doc that mention the structure of class $coupon ?

 

Ive done only simples modules right now and each time it is pretty painful to find the informations

Edited by LauraPresta (see edit history)
Link to comment
Share on other sites

  • 6 months later...
On 5/22/2013 at 3:01 PM, vekia said:

the answer is very simple: read the code.

really, it's important part of developing extensions for prestashop.

 

if you want to use default core classes / functions - for any object you've got object definition like fields and validation informations for them. In this case you're talking about cartRule class.

 

by object definition I mean a piece of code with something like:

 


/**
 * @see ObjectModel::$definition
 */
public static $definition = array();
 

 

 

so, in cartRule object definition we have got:

 

 


public static $definition = array(
 'table' => 'cart_rule',
 'primary' => 'id_cart_rule',
 'multilang' => true,
 'fields' => array(
  'id_customer' =>    array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId'),
  'date_from' =>	 array('type' => self::TYPE_DATE, 'validate' => 'isDate', 'required' => true),
  'date_to' =>	 array('type' => self::TYPE_DATE, 'validate' => 'isDate', 'required' => true),
  'description' =>    array('type' => self::TYPE_STRING, 'validate' => 'isCleanHtml', 'size' => 65534),
  'quantity' =>	 array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'),
  'quantity_per_user' =>   array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'),
  'priority' =>	 array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'),
  'partial_use' =>    array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
  'code' =>	  array('type' => self::TYPE_STRING, 'validate' => 'isCleanHtml', 'size' => 254),
  'minimum_amount' =>   array('type' => self::TYPE_FLOAT, 'validate' => 'isFloat'),
  'minimum_amount_tax' =>  array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
  'minimum_amount_currency' =>array('type' => self::TYPE_INT, 'validate' => 'isInt'),
  'minimum_amount_shipping' =>array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
  'country_restriction' => array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
  'carrier_restriction' =>  array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
  'group_restriction' =>   array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
  'cart_rule_restriction' =>  array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
  'product_restriction' =>  array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
  'shop_restriction' =>   array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
  'free_shipping' =>    array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
  'reduction_percent' =>   array('type' => self::TYPE_FLOAT, 'validate' => 'isPercentage'),
  'reduction_amount' =>   array('type' => self::TYPE_FLOAT, 'validate' => 'isFloat'),
  'reduction_tax' =>    array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
  'reduction_currency' =>  array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId'),
  'reduction_product' =>   array('type' => self::TYPE_INT, 'validate' => 'isInt'),
  'gift_product' =>    array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId'),
  'gift_product_attribute' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId'),
  'highlight' =>	 array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
  'active' =>	 array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
  'date_add' =>	 array('type' => self::TYPE_DATE, 'validate' => 'isDate'),
  'date_upd' =>	 array('type' => self::TYPE_DATE, 'validate' => 'isDate'),
  // Lang fields
  'name' =>	  array('type' => self::TYPE_STRING, 'lang' => true, 'validate' => 'isCleanHtml', 'required' => true, 'size' => 254),
 ),
);
 

 

 

 

as you can see above, the 'name' field has got 'lang' true - which mean that you have to create array with language ID => value

(create foreach loop for languages, extrude the id_lang - create array $name[$id_lang]="value" and use $name variable in object definition:

 

$cartrule->name=$name

 

voila ;-)

Hi Vekia, I know this thread is quite old but it is close to what I want. Can you tell me how I can enable product selection for the Cart Rule and provide products as well as the product names on which the Cart Rule should apply using php code?

Link to comment
Share on other sites

  • 5 months later...

for those who're looking for a way to tie products (let's say, `array( 1 => "12122",  2 => "12123", 3 => "12124");`) with a specific cart rule:

Since there is no class based implementation for the same, it has to be done manually by making entries to three database tables.

So, after you `$cartrule->add()` you get, `$cartRuleId = $cartrule->id`

        (new Cart( $cart->id) )->addCartRule( (int) $cartRuleId); // apply the cart rule this existing cart

        # first, save `id_cart_rule` & `quantity` and get id_product_rule_group
        Db::getInstance()->execute('INSERT INTO `'._DB_PREFIX_.'cart_rule_product_rule_group` (`id_cart_rule`, `quantity`)
        VALUES ('.(int)$cartRuleId.', "'.(int)$qty.'")');
        $id_product_rule_group = Db::getInstance()->Insert_ID();

        # second, save `id_product_rule_group` & `type` and get id_product_rule
        Db::getInstance()->execute('INSERT INTO `'._DB_PREFIX_.'cart_rule_product_rule` (`id_product_rule_group`, `type`)
        VALUES ('.(int)$id_product_rule_group.', "'.$type.'")');
        $id_product_rule = Db::getInstance()->Insert_ID();

# finally, using id_product_rule assign products
        foreach ($action['product_ids'] as $id) {
            $values[] = '('.(int)$id_product_rule.','.(int)$id.')';
        }
        $values = array_unique($values);
        if (count($values)) {
            Db::getInstance()->execute('INSERT INTO `'._DB_PREFIX_.'cart_rule_product_rule_value` (`id_product_rule`, `id_item`) VALUES '.implode(',', $values));
        }

 

Source: Admin controller for cart rule

 

Hope this helps.

Edited by wadhwa016 (see edit history)
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...