Example #1
0
 /**
  * @param RateRequest $request
  * @return bool|Result|null
  */
 public function collectRates(RateRequest $request)
 {
     if (!$this->getConfigFlag('active')) {
         return false;
     }
     $expressAvailable = true;
     $expressMaxWeight = $this->getConfigData('express_max_weight');
     $shippingTotalWeight = 0;
     $this->_result = $this->_rateResultFactory->create();
     if ($request->getAllItems()) {
         foreach ($request->getAllItems() as $item) {
             if ($item->getProduct()->isVirtual() || $item->getParentItem()) {
                 continue;
             }
             if ($item->getHasChildren() && $item->isShipSeparately()) {
                 foreach ($item->getChildren() as $child) {
                     if ($child->getFreeShipping() && !$child->getProduct()->isVirtual()) {
                         $shippingTotalWeight += $child->getWeight();
                     }
                 }
             } elseif ($item->getFreeShipping()) {
                 $shippingTotalWeight += $item->getWeight();
             }
         }
     }
     if ($shippingTotalWeight > $expressMaxWeight) {
         $expressAvailable = false;
     }
     if ($expressAvailable) {
         $this->_getExpressRate();
     }
     $this->_getStandardRate();
     return $this->getResult();
 }
Example #2
0
 /**
  * @param \Magento\Sales\Model\Quote\Address\RateRequest $request
  * @return Result|bool
  */
 public function collectRates(\Magento\Sales\Model\Quote\Address\RateRequest $request)
 {
     if (!$this->getConfigFlag('active')) {
         return false;
     }
     $freeBoxes = 0;
     if ($request->getAllItems()) {
         foreach ($request->getAllItems() as $item) {
             if ($item->getProduct()->isVirtual() || $item->getParentItem()) {
                 continue;
             }
             if ($item->getHasChildren() && $item->isShipSeparately()) {
                 foreach ($item->getChildren() as $child) {
                     if ($child->getFreeShipping() && !$child->getProduct()->isVirtual()) {
                         $freeBoxes += $item->getQty() * $child->getQty();
                     }
                 }
             } elseif ($item->getFreeShipping()) {
                 $freeBoxes += $item->getQty();
             }
         }
     }
     $this->setFreeBoxes($freeBoxes);
     /** @var Result $result */
     $result = $this->_rateResultFactory->create();
     if ($this->getConfigData('type') == 'O') {
         // per order
         $shippingPrice = $this->getConfigData('price');
     } elseif ($this->getConfigData('type') == 'I') {
         // per item
         $shippingPrice = $request->getPackageQty() * $this->getConfigData('price') - $this->getFreeBoxes() * $this->getConfigData('price');
     } else {
         $shippingPrice = false;
     }
     $shippingPrice = $this->getFinalPriceWithHandlingFee($shippingPrice);
     if ($shippingPrice !== false) {
         /** @var \Magento\Sales\Model\Quote\Address\RateResult\Method $method */
         $method = $this->_rateMethodFactory->create();
         $method->setCarrier('flatrate');
         $method->setCarrierTitle($this->getConfigData('title'));
         $method->setMethod('flatrate');
         $method->setMethodTitle($this->getConfigData('name'));
         if ($request->getFreeShipping() === true || $request->getPackageQty() == $this->getFreeBoxes()) {
             $shippingPrice = '0.00';
         }
         $method->setPrice($shippingPrice);
         $method->setCost($shippingPrice);
         $result->append($method);
     }
     return $result;
 }
