1

I want to apply functionality for the customer if customer place order within 72 hrs and subtotal greater than 250 then I want to give free shipping method otherwise if above 72 hrs or subtotal is less than 250 then I do not want to show free shipping. so how can I do this? I have done following coding for this functionality. My free-shipping method is not disabled when I add the product to the cart. So How can I disable free-shipping or enable free-shipping withing this condition.

namespace CustomCheckout\Checkout\Observer;

use Magento\Framework\Event\ObserverInterface;

class Totalsbefore implements ObserverInterface
{
    /**
     * custom event handler
     *
     * @param \Magento\Framework\Event\Observer $observer
     * @return void
     */

 public function execute(\Magento\Framework\Event\Observer $observer)
    {   

 $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerSession = $objectManager->create('Magento\Customer\Model\Session');

if ($customerSession->isLoggedIn()) {

    $customer_id = $customerSession->getCustomer()->getId(); 
 $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
 $orderCollection = $objectManager->create('\Magento\Sales\Model\ResourceModel\Order\Collection');
$order_Collection = $orderCollection->addAttributeToFilter('customer_id',$customer_id)
                    ->addFieldToSelect('created_at')
                    ->addAttributeToFilter('subtotal', array('gteq' => 250))
                    ->setPageSize(1)                    
                    ->setOrder('created_at', 'desc'); 

                    if(count($order_Collection)>0)
                     {

                         foreach($order_Collection as $order)
                        {
                         $LastOrderDate = $order->getCreatedAt();                    
                        }

                      $LastOrder = strtotime($LastOrderDate);
                       $NextTime = date("Y-m-d H:i:s", strtotime('-1 hours'));
                      $CheckTime = strtotime($NextTime);
                      $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
                      $cart = $objectManager->get('\Magento\Checkout\Model\Cart')->getQuote(); 
                      $subTotal = $cart->getSubtotal();
                      $store  =  $cart->getStoreId();
                      $carriers = $objectManager->get('Magento\Framework\App\Config\ScopeConfigInterface')->getValue('carriers');

                      if($LastOrder>=$CheckTime && $subTotal<=250)
                      {
                        $hiddenMethodCode   = 'freeshipping'; 

                         foreach ($carriers as $carrierCode => $carrierConfig) 
                        { 
                             $hiddenMethodCode   = 'freeshipping'; 
                           if( $carrierCode !=  $hiddenMethodCode)
                            {

                              //  $store->saveConfig("carriers/{$carrierCode}/active", '0');

                                 $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // Instance of object manager
                              $resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
                              $connection = $resource->getConnection();
                              $tableName = $resource->getTableName('core_config_data'); //gives table name with prefix

                              //Update Data into table
                              $sql = "Update " . $tableName . " Set  value= 0 where path='carriers/{$carrierCode}/active'";

                             // print_r($sql);  
                              $connection->query($sql); 
                            }
                        }          
                      }else{   // < 72 && > 250

                         $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
                      $cart = $objectManager->get('\Magento\Checkout\Model\Cart')->getQuote(); 
                      $subTotal = $cart->getSubtotal();
                      $store  =  $cart->getStoreId();
                      $carriers = $objectManager->get('Magento\Framework\App\Config\ScopeConfigInterface')->getValue('carriers');

                          $hiddenMethodCode   = 'freeshipping'; 

                          foreach ($carriers as $carrierCode => $carrierConfig) 
                          {
                            if( $carrierCode ==  $hiddenMethodCode)
                            {

                              $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // Instance of object manager
                              $resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
                              $connection = $resource->getConnection();
                              $tableName = $resource->getTableName('core_config_data'); //gives table name with prefix

                              //Update Data into table
                              $sql = "Update " . $tableName . " Set  value= 0 where path='carriers/{$carrierCode}/active'";

                               $connection->query($sql);
                             }
                          }
                        } 

                       }else{         

                      $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
                      $cart = $objectManager->get('\Magento\Checkout\Model\Cart')->getQuote(); 
                      $subTotal = $cart->getSubtotal();
                      $store  =  $cart->getStoreId();
                      $carriers = $objectManager->get('Magento\Framework\App\Config\ScopeConfigInterface')->getValue('carriers');

                              $hiddenMethodCode   = 'freeshipping'; 

                              foreach ($carriers as $carrierCode => $carrierConfig) 
                              {
                                if( $carrierCode ==  $hiddenMethodCode)
                                {

                              //  $store->saveConfig("carriers/{$carrierCode}/active", '0');

                              $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // Instance of object manager
                              $resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
                              $connection = $resource->getConnection();
                              $tableName = $resource->getTableName('core_config_data'); //gives table name with prefix

                              //Update Data into table
                              $sql = "Update " . $tableName . " Set  value= 0 where path='carriers/{$carrierCode}/active'";

                             // print_r($sql);  
                              $connection->query($sql);
                                }
                              }           
                            }

                    }   
  }  

}
0

Assuming you have created "My free-shipping" , you would have a file

MyVendor\ShippingMethod\Model\Carrier\MyFreeShipping.php and in collectRates function

 public function collectRates(RateRequest $request)
        {
            if (!$this->getConfigFlag('active')) {
                return false;
            }
            $result = $this->_rateResultFactory->create();
            $method = $this->_rateMethodFactory->create();


            if (!$this->shippingData->isFreeDeliveryAvailable()) {
                return false;
            }


            $method->setCarrier($this->_code);
            $method->setCarrierTitle($this->getConfigData('title'));

            $method->setMethod($this->_code);
            $method->setMethodTitle($this->getConfigData('name'));
            $method->setPrice('0');
            $method->setMethodDescription($deliveryDateMessage);
            $method->setCost('0');

            $result->append($method);

            return $result;
        }
public function isFreeDeliveryAvailable()
{
///check for your conditions here and return true or false
}

I have not tested this code , please let me know if face any error or issue .

This would be a better approach than event observer.

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.