cancel
Showing results for 
Search instead for 
Did you mean: 

Disable free product when coupon code is entered

Disable free product when coupon code is entered

Hello everyone,

 

I have a question about a custom plugin from a third party for free products.

 

I have the plugin installed and works as should. It adds a free product (without coupon code) on my cart.

But I also have other coupon codes for other discounts.

 

Whenever someone uses the other coupon code, the free products should be deleted and the entered coupon code should be applied.

 

Example:
Someone adds a product to the cart. Automatically the free product is entered to the cart and will be displayed.
But the customer doesn't want the free product but wants a discount. He/she enters the coupon code "discount" and the free products will be deleted from the cart en the discount will be applied.

The code from the plugin is the following:

model/observer.php

 

<?php

/**
 * Freeproduct Module
 * 
 * This module can be used free of carge to extend a magento system. Any other
 * usage requires prior permission of the code4business Software GmbH. The module
 * comes without any kind of warranty.
 * 
 * @category     C4B
 * @package      C4B_Freeproduct
 * @author       Nikolai Krambrock <freeproduct@code4business.de>
 * @copyright    code4business Software GmbH
 * @version      0.1.0
 */
class C4B_Freeproduct_Model_Observer {

    /**
     * Delete all free products that have been added through this module before.
     * This is done before discounts are given in on the event 
     * 'sales_quote_collect_totals_before'.
     * 
     * @param Varien_Event_Observer $observer
     */
    public function salesQuoteCollectTotalsBefore(Varien_Event_Observer $observer) {
        self::_resetFreeItems($observer->getEvent()->getQuote());
    }

    /**
     * Add gifts to the cart, if the current salesrule is of simple action 
     * ADD_GIFT_ACTION. The rule has been validated before the event
     * 'salesrule_validator_process' is thrown that we catch.
     * 
     * @param Varien_Event_Observer $observer
     */
    public function salesruleValidatorProcess(Varien_Event_Observer $observer) {
        /* @var $quote Mage_Sales_Model_Quote */
        $quote = $observer->getEvent()->getQuote();
        /* @var $item Mage_Sales_Model_Quote_Item */
        $item = $observer->getEvent()->getItem();
        /* @var $rule Mage_SalesRule_Model_Rule */
        $rule = $observer->getEvent()->getRule();
        
    	if ($rule->getSimpleAction() == C4B_Freeproduct_Model_Consts::ADD_GIFT_ACTION &&
		    !$item->getIsFreeProduct()) {
			self::_handleGift($quote, $item, $rule);
        }
    }

    /**
     * Add a new simple action to the salesrule in the backen. In the combo-box
     * you can now select 'Add a Gift' as one possible result of the given rule
     * evaluation positive. Additionally you have to enter a sku of the gift that
     * you want to make.
     * 
     * @param Varien_Event_Observer $observer
     */
    public function adminhtmlBlockSalesruleActionsPrepareform($observer) {
    	$field = $observer->getForm()->getElement('simple_action');
        $options = $field->getValues();
        $options[] = array(
            'value' => C4B_Freeproduct_Model_Consts::ADD_GIFT_ACTION,
            'label' => Mage::helper('freeproduct')->__('Add a Gift')
        );
        $field->setValues($options);
        
        $fieldset = $observer->getForm()->getElement('action_fieldset');
        $fieldset->addField('gift_sku', 'text', array(
            'name' => 'gift_sku',
            'label' => Mage::helper('freeproduct')->__('Gift SKU'),
            'title' => Mage::helper('freeproduct')->__('Gift SKU'),
            'note' => Mage::helper('freeproduct')->__('Enter the SKU of the gift that should be added to the cart'),
        ));
    }
    
