-1

With a custom shipping module, I am adding brokerage and duties to the shipping cost for an order from Canada. How can the shipping label be changed so that it reads "Shipping includes brokerage and duties"

enter image description here

Below is entire customshipping.php script

<?php

namespace Perfectmakeupmirrors\CustomShipping\Model\Carrier;

use Magento\Quote\Model\Quote\Address\RateRequest;
use Magento\Shipping\Model\Carrier\AbstractCarrier;
use Magento\Shipping\Model\Carrier\CarrierInterface;
use Perfectmakeupmirrors\PmmFedex\Model\PmmFedexCarrier;
use Magento\Framework\App\ResourceConnection;

/**
 * Custom shipping model
 */
class Customshipping extends AbstractCarrier implements CarrierInterface
{
    const FEDEX_METHODS = [
        'EUROPE_FIRST_INTERNATIONAL_PRIORITY' => 'Europe First Priority',
        'FEDEX_1_DAY_FREIGHT' => '1 Day Freight',
        'FEDEX_2_DAY_FREIGHT' => '2 Day Freight',
        'FEDEX_2_DAY' => '2 Day',
        'FEDEX_2_DAY_AM' => '2 Day AM',
        'FEDEX_3_DAY_FREIGHT' => '3 Day Freight',
        'FEDEX_EXPRESS_SAVER' => 'Express Saver',
        'FEDEX_GROUND' => 'Ground',
        'FIRST_OVERNIGHT' => 'First Overnight',
        'GROUND_HOME_DELIVERY' => 'Home Delivery',
        'INTERNATIONAL_ECONOMY' => 'International Economy',
        'INTERNATIONAL_ECONOMY_FREIGHT' => 'Intl Economy Freight',
        'INTERNATIONAL_FIRST' => 'International First',
        'INTERNATIONAL_GROUND' => 'International Ground',
        'INTERNATIONAL_PRIORITY' => 'International Priority',
        'INTERNATIONAL_PRIORITY_FREIGHT' => 'Intl Priority Freight',
        'PRIORITY_OVERNIGHT' => 'Priority Overnight',
        'SMART_POST' => 'Smart Post',
        'STANDARD_OVERNIGHT' => 'Standard Overnight',
        'FEDEX_FREIGHT' => 'Freight',
        'FEDEX_NATIONAL_FREIGHT' => 'National Freight'
    ];
    const SHIPPING_STANDARD = 'STD';
    const SHIPPING_2ND_DAY = '2DY';
    const SHIPPING_OVERNIGHT = 'ON';
    protected $_shipping_mode_strings = array(
        self::SHIPPING_STANDARD => 'Standard Ground',
        self::SHIPPING_2ND_DAY => 'Second Day',
        self::SHIPPING_OVERNIGHT => 'Next Day Air',
    );

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

    /**
     * @var bool
     */
    protected $_isFixed = true;

    /**
     * @var \Magento\Shipping\Model\Rate\ResultFactory
     */
    private $rateResultFactory;

    /**
     * @var \Magento\Quote\Model\Quote\Address\RateResult\MethodFactory
     */
    private $rateMethodFactory;

    /**
     * @var \Perfectmakeupmirrors\CustomShipping\Helper\Data
     */
    private $helper;

    /**
     * @var \Psr\Log\LoggerInterface
     */
    protected $_logger;

    /**
     * @var Perfectmakeupmirrors\PmmFedex\Model\PmmFedexCarrier;
     */
    private $carrierFedex;

    /**
     * @var Magento\Framework\App\ResourceConnection;
     */
    protected $resource;

    /**
     * @var Magento\Framework\App\ResourceConnection;
     */
    protected $scopeConfig;

