Exemplo n.º 1
1
 /**
  * Prepare and set request to this instance
  *
  * @param RateRequest $request
  * @return $this
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  * @SuppressWarnings(PHPMD.NPathComplexity)
  */
 public function setRequest(RateRequest $request)
 {
     $this->_request = $request;
     $r = new \Magento\Framework\DataObject();
     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)->getData('iso2_code'));
     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)->getData('iso2_code'));
     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;
 }
 /**
  * @param RateRequest $request
  * @return \Magento\Shipping\Model\Rate\Result
  */
 public function collectRates(RateRequest $request)
 {
     if (!$this->getConfigFlag('active')) {
         return false;
     }
     /** @var Result $result */
     $result = $this->_rateResultFactory->create();
     $packageValue = $request->getBaseCurrency()->convert($request->getPackageValue(), $request->getPackageCurrency());
     for ($i = 0; $i <= 5; $i++) {
         if ($this->getConfigData('type' . $i) == 'O') {
             // per order
             $shippingPrice = $this->getConfigData('price' . $i);
         } elseif ($this->getConfigData('type' . $i) == 'I') {
             // per item
             $shippingPrice = $request->getPackageQty() * $this->getConfigData('price' . $i) - $this->getFreeBoxes() * $this->getConfigData('price' . $i);
         } else {
             $shippingPrice = $this->getConfigData('price' . $i);
         }
         $shippingName = $this->getConfigData('name' . $i);
         if ($shippingName != "" && ($packageValue >= $this->getConfigData('min_shipping' . $i) && $packageValue <= $this->getConfigData('max_shipping' . $i)) or $shippingName != "" && $this->getConfigData('max_shipping' . $i) == "") {
             /** @var \Magento\Quote\Model\Quote\Address\RateResult\Method $method */
             $method = $this->_rateMethodFactory->create();
             $method->setCarrier('msmultiflat');
             $method->setCarrierTitle($this->getConfigData('title'));
             $method->setMethod($this->getConfigData('name' . $i));
             $method->setMethodTitle($this->getConfigData('name' . $i));
             $method->setMethodDetails($this->getConfigData('details' . $i));
             $method->setMethodDescription($this->getConfigData('details' . $i));
             $method->setPrice($shippingPrice);
             $method->setCost($shippingPrice);
             $result->append($method);
         }
     }
     return $result;
 }
Exemplo n.º 3
0
 public function collectRates(RateRequest $request)
 {
     if (!$this->getConfigFlag('active')) {
         return false;
     }
     //Do some filtering of items in cart
     if ($request->getAllItems()) {
         foreach ($request->getAllItems() as $item) {
             //$item->getQty();
             //$item->getFreeShipping()
             //$item->isShipSeparately()
             //$item->getHasChildren()
             //$item->getProduct()->isVirtual()
             //...
         }
     }
     //After filtering, start forming final price
     //Final price does not have to be fixed like below
     $shippingPrice = $this->getConfigData('price');
     $result = $this->_rateResultFactory->create();
     $method = $this->_rateMethodFactory->create();
     $method->setCarrier('shipbox');
     $method->setCarrierTitle($this->getConfigData('title'));
     $method->setMethod('shipbox');
     $method->setMethodTitle($this->getConfigData('name'));
     $method->setPrice($shippingPrice);
     $method->setCost($shippingPrice);
     $result->append($method);
     return $result;
 }
Exemplo n.º 4
0
 /**
  * @param RateRequest $request
  * @return Result|bool
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  * @SuppressWarnings(PHPMD.NPathComplexity)
  */
 public function collectRates(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\Quote\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;
 }
 /**
  * @param RateRequest $request
  * @return int
  */
 private function getFreeBoxesCount(RateRequest $request)
 {
     $freeBoxes = 0;
     if ($request->getAllItems()) {
         foreach ($request->getAllItems() as $item) {
             if ($item->getProduct()->isVirtual() || $item->getParentItem()) {
                 continue;
             }
             if ($item->getHasChildren() && $item->isShipSeparately()) {
                 $freeBoxes += $this->getFreeBoxesCountFromChildren($item);
             } elseif ($item->getFreeShipping()) {
                 $freeBoxes += $item->getQty();
             }
         }
     }
     return $freeBoxes;
 }