Example #3
0
 /**
  * @covers \Magento\Shipping\Model\Shipping::composePackagesForCarrier
  */
 public function testComposePackages()
 {
     $request = new RateRequest();
     /** \Magento\Catalog\Model\Product\Configuration\Item\ItemInterface */
     $item = $this->getMockBuilder('\\Magento\\Sales\\Model\\Quote\\Item')->disableOriginalConstructor()->setMethods(['getQty', 'getIsQtyDecimal', 'getProductType', 'getProduct', 'getWeight', '__wakeup'])->getMock();
     $product = $this->getMock('Magento\\Catalog\\Model\\Product', [], [], '', false);
     $item->expects($this->any())->method('getQty')->will($this->returnValue(1));
     $item->expects($this->any())->method('getWeight')->will($this->returnValue(10));
     $item->expects($this->any())->method('getIsQtyDecimal')->will($this->returnValue(true));
     $item->expects($this->any())->method('getProductType')->will($this->returnValue(\Magento\Catalog\Model\Product\Type::TYPE_SIMPLE));
     $item->expects($this->any())->method('getProduct')->will($this->returnValue($product));
     $product->expects($this->any())->method('getId')->will($this->returnValue($this->productId));
     $request->setData('all_items', [$item]);
     $this->stockItemData->expects($this->any())->method('getIsDecimalDivided')->will($this->returnValue(true));
     /** Testable service calls to CatalogInventory module */
     $this->stockItemService->expects($this->atLeastOnce())->method('getStockItem')->with($this->productId);
     $this->stockItemService->expects($this->atLeastOnce())->method('getEnableQtyIncrements')->with($this->productId)->will($this->returnValue(true));
     $this->stockItemService->expects($this->atLeastOnce())->method('getQtyIncrements')->with($this->productId)->will($this->returnValue(0.5));
     $this->shipping->composePackagesForCarrier($this->carrier, $request);
 }
Example #4
0
 /**
  * @covers \Magento\Shipping\Model\Shipping::composePackagesForCarrier
  */
 public function testComposePackages()
 {
     $this->carrier->expects($this->any())->method('getConfigData')->will($this->returnCallback(function ($key) {
         $configData = ['max_package_weight' => 10, 'showmethod' => 1];
         return isset($configData[$key]) ? $configData[$key] : 0;
     }));
     $product = $this->getMock('Magento\\Catalog\\Model\\Product', [], [], '', false);
     $product->expects($this->any())->method('getId')->will($this->returnValue($this->productId));
     $item = $this->getMockBuilder('\\Magento\\Sales\\Model\\Quote\\Item')->disableOriginalConstructor()->setMethods(['getProduct', 'getQty', 'getWeight', '__wakeup'])->getMock();
     $item->expects($this->any())->method('getProduct')->will($this->returnValue($product));
     $request = new RateRequest();
     $request->setData('all_items', [$item]);
     $request->setData('dest_postcode', 1);
     /** Testable service calls to CatalogInventory module */
     $this->stockItemService->expects($this->atLeastOnce())->method('getStockItem')->with($this->productId);
     $this->stockItemService->expects($this->atLeastOnce())->method('getEnableQtyIncrements')->with($this->productId)->will($this->returnValue(true));
     $this->stockItemService->expects($this->atLeastOnce())->method('getQtyIncrements')->with($this->productId)->will($this->returnValue(5));
     $this->stockItemData->expects($this->atLeastOnce())->method('getIsQtyDecimal')->will($this->returnValue(true));
     $this->stockItemData->expects($this->atLeastOnce())->method('getIsDecimalDivided')->will($this->returnValue(true));
     $this->carrier->proccessAdditionalValidation($request);
 }
Example #5
0
 /**
  * Return table rate array or false by rate request
  *
  * @param \Magento\Sales\Model\Quote\Address\RateRequest $request
  * @return array|bool
  */
 public function getRate(\Magento\Sales\Model\Quote\Address\RateRequest $request)
 {
     $adapter = $this->_getReadAdapter();
     $bind = array(':website_id' => (int) $request->getWebsiteId(), ':country_id' => $request->getDestCountryId(), ':region_id' => (int) $request->getDestRegionId(), ':postcode' => $request->getDestPostcode());
     $select = $adapter->select()->from($this->getMainTable())->where('website_id = :website_id')->order(array('dest_country_id DESC', 'dest_region_id DESC', 'dest_zip DESC'))->limit(1);
     // Render destination condition
     $orWhere = '(' . implode(') OR (', array("dest_country_id = :country_id AND dest_region_id = :region_id AND dest_zip = :postcode", "dest_country_id = :country_id AND dest_region_id = :region_id AND dest_zip = ''", "dest_country_id = :country_id AND dest_region_id = :region_id AND dest_zip = '*'", "dest_country_id = :country_id AND dest_region_id = 0 AND dest_zip = '*'", "dest_country_id = '0' AND dest_region_id = :region_id AND dest_zip = '*'", "dest_country_id = '0' AND dest_region_id = 0 AND dest_zip = '*'", "dest_country_id = :country_id AND dest_region_id = 0 AND dest_zip = ''", "dest_country_id = :country_id AND dest_region_id = 0 AND dest_zip = :postcode", "dest_country_id = :country_id AND dest_region_id = 0 AND dest_zip = '*'")) . ')';
     $select->where($orWhere);
     // Render condition by condition name
     if (is_array($request->getConditionName())) {
         $orWhere = array();
         $i = 0;
         foreach ($request->getConditionName() as $conditionName) {
             $bindNameKey = sprintf(':condition_name_%d', $i);
             $bindValueKey = sprintf(':condition_value_%d', $i);
             $orWhere[] = "(condition_name = {$bindNameKey} AND condition_value <= {$bindValueKey})";
             $bind[$bindNameKey] = $conditionName;
             $bind[$bindValueKey] = $request->getData($conditionName);
             $i++;
         }
         if ($orWhere) {
             $select->where(implode(' OR ', $orWhere));
         }
     } else {
         $bind[':condition_name'] = $request->getConditionName();
         $bind[':condition_value'] = $request->getData($request->getConditionName());
         $select->where('condition_name = :condition_name');
         $select->where('condition_value <= :condition_value');
     }
     $result = $adapter->fetchRow($select, $bind);
     // Normalize destination zip code
     if ($result && $result['dest_zip'] == '*') {
         $result['dest_zip'] = '';
     }
     return $result;
 }
