Автоматическое создание правила цены покупок в Magento

Я хотел бы создать правило цены корзины покупок, которое дает пользователю 10% от их заказа, когда и если они завершат процесс на моем сайте Magento.

Здесь есть метод, который вставляет правило непосредственно в базу данных. Это немного инвазивно для моих вкусов.

Как мне это сделать, используя методы Magento?

Как общий принцип, вы должны иметь возможность делать все, что сама система Magento делает без написания одной строки SQL. Почти все структуры данных Magento используют классы модели Magento.

Запустите следующий код где-нибудь, чтобы посмотреть, как выглядит модель salesrule / rule. Предполагается, что вы создали единое правило цены для корзины в admin с идентификатором 1

$coupon = Mage::getModel('salesrule/rule')->load(1); var_dump($coupon->getData()); 

Используя сбрасываемые данные в качестве руководства, мы можем программно создать модель, используя следующие

  $coupon = Mage::getModel('salesrule/rule'); $coupon->setName('test coupon') ->setDescription('this is a description') ->setFromDate('2010-05-09') ->setCouponCode('CODENAME') ->setUsesPerCoupon(1) ->setUsesPerCustomer(1) ->setCustomerGroupIds(array(1)) //an array of customer grou pids ->setIsActive(1) //serialized conditions. the following examples are empty ->setConditionsSerialized('a:6:{s:4:"type";s:32:"salesrule/rule_condition_combine";s:9:"attribute";N;s:8:"operator";N;s:5:"value";s:1:"1";s:18:"is_value_processed";N;s:10:"aggregator";s:3:"all";}') ->setActionsSerialized('a:6:{s:4:"type";s:40:"salesrule/rule_condition_product_combine";s:9:"attribute";N;s:8:"operator";N;s:5:"value";s:1:"1";s:18:"is_value_processed";N;s:10:"aggregator";s:3:"all";}') ->setStopRulesProcessing(0) ->setIsAdvanced(1) ->setProductIds('') ->setSortOrder(0) ->setSimpleAction('by_percent') ->setDiscountAmount(10) ->setDiscountQty(null) ->setDiscountStep('0') ->setSimpleFreeShipping('0') ->setApplyToShipping('0') ->setIsRss(0) ->setWebsiteIds(array(1)); $coupon->save(); 

Для любого, кто любопытен, приведенный выше код генерируется с использованием описанной здесь техники

Посмотрите на мой код. Он добавит условие действия.

 $coupon_rule = Mage::getModel('salesrule/rule'); $coupon_rule->setName($c_data[1]) ->setDescription($c_data[2]) ->setFromDate($fromDate) ->setToDate($toDate) ->setUsesPerCustomer(0) ->setCustomerGroupIds(array(0,1,2,3)) //an array of customer grou pids ->setIsActive(1) ->setCouponType(2) ->setCouponCode($c_data[0]) ->setUsesPerCoupon(1) //serialized conditions. the following examples are empty ->setConditionsSerialized('') ->setActionsSerialized('') ->setStopRulesProcessing(0) ->setIsAdvanced(1) ->setProductIds('') ->setSortOrder(0) ->setSimpleAction('by_percent') ->setDiscountAmount($c_data[5]) ->setDiscountQty(1) ->setDiscountStep('0') ->setSimpleFreeShipping('0') ->setApplyToShipping('1') ->setIsRss(1) ->setWebsiteIds(explode(',',$c_data[6])); $sku =$c_data[7]; // Put your product SKU here $skuCond = Mage::getModel('salesrule/rule_condition_product') ->setType('salesrule/rule_condition_product') ->setAttribute('sku') ->setOperator('==') ->setValue($sku); $coupon_rule->getActions()->addCondition($skuCond); $coupon_rule->save(); echo "New Coupon was added and its ID is ".$coupon_rule->getId().'<br/>';<br/> 

Если вы хотите добавить условие для правила цены корзины покупок, следуйте этому примеру.

 $sku =$c_data[7]; // Put your product SKU here $found = Mage::getModel('salesrule/rule_condition_product_found') ->setType('salesrule/rule_condition_product_found') ->setValue(1) // 1 == FOUND ->setAggregator('all'); // match ALL conditions $coupon_rule->getConditions()->addCondition($found); $skuCond = Mage::getModel('salesrule/rule_condition_product') ->setType('salesrule/rule_condition_product') ->setAttribute('sku') ->setOperator('==') ->setValue($sku); $found->addCondition($skuCond); $coupon_rule->save(); в $sku =$c_data[7]; // Put your product SKU here $found = Mage::getModel('salesrule/rule_condition_product_found') ->setType('salesrule/rule_condition_product_found') ->setValue(1) // 1 == FOUND ->setAggregator('all'); // match ALL conditions $coupon_rule->getConditions()->addCondition($found); $skuCond = Mage::getModel('salesrule/rule_condition_product') ->setType('salesrule/rule_condition_product') ->setAttribute('sku') ->setOperator('==') ->setValue($sku); $found->addCondition($skuCond); $coupon_rule->save();