Exemplo n.º 6
0
 /**
  * Allows free shipping when all product items have free shipping (promotions etc.)
  *
  * @param \Magento\Quote\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);
     }
 }
Exemplo n.º 7
0
 /**
  * @covers \Magento\Shipping\Model\Shipping::composePackagesForCarrier
  */
 public function testComposePackages()
 {
     $request = new RateRequest();
     /** \Magento\Catalog\Model\Product\Configuration\Item\ItemInterface */
     $item = $this->getMockBuilder('\\Magento\\Quote\\Model\\Quote\\Item')->disableOriginalConstructor()->setMethods(['getQty', 'getIsQtyDecimal', 'getProductType', 'getProduct', 'getWeight', '__wakeup', 'getStore'])->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));
     $store = $this->getMock('Magento\\Store\\Model\\Store', ['getWebsiteId'], [], '', false);
     $store->expects($this->any())->method('getWebsiteId')->will($this->returnValue(10));
     $item->expects($this->any())->method('getStore')->will($this->returnValue($store));
     $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->stockRegistry->expects($this->atLeastOnce())->method('getStockItem')->with($this->productId, 10)->will($this->returnValue($this->stockItemData));
     $this->stockItemData->expects($this->atLeastOnce())->method('getEnableQtyIncrements')->will($this->returnValue(true));
     $this->stockItemData->expects($this->atLeastOnce())->method('getQtyIncrements')->will($this->returnValue(0.5));
     $this->shipping->composePackagesForCarrier($this->carrier, $request);
 }
 /**
  * @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\\Quote\\Model\\Quote\\Item')->disableOriginalConstructor()->setMethods(['getProduct', 'getQty', 'getWeight', '__wakeup', 'getStore'])->getMock();
     $item->expects($this->any())->method('getProduct')->will($this->returnValue($product));
     $store = $this->getMock('Magento\\Store\\Model\\Store', ['getWebsiteId'], [], '', false);
     $store->expects($this->any())->method('getWebsiteId')->will($this->returnValue(10));
     $item->expects($this->any())->method('getStore')->will($this->returnValue($store));
     $request = new RateRequest();
     $request->setData('all_items', [$item]);
     $request->setData('dest_postcode', 1);
     /** Testable service calls to CatalogInventory module */
     $this->stockRegistry->expects($this->atLeastOnce())->method('getStockItem')->with($this->productId);
     $this->stockItemData->expects($this->atLeastOnce())->method('getEnableQtyIncrements')->will($this->returnValue(true));
     $this->stockItemData->expects($this->atLeastOnce())->method('getQtyIncrements')->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);
 }
Exemplo n.º 9
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->soap_init();
     $rates = $this->get_services();
     print_r($rates);
     die;
     //        $rates = $this->getAllowedMethods();
     foreach ($rates as $key => $rated) {
         $rate = $this->_rateMethodFactory->create();
         $rate->setCarrier($this->_code);
         $rate->setCarrierTitle($this->getConfigData('title'));
         $rate->setMethodTitle($rated);
         $rate->setPrice(1.23);
         $rate->setCost(0);
         $this->_result->append($rate);
         //            return $this;
     }
     return $this->getResult();
 }
 public function collectRates(RateRequest $request)
 {
     //$this->_debug(var_dump($request));
     $this->_request = $request;
     $city = $this->loadCityNameByPostal($this->_request->getDestPostcode(), $this->_request->getDestCountryId());
     $ammount = $this->getAmmountBycityName($city);
     $result = $this->_rateFactory->create();
     $method = $this->_rateMethodFactory->create();
     if ($ammount === false) {
         return $result;
     }
     $method->setCarrier('tmocourier');
     $method->setCarrierTitle('Ocourier');
     $method->setMethod('ocourier');
     $method->setMethodTitle('Self pick');
     $method->setPrice($ammount);
     $method->setCost($ammount);
     $result->append($method);
     // $this->_debug(var_dump($result));
     return $result;
 }
