0

I want to override _getXmlQuotes() function to set a condition for price based on discount but it's not working anyone has an idea about it?

i have created di.xml to override model/carrier:

<?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\Ups\Model\Carrier" type="Vendor\Mymodule\Model\Carrier" />    
 </config>

Created Model to override inbuilt model of ups:

  <?php
 /**
 * Copyright © Magento, Inc. All rights reserved.
  * See COPYING.txt for license details.
 */
 //declare(strict_types=1);

 namespace Vendor\Module\Model;

use Magento\Quote\Model\Quote\Address\RateResult\Error;
use Magento\Quote\Model\Quote\Address\RateRequest;
use Magento\Shipping\Model\Carrier\AbstractCarrierOnline;
use Magento\Shipping\Model\Carrier\CarrierInterface;
use Magento\Shipping\Model\Rate\Result;
use Magento\Shipping\Model\Simplexml\Element;
use Magento\Ups\Helper\Config;
use Magento\Framework\Xml\Security;
use Magento\Framework\HTTP\AsyncClientInterface;

  /**
  * UPS shipping implementation
  * @SuppressWarnings(PHPMD.ExcessiveClassComplexity)
  * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
  */
 class Carrier extends \Magento\Ups\Model\Carrier
 { 


/**
 * Collect and get rates/errors
 *
 * @param RateRequest $request
 * @return Result|Error|bool
 */
public function collectRates(RateRequest $request)
{ 
    $this->setRequest($request);
    if (!$this->canCollectRates()) {
        return $this->getErrorMessage();
    }

    $this->setRequest($request);
    //To use the correct result in the callback.
    $this->_result = $result = $this->_getQuotes();

    return $this->deferredProxyFactory->create(
        [
            'deferred' => new CallbackDeferred(
                function () use ($request, $result) {
                    $this->_result = $result;
                    $this->_updateFreeMethodQuote($request);
                    return $this->getResult();
                }
            )
        ]
    );
}

/**
 * Do remote request for  and handle errors
 *
 * @return Result|null
 */
protected function _getQuotes()
{ 
    switch ($this->getConfigData('type')) {
        case 'UPS':
            return $this->_getCgiQuotes();
        case 'UPS_XML':
            return $this->_getXmlQuotes();
        default:
            break;
    }

    return null;
}

/**
 * Prepare shipping rate result based on response
 *
 * @param mixed $xmlResponse
 * @return Result
 * @SuppressWarnings(PHPMD.CyclomaticComplexity)
 * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
 * @SuppressWarnings(PHPMD.ElseExpression)
 */
protected function _parseXmlResponse($xmlResponse)
{  
    $costArr = [];
    $priceArr = [];
    if (strlen(trim($xmlResponse)) > 0) {
        $xml = new \Magento\Framework\Simplexml\Config();
        $xml->loadString($xmlResponse);
        $arr = $xml->getXpath("//RatingServiceSelectionResponse/Response/ResponseStatusCode/text()");
        $success = (int)$arr[0];
        if ($success === 1) {
            $arr = $xml->getXpath("//RatingServiceSelectionResponse/RatedShipment");
            $allowedMethods = explode(",", $this->getConfigData('allowed_methods'));

            // Negotiated rates
            $negotiatedArr = $xml->getXpath("//RatingServiceSelectionResponse/RatedShipment/NegotiatedRates");
            $negotiatedActive = $this->getConfigFlag('negotiated_active')
                && $this->getConfigData('shipper_number')
                && !empty($negotiatedArr);

            $allowedCurrencies = $this->_currencyFactory->create()->getConfigAllowCurrencies();
            foreach ($arr as $shipElement) {
                $this->processShippingRateForItem(
                    $shipElement,
                    $allowedMethods,
                    $allowedCurrencies,
                    $costArr,
                    $priceArr,
                    $negotiatedActive,
                    $xml
                );
            }
        } else {
            $arr = $xml->getXpath("//RatingServiceSelectionResponse/Response/Error/ErrorDescription/text()");
            $errorTitle = (string)$arr[0][0];
            $error = $this->_rateErrorFactory->create();
            $error->setCarrier('ups');
            $error->setCarrierTitle($this->getConfigData('title'));
            $error->setErrorMessage($this->getConfigData('specificerrmsg'));
        }
    }

    $result = $this->_rateFactory->create();

    if (empty($priceArr)) {
        $error = $this->_rateErrorFactory->create();
        $error->setCarrier('ups');
        $error->setCarrierTitle($this->getConfigData('title'));
        if ($this->getConfigData('specificerrmsg') !== '') {
            $errorTitle = $this->getConfigData('specificerrmsg');
        }
        if (!isset($errorTitle)) {
            $errorTitle = __('Cannot retrieve shipping rates');
        }
        $error->setErrorMessage($errorTitle);
        $result->append($error);
    } else { 

        foreach ($priceArr as $method => $price) {    
            $rate = $this->_rateMethodFactory->create();
            $rate->setCarrier('ups');
            $rate->setCarrierTitle($this->getConfigData('title'));
            $rate->setMethod($method);
            $methodArr = $this->getShipmentByCode($method);
            $rate->setMethodTitle($methodArr);
            $rate->setCost($costArr[$method]);

            //update price based on shipping discount
            /* $shippingDiscount = 45;   //$this->getConfigData('shipping_discount');         
            $shippingRate = ($shippingDiscount * $price)  / 100;
            $price = $price - $shippingRate; */

            $rate->setPrice($price);      
            $result->append($rate); 
        }
    }

    return $result;
}
2
  • Please add the code that you've tried. Apr 20 '20 at 8:52
  • hello @HamendraSunthwal i have updated my code please check Apr 20 '20 at 9:05
0

A good example on magento doc about overriding a protected fn using preference - https://devdocs.magento.com/guides/v2.3/extension-dev-guide/build/di-xml-file.html

you need just the overriding function not all the things from base copy as you're extending that original class.

namespace ...;

class Success extends \Magento\Checkout\Block\Onepage\Success
{
    ...
    public function __construct(
     ..
    ) {
        parent::__construct(
          ...
        );
    }


    protected function _getXmlQuotes()
    {
       // your code 
    }
}

something like this should work

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.