Example #6
0
 /**
  * Generation Shipment Details Node according to origin region
  *
  * @param \Magento\Shipping\Model\Simplexml\Element $xml
  * @param RateRequest $rawRequest
  * @param string $originRegion
  * @return void
  */
 protected function _shipmentDetails($xml, $rawRequest, $originRegion = '')
 {
     $nodeShipmentDetails = $xml->addChild('ShipmentDetails', '', '');
     $nodeShipmentDetails->addChild('NumberOfPieces', count($rawRequest->getPackages()));
     if ($originRegion) {
         $nodeShipmentDetails->addChild('CurrencyCode', $this->_storeManager->getWebsite($this->_request->getWebsiteId())->getBaseCurrencyCode());
     }
     $nodePieces = $nodeShipmentDetails->addChild('Pieces', '', '');
     /*
      * Package type
      * EE (DHL Express Envelope), OD (Other DHL Packaging), CP (Custom Packaging)
      * DC (Document), DM (Domestic), ED (Express Document), FR (Freight)
      * BD (Jumbo Document), BP (Jumbo Parcel), JD (Jumbo Junior Document)
      * JP (Jumbo Junior Parcel), PA (Parcel), DF (DHL Flyer)
      */
     $i = 0;
     foreach ($rawRequest->getPackages() as $package) {
         $nodePiece = $nodePieces->addChild('Piece', '', '');
         $packageType = 'EE';
         if ($package['params']['container'] == self::DHL_CONTENT_TYPE_NON_DOC) {
             $packageType = 'CP';
         }
         $nodePiece->addChild('PieceID', ++$i);
         $nodePiece->addChild('PackageType', $packageType);
         $nodePiece->addChild('Weight', round($package['params']['weight'], 1));
         $params = $package['params'];
         if ($params['width'] && $params['length'] && $params['height']) {
             if (!$originRegion) {
                 $nodePiece->addChild('Width', round($params['width']));
                 $nodePiece->addChild('Height', round($params['height']));
                 $nodePiece->addChild('Depth', round($params['length']));
             } else {
                 $nodePiece->addChild('Depth', round($params['length']));
                 $nodePiece->addChild('Width', round($params['width']));
                 $nodePiece->addChild('Height', round($params['height']));
             }
         }
         $content = array();
         foreach ($package['items'] as $item) {
             $content[] = $item['name'];
         }
         $nodePiece->addChild('PieceContents', substr(implode(',', $content), 0, 34));
     }
     if (!$originRegion) {
         $nodeShipmentDetails->addChild('Weight', round($rawRequest->getPackageWeight(), 1));
         $nodeShipmentDetails->addChild('WeightUnit', substr($this->_getWeightUnit(), 0, 1));
         $nodeShipmentDetails->addChild('GlobalProductCode', $rawRequest->getShippingMethod());
         $nodeShipmentDetails->addChild('LocalProductCode', $rawRequest->getShippingMethod());
         $nodeShipmentDetails->addChild('Date', $this->_coreDate->date('Y-m-d'));
         $nodeShipmentDetails->addChild('Contents', 'DHL Parcel');
         /**
          * The DoorTo Element defines the type of delivery service that applies to the shipment.
          * The valid values are DD (Door to Door), DA (Door to Airport) , AA and DC (Door to
          * Door non-compliant)
          */
         $nodeShipmentDetails->addChild('DoorTo', 'DD');
         $nodeShipmentDetails->addChild('DimensionUnit', substr($this->_getDimensionUnit(), 0, 1));
         if ($package['params']['container'] == self::DHL_CONTENT_TYPE_NON_DOC) {
             $packageType = 'CP';
         }
         $nodeShipmentDetails->addChild('PackageType', $packageType);
         if ($this->getConfigData('content_type') == self::DHL_CONTENT_TYPE_NON_DOC) {
             $nodeShipmentDetails->addChild('IsDutiable', 'Y');
         }
         $nodeShipmentDetails->addChild('CurrencyCode', $this->_storeManager->getWebsite($this->_request->getWebsiteId())->getBaseCurrencyCode());
     } else {
         if ($package['params']['container'] == self::DHL_CONTENT_TYPE_NON_DOC) {
             $packageType = 'CP';
         }
         $nodeShipmentDetails->addChild('PackageType', $packageType);
         $nodeShipmentDetails->addChild('Weight', $rawRequest->getPackageWeight());
         $nodeShipmentDetails->addChild('DimensionUnit', substr($this->_getDimensionUnit(), 0, 1));
         $nodeShipmentDetails->addChild('WeightUnit', substr($this->_getWeightUnit(), 0, 1));
         $nodeShipmentDetails->addChild('GlobalProductCode', $rawRequest->getShippingMethod());
         $nodeShipmentDetails->addChild('LocalProductCode', $rawRequest->getShippingMethod());
         /**
          * The DoorTo Element defines the type of delivery service that applies to the shipment.
          * The valid values are DD (Door to Door), DA (Door to Airport) , AA and DC (Door to
          * Door non-compliant)
          */
         $nodeShipmentDetails->addChild('DoorTo', 'DD');
         $nodeShipmentDetails->addChild('Date', $this->_coreDate->date('Y-m-d'));
         $nodeShipmentDetails->addChild('Contents', 'DHL Parcel TEST');
     }
 }