Exemplo n.º 11
0
 /**
  * Prepare shipping rate result based on response
  *
  * @param mixed $xmlResponse
  * @return Result
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  */
 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) {
                 $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;
 }
Exemplo n.º 12
0
 /**
  * @return array
  */
 public function getBindings()
 {
     $bind = [':website_id' => (int) $this->request->getWebsiteId(), ':country_id' => $this->request->getDestCountryId(), ':region_id' => (int) $this->request->getDestRegionId(), ':postcode' => $this->request->getDestPostcode()];
     // Render condition by condition name
     if (is_array($this->request->getConditionName())) {
         $i = 0;
         foreach ($this->request->getConditionName() as $conditionName) {
             $bindNameKey = sprintf(':condition_name_%d', $i);
             $bindValueKey = sprintf(':condition_value_%d', $i);
             $bind[$bindNameKey] = $conditionName;
             $bind[$bindValueKey] = $this->request->getData($conditionName);
             $i++;
         }
     } else {
         $bind[':condition_name'] = $this->request->getConditionName();
         $bind[':condition_value'] = $this->request->getData($this->request->getConditionName());
     }
     return $bind;
 }
Exemplo n.º 13
0
 /**
  * Prepare and set request to this instance
  *
  * @param \Magento\Quote\Model\Quote\Address\RateRequest $request
  * @return $this
  */
 public function setRequest(\Magento\Quote\Model\Quote\Address\RateRequest $request)
 {
     if (is_array($request->getAllItems())) {
         $item = current($request->getAllItems());
         if ($item instanceof QuoteItem) {
             $request->setQuote($item->getQuote());
             $this->quote = $item->getQuote();
         }
     }
     //SHQ16-1261 - further detail as values not on shipping address
     if (!$this->quote) {
         $this->quote = $this->shipperDataHelper->getQuote();
     }
     $shippingAddress = $this->quote->getShippingAddress();
     $key = $this->shipperDataHelper->getAddressKey($shippingAddress);
     $existing = $this->checkoutSession->getShipAddressValidation();
     $validate = true;
     if (is_array($existing)) {
         if (isset($existing['key']) && $existing['key'] == $key) {
             $validate = false;
         }
     } else {
         $validate = $this->shipperRateHelper->shouldValidateAddress($shippingAddress->getValidationStatus(), $shippingAddress->getDestinationType());
     }
     $request->setValidateAddress($validate);
     $request->setSelectedOptions($this->getSelectedOptions($shippingAddress));
     $isCheckout = $this->shipperDataHelper->isCheckout($this->quote);
     $cartType = !is_null($isCheckout) && $isCheckout != 1 ? "CART" : "STD";
     if ($this->quote->getIsMultiShipping()) {
         $cartType = 'MAC';
     }
     $request->setCartType($cartType);
     $this->eventManager->dispatch('shipperhq_carrier_set_request', ['request' => $request]);
     $this->shipperRequest = $this->shipperMapper->getShipperTranslation($request);
     $this->rawRequest = $request;
     return $this;
 }
