protected function saveShippingAddress($cartId) { $quote = $this->quoteRepository->getActive($cartId); $address = $quote->getShippingAddress(); $region = $address->getRegion(); if (!is_null($region) && $region instanceof \Magento\Customer\Model\Data\Region) { $regionString = $region->getRegion(); $address->setRegion($regionString); } try { $address->save(); } catch (\Exception $e) { $this->shipperLogger->postCritical('Shipperhq_Shipper', 'Exception raised whilst saving shipping address', $e->getMessage()); } }
/** *Set additional information for shipping address * * @param \Magento\Checkout\Model\ShippingInformationManagement $subject * @param callable $proceed * * @return \Magento\Checkout\Api\Data\PaymentDetailsInterface $paymentDetails * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ public function aroundSaveAddressInformation(\Magento\Checkout\Model\ShippingInformationManagement $subject, $proceed, $cartId, \Magento\Checkout\Api\Data\ShippingInformationInterface $addressInformation) { try { $carrierCode = $addressInformation->getShippingCarrierCode(); $methodCode = $addressInformation->getShippingMethodCode(); $shippingMethod = $carrierCode . '_' . $methodCode; $quote = $this->quoteRepository->getActive($cartId); $address = $quote->getShippingAddress(); $validation = $this->checkoutSession->getShipAddressValidation(); if (is_array($validation) && isset($validation['key'])) { if (isset($validation['validation_status'])) { $additionalDetail['address_valid'] = $validation['validation_status']; $address->setValidationStatus($validation['validation_status']); } if (isset($validation['destination_type'])) { $additionalDetail['destination_type'] = $validation['destination_type']; $address->setDestinationType($validation['destination_type']); } $this->checkoutSession->setShipAddressValidation(null); } $address->save(); $additionalDetail = new \Magento\Framework\DataObject(); $extAttributes = $addressInformation->getShippingAddress()->getExtensionAttributes(); //push out event so other modules can save their data TODO add carrier_group_id $this->eventManager->dispatch('shipperhq_additional_detail_checkout', ['address_extn_attributes' => $extAttributes, 'additional_detail' => $additionalDetail, 'carrier_code' => $carrierCode]); $additionalDetailArray = $additionalDetail->convertToArray(); $this->shipperLogger->postDebug('ShipperHQ Shipper', 'processing additional detail ', $additionalDetail); $this->carrierGroupHelper->saveCarrierGroupInformation($address, $shippingMethod, $additionalDetailArray); } catch (\Exception $e) { $this->shipperLogger->postCritical('Shipperhq_Shipper', 'Shipping Information Plugin', 'Exception raised ' . $e->getMessage()); } $result = $proceed($cartId, $addressInformation); if ($address->getCustomerId()) { $customerAddresses = $quote->getCustomer()->getAddresses(); foreach ($customerAddresses as $oneAddress) { if ($oneAddress->getId() == $address->getCustomerAddressId()) { if ($address->getValidationStatus()) { $oneAddress->setCustomAttribute('validation_status', $address->getValidationStatus()); } if ($address->getDestinationType()) { $oneAddress->setCustomAttribute('destination_type', $address->getDestinationType()); } $this->addressRepository->save($oneAddress); } } } return $result; }
/** * @param $shipperResponse * @return Mage_Shipping_Model_Rate_Result */ protected function parseShipperResponse($shipperResponse) { $debugRequest = $this->shipperRequest; $debugData = ['request' => json_encode($debugRequest, JSON_PRETTY_PRINT), 'response' => $shipperResponse]; if (!is_object($shipperResponse)) { $this->shipperLogger->postInfo('Shipperhq_Shipper', 'Shipper HQ did not return a response', $debugData); return $this->returnGeneralError('Shipper HQ did not return a response - could not contact ShipperHQ. Please review your settings'); } $transactionId = $this->shipperRateHelper->extractTransactionId($shipperResponse); $this->registry->unregister('shipperhq_transaction'); $this->registry->register('shipperhq_transaction', $transactionId); //first check and save globals for display purposes $globals = array(); if (is_object($shipperResponse) && isset($shipperResponse->globalSettings)) { $globals = $this->shipperRateHelper->extractGlobalSettings($shipperResponse); $globals['transaction'] = $transactionId; $this->shipperDataHelper->setGlobalSettings($globals); } $result = $this->rateFactory->create(); // If no rates are found return error message if (!empty($shipperResponse->errors)) { $this->shipperLogger->postInfo('Shipperhq_Shipper', 'Shipper HQ returned an error', $debugData); if (isset($shipperResponse->errors)) { foreach ($shipperResponse->errors as $error) { $this->appendError($result, $error, $this->_code, $this->getConfigData('title')); } } return $result; } elseif (!isset($shipperResponse->carrierGroups)) { // DO NOTHING } if (isset($shipperResponse->carrierGroups)) { $carrierRates = $this->processRatesResponse($shipperResponse, $transactionId, $globals); } else { $carrierRates = []; } $this->persistAddressValidation($shipperResponse); if (count($carrierRates) == 0) { $this->shipperLogger->postInfo('Shipperhq_Shipper', 'Shipper HQ did not return any carrier rates', $debugData); return $result; } foreach ($carrierRates as $carrierRate) { if (isset($carrierRate['error'])) { $carriergroupId = null; $carrierGroupDetail = null; if (array_key_exists('carriergroup_detail', $carrierRate) && !is_null($carrierRate['carriergroup_detail'])) { if (array_key_exists('carrierGroupId', $carrierRate['carriergroup_detail'])) { $carriergroupId = $carrierRate['carriergroup_detail']['carrierGroupId']; } $carrierGroupDetail = $carrierRate['carriergroup_detail']; } $this->appendError($result, $carrierRate['error'], $carrierRate['code'], $carrierRate['title'], $carriergroupId, $carrierGroupDetail); continue; } if (!array_key_exists('rates', $carrierRate)) { $this->shipperLogger->postInfo('Shipperhq_Shipper', 'Shipper HQ did not return any rates for ' . $carrierRate['code'] . ' ' . $carrierRate['title'], $debugData); } else { $baseRate = 1; $baseCurrencyCode = $this->shipperDataHelper->getBaseCurrencyCode(); foreach ($carrierRate['rates'] as $rateDetails) { if (isset($rateDetails['currency'])) { if ($rateDetails['currency'] != $baseCurrencyCode || $baseRate != 1) { $baseRate = $this->shipperDataHelper->getBaseCurrencyRate($rateDetails['currency']); if (!$baseRate) { $error = __('Can\'t convert rate from "%1".', $rateDetails['currency']); $this->appendError($result, $error, $carrierRate['code'], $carrierRate['title'], $rateDetails['carriergroup_detail']['carrierGroupId'], $rateDetails['carriergroup_detail']); $this->shipperLogger->postCritical('Shipperhq_Shipper', 'Currency Rate Missing', 'Currency code in shipping rate is ' . $rateDetails['currency'] . ' but there is no currency conversion rate configured so we cannot display this shipping rate'); continue; } } } $rate = $this->rateMethodFactory->create(); $rate->setCarrier($carrierRate['code']); $lengthCarrierCode = strlen($carrierRate['code']); $rate->setCarrierTitle(__($carrierRate['title'])); $methodCombineCode = preg_replace('/&|;| /', "", $rateDetails['methodcode']); //SHQ16-1520 - enforce limit on length of shipping carrier code and method code of less than 35 - M2 hard limit of 40 $lengthMethodCode = strlen($methodCombineCode); if ($lengthCarrierCode + $lengthMethodCode > 40) { $total = $lengthCarrierCode + $lengthMethodCode; $trim = $total - 35; $methodCombineCode = substr($methodCombineCode, $trim, $lengthMethodCode); } $rate->setMethod($methodCombineCode); $rate->setMethodTitle(__($rateDetails['method_title'])); $rate->setTooltip($rateDetails['tooltip']); if (array_key_exists('method_description', $rateDetails)) { $rate->setMethodDescription(__($rateDetails['method_description'])); } $rate->setCost($rateDetails['cost'] * $baseRate); $rate->setPrice($rateDetails['price'] * $baseRate); if (array_key_exists('carrier_type', $rateDetails)) { $rate->setCarrierType($rateDetails['carrier_type']); } if (array_key_exists('carrier_id', $rateDetails)) { $rate->setCarrierId($rateDetails['carrier_id']); } if (array_key_exists('dispatch_date', $rateDetails)) { $rate->setDispatchDate($rateDetails['dispatch_date']); } if (array_key_exists('delivery_date', $rateDetails)) { $rate->setDeliveryDate($rateDetails['delivery_date']); } if (array_key_exists('carriergroup_detail', $rateDetails) && !is_null($rateDetails['carriergroup_detail'])) { $carrierGroupDetail = $baseRate != 1 ? $this->updateWithCurrrencyConversion($rateDetails['carriergroup_detail'], $baseRate) : $rateDetails['carriergroup_detail']; $rate->setCarriergroupShippingDetails($this->shipperDataHelper->encode($carrierGroupDetail)); if (array_key_exists('carrierGroupId', $carrierGroupDetail)) { $rate->setCarriergroupId($carrierGroupDetail['carrierGroupId']); } if (array_key_exists('checkoutDescription', $carrierGroupDetail)) { $rate->setCarriergroup($carrierGroupDetail['checkoutDescription']); } } $result->append($rate); } if (isset($carrierRate['shipments'])) { $this->persistShipments($carrierRate['shipments']); } } } return $result; }
/** * Get values for items * * @param $request * @param $magentoItems * @param bool $childItems * @return array */ private function getFormattedItems($request, $magentoItems, $childItems = false) { $formattedItems = []; if (empty($magentoItems)) { return $formattedItems; } $selectedCarriergroupId = false; if ($request->getCarriergroupId() != '') { $selectedCarriergroupId = $request->getCarriergroupId(); } foreach ($magentoItems as $magentoItem) { if (!$childItems && $magentoItem->getParentItemId()) { continue; } //strip out items not required in carriergroup specific request if ($selectedCarriergroupId && $magentoItem->getCarriergroupId() != $selectedCarriergroupId) { continue; } // TODO Excluded from first release //$taxRequest = $this->taxCalculation->getRateOriginRequest(); //$taxRequest->setProductClassId($magentoItem->getProduct()->getTaxClassId()); //$taxPercentage = $this->taxCalculation->getRate($taxRequest); $taxPercentage = 0; // Not in first release of M2 $fixedPrice = $magentoItem->getProduct()->getPriceType() == \Magento\Bundle\Model\Product\Price::PRICE_TYPE_FIXED; $fixedWeight = $magentoItem->getProduct()->getWeightType() == 1 ? true : false; $id = $magentoItem->getItemId() ? $magentoItem->getItemId() : $magentoItem->getQuoteItemId(); $productType = $magentoItem->getProductType() ? $magentoItem->getProductType() : $magentoItem->getProduct()->getTypeId(); $stdAttributes = array_merge($this->getDimensionalAttributes($magentoItem), self::$stdAttributeNames); $options = self::populateCustomOptions($magentoItem); $weight = $magentoItem->getWeight(); if (is_null($weight)) { //SHIPPERHQ-1855 if ($productType != \Magento\Catalog\Model\Product\Type::TYPE_VIRTUAL && $productType != \Magento\Downloadable\Model\Product\Type::TYPE_DOWNLOADABLE) { $this->shipperLogger->postCritical('ShipperHQ', 'Item weight is null, using 0', 'Please review the product configuration for Sku ' . $magentoItem->getSku() . ' as product has NULL weight'); } $weight = 0; } $warehouseDetails = $this->getWarehouseDetails($magentoItem); $pickupLocationDetails = $this->getPickupLocationDetails($magentoItem); $formattedItem = $this->itemFactory->create(['id' => $id, 'sku' => $magentoItem->getSku(), 'qty' => $magentoItem->getQty() ? floatval($magentoItem->getQty()) : 0, 'weight' => $weight, 'rowTotal' => $magentoItem->getRowTotal(), 'basePrice' => $magentoItem->getBasePrice(), 'baseRowTotal' => $magentoItem->getBaseRowTotal(), 'discountAmount' => $magentoItem->getDiscountAmount(), 'discountPercent' => $magentoItem->getDiscountPercent(), 'discountedBasePrice' => $magentoItem->getBasePrice() - $magentoItem->getBaseDiscountAmount() / $magentoItem->getQty(), 'discountedStorePrice' => $magentoItem->getPrice() - $magentoItem->getDiscountAmount() / $magentoItem->getQty(), 'discountedTaxInclBasePrice' => $magentoItem->getBasePrice() - $magentoItem->getBaseDiscountAmount() / $magentoItem->getQty() + $magentoItem->getBaseTaxAmount() / $magentoItem->getQty(), 'discountedTaxInclStorePrice' => $magentoItem->getPrice() - $magentoItem->getDiscountAmount() / $magentoItem->getQty() + $magentoItem->getTaxAmount() / $magentoItem->getQty(), 'fixedPrice' => $fixedPrice, 'fixedWeight' => $fixedWeight, 'freeShipping' => (bool) $magentoItem->getFreeShipping(), 'packageCurrency' => $request->getPackageCurrency()->getCurrencyCode(), 'baseCurrency' => $request->getBaseCurrency()->getCurrencyCode(), 'storeBaseCurrency' => $this->storeManager->getStore()->getBaseCurrencyCode(), 'storeCurrentCurrency' => $this->storeManager->getStore()->getCurrentCurrencyCode(), 'storePrice' => $magentoItem->getPrice() ? $magentoItem->getPrice() : 0, 'taxInclBasePrice' => $magentoItem->getBasePriceInclTax() ? $magentoItem->getBasePriceInclTax() : 0, 'taxInclStorePrice' => $magentoItem->getPriceInclTax() ? $magentoItem->getPriceInclTax() : 0, 'taxPercentage' => $taxPercentage, 'type' => $productType, 'items' => [], 'attributes' => $options ? array_merge(self::populateAttributes($stdAttributes, $magentoItem), $options) : self::populateAttributes($stdAttributes, $magentoItem), 'additionalAttributes' => self::getCustomAttributes($magentoItem), 'warehouseDetails' => $warehouseDetails, 'pickupLocationDetails' => $pickupLocationDetails]); if (count($warehouseDetails) == 0) { $formattedItem->setDefaultWarehouseStockDetail($this->getDefaultWarehouseStockDetail($magentoItem)); } if (!$childItems) { $formattedItem->setItems($this->getFormattedItems($request, $magentoItem->getChildren(), true)); } $formattedItems[] = $formattedItem; } return $formattedItems; }