Example #7
0
 /**
  * Compose Packages For Carrier.
  * Divides order into items and items into parts if it's necessary
  *
  * @param \Magento\Shipping\Model\Carrier\AbstractCarrier $carrier
  * @param \Magento\Sales\Model\Quote\Address\RateRequest $request
  * @return array [int, float]
  */
 public function composePackagesForCarrier($carrier, $request)
 {
     $allItems = $request->getAllItems();
     $fullItems = array();
     $maxWeight = (double) $carrier->getConfigData('max_package_weight');
     /** @var $item \Magento\Sales\Model\Quote\Item */
     foreach ($allItems as $item) {
         if ($item->getProductType() == \Magento\Catalog\Model\Product\Type::TYPE_BUNDLE && $item->getProduct()->getShipmentType()) {
             continue;
         }
         $qty = $item->getQty();
         $changeQty = true;
         $checkWeight = true;
         $decimalItems = array();
         if ($item->getParentItem()) {
             if (!$item->getParentItem()->getProduct()->getShipmentType()) {
                 continue;
             }
             $qty = $item->getIsQtyDecimal() ? $item->getParentItem()->getQty() : $item->getParentItem()->getQty() * $item->getQty();
         }
         $itemWeight = $item->getWeight();
         if ($item->getIsQtyDecimal() && $item->getProductType() != \Magento\Catalog\Model\Product\Type::TYPE_BUNDLE) {
             $productId = $item->getProduct()->getId();
             if ($this->stockItemService->getStockItem($productId)->getIsDecimalDivided()) {
                 if ($this->stockItemService->getEnableQtyIncrements($productId) && $this->stockItemService->getQtyIncrements($productId)) {
                     $itemWeight = $itemWeight * $this->stockItemService->getQtyIncrements($productId);
                     $qty = round($item->getWeight() / $itemWeight * $qty);
                     $changeQty = false;
                 } else {
                     $itemWeight = $itemWeight * $item->getQty();
                     if ($itemWeight > $maxWeight) {
                         $qtyItem = floor($itemWeight / $maxWeight);
                         $decimalItems[] = array('weight' => $maxWeight, 'qty' => $qtyItem);
                         $weightItem = $this->mathDivision->getExactDivision($itemWeight, $maxWeight);
                         if ($weightItem) {
                             $decimalItems[] = array('weight' => $weightItem, 'qty' => 1);
                         }
                         $checkWeight = false;
                     } else {
                         $itemWeight = $itemWeight * $item->getQty();
                     }
                 }
             } else {
                 $itemWeight = $itemWeight * $item->getQty();
             }
         }
         if ($checkWeight && $maxWeight && $itemWeight > $maxWeight) {
             return array();
         }
         if ($changeQty && !$item->getParentItem() && $item->getIsQtyDecimal() && $item->getProductType() != \Magento\Catalog\Model\Product\Type::TYPE_BUNDLE) {
             $qty = 1;
         }
         if (!empty($decimalItems)) {
             foreach ($decimalItems as $decimalItem) {
                 $fullItems = array_merge($fullItems, array_fill(0, $decimalItem['qty'] * $qty, $decimalItem['weight']));
             }
         } else {
             $fullItems = array_merge($fullItems, array_fill(0, $qty, $itemWeight));
         }
     }
     sort($fullItems);
     return $this->_makePieces($fullItems, $maxWeight);
 }