Exemplo n.º 14
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
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  * @api
  */
 public function getAllItems(RateRequest $request)
 {
     $items = [];
     if ($request->getAllItems()) {
         foreach ($request->getAllItems() as $item) {
             /* @var $item \Magento\Quote\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;
 }
Exemplo n.º 15
0
 /**
  * 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();
     $bind = [':website_id' => (int) $request->getWebsiteId(), ':country_id' => $request->getDestCountryId(), ':region_id' => (int) $request->getDestRegionId(), ':postcode' => $request->getDestPostcode()];
     $select = $connection->select()->from($this->getMainTable())->where('website_id = :website_id')->order(['dest_country_id DESC', 'dest_region_id DESC', 'dest_zip DESC'])->limit(1);
     // Render destination condition
     $orWhere = '(' . implode(') OR (', ["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 = [];
         $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 = $connection->fetchRow($select, $bind);
     // Normalize destination zip code
     if ($result && $result['dest_zip'] == '*') {
         $result['dest_zip'] = '';
     }
     return $result;
 }
Exemplo n.º 16
0
 /**
  * Enter description here...
  *
  * @param Mage_Shipping_Model_Rate_Request $data
  * @return Mage_Shipping_Model_Rate_Result
  */
 public function collectRates(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() || $item->getProductType() == 'downloadable') {
                         $request->setPackageValue($request->getPackageValue() - $child->getBaseRowTotal());
                     }
                 }
             } elseif ($item->getProduct()->isVirtual() || $item->getProductType() == 'downloadable') {
                 $request->setPackageValue($request->getPackageValue() - $item->getBaseRowTotal());
             }
         }
     }
     // Free shipping by qty
     $freeQty = 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()) {
                         $freeQty += $item->getQty() * ($child->getQty() - (is_numeric($child->getFreeShipping()) ? $child->getFreeShipping() : 0));
                     }
                 }
             } elseif ($item->getFreeShipping()) {
                 $freeQty += $item->getQty() - (is_numeric($item->getFreeShipping()) ? $item->getFreeShipping() : 0);
             }
         }
     }
     if (!$request->getMRConditionName()) {
         if ($this->areaState->getAreaCode() == 'adminhtml') {
             $request->setMRConditionName(['notempty', 'admin', $this->getConfigData('condition_name') ? $this->getConfigData('condition_name') : $this->_default_condition_name]);
         } else {
             $request->setMRConditionName($this->getConfigData('condition_name') ? $this->getConfigData('condition_name') : $this->_default_condition_name);
         }
     }
     // Package weight and qty free shipping
     $oldWeight = $request->getPackageWeight();
     $oldQty = $request->getPackageQty();
     if ($this->getConfigData('allow_free_shipping_promotions') && !$this->getConfigData('include_free_ship_items')) {
         $request->setPackageWeight($request->getFreeMethodWeight());
         $request->setPackageQty($oldQty - $freeQty);
     }
     $result = $this->_rateResultFactory->create();
     $ratearray = $this->getRate($request);
     $request->setPackageWeight($oldWeight);
     $request->setPackageQty($oldQty);
     $freeShipping = false;
     if (is_numeric($this->getConfigData('free_shipping_threshold')) && $this->getConfigData('free_shipping_threshold') > 0 && $request->getPackageValue() > $this->getConfigData('free_shipping_threshold')) {
         $freeShipping = true;
     }
     if ($this->getConfigData('allow_free_shipping_promotions') && ($request->getFreeShipping() === true || $request->getPackageQty() == $this->getFreeBoxes())) {
         $freeShipping = true;
     }
     if ($freeShipping) {
         $method = $this->_resultMethodFactory->create();
         $method->setCarrier('matrixrate');
         $method->setCarrierTitle($this->getConfigData('title'));
         $method->setMethod('matrixrate_free');
         $method->setPrice('0.00');
         $method->setMethodTitle($this->getConfigData('free_method_text'));
         $result->append($method);
         if ($this->getConfigData('show_only_free')) {
             return $result;
         }
     }
     foreach ($ratearray as $rate) {
         if (!empty($rate) && $rate['price'] >= 0) {
             $method = $this->_resultMethodFactory->create();
             $method->setCarrier('matrixrate');
             $method->setCarrierTitle($this->getConfigData('title'));
             $method->setMethod('matrixrate_' . $rate['pk']);
             $method->setMethodTitle(__($rate['delivery_type']));
             $shippingPrice = $this->getFinalPriceWithHandlingFee($rate['price']);
             $method->setCost($rate['cost']);
             $method->setDeliveryType($rate['delivery_type']);
             $method->setPrice($shippingPrice);
             $result->append($method);
         }
     }
     return $result;
 }
 /**
  * Prepare and set request to this instance
  *
  * @param \Magento\Quote\Model\Quote\Address\RateRequest $request
  * @return $this
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  * @SuppressWarnings(PHPMD.NPathComplexity)
  * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
  */
 public function setRequest(\Magento\Quote\Model\Quote\Address\RateRequest $request)
 {
     $this->_request = $request;
     $r = new \Magento\Framework\DataObject();
     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;
 }