    /**
     * @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 \Magento\Framework\App\ResourceConnection $resource
     * @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\Quote\Model\Quote\Address\RateResult\MethodFactory $rateMethodFactory,
        \Perfectmakeupmirrors\CustomShipping\Helper\Data $helper,
        \Perfectmakeupmirrors\PmmFedex\Model\PmmFedexCarrier $carrierFedex,
        \Magento\Framework\App\ResourceConnection $resource,
        array $data = []
    ) {
        parent::__construct($scopeConfig, $rateErrorFactory, $logger, $data);

        $this->rateResultFactory = $rateResultFactory;
        $this->rateMethodFactory = $rateMethodFactory;
        $this->carrierFedex = $carrierFedex;
        $this->_logger = $logger;
        $this->helper = $helper;
        $this->resource = $resource;
        $this->scopeConfig = $scopeConfig;
    }

    /**
     * Custom Shipping Rates Collector
     *
     * @param RateRequest $request
     * @return \Magento\Shipping\Model\Rate\Result|bool
     */
    public function collectRates(RateRequest $request)
    {
        if (!$this->getConfigFlag('active')) {
            return false;
        }
        
        if ($request->getDestCountryId() == "CA") {
            // Shipping to Canada.
            // 1. Get the array of method objects from $fedex_results object
            // 2. Loop through the array of method objects to set carrier.
            // 3. Set carrier to custom shipping.
            // 4. Add brokerage to the shipping cost based on the table canada_brokerage_fees.
            $fedex_results = $this->carrierFedex->collectRates($request);

            // \Magento\Quote\Model\Quote\Address\RateResult\Method $methods
            $methods = $fedex_results->getAllRates();
            foreach ($methods as $method) {
                // 3. Set carrier to custom shipping.
                $method->setCarrier($this->_code);

                // Get subtotal from the $request object.
                // The request object is not giving the subtotal directly.
                // Using Quote object.
                // Refer https://magento.stackexchange.com/questions/341393/magento-2-4-2-how-to-get-order-sub-total-in-my-custom-module/341410#341410
                $quote = null;
                $items = $request->getAllItems();
                foreach($items as $item) {
                    /** @var Quote $quote */
                    $quote = $item->getQuote();
                    break;
                }
                if (!$quote) {
                    return false;
                }
                $subtotal = $quote->getSubtotal();                

                // Convert subtotal from USD to CAD
                // Get current CAD rate.
                $current_usd_to_cad_rate = $this->get_magento_system_info("pmm/currency_conversion/usd_to_cad_conversion");
                $subtotal_cad = $subtotal * floatval($current_usd_to_cad_rate);

                // Use table canada_brokerage_fee in Magento DB
                // Create DB connection
                // http://blog.chapagain.com.np/magento-2-run-custom-sql-query/
                $connection = $this->resource->getConnection();
                $tableName = $this->resource->getTableName('canada_brokerage_fees');

                // Compute brokerage.
                // Fetch relevant fee from the table canada_brokerage_fees 
                // based on the merchandise total.
                $sql = $connection->select()->from($tableName)->where('max_merchandise_cost <= ?', $subtotal_cad)
                ->order('brokerage_cost_cad DESC')->limit(1);
                $result = $connection->fetchAll($sql);                
                $brokerage_cost_cad = $result[0]['brokerage_cost_cad'] ?? 0;

                // TODO
                // Compute duty and add it to brokerage_cost_cad.
                // All mirror and skin care products are duty free.

                // Set new price with brokerage added to the shipping cost.
                $method->setPrice($method->getPrice() + $brokerage_cost_cad);
            }
            return $fedex_results;
        } elseif (($request->getDestRegionCode() == "AK") || ($request->getDestRegionCode() == "HI") || ($request->getDestCountryId() == "PR")) {
            // For Alaska, Hawaii, and Puerto Rico
            // We want to get the shipping computation using Fedex

            $fedex_results = $this->carrierFedex->collectRates($request);
            // 1. Get the array of method objects from $fedex_results object
            // 2. Loop through the array of method objects to set carrier.
            // 3. Set carrier to custom shipping. 

            // \Magento\Quote\Model\Quote\Address\RateResult\Method $methods
            $methods = $fedex_results->getAllRates();
            foreach ($methods as $method) {
                $method->setCarrier($this->_code);
            }
            return $fedex_results;
        }

        // Below Processing is for Mainland USA.
        // Custom Shipping needs to be computed.
        /** @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'));

        $this->_logger->info(__FILE__ . ': At Start');

        // Get all the items.
        // NOTE: This getAllItems here is related to Quote and not the order.
        if ((!($items = $request->getAllItems())) or (count($items) == 0)) {
            return FALSE;
        }

        //Standard code commented. Custom code added.
        //$shippingCost = (float)$this->getConfigData('shipping_cost');
        $shippingCost = (float)$this->helper->compute_standard_shipping_cost($items);

        $method->setPrice($shippingCost);
        $method->setCost($shippingCost);

        $result->append($method);

        return $result;
    }

    /**
     * Get all the allowed methods for Custom Shipping. This sends the CustomShipping
     * method as well as all the allowed methods of Fedex. This is required to ensure
     * the Fedex shipping methods to be considered as valid methods.
     * 
     * @return array
     */
    public function getAllowedMethods()
    {
        $custom_shipping_methods = [$this->_code => $this->getConfigData('name')];
        $allowed_methods = array_merge($custom_shipping_methods, $this->FEDEX_METHODS);
        return $allowed_methods;
    }

    /**
     * get_magento_system_info - receives the path as parameter.
     * This parameter holds the path to the field.
     * This function returns a value in Magento core_config_data table.
     * 
     * @param string $path
     * @return string $config_data
     */
    private function get_magento_system_info($path)
    {
        // Refer https://store.magenest.com/blog/get-set-config-data-programmatically-magento-2/
        // Refer https://firebearstudio.com/blog/how-to-write-and-get-config-values-by-scope-in-magento-2.html

        // Call functions to get config data with default (global) scope
        return $this->scopeConfig->getValue($path);
    }
}
3
  • how you created the custom shipping method? Jul 29, 2021 at 4:35
  • Please look at the script added above, used to create a custom shipping module. Jul 29, 2021 at 5:27
  • Hi, is there a way to remove name "Federal Express" under Shipping as seen in the image above? Jul 29, 2021 at 15:47

1 Answer 1

0

From your code :

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

This line is use to set those things. Sp you need to do the changes here.

2
  • Thanks, it works. Made the change. Jul 29, 2021 at 6:18
  • if answer help, upvote and mark as solutions, so this will help other in community. Jul 29, 2021 at 6:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.