Example #8
0
 /**
  * Prepare and set request to this instance
  *
  * @param RateRequest $request
  * @return $this
  */
 public function setRequest(RateRequest $request)
 {
     $this->_request = $request;
     $r = new \Magento\Framework\Object();
     if ($request->getLimitMethod()) {
         $r->setService($request->getLimitMethod());
     }
     if ($request->getFedexAccount()) {
         $account = $request->getFedexAccount();
     } else {
         $account = $this->getConfigData('account');
     }
     $r->setAccount($account);
     if ($request->getFedexDropoff()) {
         $dropoff = $request->getFedexDropoff();
     } else {
         $dropoff = $this->getConfigData('dropoff');
     }
     $r->setDropoffType($dropoff);
     if ($request->getFedexPackaging()) {
         $packaging = $request->getFedexPackaging();
     } else {
         $packaging = $this->getConfigData('packaging');
     }
     $r->setPackaging($packaging);
     if ($request->getOrigCountry()) {
         $origCountry = $request->getOrigCountry();
     } else {
         $origCountry = $this->_scopeConfig->getValue(\Magento\Sales\Model\Order\Shipment::XML_PATH_STORE_COUNTRY_ID, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $request->getStoreId());
     }
     $r->setOrigCountry($this->_countryFactory->create()->load($origCountry)->getIso2Code());
     if ($request->getOrigPostcode()) {
         $r->setOrigPostal($request->getOrigPostcode());
     } else {
         $r->setOrigPostal($this->_scopeConfig->getValue(\Magento\Sales\Model\Order\Shipment::XML_PATH_STORE_ZIP, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $request->getStoreId()));
     }
     if ($request->getDestCountryId()) {
         $destCountry = $request->getDestCountryId();
     } else {
         $destCountry = self::USA_COUNTRY_ID;
     }
     $r->setDestCountry($this->_countryFactory->create()->load($destCountry)->getIso2Code());
     if ($request->getDestPostcode()) {
         $r->setDestPostal($request->getDestPostcode());
     } else {
     }
     $weight = $this->getTotalNumOfBoxes($request->getPackageWeight());
     $r->setWeight($weight);
     if ($request->getFreeMethodWeight() != $request->getPackageWeight()) {
         $r->setFreeMethodWeight($request->getFreeMethodWeight());
     }
     $r->setValue($request->getPackagePhysicalValue());
     $r->setValueWithDiscount($request->getPackageValueWithDiscount());
     $r->setMeterNumber($this->getConfigData('meter_number'));
     $r->setKey($this->getConfigData('key'));
     $r->setPassword($this->getConfigData('password'));
     $r->setIsReturn($request->getIsReturn());
     $r->setBaseSubtotalInclTax($request->getBaseSubtotalInclTax());
     $this->setRawRequest($r);
     return $this;
 }
