Magento – Shipping rate calculation in Table rate Shipping method Magento 2

magento2shipping-methodstable-rates

I am developing custom shipping method similar to Table rate Shipping method in which I am comparing Product SKU instead of Product Weight/Price.

I am able to import CSV with this change and store CSV data in my custom table successfully.

Now i am not able to find code in Table rate shipping method which is responsible for comparing Product weight/Price with CSV Weight/Price and display shipping rate accordingly in Checkout page.

If anybody has studied Table rate shipping method code, Please guide to find code block for this.

Thanks!

Best Answer

Open vendor/magento/module-offline-shipping/Model/Carrier/Tablerate.php


/**
 * Get rate.
 *
 * @param \Magento\Quote\Model\Quote\Address\RateRequest $request
 * @return array|bool
 */
public function getRate(\Magento\Quote\Model\Quote\Address\RateRequest $request)
{
    return $this->_tablerateFactory->create()->getRate($request);
}

vendor/magento/module-offline-shipping/Model/ResourceModel/Carrier/Tablerate.php


/**
 * Return table rate array or false by rate request
 *
 * @param \Magento\Quote\Model\Quote\Address\RateRequest $request
 * @return array|bool
 */
public function getRate(\Magento\Quote\Model\Quote\Address\RateRequest $request)
{
    $connection = $this->getConnection();

    $select = $connection->select()->from($this->getMainTable());
    /** @var RateQuery $rateQuery */
    $rateQuery = $this->rateQueryFactory->create(['request' => $request]);

    $rateQuery->prepareSelect($select);
    $bindings = $rateQuery->getBindings();

    $result = $connection->fetchRow($select, $bindings);
    // Normalize destination zip code
    if ($result && $result['dest_zip'] == '*') {
        $result['dest_zip'] = '';
    }

    return $result;
}

Also check

vendor/magento/module-offline-shipping/Model/ResourceModel/Carrier/Tablerate/RateQuery.php


public function prepareSelect(\Magento\Framework\DB\Select $select)

Now calculation shipping price:

vendor/magento/module-shipping/Model/Carrier/AbstractCarrier.php


/**
 * Get the handling fee for the shipping + cost
 *
 * @param float $cost
 * @return float final price for shipping method
 */
public function getFinalPriceWithHandlingFee($cost)
{
    $handlingFee = (float)$this->getConfigData('handling_fee');
    $handlingType = $this->getConfigData('handling_type');
    if (!$handlingType) {
        $handlingType = self::HANDLING_TYPE_FIXED;
    }
    $handlingAction = $this->getConfigData('handling_action');
    if (!$handlingAction) {
        $handlingAction = self::HANDLING_ACTION_PERORDER;
    }

    return $handlingAction == self::HANDLING_ACTION_PERPACKAGE ? $this->_getPerpackagePrice(
        $cost,
        $handlingType,
        $handlingFee
    ) : $this->_getPerorderPrice(
        $cost,
        $handlingType,
        $handlingFee
    );
}
Related Topic