Exemplo n.º 18
0
 public function testCollectRatesFail()
 {
     $this->scope->expects($this->once())->method('isSetFlag')->willReturn(true);
     $request = new RateRequest();
     $request->setPackageWeight(1);
     $this->assertSame($this->rate, $this->model->collectRates($request));
 }
Exemplo n.º 19
0
 /**
  * @param RateRequest $request
  * @return \Magento\Shipping\Model\Rate\Result
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  * @SuppressWarnings(PHPMD.NPathComplexity)
  * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
  */
 public function collectRates(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\Quote\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\Quote\Model\Quote\Address\RateResult\Error $error */
         $error = $this->_rateErrorFactory->create(['data' => ['carrier' => $this->_code, 'carrier_title' => $this->getConfigData('title'), 'error_message' => $this->getConfigData('specificerrmsg')]]);
         $result->append($error);
     }
     return $result;
 }
Exemplo n.º 20
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\Quote\Model\Quote\Address\RateRequest $request
  * @return array [int, float]
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  * @SuppressWarnings(PHPMD.NPathComplexity)
  */
 public function composePackagesForCarrier($carrier, $request)
 {
     $allItems = $request->getAllItems();
     $fullItems = [];
     $maxWeight = (double) $carrier->getConfigData('max_package_weight');
     /** @var $item \Magento\Quote\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 = [];
         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();
             $stockItem = $this->stockRegistry->getStockItem($productId, $item->getStore()->getWebsiteId());
             if ($stockItem->getIsDecimalDivided()) {
                 if ($stockItem->getEnableQtyIncrements() && $stockItem->getQtyIncrements()) {
                     $itemWeight = $itemWeight * $stockItem->getQtyIncrements();
                     $qty = round($item->getWeight() / $itemWeight * $qty);
                     $changeQty = false;
                 } else {
                     $itemWeight = $itemWeight * $item->getQty();
                     if ($itemWeight > $maxWeight) {
                         $qtyItem = floor($itemWeight / $maxWeight);
                         $decimalItems[] = ['weight' => $maxWeight, 'qty' => $qtyItem];
                         $weightItem = $this->mathDivision->getExactDivision($itemWeight, $maxWeight);
                         if ($weightItem) {
                             $decimalItems[] = ['weight' => $weightItem, 'qty' => 1];
                         }
                         $checkWeight = false;
                     } else {
                         $itemWeight = $itemWeight * $item->getQty();
                     }
                 }
             } else {
                 $itemWeight = $itemWeight * $item->getQty();
             }
         }
         if ($checkWeight && $maxWeight && $itemWeight > $maxWeight) {
             return [];
         }
         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);
 }
Exemplo n.º 21
0
 public function testCollectRatesFail()
 {
     $this->scope->expects($this->once())->method('isSetFlag')->willReturn(true);
     $this->scope->expects($this->atLeastOnce())->method('getValue')->willReturnMap([['carriers/usps/userid' => 123], ['carriers/usps/container' => 11]]);
     $request = new RateRequest();
     $request->setPackageWeight(1);
     $this->assertNotEmpty($this->carrier->collectRates($request));
 }
Exemplo n.º 22
0
 /**
  * Return table rate array or false by rate request
  *
  * @param \Magento\Quote\Model\Quote\Address\RateRequest $request
  * @param bool $zipRangeSet
  * @return array|bool
  */
 public function getRate(\Magento\Quote\Model\Quote\Address\RateRequest $request, $zipRangeSet = false)
 {
     $adapter = $this->getConnection();
     $shippingData = array();
     $postcode = $request->getDestPostcode();
     if ($zipRangeSet && is_numeric($postcode)) {
         #  Want to search for postcodes within a range
         $zipSearchString = ' AND :postcode BETWEEN dest_zip AND dest_zip_to ';
     } else {
         $zipSearchString = " AND :postcode LIKE dest_zip ";
     }
     for ($j = 0; $j < 8; $j++) {
         $select = $adapter->select()->from($this->getMainTable())->where('website_id = :website_id')->order(['dest_country_id DESC', 'dest_region_id DESC', 'dest_zip DESC', 'condition_from_value DESC']);
         $zoneWhere = '';
         $bind = array();
         switch ($j) {
             case 0:
                 // country, region, city, postcode
                 $zoneWhere = "dest_country_id = :country_id AND dest_region_id = :region_id AND STRCMP(LOWER(dest_city),LOWER(:city))= 0 " . $zipSearchString;
                 // TODO Add city
                 $bind = [':country_id' => $request->getDestCountryId(), ':region_id' => (int) $request->getDestRegionId(), ':city' => $request->getDestCity(), ':postcode' => $request->getDestPostcode()];
                 break;
             case 1:
                 // country, region, no city, postcode
                 $zoneWhere = "dest_country_id = :country_id AND dest_region_id = :region_id AND dest_city='' " . $zipSearchString;
                 $bind = [':country_id' => $request->getDestCountryId(), ':region_id' => (int) $request->getDestRegionId(), ':postcode' => $request->getDestPostcode()];
                 break;
             case 2:
                 // country, state, city, no postcode
                 $zoneWhere = "dest_country_id = :country_id AND dest_region_id = :region_id AND STRCMP(LOWER(dest_city),LOWER(:city))= 0 AND dest_zip ='*'";
                 // TODO Add city search
                 $bind = [':country_id' => $request->getDestCountryId(), ':region_id' => (int) $request->getDestRegionId(), ':city' => $request->getDestCity()];
                 break;
             case 3:
                 //country, city, no region, no postcode
                 $zoneWhere = "dest_country_id = :country_id AND dest_region_id = '0' AND STRCMP(LOWER(dest_city),LOWER(:city))= 0 AND dest_zip ='*'";
                 // TODO Add city
                 $bind = [':country_id' => $request->getDestCountryId(), ':city' => $request->getDestCity()];
                 break;
             case 4:
                 // country, postcode
                 $zoneWhere = "dest_country_id = :country_id AND dest_region_id = '0' AND dest_city ='*' " . $zipSearchString;
                 $bind = [':country_id' => $request->getDestCountryId(), ':postcode' => $request->getDestPostcode()];
                 break;
             case 5:
                 // country, region
                 $zoneWhere = "dest_country_id = :country_id AND dest_region_id = :region_id  AND dest_city ='*' AND dest_zip ='*'";
                 $bind = [':country_id' => $request->getDestCountryId(), ':region_id' => (int) $request->getDestRegionId()];
                 break;
             case 6:
                 // country
                 $zoneWhere = "dest_country_id = :country_id AND dest_region_id = '0' AND dest_city ='*' AND dest_zip ='*'";
                 $bind = [':country_id' => $request->getDestCountryId()];
                 break;
             case 7:
                 // nothing
                 $zoneWhere = "dest_country_id = '0' AND dest_region_id = '0' AND dest_city ='*' AND dest_zip ='*'";
                 break;
         }
         $select->where($zoneWhere);
         $bind[':website_id'] = (int) $request->getWebsiteId();
         $bind[':condition_name'] = $request->getConditionMRName();
         $bind[':condition_value'] = $request->getData($request->getConditionMRName());
         $select->where('condition_name = :condition_name');
         $select->where('condition_from_value < :condition_value');
         $select->where('condition_to_value >= :condition_value');
         $this->_logger->debug('SQL Select: ', $select->getPart('where'));
         $this->_logger->debug('Bindings: ', $bind);
         $results = $adapter->fetchAll($select, $bind);
         if (!empty($results)) {
             $this->_logger->debug('SQL Results: ', $results);
             foreach ($results as $data) {
                 $shippingData[] = $data;
             }
             break;
         }
     }
     return $shippingData;
 }
Exemplo n.º 23
0
 /**
  * @param \Magento\Quote\Model\Quote\Address\RateRequest $request
  * @return void
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  * @SuppressWarnings(PHPMD.NPathComplexity)
  */
 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\Quote\Model\Quote\Address\RateResult\Method) {
                 $price = $rates[0]->getPrice();
             }
             if (count($rates) > 1) {
                 foreach ($rates as $rate) {
                     if ($rate instanceof \Magento\Quote\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);
     }
 }