Example #9
0
 /**
  * @param \Magento\Sales\Model\Quote\Address\RateRequest $request
  * @return \Magento\Shipping\Model\Rate\Result
  */
 public function collectRates(\Magento\Sales\Model\Quote\Address\RateRequest $request)
 {
     if (!$this->getConfigFlag('active')) {
         return false;
     }
     // exclude Virtual products price from Package value if pre-configured
     if (!$this->getConfigFlag('include_virtual_price') && $request->getAllItems()) {
         foreach ($request->getAllItems() as $item) {
             if ($item->getParentItem()) {
                 continue;
             }
             if ($item->getHasChildren() && $item->isShipSeparately()) {
                 foreach ($item->getChildren() as $child) {
                     if ($child->getProduct()->isVirtual()) {
                         $request->setPackageValue($request->getPackageValue() - $child->getBaseRowTotal());
                     }
                 }
             } elseif ($item->getProduct()->isVirtual()) {
                 $request->setPackageValue($request->getPackageValue() - $item->getBaseRowTotal());
             }
         }
     }
     // Free shipping by qty
     $freeQty = 0;
     if ($request->getAllItems()) {
         $freePackageValue = 0;
         foreach ($request->getAllItems() as $item) {
             if ($item->getProduct()->isVirtual() || $item->getParentItem()) {
                 continue;
             }
             if ($item->getHasChildren() && $item->isShipSeparately()) {
                 foreach ($item->getChildren() as $child) {
                     if ($child->getFreeShipping() && !$child->getProduct()->isVirtual()) {
                         $freeShipping = is_numeric($child->getFreeShipping()) ? $child->getFreeShipping() : 0;
                         $freeQty += $item->getQty() * ($child->getQty() - $freeShipping);
                     }
                 }
             } elseif ($item->getFreeShipping()) {
                 $freeShipping = is_numeric($item->getFreeShipping()) ? $item->getFreeShipping() : 0;
                 $freeQty += $item->getQty() - $freeShipping;
                 $freePackageValue += $item->getBaseRowTotal();
             }
         }
         $oldValue = $request->getPackageValue();
         $request->setPackageValue($oldValue - $freePackageValue);
     }
     if (!$request->getConditionName()) {
         $conditionName = $this->getConfigData('condition_name');
         $request->setConditionName($conditionName ? $conditionName : $this->_defaultConditionName);
     }
     // Package weight and qty free shipping
     $oldWeight = $request->getPackageWeight();
     $oldQty = $request->getPackageQty();
     $request->setPackageWeight($request->getFreeMethodWeight());
     $request->setPackageQty($oldQty - $freeQty);
     /** @var \Magento\Shipping\Model\Rate\Result $result */
     $result = $this->_rateResultFactory->create();
     $rate = $this->getRate($request);
     $request->setPackageWeight($oldWeight);
     $request->setPackageQty($oldQty);
     if (!empty($rate) && $rate['price'] >= 0) {
         /** @var \Magento\Sales\Model\Quote\Address\RateResult\Method $method */
         $method = $this->_resultMethodFactory->create();
         $method->setCarrier('tablerate');
         $method->setCarrierTitle($this->getConfigData('title'));
         $method->setMethod('bestway');
         $method->setMethodTitle($this->getConfigData('name'));
         if ($request->getFreeShipping() === true || $request->getPackageQty() == $freeQty) {
             $shippingPrice = 0;
         } else {
             $shippingPrice = $this->getFinalPriceWithHandlingFee($rate['price']);
         }
         $method->setPrice($shippingPrice);
         $method->setCost($rate['cost']);
         $result->append($method);
     } else {
         /** @var \Magento\Sales\Model\Quote\Address\RateResult\Error $error */
         $error = $this->_rateErrorFactory->create(array('data' => array('carrier' => $this->_code, 'carrier_title' => $this->getConfigData('title'), 'error_message' => $this->getConfigData('specificerrmsg'))));
         $result->append($error);
     }
     return $result;
 }
