0

How can i generate coupon rule dynamically using observer method?

I have created below function, it works if we create controller action and run. But not working with observer.

function createCoupon($customer_id, $discount,$days,$type)
{
    $customer = Mage::getModel('customer/customer')->load($customer_id);

    $customerGroupIds = Mage::getModel('customer/group')->getCollection()->getAllIds();
    $websitesId = Mage::getModel('core/website')->getCollection()->getAllIds();

    $customer_name = $customer->getName();
    $couponCode = Mage::helper('core')->getRandomString(9);

    $model = Mage::getModel('salesrule/rule');
    $model->setName('Discount for ' . $customer_name);
    $model->setDescription('Discount for ' . $customer_name);
    $model->setFromDate(date('Y-m-d'));
    $model->setToDate(date('Y-m-d', strtotime('+'.$days.' days')));
    $model->setCouponType(2);
    $model->setCouponCode($couponCode);
    $model->setUsesPerCoupon(1);
    $model->setUsesPerCustomer(1);
    $model->setCustomerGroupIds($customerGroupIds);
    $model->setIsActive(1);
    $model->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\";}');
    $model->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\";}');
    $model->setStopRulesProcessing(0);
    $model->setIsAdvanced(1);
    $model->setProductIds('');
    $model->setSortOrder(1);
    $model->setSimpleAction($type);//$model->setSimpleAction('by_fixed');
    $model->setDiscountAmount($discount);
    $model->setDiscountStep(0);
    $model->setSimpleFreeShipping(0);
    $model->setTimesUsed(0);
    $model->setIsRss(0);
    $model->setWebsiteIds($websitesId);

    try {
        $model->save();
    } catch (Exception $e) {
        Mage::log($e->getMessage());
    }
}

Can anyone have idea, why these happens?

  • What exactly doesn't work? Do you get an error? Maybe the observer does not fire... – Marius Jul 25 '13 at 6:49
  • No.. observer fires but no coupon generates. – Bijal Bhavsar Jul 25 '13 at 10:29
  • It is showing error like Fatal error: Uncaught exception 'Exception' with message 'User Error: Some transactions have not been committed or rolled back in www\magento1702\lib\Varien\Db\Adapter\Pdo\Mysql.php on line 3645' in www\magento1702\app\code\core\Mage\Core\functions.php on line 245 – Bijal Bhavsar Jul 25 '13 at 10:30
  • huh?...I've never seen this error before. What event are you 'observing'? – Marius Jul 25 '13 at 10:36
  • I have created sales_order_status_after event as per magento.stackexchange.com/questions/1216/… post and using it. – Bijal Bhavsar Jul 25 '13 at 10:38
1

I found answer of above question.

Created event of sales_order_status_after

<events>
        <sales_order_save_commit_after>
            <observers>
                <modulename>
                    <type>singleton</type>
                    <class>Mycompany_Offer_Model_Observer</class>
                    <method>sales_order_save_commit_after</method>
                </modulename> 
            </observers>
        </sales_order_save_commit_after> 
    </events>

Added Method sales_order_save_commit_after in observer:

<?php

class Mycompany_Offer_Model_Observer {

    public function sales_order_save_commit_after(Varien_Event_Observer $observer)
    {               


        $order = $observer->getOrder();
        if($order->getState() == Mage_Sales_Model_Order::STATE_COMPLETE){
            $orderTotal = $order->getBaseSubTotal();
            $customerId = 0;
            if($customerId = $order->getCustomerId())
            { 
                $customer_id = $customer->getId();
            }  
            $discountAmount = 10;
            $duration = 30;  
            $discountIn = 'by_fixed'; 
            Mage::getModel('offer/offer')->createCoupon($customer_id, $discountAmount, $duration, $discountIn); 

        } 
    } 

}

Added above function createCoupon in model file:

class Mycompany_Offer_Model_Offer extends Mage_Core_Model_Abstract

        /**
         * Function to create coupon dynamically
         *
         * @param int $customer_id
         * @param int $discount
         * @param int $days
         * @param text $type
         * @return nothing
         */
        public function createCoupon($customer_id, $discount,$days,$type)
        {
            $customer = Mage::getModel('customer/customer')->load($customer_id);

            $customerGroupIds = Mage::getModel('customer/group')->getCollection()->getAllIds();
            $websitesId = Mage::getModel('core/website')->getCollection()->getAllIds();

            $customer_name = $customer->getName();
            $couponCode = Mage::helper('core')->getRandomString(9);

            $model = Mage::getModel('salesrule/rule');
            $model->setName('Discount for ' . $customer_name);
            $model->setDescription('Discount for ' . $customer_name);
            $model->setFromDate(date('Y-m-d'));
            $model->setToDate(date('Y-m-d', strtotime('+'.$days.' days'))); 
            $model->setCouponType(2);
            $model->setCouponCode($couponCode);
            $model->setUsesPerCoupon(1);
            $model->setUsesPerCustomer(1);
            $model->setCustomerGroupIds($customerGroupIds);
            $model->setIsActive(1);
            $model->setConditionsSerialized('');
            $model->setActionsSerialized('');
            $model->setStopRulesProcessing(0);
            $model->setIsAdvanced(1);
            $model->setProductIds('');
            $model->setSortOrder(1);
            $model->setSimpleAction($type);//$model->setSimpleAction('by_fixed');
            $model->setDiscountAmount($discount);
            $model->setDiscountStep(0);
            $model->setSimpleFreeShipping(0);
            $model->setTimesUsed(0);
            $model->setIsRss(0);
            $model->setWebsiteIds($websitesId);

            try {
                $model->save();  
                return $model->getData();
            } catch (Exception $e) {
                print_r($e->getMessage());exit;
                Mage::log($e->getMessage());
            }
        }
}


Mage::getModel('offer/offer')->createCoupon($customer_id, $discountAmount, $duration, $discountIn);

As per above syntax we have to pass parameters like 'customer id', 'discount amount', 'duration' (in days), and 'discountIn'( like 'by_percent' or 'by_fixed')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.