Exemplo n.º 24
0
 /**
  * @param RateRequest $request
  * @param int $basePrice
  * @param int $freeBoxes
  * @return float
  */
 public function getShippingPricePerItem(\Magento\Quote\Model\Quote\Address\RateRequest $request, $basePrice, $freeBoxes)
 {
     return $request->getPackageQty() * $basePrice - $freeBoxes * $basePrice;
 }
Exemplo n.º 25
0
 /**
  * Generation Shipment Details Node according to origin region
  *
  * @param \Magento\Shipping\Model\Simplexml\Element $xml
  * @param RateRequest $rawRequest
  * @param string $originRegion
  * @return void
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  * @SuppressWarnings(PHPMD.NPathComplexity)
  */
 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 = [];
         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');
     }
 }
Exemplo n.º 26
0
 public function getNewRate(\Magento\Quote\Model\Quote\Address\RateRequest $request, $zipRangeSet = 0)
 {
     $connection = $this->getConnection();
     $postcode = $request->getDestPostcode();
     $bind = [':website_id' => (int) $request->getWebsiteId(), ':country_id' => $request->getDestCountryId(), ':region_id' => (int) $request->getDestRegionId(), ':postcode' => (string) $request->getDestPostcode(), ':city' => (string) $request->getDestCity()];
     if ($zipRangeSet && is_numeric($postcode)) {
         #  Want to search for postcodes within a range
         $zipSearchString = ' AND ' . $postcode . ' BETWEEN dest_zip AND dest_zip_to )';
     } else {
         $zipSearchString = $connection->quoteInto(" AND ? LIKE dest_zip )", $postcode);
     }
     for ($j = 0; $j < 10; $j++) {
         $select = $connection->select()->from($this->getMainTable())->where($connection->quoteInto("website_id = ?", $bind[':website_id']))->order(['dest_country_id DESC', 'dest_region_id DESC', 'dest_zip DESC']);
         switch ($j) {
             case 0:
                 $select->where($connection->quoteInto(" (dest_country_id=? ", $bind[':country_id']) . $connection->quoteInto(" AND dest_region_id=? ", $bind[':region_id']) . $connection->quoteInto(" AND STRCMP(LOWER(dest_city),LOWER(?)) = 0  ", $bind[':city']) . $zipSearchString);
                 break;
             case 1:
                 $select->where($connection->quoteInto(" (dest_country_id=? ", $bind[':country_id']) . $connection->quoteInto(" AND dest_region_id=?  AND dest_city=''", $bind[':region_id']) . $zipSearchString);
                 break;
             case 2:
                 $select->where($connection->quoteInto(" (dest_country_id=? ", $request->getDestCountryId()) . $connection->quoteInto(" AND dest_region_id=? ", $request->getDestRegionId()) . $connection->quoteInto(" AND STRCMP(LOWER(dest_city),LOWER(?)) = 0  AND dest_zip='')", $bind[':city']));
                 break;
             case 3:
                 $select->where($connection->quoteInto("  (dest_country_id=? ", $bind[':country_id']) . $connection->quoteInto(" AND STRCMP(LOWER(dest_city),LOWER(?)) = 0  AND dest_region_id='0'", $bind[':city']) . $zipSearchString);
                 break;
             case 4:
                 $select->where($connection->quoteInto("  (dest_country_id=? ", $bind[':country_id']) . $connection->quoteInto(" AND STRCMP(LOWER(dest_city),LOWER(?)) = 0  AND dest_region_id='0' AND dest_zip='') ", $bind[':city']));
                 break;
             case 5:
                 $select->where($connection->quoteInto("  (dest_country_id=? AND dest_region_id='0' AND dest_city='' ", $bind[':country_id']) . $zipSearchString);
                 break;
             case 6:
                 $select->where($connection->quoteInto("  (dest_country_id=? ", $bind[':country_id']) . $connection->quoteInto(" AND dest_region_id=? AND dest_city='' AND dest_zip='') ", $bind[':region_id']));
                 break;
             case 7:
                 $select->where($connection->quoteInto("  (dest_country_id=? AND dest_region_id='0' AND dest_city='' AND dest_zip='') ", $bind[':country_id']));
                 break;
             case 8:
                 $select->where("  (dest_country_id='0' AND dest_region_id='0'" . $zipSearchString);
                 break;
             case 9:
                 $select->where("  (dest_country_id='0' AND dest_region_id='0' AND dest_zip='')");
                 break;
         }
         if (is_array($request->getMRConditionName())) {
             $i = 0;
             foreach ($request->getMRConditionName() as $conditionName) {
                 if ($i == 0) {
                     $select->where('condition_name=?', $conditionName);
                 } else {
                     $select->orWhere('condition_name=?', $conditionName);
                 }
                 $select->where('condition_from_value<=?', $request->getData($conditionName));
                 $i++;
             }
         } else {
             $select->where('condition_name=?', $request->getMRConditionName());
             $select->where('condition_from_value<=?', $request->getData($request->getMRConditionName()));
             $select->where('condition_to_value>=?', $request->getData($request->getMRConditionName()));
         }
         $newdata = array();
         $row = $connection->fetchAll($select, $bind);
         if (!empty($row)) {
             // have found a result or found nothing and at end of list!
             foreach ($row as $data) {
                 $newdata[] = $data;
             }
             break;
         }
     }
     return $newdata;
 }