Example #10
0
 /**
  * Prepare and set request to this instance
  *
  * @param \Magento\Sales\Model\Quote\Address\RateRequest $request
  * @return $this
  */
 public function setRequest(\Magento\Sales\Model\Quote\Address\RateRequest $request)
 {
     $this->_request = $request;
     $r = new \Magento\Framework\Object();
     if ($request->getLimitMethod()) {
         $r->setService($request->getLimitMethod());
     } else {
         $r->setService('ALL');
     }
     if ($request->getUspsUserid()) {
         $userId = $request->getUspsUserid();
     } else {
         $userId = $this->getConfigData('userid');
     }
     $r->setUserId($userId);
     if ($request->getUspsContainer()) {
         $container = $request->getUspsContainer();
     } else {
         $container = $this->getConfigData('container');
     }
     $r->setContainer($container);
     if ($request->getUspsSize()) {
         $size = $request->getUspsSize();
     } else {
         $size = $this->getConfigData('size');
     }
     $r->setSize($size);
     if ($request->getGirth()) {
         $girth = $request->getGirth();
     } else {
         $girth = $this->getConfigData('girth');
     }
     $r->setGirth($girth);
     if ($request->getHeight()) {
         $height = $request->getHeight();
     } else {
         $height = $this->getConfigData('height');
     }
     $r->setHeight($height);
     if ($request->getLength()) {
         $length = $request->getLength();
     } else {
         $length = $this->getConfigData('length');
     }
     $r->setLength($length);
     if ($request->getWidth()) {
         $width = $request->getWidth();
     } else {
         $width = $this->getConfigData('width');
     }
     $r->setWidth($width);
     if ($request->getUspsMachinable()) {
         $machinable = $request->getUspsMachinable();
     } else {
         $machinable = $this->getConfigData('machinable');
     }
     $r->setMachinable($machinable);
     if ($request->getOrigPostcode()) {
         $r->setOrigPostal($request->getOrigPostcode());
     } else {
         $r->setOrigPostal($this->_scopeConfig->getValue(\Magento\Sales\Model\Order\Shipment::XML_PATH_STORE_ZIP, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $request->getStoreId()));
     }
     if ($request->getOrigCountryId()) {
         $r->setOrigCountryId($request->getOrigCountryId());
     } else {
         $r->setOrigCountryId($this->_scopeConfig->getValue(\Magento\Sales\Model\Order\Shipment::XML_PATH_STORE_COUNTRY_ID, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $request->getStoreId()));
     }
     if ($request->getDestCountryId()) {
         $destCountry = $request->getDestCountryId();
     } else {
         $destCountry = self::USA_COUNTRY_ID;
     }
     $r->setDestCountryId($destCountry);
     if (!$this->_isUSCountry($destCountry)) {
         $r->setDestCountryName($this->_getCountryName($destCountry));
     }
     if ($request->getDestPostcode()) {
         $r->setDestPostal($request->getDestPostcode());
     }
     $weight = $this->getTotalNumOfBoxes($request->getPackageWeight());
     $r->setWeightPounds(floor($weight));
     $r->setWeightOunces(round(($weight - floor($weight)) * self::OUNCES_POUND, 1));
     if ($request->getFreeMethodWeight() != $request->getPackageWeight()) {
         $r->setFreeMethodWeight($request->getFreeMethodWeight());
     }
     $r->setValue($request->getPackageValue());
     $r->setValueWithDiscount($request->getPackageValueWithDiscount());
     $r->setBaseSubtotalInclTax($request->getBaseSubtotalInclTax());
     $this->setRawRequest($r);
     return $this;
 }
Example #11
0
 /**
  * Allows free shipping when all product items have free shipping (promotions etc.)
  *
  * @param \Magento\Sales\Model\Quote\Address\RateRequest $request
  * @return void
  */
 protected function _updateFreeMethodQuote($request)
 {
     $freeShipping = false;
     $items = $request->getAllItems();
     $c = count($items);
     for ($i = 0; $i < $c; $i++) {
         if ($items[$i]->getProduct() instanceof \Magento\Catalog\Model\Product) {
             if ($items[$i]->getFreeShipping()) {
                 $freeShipping = true;
             } else {
                 return;
             }
         }
     }
     if ($freeShipping) {
         $request->setFreeShipping(true);
     }
 }
