Magento 2: How to implement First Order Discount?first order discount in magento2Admin only coupon code?Magento - Discount price including tax/vatApply free shipping promotion when reordering from admin panelMagento 2 - How to add custom discount in cart programmatically?Which event should I catch if I want a “complete” order?Magento 2 - discount depend on Payment Method does not workHow to add custom extra discount(%) to order or override default coupon code when placed from back end only?Force order status and state to processing after creating shipment using observerCart Price Rules: Minimum Purchase of 2 of the same items to get 15% discount

Rejected in 4th interview round citing insufficient years of experience

In the late 1940’s to early 1950’s what technology was available that could melt a LOT of ice?

The bar has been raised

How do anti-virus programs start at Windows boot?

How did Alan Turing break the enigma code using the hint given by the lady in the bar?

Are babies of evil humanoid species inherently evil?

Making a sword in the stone, in a medieval world without magic

What is the meaning of triple curly braces in phtml template files? When and how do we use them?

Should I take out a loan for a friend to invest on my behalf?

What to do when during a meeting client people start to fight (even physically) with each others?

My story is written in English, but is set in my home country. What language should I use for the dialogue?

Do I really need to have a scientific explanation for my premise?

Virginia employer terminated employee and wants signing bonus returned

Why don't MCU characters ever seem to have language issues?

Could you please stop shuffling the deck and play already?

Are the terms "stab" and "staccato" synonyms?

Unreachable code, but reachable with exception

How to pass a string to a command that expects a file?

Subset counting for even numbers

Is having access to past exams cheating and, if yes, could it be proven just by a good grade?

PTIJ: Why can't I eat anything?

How are such low op-amp input currents possible?

Why does Deadpool say "You're welcome, Canada," after shooting Ryan Reynolds in the end credits?

How much attack damage does the AC boost from a shield prevent on average?



Magento 2: How to implement First Order Discount?


first order discount in magento2Admin only coupon code?Magento - Discount price including tax/vatApply free shipping promotion when reordering from admin panelMagento 2 - How to add custom discount in cart programmatically?Which event should I catch if I want a “complete” order?Magento 2 - discount depend on Payment Method does not workHow to add custom extra discount(%) to order or override default coupon code when placed from back end only?Force order status and state to processing after creating shipment using observerCart Price Rules: Minimum Purchase of 2 of the same items to get 15% discount













4















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)?










share|improve this question




























    4















    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)?










    share|improve this question


























      4












      4








      4


      2






      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)?










      share|improve this question
















      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)?







      magento2 checkout event-observer discount promotions






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 19 '18 at 4:55









      Teja Bhagavan Kollepara

      2,98141947




      2,98141947










      asked Feb 17 '18 at 7:41









      MidlajMidlaj

      122214




      122214




















          5 Answers
          5






          active

          oldest

          votes


















          4














          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 MagentoSalesRuleModelRuleConditionCombine 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

          MagentoFrameworkComponentComponentRegistrar::register(
          MagentoFrameworkComponentComponentRegistrar::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="ItdesireCustomerRuleObserverCustomerConditionObserver" />
          </event>
          </config>



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




           <?php

          namespace ItdesireCustomerRuleObserver;

          /**
          * Class CustomerConditionObserver
          */
          class CustomerConditionObserver implements MagentoFrameworkEventObserverInterface

          /**
          * Execute observer.
          * @param MagentoFrameworkEventObserver $observer
          * @return $this
          */
          public function execute(MagentoFrameworkEventObserver $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'=> ItdesireCustomerRuleModelRuleConditionCustomer::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="ItdesireCustomerRuleModelRuleConditionCustomer">
          <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 ItdesireCustomerRuleModelRuleCondition;

          /**
          * Class Customer
          */
          class Customer extends MagentoRuleModelConditionAbstractCondition
          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 MagentoFrameworkModelAbstractModel $model
          * @return bool
          */
          public function validate(MagentoFrameworkModelAbstractModel $model)

          $customerId = $model->getCustomerId();
          $order = $this->orderFactory->create()
          ->addAttributeToSelect('customer_id')
          ->addFieldToFilter('customer_id',['eq' => $customerId])
          ->getFirstItem();

          $firstOrder = 1;
          if ($order->getId())
          $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






          share|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


















          1














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



          enter image description here






          share|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.





            share|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.





            share|improve this answer






























              0














              <?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="MagentoOfflineShippingModelCarrierTablerate" type="CustomerFreeShipModelTablerate" />
              </config>
              Override and Create new di.xml



              ---- After--- Create Model in Custome module set This code`





              share
























                Your Answer








                StackExchange.ready(function()
                var channelOptions =
                tags: "".split(" "),
                id: "479"
                ;
                initTagRenderer("".split(" "), "".split(" "), channelOptions);

                StackExchange.using("externalEditor", function()
                // Have to fire editor after snippets, if snippets enabled
                if (StackExchange.settings.snippets.snippetsEnabled)
                StackExchange.using("snippets", function()
                createEditor();
                );

                else
                createEditor();

                );

                function createEditor()
                StackExchange.prepareEditor(
                heartbeatType: 'answer',
                autoActivateHeartbeat: false,
                convertImagesToLinks: false,
                noModals: true,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: null,
                bindNavPrevention: true,
                postfix: "",
                imageUploader:
                brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                allowUrls: true
                ,
                onDemand: true,
                discardSelector: ".discard-answer"
                ,immediatelyShowMarkdownHelp:true
                );



                );













                draft saved

                draft discarded


















                StackExchange.ready(
                function ()
                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f213903%2fmagento-2-how-to-implement-first-order-discount%23new-answer', 'question_page');

                );

                Post as a guest















                Required, but never shown

























                5 Answers
                5






                active

                oldest

                votes








                5 Answers
                5






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes









                4














                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 MagentoSalesRuleModelRuleConditionCombine 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

                MagentoFrameworkComponentComponentRegistrar::register(
                MagentoFrameworkComponentComponentRegistrar::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="ItdesireCustomerRuleObserverCustomerConditionObserver" />
                </event>
                </config>



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




                 <?php

                namespace ItdesireCustomerRuleObserver;

                /**
                * Class CustomerConditionObserver
                */
                class CustomerConditionObserver implements MagentoFrameworkEventObserverInterface

                /**
                * Execute observer.
                * @param MagentoFrameworkEventObserver $observer
                * @return $this
                */
                public function execute(MagentoFrameworkEventObserver $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'=> ItdesireCustomerRuleModelRuleConditionCustomer::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="ItdesireCustomerRuleModelRuleConditionCustomer">
                <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 ItdesireCustomerRuleModelRuleCondition;

                /**
                * Class Customer
                */
                class Customer extends MagentoRuleModelConditionAbstractCondition
                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 MagentoFrameworkModelAbstractModel $model
                * @return bool
                */
                public function validate(MagentoFrameworkModelAbstractModel $model)

                $customerId = $model->getCustomerId();
                $order = $this->orderFactory->create()
                ->addAttributeToSelect('customer_id')
                ->addFieldToFilter('customer_id',['eq' => $customerId])
                ->getFirstItem();

                $firstOrder = 1;
                if ($order->getId())
                $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






                share|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















                4














                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 MagentoSalesRuleModelRuleConditionCombine 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

                MagentoFrameworkComponentComponentRegistrar::register(
                MagentoFrameworkComponentComponentRegistrar::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="ItdesireCustomerRuleObserverCustomerConditionObserver" />
                </event>
                </config>



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




                 <?php

                namespace ItdesireCustomerRuleObserver;

                /**
                * Class CustomerConditionObserver
                */
                class CustomerConditionObserver implements MagentoFrameworkEventObserverInterface

                /**
                * Execute observer.
                * @param MagentoFrameworkEventObserver $observer
                * @return $this
                */
                public function execute(MagentoFrameworkEventObserver $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'=> ItdesireCustomerRuleModelRuleConditionCustomer::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="ItdesireCustomerRuleModelRuleConditionCustomer">
                <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 ItdesireCustomerRuleModelRuleCondition;

                /**
                * Class Customer
                */
                class Customer extends MagentoRuleModelConditionAbstractCondition
                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 MagentoFrameworkModelAbstractModel $model
                * @return bool
                */
                public function validate(MagentoFrameworkModelAbstractModel $model)

                $customerId = $model->getCustomerId();
                $order = $this->orderFactory->create()
                ->addAttributeToSelect('customer_id')
                ->addFieldToFilter('customer_id',['eq' => $customerId])
                ->getFirstItem();

                $firstOrder = 1;
                if ($order->getId())
                $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






                share|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













                4












                4








                4







                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 MagentoSalesRuleModelRuleConditionCombine 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

                MagentoFrameworkComponentComponentRegistrar::register(
                MagentoFrameworkComponentComponentRegistrar::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="ItdesireCustomerRuleObserverCustomerConditionObserver" />
                </event>
                </config>



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




                 <?php

                namespace ItdesireCustomerRuleObserver;

                /**
                * Class CustomerConditionObserver
                */
                class CustomerConditionObserver implements MagentoFrameworkEventObserverInterface

                /**
                * Execute observer.
                * @param MagentoFrameworkEventObserver $observer
                * @return $this
                */
                public function execute(MagentoFrameworkEventObserver $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'=> ItdesireCustomerRuleModelRuleConditionCustomer::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="ItdesireCustomerRuleModelRuleConditionCustomer">
                <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 ItdesireCustomerRuleModelRuleCondition;

                /**
                * Class Customer
                */
                class Customer extends MagentoRuleModelConditionAbstractCondition
                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 MagentoFrameworkModelAbstractModel $model
                * @return bool
                */
                public function validate(MagentoFrameworkModelAbstractModel $model)

                $customerId = $model->getCustomerId();
                $order = $this->orderFactory->create()
                ->addAttributeToSelect('customer_id')
                ->addFieldToFilter('customer_id',['eq' => $customerId])
                ->getFirstItem();

                $firstOrder = 1;
                if ($order->getId())
                $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






                share|improve this answer













                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 MagentoSalesRuleModelRuleConditionCombine 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

                MagentoFrameworkComponentComponentRegistrar::register(
                MagentoFrameworkComponentComponentRegistrar::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="ItdesireCustomerRuleObserverCustomerConditionObserver" />
                </event>
                </config>



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




                 <?php

                namespace ItdesireCustomerRuleObserver;

                /**
                * Class CustomerConditionObserver
                */
                class CustomerConditionObserver implements MagentoFrameworkEventObserverInterface

                /**
                * Execute observer.
                * @param MagentoFrameworkEventObserver $observer
                * @return $this
                */
                public function execute(MagentoFrameworkEventObserver $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'=> ItdesireCustomerRuleModelRuleConditionCustomer::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="ItdesireCustomerRuleModelRuleConditionCustomer">
                <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 ItdesireCustomerRuleModelRuleCondition;

                /**
                * Class Customer
                */
                class Customer extends MagentoRuleModelConditionAbstractCondition
                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 MagentoFrameworkModelAbstractModel $model
                * @return bool
                */
                public function validate(MagentoFrameworkModelAbstractModel $model)

                $customerId = $model->getCustomerId();
                $order = $this->orderFactory->create()
                ->addAttributeToSelect('customer_id')
                ->addFieldToFilter('customer_id',['eq' => $customerId])
                ->getFirstItem();

                $firstOrder = 1;
                if ($order->getId())
                $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







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered May 23 '18 at 6:39









                Pramod KharadePramod Kharade

                1,7271028




                1,7271028












                • 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

















                • 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
















                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





                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













                1














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



                enter image description here






                share|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






                  share|improve this answer

























                    1












                    1








                    1







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



                    enter image description here






                    share|improve this answer













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



                    enter image description here







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered May 5 '18 at 5:48









                    Yogesh AgarwalYogesh Agarwal

                    712316




                    712316





















                        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.





                        share|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














                        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.





                        share|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












                        0








                        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.





                        share|improve this answer















                        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.






                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited Mar 19 '18 at 4:55









                        Teja Bhagavan Kollepara

                        2,98141947




                        2,98141947










                        answered Feb 17 '18 at 8:03









                        Arun TyagiArun Tyagi

                        374




                        374












                        • 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

















                        • 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
















                        sales_quote_collect_totals_before is this observer is okey??

                        – Midlaj
                        Feb 17 '18 at 10:09





                        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





                        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.





                        share|improve this answer



























                          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.





                          share|improve this answer

























                            0












                            0








                            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.





                            share|improve this answer













                            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.






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered May 5 '18 at 5:34









                            Kandarp B PatelKandarp B Patel

                            1706




                            1706





















                                0














                                <?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="MagentoOfflineShippingModelCarrierTablerate" type="CustomerFreeShipModelTablerate" />
                                </config>
                                Override and Create new di.xml



                                ---- After--- Create Model in Custome module set This code`





                                share





























                                  0














                                  <?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="MagentoOfflineShippingModelCarrierTablerate" type="CustomerFreeShipModelTablerate" />
                                  </config>
                                  Override and Create new di.xml



                                  ---- After--- Create Model in Custome module set This code`





                                  share



























                                    0












                                    0








                                    0







                                    <?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="MagentoOfflineShippingModelCarrierTablerate" type="CustomerFreeShipModelTablerate" />
                                    </config>
                                    Override and Create new di.xml



                                    ---- After--- Create Model in Custome module set This code`





                                    share















                                    <?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="MagentoOfflineShippingModelCarrierTablerate" type="CustomerFreeShipModelTablerate" />
                                    </config>
                                    Override and Create new di.xml



                                    ---- After--- Create Model in Custome module set This code`






                                    share













                                    share


                                    share








                                    edited 1 min ago

























                                    answered 7 mins ago









                                    hirokapuriyahirokapuriya

                                    213




                                    213



























                                        draft saved

                                        draft discarded
















































                                        Thanks for contributing an answer to Magento Stack Exchange!


                                        • Please be sure to answer the question. Provide details and share your research!

                                        But avoid


                                        • Asking for help, clarification, or responding to other answers.

                                        • Making statements based on opinion; back them up with references or personal experience.

                                        To learn more, see our tips on writing great answers.




                                        draft saved


                                        draft discarded














                                        StackExchange.ready(
                                        function ()
                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f213903%2fmagento-2-how-to-implement-first-order-discount%23new-answer', 'question_page');

                                        );

                                        Post as a guest















                                        Required, but never shown





















































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown

































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown







                                        Popular posts from this blog

                                        Nidaros erkebispedøme

                                        Birsay

                                        Was Woodrow Wilson really a Liberal?Was World War I a war of liberals against authoritarians?Founding Fathers...