6

I am planning to give the discount to the customers for their first order purchase.

After shipment selection, I want to show the discount in the order summary(discount is only for the first order).

Is there any event observer available after shipment selection? which is the best way to achieve this (Programmatically or admin side promotion)?

9

Admin panel -> Marketing -> Cart Sales Rules.

enter image description here

When you expand the “Conditions” tab, you’ll be able to set when a given discount applies. For example, you can select the cart value option and this way specify that: If the cart value is greater than 50 – the discount should be applied.

enter image description here

However, the default options don’t cover all possible situations. Let’s imagine that we want to reward our client for the dedication he put in creating an account in our store. We have the following scenario: If this is a first order of a given client – the discount should be applied.

Unfortunately, Magento doesn’t offer this option out-of-the-box

Custom Cart Sales Rule Conditions

we will focus on extending the available discount conditions. To understand how the available conditions are collected, you need to look into the Magento\SalesRule\Model\Rule\Condition\Combine class, more specifically into the getNewChildSelectOptions() method. You’ll notice that after the default conditions, the salesrule_rule_condition_combine event is dispatched and then the collected conditions are combined.

As usual, we will start with creating the foundations of our module:

app/code/Itdesire/CustomerRule/etc/module.xml

<?xml version="1.0"?>
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
        <module name="Itdesire_CustomerRule" setup_version="1.0.0">
        </module>
    </config>

app/code/Itdesire/CustomerRule/registration.php

<?php

\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Itdesire_CustomerRule',
    __DIR__
);

Next, we will create an observer that will add our condition:

app/code/Itdesire/CustomerRule/etc/events.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="salesrule_rule_condition_combine">
        <observer name="customer_rule" instance="Itdesire\CustomerRule\Observer\CustomerConditionObserver" />
    </event>
</config>

app/code/Itdesire/CustomerRule/Observer/CustomerConditionObserver.php

   <?php

namespace Itdesire\CustomerRule\Observer;

/**
 * Class CustomerConditionObserver
 */
class CustomerConditionObserver implements \Magento\Framework\Event\ObserverInterface
{
    /**
     * Execute observer.
     * @param \Magento\Framework\Event\Observer $observer
     * @return $this
     */
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $additional = $observer->getAdditional();
        $conditions = (array) $additional->getConditions();

        $conditions = array_merge_recursive($conditions, [
            $this->getCustomerFirstOrderCondition()
        ]);

        $additional->setConditions($conditions);
        return $this;
    }

    /**
     * Get condition for customer first order.
     * @return array
     */
    private function getCustomerFirstOrderCondition()
    {
        return [
            'label'=> __('Customer first order'),
            'value'=> \Itdesire\CustomerRule\Model\Rule\Condition\Customer::class
        ];
    }
}

What happens in the observer? We’re fetching other conditions, for example the ones added in other observers, and merge them with ours. As you can see, one condition consists of a name and a value which means that it includes our class that will handle the condition.

Now, we can move on to the logic responsible for our condition:

app/code/Itdesire/CustomerRule/etc/di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Itdesire\CustomerRule\Model\Rule\Condition\Customer">
        <arguments>
            <argument name="data" xsi:type="array">
                <item name="form_name" xsi:type="string">sales_rule_form</item>
            </argument>
        </arguments>
    </type>
</config>

app/code/Itdesire/CustomerRule/Model/Rule/Condition/Customer.php

   <?php

namespace Itdesire\CustomerRule\Model\Rule\Condition;

/**
 * Class Customer
 */
class Customer extends \Magento\Rule\Model\Condition\AbstractCondition
{
    /**
     * @var \Magento\Config\Model\Config\Source\Yesno
     */
    protected $sourceYesno;

    /**
     * @var \Magento\Sales\Model\ResourceModel\Order\CollectionFactory
     */
    protected $orderFactory;