    /**
     * Make sure that a gift is only added once, create a free item and add it to the cart.
     * 
     * @param Mage_Sales_Model_Quote $quote
     * @param Mage_Sales_Model_Quote_Item $item
     * @param Mage_Sales_Model_Quote_Item $rule
     */   
    protected static function _handleGift(Mage_Sales_Model_Quote $quote,
                                          Mage_Sales_Model_Quote_Item $item,
                                          Mage_SalesRule_Model_Rule $rule) {
    	if ($rule->getIsApplied()) {
    		return;
    	}
    	
    	$qty = (integer) $rule->getDiscountAmount();
    	if ($qty) {
    		$freeItem = self::_getFreeQuoteItem($quote, $rule->getGiftSku(), $item->getStoreId(), $qty);
    		self::_addAndApply($quote, $freeItem, $rule);
    	}
    }

    /**
     * Create a free item. It has a value of 0$ in the cart no matter what the price was
     * originally.
     * 
     * @param Mage_Sales_Model_Quote $quote
     * @param string $sku
     * @param int $storeId
     * @param int $qty
     * @return Mage_Sales_Quote_Item
     */
    protected static function _getFreeQuoteItem(Mage_Sales_Model_Quote $quote, $sku, $storeId, $qty) {
        if ($qty < 1) {
            return;
        }

        $product = Mage::getModel('catalog/product')->loadByAttribute('sku', $sku);
        Mage::getModel('cataloginventory/stock_item')->assignProduct($product);
        $quoteItem = Mage::getModel('sales/quote_item')->setProduct($product);
        $quoteItem->setQuote($quote)
                ->setQty($qty)
                ->setCustomPrice(0.0)
                ->setOriginalCustomPrice($product->getPrice())
                ->setIsFreeProduct(true)
                ->setStoreId($storeId);

        return $quoteItem;
    }    
    
    /**
     * Add a free item and mark that the rule was used on this item.
     * 
     * @param Mage_Sales_Model_Quote $quote
     * @param Mage_Sales_Model_Quote_Item $item
     * @param Mage_Sales_Model_Quote_Item $rule
     */
    protected static function _addAndApply(Mage_Sales_Model_Quote $quote,
                                           Mage_Sales_Model_Quote_Item $item,
                                           Mage_SalesRule_Model_Rule $rule) {
   		$quote->addItem($item);
		$item->setApplyingRule($rule);
    	$rule->setIsApplied(true);
    }

    /**
     * Delete all free items from the cart.
     * 
     * @param Mage_Sales_Model_Quote $quote
     */
    protected static function _resetFreeItems(Mage_Sales_Model_Quote $quote) {
        foreach ($quote->getAllItems() as $item) {
            if ($item->getIsFreeProduct()) {
                $quote->removeItem($item->getId());
            }
        }
    }
}

model/consts.php

 

 

<?php

/**
 * Freeproduct Module
 * 
 * This module can be used free of carge to extend a magento system. Any other
 * usage requires prior permission of the code4business Software GmbH. The module
 * comes without any kind of warranty.
 * 
 * @category     C4B
 * @package      C4B_Freeproduct
 * @author       Nikolai Krambrock <freeproduct@code4business.de>
 * @copyright    code4business Software GmbH
 * @version      0.1.0
 */
class C4B_Freeproduct_Model_Consts {
    const ADD_GIFT_ACTION = 'add_gift';
}

helper/data.php

 

 

<?php

/**
 * Freeproduct Module
 * 
 * This module can be used free of carge to extend a magento system. Any other
 * usage requires prior permission of the code4business Software GmbH. The module
 * comes without any kind of warranty.
 * 
 * @category     C4B
 * @package      C4B_Freeproduct
 * @author       Nikolai Krambrock <freeproduct@code4business.de>
 * @copyright    code4business Software GmbH
 * @version      0.1.0
 */
class C4B_Freeproduct_Helper_Data extends Mage_Core_Helper_Abstract {
	
	/**
	 * This logs a message in a custom log file.
	 * 
	 * @param string $msg
	 */
	public function log($msg) {
		Mage::log($msg, Zend_Log::INFO, 'freeproduct.log');
	}
}

 

 

etc/config.xml

