Claudiu Persoiu

Blog-ul lui Claudiu Persoiu


Archive for 8 March 2012

Magento – Create a custom shopping cart price rule

with 2 comments

This is not a tutorial about setting up a Shopping Cart Price Rule in Magento, but rather about implementing a new one.

A new type of rule in Magento needs a couple of things:
– modify the admin area to add the new rule using an observer for adminhtml_block_salesrule_actions_prepareform,
– a way to apply the new rule using an observer for salesrule_validator_process.

Let’s build an example. Let’s say there is a Shopping Cart Price Rule that offers different discounts according to the number of products in the cart. The value that’s going to be used for the discount increment ($step) will be calculated. The first product will not receive a discount, the second product will receive a discount of $step, the third product will have a discount of 2*$step, until the maximum discount value will be reached. The following products will have a maximum discount. Ex:
Discount Amount = 50
Discount Qty = 5
Step = Discount Amount / Discount Qty = 10

Discount outcome:
– 0% prod 1
– 10% prod 2

– 50% prod 6
– 50% prod 7

The first step is the module activation using the file: app/etc/modules/CP_ProductNrDiscount.xml

<?xml version="1.0" encoding="UTF-8"?>
<config>
    <modules>
        <CP_ProductNrDiscount>
            <active>true</active>
            <codePool>local</codePool>
        </CP_ProductNrDiscount>
    </modules>
</config>

The first observer, adminhtml_block_salesrule_actions_prepareform, must be in the “adminhtml” section of the config, because it will involve the admin. This observer will have access to the admin form, in order to modify it.

The second observer, salesrule_validator_process, can be in the “frontend” or “global” section of the config. If it’s in the frontend section, it will only apply to the frontend section. If it’s in the global section it will also apply to backend. Usually, global is necessary when there are actions on the cart in the backend.

<?xml version="1.0" encoding="UTF-8"?>
<config>
    <modules>
        <CP_ProductNrDiscount>
            <version>0.0.1</version>
        </CP_ProductNrDiscount>
    </modules>
    <global>
        <models>
            <productnrdiscount>
                <class>CP_ProductNrDiscount_Model</class>
            </productnrdiscount>
        </models>
        <events>
            <salesrule_validator_process>
                <observers>
                    <productnrdiscount>
                        <type>model</type>
                        <class>productnrdiscount/observer</class>
                        <method>salesruleValidatorProcess</method>
                    </productnrdiscount>
                </observers>
            </salesrule_validator_process>
        </events>
    </global>
    <adminhtml>
        <events>
            <adminhtml_block_salesrule_actions_prepareform>
            <observers>
                <productnrdiscount>
                    <type>model</type>
                    <class>productnrdiscount/observer</class>
                <method>adminhtmlBlockSalesruleActionsPrepareform</method>
                </productnrdiscount>
            </observers>
            </adminhtml_block_salesrule_actions_prepareform>
        </events>
    </adminhtml>
</config>

As you can see above, there must be an Observer model that will have the two methods which modify the admin and apply the discount.

<?php
/**
 * Number of product discount module
 *
 * @author Claudiu Persoiu http://blog.claudiupersoiu.ro
 */
class CP_ProductNrDiscount_Model_Observer {

    // The new rule type
    const PRODUCT_NR_DISCOUNT = 'product_nr_discount';

    /**
     * Add the new rule type to the admin menu
     *
     * @param Varien_Event_Observer $observer
     */
    public function adminhtmlBlockSalesruleActionsPrepareform
              (Varien_Event_Observer $observer) {
        // Extract the form field
        $field = $observer->getForm()->getElement('simple_action');
        // Extract the field values
        $options = $field->getValues();
        // Add the new value
        $options[] = array(
            'value' => self::PRODUCT_NR_DISCOUNT,
            'label' => 'Product Number Discount'
        );
        // Set the field
        $field->setValues($options);
    }

    /**
     * Apply the discount
     * The discount will be applied for at least 2 products increasing
     * with a "step" for each product, where "step" is
     * maximum discount / number of products.
     *
     * @param Varien_Event_Observer $observer
     */
    public function salesruleValidatorProcess(Varien_Event_Observer $observer) {

        // $item typeof Mage_Sales_Model_Quote_Item
        $item = $observer->getEvent()->getItem();
        // $rule typeof Mage_SalesRule_Model_Rule
        $rule = $observer->getEvent()->getRule();

        // Number of products
        $qty = $item->getQty();

        // We must check the rule type in order to isolate our rule type
        if($rule->getSimpleAction() == self::PRODUCT_NR_DISCOUNT && $qty > 1) {

            // Extract rule details
            $discountAmount = $rule->getDiscountAmount();
            $discountQty = $rule->getDiscountQty();

            // Discount step
            $step = $discountAmount/$discountQty;

            // Discount calculation
            $discount = 0;
            for($i = 1; $i < $qty; $i++) {
                $itemDiscount = $i * $step;
                // If the discount is bigger then the maximum discount
                // then the maximum discount is used
                if($itemDiscount > $discountAmount) {
                    $itemDiscount = $discountAmount;
                }

                $discount += $itemDiscount;
            }
            // Effective discount
            $totalDiscountAmount = ($item->getPrice() * $discount)/100;

            // Discount in percent for each item
            $item->setDiscountPercent($discount / $qty);

            // Setting up the effective discount, basically this is the discount value
            $result = $observer->getResult();
            $result->setDiscountAmount($totalDiscountAmount);
            $result->setBaseDiscountAmount($totalDiscountAmount);

        }
    }

}

This observer will run at each request if there are items in cart that for which the rule is applicable. If the discount should be applied only for specific products, there can be filtered using the rule’s “Conditions” tab, just as you would normally do.

Written by Claudiu Persoiu

8 March 2012 at 9:37 PM

PHP 5.4 was released!

without comments

PHP 5.4 was released!

Even though is already yesterday news… literally, yesterday 1 March was released.

The complete list of changes is available on php.net.

I’m sorry that we still don’t have scalar type hinting in this version. The only change to type hinting was the “callable” word was added, about which I’ve talked in the closure in PHP 5.4  blog.

Another interesting thing is that this time register_globals and magic_quotes_gpc were really removed, so the old PHP 4 apps don’t get to be compatible anymore with the help of a couple of flags in php.ini.

Also the hex2bin() function was added, of course is not that important, but is interesting that the  bin2hex() function existed since PHP 4. 🙂

Written by Claudiu Persoiu

2 March 2012 at 9:43 PM

Posted in PHP

Tagged with , ,