Thursday 19 May 2016

Solved: Coupon Codes Used when Payment pending Magento


Solved: Coupon Codes Used when Payment pending Magento

When site owner assign a single coupon code to customer and suppose customer use coupon without complete the order and he thought he will place the order next time then customer can not use this coupon in next order. In this case we have only two option to use coupon either you can increase the use of coupon or cancel the order. If customer cancel the order then you have to release the coupon on cancelling.

Here is the code to automatically decrease coupon usage upon a cancel the order.

Put below code in your module/any module config.xml file after <models> block

    <sales_order_payment_cancel>
        <observers>
          <order_cancel_couponfix_observer>
            <type>singleton</type>
            <class>Setblue_Banner_Model_Observer</class>
            <method>cancel</method>
          </order_cancel_couponfix_observer>
        </observers>
    </sales_order_payment_cancel>  

Next we need to create observer file to read this code. Create Observer.php in /yourmodule/Model/Observer.php and put the below code :

public function cancel($observer)
    {
$event = $observer->getEvent();
      $order = $event->getPayment()->getOrder();
        if ($order->canCancel()) {
if ($code = $order->getCouponCode()) {
$coupon = Mage::getModel('salesrule/coupon')->load($code, 'code');
if ($coupon->getTimesUsed() > 0) {
$customerId = $order->getCustomerId();
$resource = Mage::getSingleton('core/resource');
$writeConnection = $resource->getConnection('core_write');
$tableName = $resource->getTableName('salesrule_coupon_usage');

$query = "UPDATE {$tableName} SET times_used = times_used-1 "
.  "WHERE coupon_id = {$coupon->getId()} AND customer_id = {$customerId} AND times_used > 0";

$writeConnection->query($query);

$tableName = $resource->getTableName('salesrule_customer');
$query = "UPDATE {$tableName} SET times_used = times_used-1 "
.  "WHERE rule_id = {$coupon->getRuleId()} AND customer_id = {$customerId} AND times_used > 0";

$writeConnection->query($query);

}
                 
}
}
    }

No comments: