2

I am learning magento , so I am trying to create a custom vat module that will allow users to validate vat and on success vat validation tax will be 0. I have added field on frontend checkout step to add input on clicking next I am not getting value of the field on first time " next " , but I get that value on clicking second time after coming back from checkout/#payment page..

Here is the code I have added so far this is my module.xml file

    <?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="Mac_DiscountPlugin" setup_version="0.0.1">
            <sequence>
                <module name="Magento_Quote" />
                <module name="Magento_Checkout" />
            </sequence>
    </module>
</config>

This is the layout proccessor to add input field on checkout step

class LayoutProcessor
{
    /**
     * @param \Magento\Checkout\Block\Checkout\LayoutProcessor $subject
     * @param array $jsLayout
     * @return array
     */
    public function afterProcess(
        \Magento\Checkout\Block\Checkout\LayoutProcessor $subject,
        array  $jsLayout
    ) {

        $customAttributeCode = 'save_vat_discount';
        $customField = [
            'component' => 'Magento_Ui/js/form/element/select',
            'config' => [
                'customScope' => 'shippingAddress',
                'template' => 'ui/form/field',
                'elementTmpl' => 'ui/form/element/input',
            ],
            'dataScope' => 'shippingAddress.save_vat_discount',
            'label' => 'Vat Code',
            'provider' => 'checkoutProvider',
            'visible' => true,
            'validation' => ['required-entry' => false],
            'sortOrder' => 150,
        ];

        $jsLayout['components']['checkout']['children']['steps']['children']['shipping-step']['children']['shippingAddress']['children']['shipping-address-fieldset']['children'][$customAttributeCode] = $customField;

        return $jsLayout;
    }
}

this is my mixin file

define(
    [
        'ko',
        'jquery',
        'Magento_Checkout/js/model/quote',
        'Magento_Checkout/js/model/resource-url-manager',
        'mage/storage',
        'Magento_Checkout/js/model/payment-service',
        'Magento_Checkout/js/model/payment/method-converter',
        'Magento_Checkout/js/model/error-processor'
    ],
    function (ko, $, quote, resourceUrlManager, storage, paymentService, methodConverter, errorProcessor) {
        'use strict';


        $(document).ready(function () {
            $(document).on('change', "[name='country_id']", function () {
                $("input:text[name='save_vat_discount']").parent('div').parent('div').hide();
                var optionSelected = $("option:selected", this);
                var valueSelected = this.value;
                if(valueSelected=='GB'){
                    $("input:text[name='save_vat_discount']").parent('div').parent('div').show();
                    $(document).on('blur', "input:text[name='save_vat_discount']", function () {
                        var vatcode = $(this).val();
                        $.ajax({
                            url: '/discountplugin/index/validationcall',
                            data:  {
                                'vatnumber':vatcode
                            },
                            type: "post",
                            cache: false,
                            success: function (data) {

                            }
                        });

                    });
                }else{
                    $("input:text[name='save_vat_discount']").parent('div').parent('div').hide();
                }
            });
        });





        return {
            saveShippingInformation: function() {
                var payload = {

                    addressInformation: {
                        shipping_address: quote.shippingAddress(),
                        shipping_method_code: quote.shippingMethod().method_code,
                        shipping_carrier_code: quote.shippingMethod().carrier_code,
                        extension_attributes: {
                            save_vat_discount: $('[name="save_vat_discount"]').val()
                        }
                    }
                };

                return storage.post(
                    resourceUrlManager.getUrlForSetShippingInformation(quote),
                    JSON.stringify(payload)
                ).done(
                    function (response) {
                        quote.setTotals(response.totals);
                        paymentService.setPaymentMethods(methodConverter(response.payment_methods));
                    }
                ).fail(
                    function (response) {
                        errorProcessor.process(response);
                    }
                );
            }
        };
    }
);

this is my extension_attributes.xml file

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Sales:etc/sales.xsd">
    <section name="quote">
        <group name="totals">
            <item name="sat_vat_discount" instance="Mac\DiscountPlugin\Model\DiscountCalculation" sort_order="500"/>
        </group>
    </section>
</config>

this is my di.xml file

<?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="Magento\Checkout\Block\Checkout\LayoutProcessor">
       <plugin name="add_vat_discount_field" type="Mac\DiscountPlugin\Plugin\Checkout\LayoutProcessor" sortOrder="10"/>
   </type>
   <type name="Magento\Checkout\Model\ShippingInformationManagement">
      <plugin name="save_to_quote_table" type="Mac\DiscountPlugin\Plugin\Checkout\SaveAddressInformation" sortOrder="10"/>
   </type>
   <type name="Magento\Quote\Model\ShippingAddressManagement">
      <plugin  name="shipping_management_custom" sortOrder="10" type="Mac\DiscountPlugin\Plugin\Checkout\ShippingAddressManagement"/>
   </type>
