diff --git a/Model/Sales/TrackTraceHolder.php b/Model/Sales/TrackTraceHolder.php index 964c8584..173f19bf 100755 --- a/Model/Sales/TrackTraceHolder.php +++ b/Model/Sales/TrackTraceHolder.php @@ -1,19 +1,20 @@ - * @copyright 2010-2019 MyParcel * @license http://creativecommons.org/licenses/by-nc-nd/3.0/nl/deed.en_US CC BY-NC-ND 3.0 NL * @link https://github.com/myparcelnl/magento + * @copyright 2010-2019 MyParcel * @since File available since Release v0.1.0 */ namespace MyParcelNL\Magento\Model\Sales; +use BadMethodCallException; +use Exception; use Magento\Framework\App\ObjectManager; use Magento\Framework\App\ResourceConnection; use Magento\Framework\Exception\LocalizedException; @@ -33,9 +34,11 @@ use MyParcelNL\Sdk\src\Model\Carrier\CarrierFactory; use MyParcelNL\Sdk\src\Model\Consignment\AbstractConsignment; use MyParcelNL\Sdk\src\Model\MyParcelCustomsItem; +use RuntimeException; /** * Class TrackTraceHolder + * * @package MyParcelNL\Magento\Model\Sales */ class TrackTraceHolder @@ -43,20 +46,25 @@ class TrackTraceHolder /** * Track title showing in Magento */ - public const MYPARCEL_TRACK_TITLE = 'MyParcel'; - public const MYPARCEL_CARRIER_CODE = 'myparcel'; - public const EXPORT_MODE_PPS = 'pps'; - public const EXPORT_MODE_SHIPMENTS = 'shipments'; + public const MYPARCEL_TRACK_TITLE = 'MyParcel'; + public const MYPARCEL_CARRIER_CODE = 'myparcel'; + public const EXPORT_MODE_PPS = 'pps'; + public const EXPORT_MODE_SHIPMENTS = 'shipments'; /** - * @var string|null + * @var \MyParcelNL\Magento\Model\Source\DefaultOptions */ - private $carrier; + private static $defaultOptions; /** - * @var ObjectManagerInterface + * @var \MyParcelNL\Sdk\src\Model\Consignment\AbstractConsignment|null */ - private $objectManager; + public $consignment; + + /** + * @var Order\Shipment\Track + */ + public $mageTrack; /** * @var \Magento\Framework\Message\ManagerInterface @@ -64,9 +72,9 @@ class TrackTraceHolder protected $messageManager; /** - * @var \MyParcelNL\Magento\Model\Source\DefaultOptions + * @var string|null */ - private static $defaultOptions; + private $carrier; /** * @var \MyParcelNL\Magento\Helper\Data @@ -74,31 +82,26 @@ class TrackTraceHolder private $dataHelper; /** - * @var \MyParcelNL\Magento\Helper\ShipmentOptions - */ - private $shipmentOptionsHelper; - - /** - * @var Order\Shipment\Track + * @var ObjectManagerInterface */ - public $mageTrack; + private $objectManager; /** - * @var \MyParcelNL\Sdk\src\Model\Consignment\AbstractConsignment|null + * @var \MyParcelNL\Magento\Helper\ShipmentOptions */ - public $consignment; + private $shipmentOptionsHelper; /** * TrackTraceHolder constructor. * - * @param ObjectManagerInterface $objectManager - * @param Data $helper - * @param \Magento\Sales\Model\Order $order + * @param ObjectManagerInterface $objectManager + * @param Data $helper + * @param \Magento\Sales\Model\Order $order */ public function __construct( ObjectManagerInterface $objectManager, - Data $helper, - Order $order + Data $helper, + Order $order ) { $this->objectManager = $objectManager; $this->dataHelper = $helper; @@ -110,31 +113,20 @@ public function __construct( } /** - * Create Magento Track from Magento shipment - * - * @param \Magento\Sales\Model\Order\Shipment $shipment + * @param float $price * - * @return $this + * @return int */ - public function createTrackTraceFromShipment(Shipment $shipment) + public static function getCentsByPrice(float $price): int { - $this->mageTrack = $this->objectManager->create(Track::class); - $this->mageTrack - ->setOrderId($shipment->getOrderId()) - ->setShipment($shipment) - ->setCarrierCode(self::MYPARCEL_CARRIER_CODE) - ->setTitle(self::MYPARCEL_TRACK_TITLE) - ->setQty($shipment->getTotalQty()) - ->setTrackNumber(TrackAndTrace::VALUE_EMPTY); - - return $this; + return (int) $price * 100; } /** * Set all data to MyParcel object * - * @param Order\Shipment\Track $magentoTrack - * @param array $options + * @param Order\Shipment\Track $magentoTrack + * @param array $options * * @return $this * @throws \Exception @@ -150,7 +142,8 @@ public function convertDataFromMagentoToApi(Track $magentoTrack, array $options) $deliveryOptions['packageType'] = $options['package_type']; $deliveryOptions['carrier'] = $this->getCarrierFromOptions($options) ?? $deliveryOptions['carrier'] - ?? DefaultOptions::getDefaultCarrier()->getName(); + ?? DefaultOptions::getDefaultCarrier() + ->getName(); $totalWeight = $options['digital_stamp_weight'] !== null ? (int) $options['digital_stamp_weight'] : (int) self::$defaultOptions->getDigitalStampDefaultWeight(); @@ -158,7 +151,7 @@ public function convertDataFromMagentoToApi(Track $magentoTrack, array $options) try { // create new instance from known json $deliveryOptionsAdapter = DeliveryOptionsAdapterFactory::create((array) $deliveryOptions); - } catch (\BadMethodCallException $e) { + } catch (BadMethodCallException $e) { // create new instance from unknown json data $deliveryOptions = (new ConsignmentNormalizer((array) $deliveryOptions + $options))->normalize(); $deliveryOptionsAdapter = new DeliveryOptionsFromOrderAdapter($deliveryOptions); @@ -193,10 +186,15 @@ public function convertDataFromMagentoToApi(Track $magentoTrack, array $options) $this->consignment ->setFullStreet($address->getData('street')) ->setPostalCode(preg_replace('/\s+/', '', $address->getPostcode())); - } catch (\Exception $e) { - $errorHuman = sprintf('An error has occurred while validating order number %s. Check address.', $order->getIncrementId()); + } catch (Exception $e) { + $errorHuman = + sprintf( + 'An error has occurred while validating order number %s. Check address.', + $order->getIncrementId() + ); $this->messageManager->addErrorMessage($errorHuman . ' View log file for more information.'); - $this->objectManager->get('Psr\Log\LoggerInterface')->critical($errorHuman . '-' . $e); + $this->objectManager->get('Psr\Log\LoggerInterface') + ->critical($errorHuman . '-' . $e); $this->dataHelper->setOrderStatus($magentoTrack->getOrderId(), Order::STATE_NEW); } @@ -206,8 +204,12 @@ public function convertDataFromMagentoToApi(Track $magentoTrack, array $options) CarrierFactory::createFromName($deliveryOptionsAdapter->getCarrier()) ); + $regionCode = $address->getRegionCode(); + $state = $regionCode && strlen($regionCode) === 2 ? $regionCode : null; + $this->consignment ->setCity($address->getCity()) + ->setState($state) ->setPhone($address->getTelephone()) ->setEmail($address->getEmail()) ->setLabelDescription($this->shipmentOptionsHelper->getLabelDescription()) @@ -248,7 +250,7 @@ public function convertDataFromMagentoToApi(Track $magentoTrack, array $options) try { $this->convertDataForCdCountry($magentoTrack) ->calculateTotalWeight($magentoTrack, $totalWeight); - } catch (\Exception $e) { + } catch (Exception $e) { $this->messageManager->addErrorMessage($e->getMessage()); return $this; } @@ -257,86 +259,125 @@ public function convertDataFromMagentoToApi(Track $magentoTrack, array $options) } /** - * @param array $options - * @param Order\Shipment\Track $magentoTrack - * @param object $address + * Create Magento Track from Magento shipment * - * @return int - * @throws LocalizedException + * @param \Magento\Sales\Model\Order\Shipment $shipment + * + * @return $this */ - private function getPackageType(array $options, Track $magentoTrack, $address): int + public function createTrackTraceFromShipment(Shipment $shipment) { - // get packagetype from delivery_options and use it for process directly - $packageType = self::$defaultOptions->getPackageType(); - // get packagetype from selected radio buttons and check if package type is set - if ($options['package_type'] && 'default' !== $options['package_type']) { - $packageType = $options['package_type'] ?? AbstractConsignment::PACKAGE_TYPE_PACKAGE; - } - - if (! is_numeric($packageType)) { - $packageType = AbstractConsignment::PACKAGE_TYPES_NAMES_IDS_MAP[$packageType]; - } + $this->mageTrack = $this->objectManager->create(Track::class); + $this->mageTrack + ->setOrderId($shipment->getOrderId()) + ->setShipment($shipment) + ->setCarrierCode(self::MYPARCEL_CARRIER_CODE) + ->setTitle(self::MYPARCEL_TRACK_TITLE) + ->setQty($shipment->getTotalQty()) + ->setTrackNumber(TrackAndTrace::VALUE_EMPTY); - return $this->getAgeCheck($magentoTrack, $address, $options) ? AbstractConsignment::PACKAGE_TYPE_PACKAGE : $packageType; + return $this; } /** - * @param array $options + * Get country of origin from product settings or, if they are not found, from the MyParcel settings. * - * @return null|string + * @param $product_id + * + * @return string */ - private function getCarrierFromOptions(array $options): ?string + public function getCountryOfOrigin(int $product_id): string { - $carrier = null; + $product = + $this->objectManager->get('Magento\Catalog\Api\ProductRepositoryInterface') + ->getById($product_id); + $productCountryOfManufacture = $product->getCountryOfManufacture(); - if (array_key_exists('carrier', $options) && $options['carrier']) { - $carrier = DefaultOptions::DEFAULT_OPTION_VALUE === $options['carrier'] ? self::$defaultOptions->getCarrier() - : $options['carrier']; + if ($productCountryOfManufacture) { + return $productCountryOfManufacture; } - return $carrier; + return $this->dataHelper->getGeneralConfig('print/country_of_origin'); } /** - * @param Order\Shipment\Track $magentoTrack - * @param object $address - * @param array $options + * Override to check if key isset * - * @return bool + * @param null|string $apiKey + * + * @return $this * @throws \Magento\Framework\Exception\LocalizedException */ - private function getAgeCheck(Track $magentoTrack, $address, array $options = []): bool + public function validateApiKey(?string $apiKey): self { - if ($address->getCountryId() !== AbstractConsignment::CC_NL) { - return false; + if (null === $apiKey) { + throw new LocalizedException( + __( + 'API key is not known. Go to the settings in the backoffice to create an API key. Fill the API key in the settings.' + ) + ); } - $ageCheckFromOptions = ShipmentOptions::getValueOfOptionWhenSet('age_check', $options); - $ageCheckOfProduct = ShipmentOptions::getAgeCheckFromProduct($magentoTrack); - $ageCheckFromSettings = self::$defaultOptions->hasDefaultOptionsWithoutPrice($this->carrier, 'age_check'); - - return $ageCheckFromOptions ?? $ageCheckOfProduct ?? $ageCheckFromSettings; + return $this; } /** - * Override to check if key isset - * - * @param null|string $apiKey + * @param Order\Shipment\Track $magentoTrack + * @param int $totalWeight * - * @return $this - * @throws \Magento\Framework\Exception\LocalizedException + * @return TrackTraceHolder + * @throws LocalizedException + * @throws \Exception */ - public function validateApiKey(?string $apiKey): self + private function calculateTotalWeight(Track $magentoTrack, int $totalWeight = 0): self { - if (null === $apiKey) { - throw new LocalizedException(__('API key is not known. Go to the settings in the backoffice to create an API key. Fill the API key in the settings.')); + if ($this->consignment->getPackageType() !== AbstractConsignment::PACKAGE_TYPE_DIGITAL_STAMP) { + return $this; + } + + if ($totalWeight > 0) { + $this->consignment->setPhysicalProperties(["weight" => $totalWeight]); + + return $this; + } + + $weightFromSettings = (int) self::$defaultOptions->getDigitalStampDefaultWeight(); + if ($weightFromSettings) { + $this->consignment->setPhysicalProperties(["weight" => $weightFromSettings]); + + return $this; } + $shipmentItems = + $magentoTrack->getShipment() + ->getItems(); + + foreach ($shipmentItems as $shipmentItem) { + $totalWeight += $shipmentItem['weight'] * $shipmentItem['qty']; + } + + $totalWeight = $this->dataHelper->convertToGrams($totalWeight); + + if (0 === $totalWeight) { + throw new RuntimeException( + sprintf( + 'Order %s can not be exported as digital stamp, no weights have been entered.', + $magentoTrack->getShipment() + ->getOrder() + ->getIncrementId() + ) + ); + } + + $this->consignment->setPhysicalProperties([ + 'weight' => $totalWeight, + ]); + return $this; } /** - * @param Order\Shipment\Track $magentoTrack + * @param Order\Shipment\Track $magentoTrack * * @return $this * @throws LocalizedException @@ -349,7 +390,9 @@ private function convertDataForCdCountry(Track $magentoTrack) return $this; } - if ($products = $magentoTrack->getShipment()->getData('items')) { + if ($products = + $magentoTrack->getShipment() + ->getData('items')) { foreach ($products as $product) { $myParcelProduct = (new MyParcelCustomsItem()) ->setDescription($product->getName()) @@ -357,20 +400,31 @@ private function convertDataForCdCountry(Track $magentoTrack) ->setWeight($this->dataHelper->convertToGrams($product->getWeight()) ?: 1) ->setItemValue($this->getCentsByPrice($product->getPrice())) ->setClassification( - (int) $this->getAttributeValue('catalog_product_entity_int', $product['product_id'], 'classification') + (int) $this->getAttributeValue( + 'catalog_product_entity_int', + $product['product_id'], + 'classification' + ) ) ->setCountry($this->getCountryOfOrigin($product['product_id'])); $this->consignment->addItem($myParcelProduct); } } - foreach ($magentoTrack->getShipment()->getItems() as $item) { + foreach ($magentoTrack->getShipment() + ->getItems() as $item) { $myParcelProduct = (new MyParcelCustomsItem()) ->setDescription($item->getName()) ->setAmount($item->getQty()) ->setWeight($this->dataHelper->convertToGrams($item->getWeight() * $item->getQty())) ->setItemValue($item->getPrice() * 100) - ->setClassification((int) $this->getAttributeValue('catalog_product_entity_int', $item->getProductId(), 'classification')) + ->setClassification( + (int) $this->getAttributeValue( + 'catalog_product_entity_int', + $item->getProductId(), + 'classification' + ) + ) ->setCountry($this->getCountryOfOrigin($item->getProductId())); $this->consignment->addItem($myParcelProduct); @@ -380,28 +434,30 @@ private function convertDataForCdCountry(Track $magentoTrack) } /** - * Get country of origin from product settings or, if they are not found, from the MyParcel settings. + * @param Order\Shipment\Track $magentoTrack + * @param object $address + * @param array $options * - * @param $product_id - * - * @return string + * @return bool + * @throws \Magento\Framework\Exception\LocalizedException */ - public function getCountryOfOrigin(int $product_id): string + private function getAgeCheck(Track $magentoTrack, $address, array $options = []): bool { - $product = $this->objectManager->get('Magento\Catalog\Api\ProductRepositoryInterface')->getById($product_id); - $productCountryOfManufacture = $product->getCountryOfManufacture(); - - if ($productCountryOfManufacture) { - return $productCountryOfManufacture; + if ($address->getCountryId() !== AbstractConsignment::CC_NL) { + return false; } - return $this->dataHelper->getGeneralConfig('print/country_of_origin'); + $ageCheckFromOptions = ShipmentOptions::getValueOfOptionWhenSet('age_check', $options); + $ageCheckOfProduct = ShipmentOptions::getAgeCheckFromProduct($magentoTrack); + $ageCheckFromSettings = self::$defaultOptions->hasDefaultOptionsWithoutPrice($this->carrier, 'age_check'); + + return $ageCheckFromOptions ?? $ageCheckOfProduct ?? $ageCheckFromSettings; } /** - * @param string $tableName - * @param string $entityId - * @param string $column + * @param string $tableName + * @param string $entityId + * @param string $column * * @return string|null */ @@ -425,63 +481,45 @@ private function getAttributeValue(string $tableName, string $entityId, string $ } /** - * @param Order\Shipment\Track $magentoTrack - * @param int $totalWeight + * @param array $options * - * @return TrackTraceHolder - * @throws LocalizedException - * @throws \Exception + * @return null|string */ - private function calculateTotalWeight(Track $magentoTrack, int $totalWeight = 0): self + private function getCarrierFromOptions(array $options): ?string { - if ($this->consignment->getPackageType() !== AbstractConsignment::PACKAGE_TYPE_DIGITAL_STAMP) { - return $this; - } - - if ($totalWeight > 0) { - $this->consignment->setPhysicalProperties(["weight" => $totalWeight]); - - return $this; - } - - $weightFromSettings = (int) self::$defaultOptions->getDigitalStampDefaultWeight(); - if ($weightFromSettings) { - $this->consignment->setPhysicalProperties(["weight" => $weightFromSettings]); - - return $this; - } - - $shipmentItems = $magentoTrack->getShipment()->getItems(); - - foreach ($shipmentItems as $shipmentItem) { - $totalWeight += $shipmentItem['weight'] * $shipmentItem['qty']; - } - - $totalWeight = $this->dataHelper->convertToGrams($totalWeight); + $carrier = null; - if (0 === $totalWeight) { - throw new \RuntimeException( - sprintf( - 'Order %s can not be exported as digital stamp, no weights have been entered.', - $magentoTrack->getShipment()->getOrder()->getIncrementId() - ) - ); + if (array_key_exists('carrier', $options) && $options['carrier']) { + $carrier = + DefaultOptions::DEFAULT_OPTION_VALUE === $options['carrier'] ? self::$defaultOptions->getCarrier() + : $options['carrier']; } - $this->consignment->setPhysicalProperties([ - 'weight' => $totalWeight, - ]); - - return $this; + return $carrier; } /** - * @param float $price + * @param array $options + * @param Order\Shipment\Track $magentoTrack + * @param object $address * * @return int + * @throws LocalizedException */ - public static function getCentsByPrice(float $price): int + private function getPackageType(array $options, Track $magentoTrack, $address): int { - return (int) $price * 100; + // get packagetype from delivery_options and use it for process directly + $packageType = self::$defaultOptions->getPackageType(); + // get packagetype from selected radio buttons and check if package type is set + if ($options['package_type'] && 'default' !== $options['package_type']) { + $packageType = $options['package_type'] ?? AbstractConsignment::PACKAGE_TYPE_PACKAGE; + } + + if (! is_numeric($packageType)) { + $packageType = AbstractConsignment::PACKAGE_TYPES_NAMES_IDS_MAP[$packageType]; + } + + return $this->getAgeCheck($magentoTrack, $address, $options) ? AbstractConsignment::PACKAGE_TYPE_PACKAGE + : $packageType; } } diff --git a/composer.json b/composer.json index 73950db3..c49c7990 100755 --- a/composer.json +++ b/composer.json @@ -30,7 +30,7 @@ "type": "magento2-module", "require": { "php": "~5.6.5 || ^7.0 || ^8.0", - "myparcelnl/sdk": "~v7.9.1", + "myparcelnl/sdk": "~v7.10.0", "magento/framework": ">=101.0.8 <102 || >=102.0.1" }, "require-dev": {