Example #12
0
 /**
  * Return items for further shipment rate evaluation. We need to pass children of a bundle instead passing the
  * bundle itself, otherwise we may not get a rate at all (e.g. when total weight of a bundle exceeds max weight
  * despite each item by itself is not)
  *
  * @param RateRequest $request
  * @return array
  */
 public function getAllItems(RateRequest $request)
 {
     $items = array();
     if ($request->getAllItems()) {
         foreach ($request->getAllItems() as $item) {
             /* @var $item \Magento\Sales\Model\Quote\Item */
             if ($item->getProduct()->isVirtual() || $item->getParentItem()) {
                 // Don't process children here - we will process (or already have processed) them below
                 continue;
             }
             if ($item->getHasChildren() && $item->isShipSeparately()) {
                 foreach ($item->getChildren() as $child) {
                     if (!$child->getFreeShipping() && !$child->getProduct()->isVirtual()) {
                         $items[] = $child;
                     }
                 }
             } else {
                 // Ship together - count compound item as one solid
                 $items[] = $item;
             }
         }
     }
     return $items;
 }
Example #13
0
 /**
  * @param \Magento\Sales\Model\Quote\Address\RateRequest $request
  * @return void
  */
 protected function _updateFreeMethodQuote($request)
 {
     if ($request->getFreeMethodWeight() == $request->getPackageWeight() || !$request->hasFreeMethodWeight()) {
         return;
     }
     $freeMethod = $this->getConfigData($this->_freeMethod);
     if (!$freeMethod) {
         return;
     }
     $freeRateId = false;
     if (is_object($this->_result)) {
         foreach ($this->_result->getAllRates() as $i => $item) {
             if ($item->getMethod() == $freeMethod) {
                 $freeRateId = $i;
                 break;
             }
         }
     }
     if ($freeRateId === false) {
         return;
     }
     $price = null;
     if ($request->getFreeMethodWeight() > 0) {
         $this->_setFreeMethodRequest($freeMethod);
         $result = $this->_getQuotes();
         if ($result && ($rates = $result->getAllRates()) && count($rates) > 0) {
             if (count($rates) == 1 && $rates[0] instanceof \Magento\Sales\Model\Quote\Address\RateResult\Method) {
                 $price = $rates[0]->getPrice();
             }
             if (count($rates) > 1) {
                 foreach ($rates as $rate) {
                     if ($rate instanceof \Magento\Sales\Model\Quote\Address\RateResult\Method && $rate->getMethod() == $freeMethod) {
                         $price = $rate->getPrice();
                     }
                 }
             }
         }
     } else {
         /**
          * if we can apply free shipping for all order we should force price
          * to $0.00 for shipping with out sending second request to carrier
          */
         $price = 0;
     }
     /**
      * if we did not get our free shipping method in response we must use its old price
      */
     if (!is_null($price)) {
         $this->_result->getRateById($freeRateId)->setPrice($price);
     }
 }
Example #14
0
 /**
  * Prepare shipping rate result based on response
  *
  * @param mixed $xmlResponse
  * @return Result
  */
 protected function _parseXmlResponse($xmlResponse)
 {
     $costArr = array();
     $priceArr = array();
     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) {
                 $code = (string) $shipElement->Service->Code;
                 if (in_array($code, $allowedMethods)) {
                     if ($negotiatedActive) {
                         $cost = $shipElement->NegotiatedRates->NetSummaryCharges->GrandTotal->MonetaryValue;
                     } else {
                         $cost = $shipElement->TotalCharges->MonetaryValue;
                     }
                     //convert price with Origin country currency code to base currency code
                     $successConversion = true;
                     $responseCurrencyCode = (string) $shipElement->TotalCharges->CurrencyCode;
                     if ($responseCurrencyCode) {
                         if (in_array($responseCurrencyCode, $allowedCurrencies)) {
                             $cost = (double) $cost * $this->_getBaseCurrencyRate($responseCurrencyCode);
                         } else {
                             $errorTitle = __('We can\'t convert a rate from "%1-%2".', $responseCurrencyCode, $this->_request->getPackageCurrency()->getCode());
                             $error = $this->_rateErrorFactory->create();
                             $error->setCarrier('ups');
                             $error->setCarrierTitle($this->getConfigData('title'));
                             $error->setErrorMessage($errorTitle);
                             $successConversion = false;
                         }
                     }
                     if ($successConversion) {
                         $costArr[$code] = $cost;
                         $priceArr[$code] = $this->getMethodPrice(floatval($cost), $code);
                     }
                 }
             }
         } 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 (!isset($errorTitle)) {
             $errorTitle = __('Cannot retrieve shipping rates');
         }
         $error->setErrorMessage($this->getConfigData('specificerrmsg'));
         $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]);
             $rate->setPrice($price);
             $result->append($rate);
         }
     }
     return $result;
 }