</config>

this is to store inout field to quote table

class SaveAddressInformation
{
    /**
     * @var \Magento\Quote\Model\QuoteRepository
     */
    protected $quoteRepository;

    /**
     * SaveAddressInformation constructor.
     * @param \Magento\Quote\Model\QuoteRepository $quoteRepository
     */
    public function __construct(
        \Magento\Quote\Model\QuoteRepository $quoteRepository
    ) {
        $this->quoteRepository = $quoteRepository;
    }

    /**
     * @param \Magento\Checkout\Model\ShippingInformationManagement $subject
     * @param $cartId
     * @param \Magento\Checkout\Api\Data\ShippingInformationInterface $addressInformation
     */
    public function beforeSaveAddressInformation(
        \Magento\Checkout\Model\ShippingInformationManagement $subject,
        $cartId,
        \Magento\Checkout\Api\Data\ShippingInformationInterface $addressInformation
    ) {
        $extAttributes = $addressInformation->getExtensionAttributes();
        $discount = $extAttributes->getSaveVatDiscount();
        $quote = $this->quoteRepository->getActive($cartId);
        $quote->setSaveVatDiscount($discount);

    }
}

and finally this is the collect() method where i am not getting vat discount input field value

class DiscountCalculation extends \Magento\Quote\Model\Quote\Address\Total\AbstractTotal
{
    public function __construct(
        \Magento\Framework\Event\ManagerInterface $eventManager,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\SalesRule\Model\Validator $validator,
        \Magento\Framework\Pricing\PriceCurrencyInterface $priceCurrency
    )
    {
        $this->setCode('save_vat_discount');
        $this->eventManager = $eventManager;
        $this->calculator = $validator;
        $this->storeManager = $storeManager;
        $this->priceCurrency = $priceCurrency;
    }

    public function collect(
        \Magento\Quote\Model\Quote $quote,
        \Magento\Quote\Api\Data\ShippingAssignmentInterface $shippingAssignment,
        \Magento\Quote\Model\Quote\Address\Total $total
    ) {
        parent::collect($quote, $shippingAssignment, $total);
        $address             = $shippingAssignment->getShipping()->getAddress();
        $extAttributes = $address->getExtensionAttributes();

            $vatcode = $quote->getSaveVatDiscount();
            if(isset($tax) && $tax>0){
                $label               = 'Vat Discount';
                $discountAmount      = -$tax;

                $appliedCartDiscount = 0;
                if($total->getDiscountDescription()) {
                    // If a discount exists in cart and another discount is applied, the add both discounts.
                    $appliedCartDiscount = $total->getDiscountAmount();
                    $discountAmount      = $total->getDiscountAmount()+$discountAmount;
                    $label               = $total->getDiscountDescription().', '.$label;
                }

                $total->setDiscountDescription($label);
                $total->setDiscountAmount($discountAmount);
                $total->setBaseDiscountAmount($discountAmount);
                $total->setSubtotalWithDiscount($total->getSubtotal() + $discountAmount);
                $total->setBaseSubtotalWithDiscount($total->getBaseSubtotal() + $discountAmount);

                if(isset($appliedCartDiscount)) {
                    $total->addTotalAmount($this->getCode(), $discountAmount - $appliedCartDiscount);
                    $total->addBaseTotalAmount($this->getCode(), $discountAmount - $appliedCartDiscount);
                } else {
                    $total->addTotalAmount($this->getCode(), $discountAmount);
                    $total->addBaseTotalAmount($this->getCode(), $discountAmount);
                }
            }

       /* }*/
        return $this;
    }

    public function fetch(\Magento\Quote\Model\Quote $quote, \Magento\Quote\Model\Quote\Address\Total $total)
    {
        $result = null;
        $amount = $total->getDiscountAmount();

        if ($amount != 0)
        {
            $description = $total->getDiscountDescription();
            $result = [
                'code' => $this->getCode(),
                'title' => 'Discountsdsssd',
                'value' => $amount
            ];
        }
        return $result;
    }
}

I am not getting $quote->getSaveVatDiscount() on first next click of checkout page .

Magento 2 .

Looking for your help friends .

Thanks in Advance

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.