    /**
     * Constructor
     * @param \Magento\Rule\Model\Condition\Context $context
     * @param \Magento\Config\Model\Config\Source\Yesno $sourceYesno
     * @param \Magento\Sales\Model\ResourceModel\Order\CollectionFactory $orderFactory
     * @param array $data
     */
    public function __construct(
        \Magento\Rule\Model\Condition\Context $context,
        \Magento\Config\Model\Config\Source\Yesno $sourceYesno,
        \Magento\Sales\Model\ResourceModel\Order\CollectionFactory $orderFactory,
        array $data = []
    ) {
        parent::__construct($context, $data);
        $this->sourceYesno = $sourceYesno;
        $this->orderFactory = $orderFactory;
    }

    /**
     * Load attribute options
     * @return $this
     */
    public function loadAttributeOptions()
    {
        $this->setAttributeOption([
            'customer_first_order' => __('Customer first order')
        ]);
        return $this;
    }

    /**
     * Get input type
     * @return string
     */
    public function getInputType()
    {
        return 'select';
    }

    /**
     * Get value element type
     * @return string
     */
    public function getValueElementType()
    {
        return 'select';
    }

    /**
     * Get value select options
     * @return array|mixed
     */
    public function getValueSelectOptions()
    {
        if (!$this->hasData('value_select_options')) {
            $this->setData(
                'value_select_options',
                $this->sourceYesno->toOptionArray()
            );
        }
        return $this->getData('value_select_options');
    }