Exemplo n.º 27
0
 public function testCollectRatesErrorMessage()
 {
     $this->scope->expects($this->once())->method('isSetFlag')->willReturn(false);
     $this->error->expects($this->once())->method('setCarrier')->with('fedex');
     $this->error->expects($this->once())->method('setCarrierTitle');
     $this->error->expects($this->once())->method('setErrorMessage');
     $request = new RateRequest();
     $request->setPackageWeight(1);
     $this->assertSame($this->error, $this->_model->collectRates($request));
 }
Exemplo n.º 28
0
 /**
  * @param RateRequest $request
  * @return \Magento\Shipping\Model\Rate\Result|bool
  */
 public function collectRates(RateRequest $request)
 {
     if (!$this->getConfigFlag('active')) {
         return false;
     }
     #print_r(get_class_methods($request));
     $info = array('city' => $request->getDestCity(), 'company' => $request->getDestCompany(), 'country_id' => $request->getDestCountryId(), 'firstname' => $request->getDestFirstname(), 'lastname' => $request->getDestLastname(), 'postcode' => $request->getDestPostcode(), 'region' => $request->getDestRegion(), 'region_code' => $request->getDestRegionCode(), 'region_id' => $request->getDestRegionId(), 'street' => $request->getDestStreet(), 'telphone' => $request->getDestTelphone());
     #$this->_logger->addDebug('$info');
     $this->_logger->log(100, print_r($info, true));
     $quoteArr = null;
     foreach ($request->getAllItems() as $item) {
         $quoteArr['item_id'] = $item->getitem_id();
         $quoteArr['quote_id'] = $item->getquote_id();
         $quoteArr['product_id'] = $item->getproduct_id();
         $quoteArr['parent_item_id'] = $item->getparent_item_id();
         $quoteArr['is_virtual'] = $item->getis_virtual();
         $quoteArr['sku'] = $item->getsku();
         $quoteArr['name'] = $item->getname();
         $quoteArr['qty'] = $item->getqty();
         $quoteArr['weight'] = $item->getweight();
         $quoteArr['price'] = $item->getprice();
         $quoteArr['base_price'] = $item->getbase_price();
         $quoteArr['custom_price'] = $item->getcustom_price();
         $quoteArr['discount_percent'] = $item->getdiscount_percent();
         $quoteArr['discount_amount'] = $item->getdiscount_amount();
     }
     #$this->_logger->addDebug('测试');
     $this->_logger->log(100, print_r($quoteArr, true));
     /** @var \Magento\Shipping\Model\Rate\Result $result */
     $result = $this->_rateResultFactory->create();
     $shippingPrice = $this->getConfigData('price');
     $method = $this->_rateMethodFactory->create();
     $method->setCarrier($this->_code);
     $method->setCarrierTitle($this->getConfigData('title'));
     $method->setMethod($this->_code);
     $method->setMethodTitle($this->getConfigData('name'));
     $method->setPrice($shippingPrice);
     $method->setCost($shippingPrice);
     $result->append($method);
     return $result;
 }