On Commerce Kickstart 2.x we are trying to #2245341: Actually create the discounts stated on the frontpage of Demo Store. I am looking into "SAVE 25% Purchases made between June 5 - 12 will be discounted". It is easy enough to just create it in the interface and export using features. But I want to create the discount programmatically so it can be installed during the install process like all the other demo content.

How can this be achieved?

Comments

lsolesen’s picture

mglaman’s picture

Looks like you'd have to create the entity object and just save it. On entity insert it flushes the Rules config.

In rules_defaults.inc you have the below which adds the proper rules.

  // Create a rule for each commerce discount entity.
  foreach (entity_load('commerce_discount') as $discount) {
    $wrapper = entity_metadata_wrapper('commerce_discount', $discount);
    $wrapper_properties = $wrapper->getPropertyInfo();
    // Only for Commerce Discount wrappers with Commerce Discount Offer defined.
    if (in_array('commerce_discount_offer', array_keys($wrapper_properties))) {
      $type = $types[$discount->type];
      $offer_type = $offer_types[$wrapper->commerce_discount_offer->getBundle()];

      $rule = rules_reaction_rule();

      $rule->label = $discount->label;
      $rule->active = $discount->status;
      $rule->tags = array('Commerce Discount', check_plain($type['label']));

      $rule
        ->event(!empty($offer_type['event']) ? $offer_type['event'] : $type['event'])
        ->action(
          $offer_type['action'], array(
            'entity:select' => $type['entity type'],
            'commerce_discount' => $discount->name,
          )
        );
discipolo’s picture

i think the question was precisely how to create and save commerce_discount objects in a profile or module .install file (while installing the profile or enabling a module. it seems discounts exported with features dont get saved completely - although they do get created - the corresponding rules only get created by resaving them manually)

tobiasb’s picture

andrews501’s picture

I've been trying to create discounts programatically using rules/components (new product creates its discount) but it seems the option for creating a commerce discount entity doesnt exist. At the moment it seems that creating a discount can be done manually only as it needs filling : admin title, name, choose discount type, Order/Product discount conditions, choose offer type, discount dates and coupon conditions.

The nearest option is the current discount offer entity (fills in choose offer type only) but lacks of many of the previous fields. Also the commerce product entity has the option of adding the discount programatically as Discount Price but it is as a fixed amount.

Any suggestions, please?

briantes’s picture

Hello. I could do it with the next code for percentage discount. You can change it for other discounts types:

$entity2 = entity_get_controller('commerce_discount_offer')->create();
$entity2->type='percentage';
$entity2->commerce_percentage['und'][0]['value']=0.08;    // For 8% off
entity_get_controller('commerce_discount_offer')->save($entity2);

$entity = entity_get_controller('commerce_discount')->create();
$entity->name='my_new_discount_machine_name';
$entity->label='Discount 8% off';
$entity->component_title='Discount 8% off';
$entity->type='product_discount';
$entity->commerce_discount_offer['und'][0]['target_id'] = $entity2->discount_offer_id;
entity_get_controller('commerce_discount')->save($entity);

Hope it can help you.

smichel’s picture

@briantes, this code works really well, thanks.

You can add conditions to the discount like this, where I have a product family taxonomy, and different discounts apply to different products:

$entity->inline_conditions[LANGUAGE_NONE][0] = array(
  "condition_name" => "commerce_product_has_specified_terms",
    "condition_settings" => array(
      "terms" => array(array( "target_id" => $product_family_tid)),
      "condition_logic_operator" => null,
      "condition_negate" => 0,
      ),
);

And I also added a coupon with this:

  $values = array(
    'type' => 'discount_coupon',
    'code' => 'DISCOUNT CODE',
    'status' => 1,
  );
  $coupon = entity_create('commerce_coupon', $values);
  $coupon->commerce_discount_reference[LANGUAGE_NONE][0] = array('target_id' => $entity2->discount_id);
  entity_save('commerce_coupon', $coupon);

In my case, I'm importing discounts from Salesforce, and have this working now. Thanks again.

joelpittet’s picture

Category: Feature request » Support request
Status: Active » Fixed

A great source of how to write programmatically is through the simpletests. They try to be succinct to show a certain bit of functionality to ensure it continues to work. They are recently working and enabled on commerce_discount and I'd implore you to use them.

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.

hiramanpatil’s picture

Hi briantes,

I was trying your code to create new fixed discount. Below is the updated code for fixed discount.

$entity2->type='fixed_amount';
$entity2->commerce_fixed_amount'['und'][0]['value' ] = 2.00;

But its not working. is there anything wrong with second line in above code?

Thanks

Anonymous’s picture

@hiramanpatil

If you're setting up a fixed amount discount - it uses different field indexes, not value to store its data.

Try this out.

$entity2->commerce_fixed_amount['und'][0]['amount'] = 1000; // Cents, not dollars.
$entity2->commerce_fixed_amount['und'][0]['currency_code'] = 'USD';
hiramanpatil’s picture

Thank you @rsmylski

I have used ['amount'] instead of ['value'] and it works.

sardis’s picture

@smichel, so i've been trying to add conditions to the coupon same way as you do with discounts:

$coupon->commerce_coupon_conditions['und'][0] = array(
  'condition_name' => 'commerce_coupon_usage_evaluate_usage',
  'condition_settings' => array(
     'max_usage' => 1,
     'condition_logic_operator' => NULL,
   ),
   'condition_negate' => 0,
);

but it returns me an error after i try to save coupon:

Unsupported operand types in sites/all/modules/contrib/commerce_coupon/commerce_coupon.module on line 592
I know, it's not quite correct place to ask, but could you help me with this?

kiss.jozsef’s picture