    /**
     * Validate Customer First Order Rule Condition
     * @param \Magento\Framework\Model\AbstractModel $model
     * @return bool
     */
    public function validate(\Magento\Framework\Model\AbstractModel $model)
    {
        $customerId = $model->getCustomerId();
        $order = $this->orderFactory->create()
            ->addAttributeToSelect('entity_id')
            ->addFieldToFilter('customer_id',['eq' => $customerId])
            ->getFirstItem();

        $firstOrder = 1;
        if ($order->getEntityId()) {
            $firstOrder = 0;
        }
        $model->setData('customer_first_orde
r', $firstOrder);
        return parent::validate($model);
    }
}

We load the Yesno model in the constructor of our logic that is mainly used as a source_model in the backend. We’ll fetch from it the available values for our select fields. Moreover, we load the factory of order collection that we will use for validating the condition correctness. We need to set the name and label of our condition in the loadAttributeOptions() method. getInputType() defines what will be displayed as an operator for comparing our attribute – the returned select field will allow us to choose “is” or “is not”. Returning a numeric value here would allow you to select available operators for comparing numbers, such as “greater than” or “less than”. getValueElementType() defines the type of the value with which we will compare our values. The returned select will render the field with available options, which we will define in getValueSelectOptions().

In case we don’t want to define imposed values, we can return text – an input with the option to write a given value will then be displayed (using numeric value and text would allow you to create a condition “if the number of customer’s orders is greater than X – apply the discount”).

The last method is validate() that we use to check whether the customer has other orders placed with his account, and then we can set the value that will be compared with the one we previously defined.

Now, we only need to create a discount with our condition

Originally posted on Magently: https://magently.com/blog/magento-2-custom-sales-rule-condition/

| improve this answer | |
  • I have use above code for Magento 2.1.6. When i apply coupon code for first order, it apply, display success message but discount not deduct from order total. Do you have any idea? – user55548 Nov 14 '18 at 6:55
2

<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> <preference for="Magento\OfflineShipping\Model\Carrier\Tablerate" type="Customer\FreeShip\Model\Tablerate" /> </config> Override and Create new di.xml

After Create The New Model in your Custome module and set this code

namespace Customer\FreeShip\Model;

use Magento\Quote\Model\Quote\Address\RateRequest;

use Magento\Shipping\Model\Rate\Result;

class Shipping extends \Magento\Shipping\Model\Carrier\AbstractCarrier implements \Magento\Shipping\Model\Carrier\CarrierInterface {

/** * @var string */ protected $_code = 'simpleshipping';

/**
 * @var \Magento\Shipping\Model\Rate\ResultFactory
 */
protected $_rateResultFactory;

/**
 * @var \Magento\Quote\Model\Quote\Address\RateResult\MethodFactory
 */
protected $_rateMethodFactory;

protected $_session;

protected $orderFactory;

/**
 * Shipping constructor.
 *
 * @param \Magento\Framework\App\Config\ScopeConfigInterface          $scopeConfig
 * @param \Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory  $rateErrorFactory
 * @param \Psr\Log\LoggerInterface                                    $logger
 * @param \Magento\Shipping\Model\Rate\ResultFactory                  $rateResultFactory
 * @param \Magento\Quote\Model\Quote\Address\RateResult\MethodFactory $rateMethodFactory
 * @param array                                                       $data
 */
public function __construct(
    \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
    \Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory $rateErrorFactory,
    \Psr\Log\LoggerInterface $logger,
    \Magento\Shipping\Model\Rate\ResultFactory $rateResultFactory,
    \Magento\Customer\Model\Session $session,
    \Magento\Sales\Model\OrderFactory $orderFactory,
    \Magento\Quote\Model\Quote\Address\RateResult\MethodFactory $rateMethodFactory,
    array $data = []
) {
    $this->_rateResultFactory = $rateResultFactory;
    $this->_rateMethodFactory = $rateMethodFactory;
    $this->_session = $session;
    $this->orderFactory = $orderFactory;
    parent::__construct($scopeConfig, $rateErrorFactory, $logger, $data);
}

/**
 * get allowed methods
 * @return array
 */
public function getAllowedMethods()
{
    return [$this->_code => $this->getConfigData('name')];
}

/**
 * @return float
 */
// private function getShippingPrice()
// {
//     $configPrice = $this->getConfigData('price');

//     $shippingPrice = $this->getFinalPriceWithHandlingFee($configPrice);

//     return $shippingPrice;
// }

/**
 * @param RateRequest $request
 * @return bool|Result
 */
public function collectRates(RateRequest $request)
{
    if (!$this->getConfigFlag('active')) {
        return false;
    }

    if($this->_session->isLoggedIn()){
        $customer_id = $this->_session->getCustomer()->getId();
        //$customer_email = $this->_session->getCustomer()->getEmail();

        //$order = $this->_objectManager->create('\Magento\Sales\Model\Order')->load($customer_id);

        $order = $this->orderFactory->create()->getCollection()->addAttributeToSelect('customer_id')
            ->addFieldToFilter('customer_id',$customer_id);
        //var_dump($order->getCustomerEmail()); die('uiuiuiuiuiu');
            if(count($order->getData())>0){
               return false;
            }        
        }

    /** @var \Magento\Shipping\Model\Rate\Result $result */
    $result = $this->_rateResultFactory->create();

    /** @var \Magento\Quote\Model\Quote\Address\RateResult\Method $method */
    $method = $this->_rateMethodFactory->create();

    $method->setCarrier($this->_code);
    $method->setCarrierTitle($this->getConfigData('title'));

    $method->setMethod($this->_code);
    $method->setMethodTitle($this->getConfigData('name'));

    //$amount = $this->getShippingPrice();

    $method->setPrice('0');
    $method->setCost('0');

    $result->append($method);

    return $result;
}

}

| improve this answer | |
1

No Coding required. Create a coupon with the discounts and restrict the coupon to be used once per customer.

enter image description here

| improve this answer | |
0
  1. Create coupon code and auto apply the by the observer at any step of the one-page checkout if it is customers 1st or order.
  2. Send a coupon code on customer registration email.
| improve this answer | |
  • sales_quote_collect_totals_before is this observer is okey?? – Midlaj Feb 17 '18 at 10:09
  • can you just elaborate in code level?. – Midlaj Feb 19 '18 at 3:48
0

For this feature, we have to customize magento 2 using below steps.

  • Create a cart price rule for your "first time" discount.
  • Add an attribute to the customer object named something like "used_first_coupon". Defaults to 0/false
  • Add an event on customer creation that send the coupon code to the customer.
  • Hook into the coupon applying code where you can check for the first time order base on it you can manipulate the coupon validation.
  • Add an event listener post-order that will mark the customers used_first_coupon attribute as true.
| improve this answer | |

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.