<?xml version="1.0"?>
<config>
    <modules>
        <C4B_Freeproduct>
            <version>0.1.0</version>
        </C4B_Freeproduct>
    </modules>
    <global>
        <models>
            <freeproduct>
                <class>C4B_Freeproduct_Model</class>
            </freeproduct>         
        </models>     
        <helpers>
            <freeproduct>
                <class>C4B_Freeproduct_Helper</class>
            </freeproduct>
        </helpers>
        <resources>
            <freeproduct_setup>
                <setup>
                    <module>C4B_Freeproduct</module>
                    <class>Mage_Eav_Model_Entity_Setup</class>
                </setup>
                <connection>
                    <use>core_setup</use>
                </connection>
            </freeproduct_setup>
        </resources>
        <fieldsets>
            <sales_convert_quote_item>
                <is_free_product>
                    <to_order_item>is_free_product</to_order_item>
                </is_free_product>           
            </sales_convert_quote_item>
        </fieldsets>
    </global>
    <adminhtml>
        <events>    
    		<adminhtml_block_salesrule_actions_prepareform>
                <observers>
                    <freeproduct>
                        <type>model</type>
                        <class>freeproduct/observer</class>
                        <method>adminhtmlBlockSalesruleActionsPrepareform</method>
                    </freeproduct>
                </observers>
       		</adminhtml_block_salesrule_actions_prepareform>
        </events>
	    <translate>
            <modules>
                <C4B_Freeproduct>
                    <files>
                        <default>C4B_Freeproduct.csv</default>
                    </files>
                </C4B_Freeproduct>
            </modules>
	    </translate>
    </adminhtml>
    <frontend>
    	<layout>
    		<updates>
    			<freeproduct>
    				<file>freeproduct.xml</file>
    			</freeproduct>
    		</updates>
    	</layout>
        <events>
            <salesrule_validator_process>
                <observers>
                    <freeproduct>
                        <type>model</type>
                        <class>freeproduct/observer</class>
                        <method>salesruleValidatorProcess</method>
                    </freeproduct>
                </observers>
            </salesrule_validator_process>
            <sales_quote_collect_totals_before>
                <observers>
                    <freeproduct>
                        <type>model</type>
                        <class>freeproduct/observer</class>
                        <method>salesQuoteCollectTotalsBefore</method>
                    </freeproduct>
                </observers>
            </sales_quote_collect_totals_before>
            <!-- CUSTOM PART TO REMOVE FREE PRODUCTS IF COUPON CODE IS ENTERED
            <controller_action_predispatch_checkout_cart_couponPost>
                <observers>
                    <freeproduct>
                        <type>singleton</type>
                        <class>freeproduct/observer</class>
                        <method>salesQuoteCollectTotalsBefore</method>
                    </freeproduct>
                </observers>
            </controller_action_predispatch_checkout_cart_couponPost>
            <!-- END CUSTOM PART //-->
        </events>
    </frontend>
</config>

sql/freeproduct_setup/mysql-install-0.1.0.php

 

 

<?php
/**
 * Freeproduct Module
 * 
 * This module can be used free of carge to extend a magento system. Any other
 * usage requires prior permission of the code4business Software GmbH. The module
 * comes without any kind of warranty.
 * 
 * @category     C4B
 * @package      C4B_Freeproduct
 * @author       Nikolai Krambrock <freeproduct@code4business.de>
 * @copyright    code4business Software GmbH
 * @version      0.1.0
 */

/**
 * @var $installer Mage_Sales_Model_Mysql4_Setup
 */
$installer = $this;
$installer->startSetup();
$installer->getConnection()->addColumn($installer->getTable('sales/quote_item'), 'is_free_product', "tinyint(4) NOT NULL default '0'");
$installer->getConnection()->addColumn($installer->getTable('sales/order_item'), 'is_free_product', "tinyint(4) NOT NULL default '0'");
$installer->getConnection()->addColumn($installer->getTable('salesrule'), 'gift_sku', "varchar(255) NOT NULL default ''");
$installer->endSetup();

 

Thanks in advance!