From 4b106f05345962f20e8804795a9ea89ea1f0fd21 Mon Sep 17 00:00:00 2001 From: Joeri van Veen Date: Tue, 3 Sep 2024 13:01:10 +0200 Subject: [PATCH 01/29] feat: add myparcel delivery method --- Model/{Checkout => Carrier}/Carrier.php | 54 ++++++++++++++++--- ...SaveOrderBeforeSalesModelQuoteObserver.php | 2 +- Model/Rate/Result.php | 1 + etc/adminhtml/system.xml | 37 +++++++++++++ etc/config.xml | 13 +++++ 5 files changed, 99 insertions(+), 8 deletions(-) rename Model/{Checkout => Carrier}/Carrier.php (80%) diff --git a/Model/Checkout/Carrier.php b/Model/Carrier/Carrier.php similarity index 80% rename from Model/Checkout/Carrier.php rename to Model/Carrier/Carrier.php index 0c9a8949..cdddd193 100644 --- a/Model/Checkout/Carrier.php +++ b/Model/Carrier/Carrier.php @@ -16,7 +16,7 @@ * @since File available since Release 0.1.0 */ -namespace MyParcelNL\Magento\Model\Checkout; +namespace MyParcelNL\Magento\Model\Carrier; use Magento\CatalogInventory\Api\StockRegistryInterface; use Magento\Checkout\Model\Session; @@ -28,6 +28,7 @@ use Magento\Framework\Xml\Security; use Magento\Quote\Model\Quote\Address\RateRequest; use Magento\Quote\Model\Quote\Address\RateResult\MethodFactory; +use Magento\Shipping\Model\Carrier\AbstractCarrier; use Magento\Shipping\Model\Carrier\AbstractCarrierOnline; use Magento\Shipping\Model\Carrier\CarrierInterface; use Magento\Shipping\Model\Simplexml\ElementFactory; @@ -39,11 +40,12 @@ use MyParcelNL\Magento\Model\Sales\Repository\PackageRepository; use Psr\Log\LoggerInterface; -class Carrier extends AbstractCarrierOnline implements CarrierInterface +class Carrier extends AbstractCarrier implements CarrierInterface { - const CODE = 'mypa'; + const CODE = 'myparcelnl_delivery'; + protected $_code = self::CODE; - protected $_localeFormat; + protected $_freeShipping; /** * @var \Magento\Quote\Model\Quote @@ -105,12 +107,14 @@ public function __construct( Session $session, Checkout $myParcelHelper, PackageRepository $package, + \Magento\OfflineShipping\Model\Carrier\Freeshipping $freeShipping, array $data = [] ) { parent::__construct( $scopeConfig, $rateErrorFactory, $logger, + $data, // remove this line when you extend AbstractCarrierOnline, add it for AbstractCarrier $xmlSecurity, $xmlElFactory, $rateFactory, @@ -128,6 +132,9 @@ public function __construct( $this->quote = $session->getQuote(); $this->myParcelHelper = $myParcelHelper; $this->package = $package; + $this->_rateFactory = $rateFactory; + $this->_rateMethodFactory = $rateMethodFactory; + $this->_freeShipping = $freeShipping; } protected function _doShipmentRequest(DataObject $request) @@ -136,6 +143,33 @@ protected function _doShipmentRequest(DataObject $request) public function collectRates(RateRequest $request) { + if (!$this->getConfigFlag('active')) { + return false; + } + /** @var \Magento\Shipping\Model\Rate\Result $result */ + $result = $this->_rateFactory->create(); + + /** @var \Magento\Quote\Model\Quote\Address\RateResult\Method $method */ + $method = $this->_rateMethodFactory->create(); + + // todo: get actual title based on chosen and possible options for this quote / cart + $method->setCarrier($this->_code); + $method->setCarrierTitle('MyParcel'); + + $method->setMethod($this->_code); + $method->setMethodTitle('Todo: chosen options here'); + + $freeShippingIsAvailable = false; // todo // $this->_freeShipping->getConfigData('active') + // todo: get actual price based on chosen and possible options for this quote / cart + $amount = $freeShippingIsAvailable ? '0.00' : '10.00'; + + $method->setPrice($amount); + $method->setCost($amount); + + //$result->append($method); + $result = $this->addShippingMethods($result); +//$bla = $this->quote->getCheckoutMethod(); + return $result; /** @var \Magento\Quote\Model\Quote\Address\RateRequest $result */ $result = $this->_rateFactory->create(); $result = $this->addShippingMethods($result); @@ -248,10 +282,16 @@ private function createTitle($settingPath) */ private function createPrice($alias, $settingPath) { - $price = 0; + if ($this->_freeShipping->getConfigData('active')) { + return 0; + } - $price += $this->myParcelHelper->getMethodPrice($settingPath . 'fee', $alias); + return 10 + $this->myParcelHelper->getMethodPrice($settingPath . 'fee', $alias); + } - return $price; + public function isTrackingAvailable(): bool + { + // TODO: Implement isTrackingAvailable() method. + return true; } } diff --git a/Model/Quote/SaveOrderBeforeSalesModelQuoteObserver.php b/Model/Quote/SaveOrderBeforeSalesModelQuoteObserver.php index 57403d17..4322e06c 100644 --- a/Model/Quote/SaveOrderBeforeSalesModelQuoteObserver.php +++ b/Model/Quote/SaveOrderBeforeSalesModelQuoteObserver.php @@ -25,7 +25,7 @@ use Magento\Quote\Model\Quote; use Magento\Sales\Model\Order; use MyParcelNL\Magento\Helper\Checkout; -use MyParcelNL\Magento\Model\Checkout\Carrier; +use MyParcelNL\Magento\Model\Carrier\Carrier; use MyParcelNL\Magento\Model\Sales\Repository\DeliveryRepository; use MyParcelNL\Sdk\src\Helper\ValidatePostalCode; use MyParcelNL\Sdk\src\Helper\ValidateStreet; diff --git a/Model/Rate/Result.php b/Model/Rate/Result.php index 12562455..098eb615 100755 --- a/Model/Rate/Result.php +++ b/Model/Rate/Result.php @@ -170,6 +170,7 @@ public static function getMethods(): array */ private function addMyParcelRates(Method $parentRate): void { + return;//todo joeri $parentShippingMethod = $parentRate->getData('carrier'); if (! in_array($parentShippingMethod, $this->parentMethods, true)) { return; diff --git a/etc/adminhtml/system.xml b/etc/adminhtml/system.xml index 433d09f4..d0e5946d 100755 --- a/etc/adminhtml/system.xml +++ b/etc/adminhtml/system.xml @@ -1292,5 +1292,42 @@ +
+ + + + + Magento\Config\Model\Config\Source\Yesno + + + + + + + + + + validate-number validate-zero-or-greater + + + + shipping-applicable-country + Magento\Shipping\Model\Config\Source\Allspecificcountries + + + + Magento\Directory\Model\Config\Source\Country + 1 + + + + Magento\Config\Model\Config\Source\Yesno + shipping-skip-hide + + + + + +
diff --git a/etc/config.xml b/etc/config.xml index fdcaf32d..422f0426 100755 --- a/etc/config.xml +++ b/etc/config.xml @@ -244,5 +244,18 @@ bcc + + + + 1 + Custom Shipping Title + Custom Shipping Method Name + 10 + 0 + 15 + MyparcelNL\Magento\Model\Carrier\Carrier + + + From febf6c25b3d2c83b5adc7e389eb42b38f3ed843e Mon Sep 17 00:00:00 2001 From: Joeri van Veen Date: Thu, 26 Sep 2024 11:50:42 +0200 Subject: [PATCH 02/29] wip --- Block/Sales/NewShipment.php | 68 +++--- .../Config/Form/SupportTabRepository.php | 6 - Helper/Checkout.php | 47 +--- Helper/CustomsDeclarationFromOrder.php | 19 +- Helper/Data.php | 54 +---- Helper/ShipmentOptions.php | 15 +- Model/Carrier/Carrier.php | 131 +++++------ .../DeliveryOptionsToShippingMethods.php | 6 +- Model/Quote/Checkout.php | 152 ++++++------- ...SaveOrderBeforeSalesModelQuoteObserver.php | 25 +-- Model/Rate/Result.php | 54 ++--- Model/Sales/Delivery.php | 50 ----- Model/Sales/MagentoOrderCollection.php | 2 +- Model/Sales/Package.php | 26 +-- Model/Sales/Repository/DeliveryRepository.php | 27 ++- Model/Sales/TrackTraceHolder.php | 66 +++--- Model/Source/AgeCheckNo.php | 13 +- Model/Source/AgeCheckYes.php | 10 +- Model/Source/DefaultOptions.php | 58 ++--- Model/Source/DigitalStampWeightOptions.php | 15 +- Service/Config/ConfigService.php | 204 ++++++++++++++++++ Service/Costs/DeliveryCostsService.php | 23 ++ Service/Costs/TaxService.php | 10 + .../Normalizer/ConsignmentNormalizer.php | 2 +- Service/Weight/WeightService.php | 39 ++++ 25 files changed, 625 insertions(+), 497 deletions(-) delete mode 100755 Model/Sales/Delivery.php create mode 100644 Service/Config/ConfigService.php create mode 100644 Service/Costs/DeliveryCostsService.php create mode 100644 Service/Costs/TaxService.php rename {Services => Service}/Normalizer/ConsignmentNormalizer.php (93%) create mode 100644 Service/Weight/WeightService.php diff --git a/Block/Sales/NewShipment.php b/Block/Sales/NewShipment.php index ba1f7cda..7610e1ad 100755 --- a/Block/Sales/NewShipment.php +++ b/Block/Sales/NewShipment.php @@ -20,78 +20,65 @@ use Magento\Framework\ObjectManagerInterface; use Magento\Framework\Registry; use Magento\Sales\Block\Adminhtml\Items\AbstractItems; -use MyParcelNL\Magento\Helper\Checkout; use MyParcelNL\Magento\Model\Sales\MagentoOrderCollection; use MyParcelNL\Magento\Model\Source\DefaultOptions; use MyParcelNL\Magento\Helper\Data; use MyParcelNL\Magento\Model\Sales\TrackTraceHolder; +use MyParcelNL\Magento\Service\Config\ConfigService; +use MyParcelNL\Magento\Service\Weight\WeightService; +use MyParcelNL\Sdk\src\Model\Carrier\CarrierPostNL; use MyParcelNL\Sdk\src\Model\Consignment\AbstractConsignment; class NewShipment extends AbstractItems { - /** - * @var \MyParcelNL\Magento\Helper\Data - */ - private $dataHelper; - /** * @var \Magento\Sales\Model\Order */ private $order; - /** - * @var \Magento\Framework\ObjectManagerInterface - */ - private $objectManager; - /** * @var \MyParcelNL\Magento\Model\Source\DefaultOptions */ - private $defaultOptions; + private DefaultOptions $defaultOptions; /** * @var \MyParcelNL\Magento\Block\Sales\NewShipmentForm */ - private $form; + private NewShipmentForm $form; /** * @var \MyParcelNL\Magento\Model\Sales\MagentoOrderCollection */ - private $orderCollection; + private MagentoOrderCollection $orderCollection; /** - * @var mixed - */ - private $request; - - /** - * @param \Magento\Backend\Block\Template\Context $context - * @param \Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry - * @param \Magento\CatalogInventory\Api\StockConfigurationInterface $stockConfiguration - * @param \Magento\Framework\Registry $registry - * @param \Magento\Framework\ObjectManagerInterface $objectManager + * @param Context $context + * @param WeightService $weightService + * @param StockRegistryInterface $stockRegistry + * @param StockConfigurationInterface $stockConfiguration + * @param Registry $registry + * @param ConfigService $configService */ public function __construct( Context $context, - Data $helper, + WeightService $weightService, StockRegistryInterface $stockRegistry, StockConfigurationInterface $stockConfiguration, Registry $registry, ObjectManagerInterface $objectManager ) { - // Set order $this->order = $registry->registry('current_shipment')->getOrder(); - $this->dataHelper = $helper; - $this->objectManager = $objectManager; + $this->weightService = $weightService; $this->form = new NewShipmentForm(); $this->defaultOptions = new DefaultOptions( $this->order, - $this->objectManager->get(Data::class) + $objectManager->get(ConfigService::class), + $weightService ); - $this->request = $this->objectManager->get('Magento\Framework\App\RequestInterface'); - $this->orderCollection = new MagentoOrderCollection($this->objectManager, $this->request); + $request = $objectManager->get('Magento\Framework\App\RequestInterface'); + $this->orderCollection = new MagentoOrderCollection($objectManager, $request); parent::__construct($context, $stockRegistry, $stockConfiguration, $registry); } @@ -138,7 +125,7 @@ public function getDefaultInsurance(string $carrier): int */ public function getDigitalStampWeight(): int { - $weight = $this->dataHelper->convertToGrams($this->order->getWeight() ?? 0.0); + $weight = $this->weightService->convertToGrams($this->order->getWeight() ?? 0.0); if (0 === $weight) { $weight = $this->defaultOptions->getDigitalStampDefaultWeight(); @@ -173,7 +160,22 @@ public function getCountry() public function consignmentHasShipmentOption(AbstractConsignment $consignment, string $shipmentOption): bool { - return $this->dataHelper->consignmentHasShipmentOption($consignment, $shipmentOption); + /** + * Business logic determining what shipment options to show, if any. + */ + if (AbstractConsignment::CC_NL === $consignment->getCountry()) { + return $consignment->canHaveShipmentOption($shipmentOption); + } + + // For PostNL in Belgium - only recipient-only/signature is available + if (AbstractConsignment::CC_BE === $consignment->getCountry() && CarrierPostNL::NAME === $consignment->getCarrierName()) { + return in_array($shipmentOption, [ + AbstractConsignment::SHIPMENT_OPTION_ONLY_RECIPIENT, + AbstractConsignment::SHIPMENT_OPTION_SIGNATURE], true); + } + + // No shipment options available in any other cases + return false; } /** diff --git a/Block/System/Config/Form/SupportTabRepository.php b/Block/System/Config/Form/SupportTabRepository.php index e1e582fe..e10a67ad 100755 --- a/Block/System/Config/Form/SupportTabRepository.php +++ b/Block/System/Config/Form/SupportTabRepository.php @@ -18,17 +18,11 @@ namespace MyParcelNL\Magento\Block\System\Config\Form; -use MyParcelNL\Magento\Helper\Data; - class SupportTabRepository extends \Magento\Sales\Block\Adminhtml\Order\AbstractOrder {/** * @var \Magento\Framework\Module\ModuleListInterface */ protected $moduleList; - /** - * @var \MyParcelNL\Magento\Helper\Data - */ - private $helper; /** * MyParcelSupportTab constructor diff --git a/Helper/Checkout.php b/Helper/Checkout.php index ca1610e2..8e48505d 100755 --- a/Helper/Checkout.php +++ b/Helper/Checkout.php @@ -74,6 +74,7 @@ public function __construct( CheckApiKeyService $checkApiKeyService, Session $session ) { + throw new \Exception('Do not use Helper/Checkout.php'); parent::__construct($context, $moduleList, $checkApiKeyService); $this->shippingMethodManagement = $shippingMethodManagement; $this->estimatedAddressFactory = $estimatedAddressFactory; @@ -85,6 +86,7 @@ public function __construct( */ public function getBasePrice() { + return 5; //joeri return $this->base_price; } @@ -194,8 +196,8 @@ private function getEstimatedAddress( */ public function getMethodPrice(string $carrier, string $key, bool $addBasePrice = true): float { - $value = (float) $this->getCarrierConfig($key, $carrier); - $showTotalPrice = $this->getCarrierConfig('shipping_methods/delivery_options_prices', Data::XML_PATH_GENERAL) === PriceDeliveryOptionsView::TOTAL; + $value = (float) $this->getConfigValue("$carrier$key"); + $showTotalPrice = $this->getConfigValue(Data::XML_PATH_GENERAL . 'shipping_methods/delivery_options_prices') === PriceDeliveryOptionsView::TOTAL; if ($showTotalPrice && $addBasePrice) { // Calculate value @@ -205,39 +207,6 @@ public function getMethodPrice(string $carrier, string $key, bool $addBasePrice return $value; } - /** - * Get shipping price - * - * @param $price - * @param $flag - * - * @return mixed - */ - /*private function getShippingPrice($price, $flag = false) - { - $flag = $flag ? true : Mage::helper('tax')->displayShippingPriceIncludingTax(); - return (float)Mage::helper('tax')->getShippingPrice($price, $flag, $quoteId->getShippingAddress()); - }*/ - - /** - * Get checkout setting - * - * @param string $carrier - * @param string $code - * - * @return mixed - */ - public function getCarrierConfig(string $code, string $carrier) - { - $value = $this->getConfigValue($carrier . $code); - if (null === $value) { - $this->_logger->critical('Can\'t get setting with path:' . $carrier . $code); - return 0; - } - - return $value; - } - /** * Get bool of setting * @@ -248,7 +217,7 @@ public function getCarrierConfig(string $code, string $carrier) */ public function getBoolConfig(string $carrier, string $key): bool { - return '1' === $this->getCarrierConfig($key, $carrier); + return '1' === $this->getConfigValue("$carrier$key"); } /** @@ -261,7 +230,7 @@ public function getBoolConfig(string $carrier, string $key): bool */ public function getTimeConfig(string $carrier, string $key): string { - $timeAsString = str_replace(',', ':', (string) $this->getCarrierConfig($key, $carrier)); + $timeAsString = str_replace(',', ':', (string) $this->getConfigValue("$carrier$key")); $timeComponents = explode(':', $timeAsString ?? ''); if (count($timeComponents) >= 3) { [$hours, $minutes] = $timeComponents; @@ -283,7 +252,7 @@ public function getArrayConfig(string $carrier, string $key): array { return array_map(static function($val) { return is_numeric($val) ? (int) $val : $val; - }, explode(',', (string) ($this->getCarrierConfig($key, $carrier) ?? ''))); + }, explode(',', (string) ($this->getConfigValue("$carrier$key") ?? ''))); } /** @@ -296,6 +265,6 @@ public function getArrayConfig(string $carrier, string $key): array */ public function getIntegerConfig($carrier, $key) { - return (float) $this->getCarrierConfig($key, $carrier); + return (float) $this->getConfigValue("$carrier$key"); } } diff --git a/Helper/CustomsDeclarationFromOrder.php b/Helper/CustomsDeclarationFromOrder.php index 4d14fcd3..55b11425 100644 --- a/Helper/CustomsDeclarationFromOrder.php +++ b/Helper/CustomsDeclarationFromOrder.php @@ -5,13 +5,13 @@ use Magento\Catalog\Model\Product; use Magento\Framework\ObjectManagerInterface; use Magento\Sales\Model\Order; -use MyParcelNL\Magento\Model\Sales\TrackTraceHolder; +use MyParcelNL\Magento\Service\Costs\DeliveryCostsService; +use MyParcelNL\Magento\Service\Weight\WeightService; use MyParcelNL\Sdk\src\Model\Consignment\AbstractConsignment; use MyParcelNL\Sdk\src\Model\CustomsDeclaration; use MyParcelNL\Sdk\src\Model\MyParcelCustomsItem; use Magento\Catalog\Api\ProductRepositoryInterface; use MyParcelNL\Sdk\src\Support\Str; -use MyParcelNL\Magento\Helper\Data; class CustomsDeclarationFromOrder { @@ -32,15 +32,20 @@ class CustomsDeclarationFromOrder */ private $order; + /** + * @var WeightService + */ + private $WeightService; + /** * @param \Magento\Sales\Model\Order $order * @param \Magento\Framework\ObjectManagerInterface $objectManager */ - public function __construct(Order $order, ObjectManagerInterface $objectManager) + public function __construct(Order $order, ObjectManagerInterface $objectManager, WeightService $WeightService) { $this->order = $order; $this->objectManager = $objectManager; - $this->helper = $this->objectManager->get(Data::class); + $this->WeightService = $WeightService; } /** @@ -61,15 +66,15 @@ public function createCustomsDeclaration(): CustomsDeclaration } $amount = (float) $item->getQtyShipped() ? $item->getQtyShipped() : $item->getQtyOrdered(); - $totalWeight += $this->helper->convertToGrams($product->getWeight() * $amount); + $totalWeight += $this->WeightService->convertToGrams($product->getWeight() * $amount); $description = Str::limit($product->getName(), AbstractConsignment::DESCRIPTION_MAX_LENGTH); $customsItem = (new MyParcelCustomsItem()) ->setDescription($description) ->setAmount($amount) - ->setWeight($this->helper->convertToGrams($product->getWeight())) + ->setWeight($this->WeightService->convertToGrams($product->getWeight())) ->setItemValueArray([ - 'amount' => TrackTraceHolder::getCentsByPrice($product->getPrice()), + 'amount' => DeliveryCostsService::getCentsByPrice($product->getPrice()), 'currency' => $this->order->getOrderCurrency()->getCode() ?? self::CURRENCY_EURO, ]) ->setCountry($this->getCountryOfOrigin($product)) diff --git a/Helper/Data.php b/Helper/Data.php index 3e50b30a..bd102b40 100755 --- a/Helper/Data.php +++ b/Helper/Data.php @@ -30,7 +30,6 @@ class Data extends AbstractHelper public const XML_PATH_UPS_SETTINGS = 'myparcelnl_magento_ups_settings/'; public const XML_PATH_DPD_SETTINGS = 'myparcelnl_magento_dpd_settings/'; public const XML_PATH_LOCALE_WEIGHT_UNIT = 'general/locale/weight_unit'; - public const DEFAULT_WEIGHT = 1000; public const CARRIERS_XML_PATH_MAP = [ CarrierPostNL::NAME => self::XML_PATH_POSTNL_SETTINGS, CarrierDHLForYou::NAME => self::XML_PATH_DHLFORYOU_SETTINGS, @@ -65,6 +64,7 @@ public function __construct( parent::__construct($context); $this->moduleList = $moduleList; $this->checkApiKeyService = $checkApiKeyService; + throw new \Exception('do not use Data.php'); } /** @@ -123,36 +123,11 @@ public function getDropOffPoint(AbstractCarrier $carrier): ?DropOffPoint * * @return mixed */ - public function getStandardConfig(string $carrier, string $code = '', $storeId = null) + public function getCarrierConfig(string $carrier, string $code = '', $storeId = null) { return $this->getConfigValue(self::CARRIERS_XML_PATH_MAP[$carrier] . $code, $storeId); } - /** - * Get carrier setting - * - * @param string $code - * @param string $carrier - * - * @return mixed - */ - public function getCarrierConfig(string $code, string $carrier) - { - $settings = $this->getConfigValue($carrier . $code); - - if (null === $settings) { - $value = $this->getConfigValue($carrier . $code); - - if (null === $value) { - $this->_logger->critical('Can\'t get setting with path:' . $carrier . $code); - } - - return $value; - } - - return $settings; - } - /** * Get the version number of the installed module * @@ -271,29 +246,4 @@ public function consignmentHasShipmentOption(AbstractConsignment $consignment, s return false; } - /** - * Get the correct weight type - * - * @param null|float $weight - * - * @return int - */ - public function convertToGrams(?float $weight): int - { - $weightType = $this->getGeneralConfig('print/weight_indication'); - - if ('kilo' === $weightType) { - return (int) ($weight * 1000); - } - - return (int) $weight ?: self::DEFAULT_WEIGHT; - } - - /** - * @return string|null - */ - public function getExportMode(): ?string - { - return $this->getGeneralConfig('print/export_mode'); - } } diff --git a/Helper/ShipmentOptions.php b/Helper/ShipmentOptions.php index 27ebf134..002ca72e 100644 --- a/Helper/ShipmentOptions.php +++ b/Helper/ShipmentOptions.php @@ -5,6 +5,7 @@ use Magento\Framework\App\ObjectManager; use Magento\Framework\ObjectManagerInterface; use MyParcelNL\Magento\Model\Source\DefaultOptions; +use MyParcelNL\Magento\Service\Config\ConfigService; use MyParcelNL\Sdk\src\Model\Consignment\AbstractConsignment; use Magento\Framework\App\ResourceConnection; @@ -48,7 +49,7 @@ class ShipmentOptions /** * @var \MyParcelNL\Magento\Helper\Data */ - private $helper; + private $configService; /** * @var \Magento\Sales\Model\Order @@ -62,7 +63,7 @@ class ShipmentOptions /** * @param \MyParcelNL\Magento\Model\Source\DefaultOptions $defaultOptions - * @param \MyParcelNL\Magento\Helper\Data $helper + * @param \MyParcelNL\Magento\Helper\ConfigService $configService * @param \Magento\Sales\Model\Order $order * @param \Magento\Framework\ObjectManagerInterface $objectManager * @param string $carrier @@ -70,14 +71,14 @@ class ShipmentOptions */ public function __construct( DefaultOptions $defaultOptions, - Data $helper, + ConfigService $configService, \Magento\Sales\Model\Order $order, ObjectManagerInterface $objectManager, string $carrier, array $options = [] ) { self::$defaultOptions = $defaultOptions; - $this->helper = $helper; + $this->configService = $configService; $this->order = $order; $this->objectManager = $objectManager; $this->carrier = $carrier; @@ -288,7 +289,7 @@ public function hasLargeFormat(): bool public function getLabelDescription(): string { $checkoutData = $this->order->getData('myparcel_delivery_options'); - $labelDescription = $this->helper->getGeneralConfig( + $labelDescription = $this->configService->getGeneralConfig( 'print/label_description', $this->order->getStoreId() ); @@ -298,7 +299,7 @@ public function getLabelDescription(): string } $productInfo = $this->getItemsCollectionByShipmentId($this->order->getId()); - $deliveryDate = $checkoutData ? date('d-m-Y', strtotime($this->helper->convertDeliveryDate($checkoutData))) : null; + $deliveryDate = $checkoutData ? date('d-m-Y', strtotime($this->configService->convertDeliveryDate($checkoutData))) : null; $labelDescription = str_replace( [ self::ORDER_NUMBER, @@ -309,7 +310,7 @@ public function getLabelDescription(): string ], [ $this->order->getIncrementId(), - $this->helper->convertDeliveryDate($checkoutData) ? $deliveryDate : '', + $this->configService->convertDeliveryDate($checkoutData) ? $deliveryDate : '', $this->getProductInfo($productInfo, 'product_id'), $this->getProductInfo($productInfo, 'name'), $productInfo ? round($this->getProductInfo($productInfo, 'qty')) : null, diff --git a/Model/Carrier/Carrier.php b/Model/Carrier/Carrier.php index cdddd193..aad7e737 100644 --- a/Model/Carrier/Carrier.php +++ b/Model/Carrier/Carrier.php @@ -18,44 +18,29 @@ namespace MyParcelNL\Magento\Model\Carrier; -use Magento\CatalogInventory\Api\StockRegistryInterface; +use Composer\Config; use Magento\Checkout\Model\Session; -use Magento\Directory\Model\CountryFactory; -use Magento\Directory\Model\CurrencyFactory; -use Magento\Directory\Model\RegionFactory; use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\DataObject; use Magento\Framework\Xml\Security; use Magento\Quote\Model\Quote\Address\RateRequest; use Magento\Quote\Model\Quote\Address\RateResult\MethodFactory; use Magento\Shipping\Model\Carrier\AbstractCarrier; -use Magento\Shipping\Model\Carrier\AbstractCarrierOnline; use Magento\Shipping\Model\Carrier\CarrierInterface; -use Magento\Shipping\Model\Simplexml\ElementFactory; -use Magento\Shipping\Model\Tracking\Result\ErrorFactory; -use Magento\Shipping\Model\Tracking\Result\StatusFactory; -use Magento\Shipping\Model\Tracking\ResultFactory; -use MyParcelNL\Magento\Helper\Checkout; -use MyParcelNL\Magento\Helper\Data; use MyParcelNL\Magento\Model\Sales\Repository\PackageRepository; +use MyParcelNL\Magento\Service\Config\ConfigService; +use MyParcelNL\Magento\Service\Costs\DeliveryCostsService; +use MyParcelNL\Sdk\src\Adapter\DeliveryOptions\DeliveryOptionsV3Adapter; +use MyParcelNL\Sdk\src\Factory\DeliveryOptionsAdapterFactory; use Psr\Log\LoggerInterface; class Carrier extends AbstractCarrier implements CarrierInterface { const CODE = 'myparcelnl_delivery'; - protected $_code = self::CODE; + protected $_code = self::CODE; // $_code is a mandatory property for Magento carrier protected $_freeShipping; - /** - * @var \Magento\Quote\Model\Quote - */ - private $quote; - - /** - * @var Checkout - */ - private $myParcelHelper; /** * @var PackageRepository @@ -81,7 +66,6 @@ class Carrier extends AbstractCarrier implements CarrierInterface * @param \Magento\Directory\Helper\Data $directoryData * @param \Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry * @param \Magento\Checkout\Model\Session $session - * @param Checkout $myParcelHelper * @param PackageRepository $package * @param array $data * @@ -92,20 +76,11 @@ public function __construct( ScopeConfigInterface $scopeConfig, \Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory $rateErrorFactory, LoggerInterface $logger, - Security $xmlSecurity, - ElementFactory $xmlElFactory, + ConfigService $configService, + DeliveryCostsService $deliveryCostsService, \Magento\Shipping\Model\Rate\ResultFactory $rateFactory, MethodFactory $rateMethodFactory, - ResultFactory $trackFactory, - ErrorFactory $trackErrorFactory, - StatusFactory $trackStatusFactory, - RegionFactory $regionFactory, - CountryFactory $countryFactory, - CurrencyFactory $currencyFactory, - \Magento\Directory\Helper\Data $directoryData, - StockRegistryInterface $stockRegistry, Session $session, - Checkout $myParcelHelper, PackageRepository $package, \Magento\OfflineShipping\Model\Carrier\Freeshipping $freeShipping, array $data = [] @@ -114,27 +89,20 @@ public function __construct( $scopeConfig, $rateErrorFactory, $logger, - $data, // remove this line when you extend AbstractCarrierOnline, add it for AbstractCarrier - $xmlSecurity, - $xmlElFactory, - $rateFactory, - $rateMethodFactory, - $trackFactory, - $trackErrorFactory, - $trackStatusFactory, - $regionFactory, - $countryFactory, - $currencyFactory, - $directoryData, - $stockRegistry, - $data + $data, ); - $this->quote = $session->getQuote(); - $this->myParcelHelper = $myParcelHelper; + //$this->quote = $session->getQuote(); + try { + $this->deliveryOptions = DeliveryOptionsAdapterFactory::create(json_decode($session->getQuote()->getData('myparcel_delivery_options'), true)); + } catch (\Throwable $e) { + $this->deliveryOptions = DeliveryOptionsAdapterFactory::create(DeliveryOptionsV3Adapter::DEFAULTS); + } $this->package = $package; - $this->_rateFactory = $rateFactory; - $this->_rateMethodFactory = $rateMethodFactory; + $this->rateResultFactory = $rateFactory; + $this->rateMethodFactory = $rateMethodFactory; $this->_freeShipping = $freeShipping; + $this->configService = $configService; + $this->deliveryCostsService = $deliveryCostsService; } protected function _doShipmentRequest(DataObject $request) @@ -146,35 +114,48 @@ public function collectRates(RateRequest $request) if (!$this->getConfigFlag('active')) { return false; } - /** @var \Magento\Shipping\Model\Rate\Result $result */ - $result = $this->_rateFactory->create(); - /** @var \Magento\Quote\Model\Quote\Address\RateResult\Method $method */ - $method = $this->_rateMethodFactory->create(); + $result = $this->rateResultFactory->create(); + $method = $this->rateMethodFactory->create(); - // todo: get actual title based on chosen and possible options for this quote / cart $method->setCarrier($this->_code); $method->setCarrierTitle('MyParcel'); + $method->setMethod('MyParcel'); + $method->setMethodTitle($this->getMethodTitle()); + $method->setPrice((string) $this->getMethodAmount()); - $method->setMethod($this->_code); - $method->setMethodTitle('Todo: chosen options here'); + $result->append($method); + + return $result; + } + private function getMethodAmount(): float { + $path = ConfigService::CARRIERS_XML_PATH_MAP[$this->deliveryOptions->getCarrier()]??''; + $dinges = [ + "{$this->deliveryOptions->getDeliveryType()}/fee"=>true, + "{$this->deliveryOptions->getPackageType()}/fee"=>true, + 'delivery/signature_fee'=> $this->deliveryOptions->getShipmentOptions()->hasSignature(), + 'delivery/only_recipient_fee'=> $this->deliveryOptions->getShipmentOptions()->hasOnlyRecipient(), + ]; + $amount = $this->deliveryCostsService->getBasePrice(); + foreach ($dinges as $key=>$value) { + //echo $key, ' ', $value, ': ',$this->myParcelHelper->getCarrierConfig($key, $path), PHP_EOL; + if (! $value) continue; + $amount += (float) $this->configService->getConfigValue("$path$key"); + } + //$bla = $this->myParcelHelper->getCarrierConfig('evening/fee', $path); + return $amount; + die(' weflweiuryfuhj'); + //$this->configService->getMethodPrice(ConfigService::XML_PATH_POSTNL_SETTINGS . 'fee', $alias); $freeShippingIsAvailable = false; // todo // $this->_freeShipping->getConfigData('active') // todo: get actual price based on chosen and possible options for this quote / cart - $amount = $freeShippingIsAvailable ? '0.00' : '10.00'; - - $method->setPrice($amount); - $method->setCost($amount); - - //$result->append($method); - $result = $this->addShippingMethods($result); -//$bla = $this->quote->getCheckoutMethod(); - return $result; - /** @var \Magento\Quote\Model\Quote\Address\RateRequest $result */ - $result = $this->_rateFactory->create(); - $result = $this->addShippingMethods($result); + $amount = $freeShippingIsAvailable ? 0.00 : 10.00; +return $amount; + } - return $result; + private function getMethodTitle(): string { + // todo make a nice title from the options + return var_export($this->deliveryOptions, true); } public function proccessAdditionalValidation(DataObject $request) @@ -223,7 +204,7 @@ private function addShippingMethods($result) $this->package->setMailboxSettings(); foreach ($this->getAllowedMethods() as $alias => $settingPath) { - $active = $this->myParcelHelper->getConfigValue(Data::XML_PATH_POSTNL_SETTINGS . $settingPath . 'active') === '1'; + $active = $this->configService->getConfigValue(ConfigService::XML_PATH_POSTNL_SETTINGS . $settingPath . 'active') === '1'; if ($active) { $method = $this->getShippingMethod($alias, $settingPath); $result->append($method); @@ -244,7 +225,7 @@ private function getShippingMethod($alias, string $settingPath) $title = $this->createTitle($settingPath); $price = $this->createPrice($alias, $settingPath); - $method = $this->_rateMethodFactory->create(); + $method = $this->rateMethodFactory->create(); $method->setCarrier($this->_code); $method->setCarrierTitle($alias); $method->setMethod($alias); @@ -263,7 +244,7 @@ private function getShippingMethod($alias, string $settingPath) */ private function createTitle($settingPath) { - $title = $this->myParcelHelper->getConfigValue(Data::XML_PATH_POSTNL_SETTINGS . $settingPath . 'title'); + $title = $this->configService->getConfigValue(ConfigService::XML_PATH_POSTNL_SETTINGS . $settingPath . 'title'); if ($title === null) { $title = __($settingPath . 'title'); @@ -286,7 +267,7 @@ private function createPrice($alias, $settingPath) return 0; } - return 10 + $this->myParcelHelper->getMethodPrice($settingPath . 'fee', $alias); + return 10 + $this->configService->getMethodPrice($settingPath . 'fee', $alias); } public function isTrackingAvailable(): bool diff --git a/Model/Checkout/DeliveryOptionsToShippingMethods.php b/Model/Checkout/DeliveryOptionsToShippingMethods.php index a198b451..fd50937f 100755 --- a/Model/Checkout/DeliveryOptionsToShippingMethods.php +++ b/Model/Checkout/DeliveryOptionsToShippingMethods.php @@ -5,7 +5,7 @@ namespace MyParcelNL\Magento\Model\Checkout; use Exception; -use MyParcelNL\Magento\Helper\Data; +use MyParcelNL\Magento\Service\Config\ConfigService; use MyParcelNL\Sdk\src\Factory\DeliveryOptionsAdapterFactory; class DeliveryOptionsToShippingMethods @@ -57,8 +57,8 @@ private function getCarrierXmlPath(): string { $carrier = $this->deliveryOptions->getCarrier(); - if (array_key_exists($carrier, Data::CARRIERS_XML_PATH_MAP)) { - return Data::CARRIERS_XML_PATH_MAP[$carrier]; + if (array_key_exists($carrier, ConfigService::CARRIERS_XML_PATH_MAP)) { + return ConfigService::CARRIERS_XML_PATH_MAP[$carrier]; } throw new Exception("No XML path found for carrier '{$carrier}'."); diff --git a/Model/Quote/Checkout.php b/Model/Quote/Checkout.php index 7f184cde..8e5a56cd 100644 --- a/Model/Quote/Checkout.php +++ b/Model/Quote/Checkout.php @@ -5,9 +5,10 @@ use Magento\Checkout\Model\Cart; use Magento\Checkout\Model\Session; use Magento\Store\Model\StoreManagerInterface; -use MyParcelNL\Magento\Helper\Data; use MyParcelNL\Magento\Model\Sales\Repository\PackageRepository; use MyParcelNL\Magento\Model\Source\PriceDeliveryOptionsView; +use MyParcelNL\Magento\Service\Config\ConfigService; +use MyParcelNL\Magento\Service\Costs\DeliveryCostsService; use MyParcelNL\Sdk\src\Factory\ConsignmentFactory; use MyParcelNL\Sdk\src\Model\Consignment\AbstractConsignment; @@ -19,7 +20,7 @@ class Checkout /** * @var \MyParcelNL\Magento\Helper\Checkout */ - private $helper; + private $configService; /** * @var \Magento\Quote\Model\Quote @@ -45,25 +46,27 @@ class Checkout * @var mixed */ private $country; + private DeliveryCostsService $deliveryCostsService; /** * Checkout constructor. * - * @param \Magento\Checkout\Model\Session $session - * @param \Magento\Checkout\Model\Cart $cart - * @param \MyParcelNL\Magento\Helper\Checkout $helper - * @param PackageRepository $package - * @param \Magento\Store\Model\StoreManagerInterface $currency - * + * @param Session $session + * @param Cart $cart + * @param ConfigService $configService + * @param PackageRepository $package + * @param StoreManagerInterface $currency */ public function __construct( Session $session, Cart $cart, - \MyParcelNL\Magento\Helper\Checkout $helper, + ConfigService $configService, + DeliveryCostsService $deliveryCostsService, PackageRepository $package, StoreManagerInterface $currency ) { - $this->helper = $helper; + $this->configService = $configService; + $this->deliveryCostsService= $deliveryCostsService; $this->quoteId = $session->getQuoteId(); $this->cart = $cart->getQuote(); $this->package = $package; @@ -80,7 +83,6 @@ public function __construct( */ public function getDeliveryOptions(array $forAddress = []): array { - $this->helper->setBasePriceFromQuote((int) $this->quoteId, $forAddress); $this->hideDeliveryOptionsForProduct(); if (isset($forAddress['countryId'])) { @@ -91,7 +93,7 @@ public function getDeliveryOptions(array $forAddress = []): array $data = [ /* the 'method' string here is actually the carrier_code of the method */ - 'methods' => explode(',', $this->helper->getGeneralConfig('shipping_methods/methods') ?? ''), + 'methods' => explode(',', $this->configService->getGeneralConfig('shipping_methods/methods') ?? ''), 'config' => array_merge( $this->getGeneralData(), $this->getDeliveryData($packageType), @@ -103,8 +105,8 @@ public function getDeliveryOptions(array $forAddress = []): array return [ 'root' => [ - 'version' => (string) $this->helper->getVersion(), - 'data' => (array) $data, + 'version' => $this->configService->getVersion(), + 'data' => $data, ], ]; } @@ -122,12 +124,12 @@ private function getGeneralData() 'platform' => self::PLATFORM, 'carriers' => $this->getActiveCarriers(), 'currency' => $this->currency->getStore()->getCurrentCurrency()->getCode(), - 'allowShowDeliveryDate' => $this->helper->getBoolConfig(Data::XML_PATH_GENERAL, 'date_settings/allow_show_delivery_date'), - 'deliveryDaysWindow' => $this->helper->getIntegerConfig(Data::XML_PATH_GENERAL, 'date_settings/deliverydays_window'), - 'dropOffDelay' => $this->getDropOffDelay(Data::XML_PATH_GENERAL, 'date_settings/dropoff_delay'), - 'pickupLocationsDefaultView' => $this->helper->getCarrierConfig('shipping_methods/pickup_locations_view', Data::XML_PATH_GENERAL), - 'showPriceSurcharge' => $this->helper->getCarrierConfig('shipping_methods/delivery_options_prices', Data::XML_PATH_GENERAL) === PriceDeliveryOptionsView::SURCHARGE, - 'basePrice' => $this->helper->getBasePrice(), + 'allowShowDeliveryDate' => $this->configService->getBoolConfig(ConfigService::XML_PATH_GENERAL, 'date_settings/allow_show_delivery_date'), + 'deliveryDaysWindow' => $this->configService->getIntegerConfig(ConfigService::XML_PATH_GENERAL, 'date_settings/deliverydays_window'), + 'dropOffDelay' => $this->getDropOffDelay(ConfigService::XML_PATH_GENERAL, 'date_settings/dropoff_delay'), + 'pickupLocationsDefaultView' => $this->configService->getConfigValue(ConfigService::XML_PATH_GENERAL . 'shipping_methods/pickup_locations_view'), + 'showPriceSurcharge' => $this->configService->getConfigValue(ConfigService::XML_PATH_GENERAL . 'shipping_methods/delivery_options_prices') === PriceDeliveryOptionsView::SURCHARGE, + 'basePrice' => $this->deliveryCostsService->getBasePrice(), ]; } @@ -168,8 +170,8 @@ private function getDeliveryData(?string $packageType = null): array { $myParcelConfig = []; $activeCarriers = $this->getActiveCarriers(); - $carrierPaths = Data::CARRIERS_XML_PATH_MAP; - $showTotalPrice = $this->helper->getCarrierConfig('shipping_methods/delivery_options_prices', Data::XML_PATH_GENERAL) === PriceDeliveryOptionsView::TOTAL; + $carrierPaths = ConfigService::CARRIERS_XML_PATH_MAP; + $showTotalPrice = $this->configService->getConfigValue(ConfigService::XML_PATH_GENERAL . 'shipping_methods/delivery_options_prices') === PriceDeliveryOptionsView::TOTAL; foreach ($activeCarriers as $carrier) { $carrierPath = $carrierPaths[$carrier]; @@ -178,7 +180,7 @@ private function getDeliveryData(?string $packageType = null): array $consignment = ConsignmentFactory::createByCarrierName($carrier); $consignment->setPackageType(AbstractConsignment::PACKAGE_TYPE_PACKAGE); } catch (\Throwable $ex) { - $this->helper->log(sprintf('getDeliveryData: Could not create default consignment for %s', $carrier)); + $this->configService->log(sprintf('getDeliveryData: Could not create default consignment for %s', $carrier)); continue; } @@ -198,44 +200,44 @@ private function getDeliveryData(?string $packageType = null): array if ($canHaveMailbox) { $cc = $this->country ?? $this->cart->getShippingAddress()->getCountryId() ?? AbstractConsignment::CC_NL; if (AbstractConsignment::CC_NL === $cc) { - $mailboxFee = $this->helper->getMethodPrice($carrierPath, 'mailbox/fee', false); + $mailboxFee = $this->configService->getMethodPrice($carrierPath, 'mailbox/fee', false); } else { - $mailboxFee = $this->helper->getMethodPrice($carrierPath, 'mailbox/international_fee', false); + $mailboxFee = $this->configService->getMethodPrice($carrierPath, 'mailbox/international_fee', false); } } - $basePrice = $this->helper->getBasePrice(); - $mondayFee = $canHaveMonday ? $this->helper->getMethodPrice($carrierPath, 'delivery/monday_fee') : 0; - $morningFee = $canHaveMorning ? $this->helper->getMethodPrice($carrierPath, 'morning/fee') : 0; - $eveningFee = $canHaveEvening ? $this->helper->getMethodPrice($carrierPath, 'evening/fee') : 0; - $sameDayFee = $canHaveSameDay ? (int) $this->helper->getMethodPrice($carrierPath, 'delivery/same_day_delivery_fee') : 0; - $signatureFee = $canHaveSignature ? $this->helper->getMethodPrice($carrierPath, 'delivery/signature_fee', false) : 0; - $onlyRecipientFee = $canHaveOnlyRecipient ? $this->helper->getMethodPrice($carrierPath, 'delivery/only_recipient_fee', false) : 0; + $basePrice = $this->deliveryCostsService->getBasePrice($consignment); + $mondayFee = $canHaveMonday ? $this->configService->getMethodPrice($carrierPath, 'delivery/monday_fee') : 0; + $morningFee = $canHaveMorning ? $this->configService->getMethodPrice($carrierPath, 'morning/fee') : 0; + $eveningFee = $canHaveEvening ? $this->configService->getMethodPrice($carrierPath, 'evening/fee') : 0; + $sameDayFee = $canHaveSameDay ? (int) $this->configService->getMethodPrice($carrierPath, 'delivery/same_day_delivery_fee') : 0; + $signatureFee = $canHaveSignature ? $this->configService->getMethodPrice($carrierPath, 'delivery/signature_fee', false) : 0; + $onlyRecipientFee = $canHaveOnlyRecipient ? $this->configService->getMethodPrice($carrierPath, 'delivery/only_recipient_fee', false) : 0; $isAgeCheckActive = $canHaveAgeCheck && $this->isAgeCheckActive($carrierPath); - $allowPickup = $this->helper->getBoolConfig($carrierPath, 'pickup/active'); - $allowStandardDelivery = $this->helper->getBoolConfig($carrierPath, 'delivery/active'); - $allowMorningDelivery = ! $isAgeCheckActive && $canHaveMorning && $this->helper->getBoolConfig($carrierPath, 'morning/active'); - $allowEveningDelivery = ! $isAgeCheckActive && $canHaveEvening && $this->helper->getBoolConfig($carrierPath, 'evening/active'); + $allowPickup = $this->configService->getBoolConfig($carrierPath, 'pickup/active'); + $allowStandardDelivery = $this->configService->getBoolConfig($carrierPath, 'delivery/active'); + $allowMorningDelivery = ! $isAgeCheckActive && $canHaveMorning && $this->configService->getBoolConfig($carrierPath, 'morning/active'); + $allowEveningDelivery = ! $isAgeCheckActive && $canHaveEvening && $this->configService->getBoolConfig($carrierPath, 'evening/active'); $allowDeliveryOptions = ! $this->package->deliveryOptionsDisabled && ($allowPickup || $allowStandardDelivery || $allowMorningDelivery || $allowEveningDelivery); if ($allowDeliveryOptions && $packageType === AbstractConsignment::PACKAGE_TYPE_MAILBOX_NAME) { $this->package->setMailboxSettings($carrierPath); - $allowDeliveryOptions = $this->helper->getBoolConfig($carrierPath, 'mailbox/active') + $allowDeliveryOptions = $this->configService->getBoolConfig($carrierPath, 'mailbox/active') && $this->package->getMaxMailboxWeight() >= $this->package->getWeight(); } $myParcelConfig['carrierSettings'][$carrier] = [ 'allowDeliveryOptions' => $allowDeliveryOptions, 'allowStandardDelivery' => $allowStandardDelivery, - 'allowSignature' => $canHaveSignature && $this->helper->getBoolConfig($carrierPath, 'delivery/signature_active'), - 'allowOnlyRecipient' => $canHaveOnlyRecipient && $this->helper->getBoolConfig($carrierPath, 'delivery/only_recipient_active'), + 'allowSignature' => $canHaveSignature && $this->configService->getBoolConfig($carrierPath, 'delivery/signature_active'), + 'allowOnlyRecipient' => $canHaveOnlyRecipient && $this->configService->getBoolConfig($carrierPath, 'delivery/only_recipient_active'), 'allowMorningDelivery' => $allowMorningDelivery, 'allowEveningDelivery' => $allowEveningDelivery, 'allowPickupLocations' => $canHavePickup && $this->isPickupAllowed($carrierPath), - 'allowMondayDelivery' => $canHaveMonday && $this->helper->getBoolConfig($carrierPath, 'delivery/monday_active'), - 'allowSameDayDelivery' => $canHaveSameDay && $this->helper->getBoolConfig($carrierPath, 'delivery/same_day_delivery_active'), + 'allowMondayDelivery' => $canHaveMonday && $this->configService->getBoolConfig($carrierPath, 'delivery/monday_active'), + 'allowSameDayDelivery' => $canHaveSameDay && $this->configService->getBoolConfig($carrierPath, 'delivery/same_day_delivery_active'), 'dropOffDays' => $this->getDropOffDays($carrierPath), @@ -252,10 +254,10 @@ private function getDeliveryData(?string $packageType = null): array 'priceEveningSignature' => ($eveningFee + $signatureFee), 'priceSignatureAndOnlyRecipient' => ($basePrice + $signatureFee + $onlyRecipientFee), - 'pricePickup' => $canHavePickup ? $this->helper->getMethodPrice($carrierPath, 'pickup/fee') : 0, + 'pricePickup' => $canHavePickup ? $this->configService->getMethodPrice($carrierPath, 'pickup/fee') : 0, 'pricePackageTypeMailbox' => $mailboxFee, - 'pricePackageTypeDigitalStamp' => $canHaveDigitalStamp ? $this->helper->getMethodPrice($carrierPath, 'digital_stamp/fee', false) : 0, - 'pricePackageTypePackageSmall' => $canHavePackageSmall ? $this->helper->getMethodPrice($carrierPath, 'package_small/fee', false) : 0, + 'pricePackageTypeDigitalStamp' => $canHaveDigitalStamp ? $this->configService->getMethodPrice($carrierPath, 'digital_stamp/fee', false) : 0, + 'pricePackageTypePackageSmall' => $canHavePackageSmall ? $this->configService->getMethodPrice($carrierPath, 'package_small/fee', false) : 0, ]; } @@ -270,9 +272,9 @@ private function getDeliveryData(?string $packageType = null): array public function getActiveCarriers(): array { $carriers = []; - foreach (Data::CARRIERS_XML_PATH_MAP as $carrier => $path) { - if ($this->helper->getBoolConfig($path, 'delivery/active') || - $this->helper->getBoolConfig($path, 'pickup/active') + foreach (ConfigService::CARRIERS_XML_PATH_MAP as $carrier => $path) { + if ($this->configService->getBoolConfig($path, 'delivery/active') || + $this->configService->getBoolConfig($path, 'pickup/active') ) { $carriers[] = $carrier; } @@ -284,12 +286,12 @@ public function getActiveCarriers(): array private function getDropOffDays(string $carrierPath): array { $dropOffDays = []; for ($weekday = 0; $weekday < 7; $weekday++) { - $cutoffTimeSameDay = $this->helper->getTimeConfig($carrierPath, "drop_off_days/cutoff_time_same_day_$weekday"); + $cutoffTimeSameDay = $this->configService->getTimeConfig($carrierPath, "drop_off_days/cutoff_time_same_day_$weekday"); $sameDayTimeEntry = $cutoffTimeSameDay ? ['cutoffTimeSameDay' => $cutoffTimeSameDay] : []; - if ($this->helper->getBoolConfig($carrierPath, "drop_off_days/day_{$weekday}_active")) { + if ($this->configService->getBoolConfig($carrierPath, "drop_off_days/day_{$weekday}_active")) { $dropOffDays[] = (object) array_merge([ 'weekday' => $weekday, - 'cutoffTime' => $this->helper->getTimeConfig($carrierPath, "drop_off_days/cutoff_time_$weekday"), + 'cutoffTime' => $this->configService->getTimeConfig($carrierPath, "drop_off_days/cutoff_time_$weekday"), ], $sameDayTimeEntry); } } @@ -305,22 +307,22 @@ private function getDropOffDays(string $carrierPath): array { private function getDeliveryOptionsStrings(): array { return [ - 'deliveryTitle' => $this->helper->getGeneralConfig('delivery_titles/delivery_title') ?: __('delivery_title'), - 'deliveryStandardTitle' => $this->helper->getGeneralConfig('delivery_titles/standard_delivery_title') ?: __('standard_delivery'), - 'deliveryMorningTitle' => $this->helper->getGeneralConfig('delivery_titles/morning_title') ?: __('morning_title'), - 'deliveryEveningTitle' => $this->helper->getGeneralConfig('delivery_titles/evening_title') ?: __('evening_title'), - 'deliveryPickupTitle' => $this->helper->getGeneralConfig('delivery_titles/pickup_title') ?: __('pickup_title'), - 'pickupTitle' => $this->helper->getGeneralConfig('delivery_titles/pickup_title') ?: __('pickup_title'), - 'deliverySameDayTitle' => $this->helper->getGeneralConfig('delivery_titles/same_day_title') ?: __('same_day_title'), - 'hideSenderTitle' => $this->helper->getGeneralConfig('delivery_titles/hide_sender_title') ?: __('hide_sender_title'), - 'list' => $this->helper->getGeneralConfig('delivery_titles/pickup_list_button_title') ?: __('list_title'), - 'map' => $this->helper->getGeneralConfig('delivery_titles/pickup_map_button_title') ?: __('map_title'), - 'packageTypeMailbox' => $this->helper->getGeneralConfig('delivery_titles/mailbox_title') ?: __('mailbox_title'), - 'packageTypeDigitalStamp' => $this->helper->getGeneralConfig('delivery_titles/digital_stamp_title') ?: __('digital_stamp_title'), - 'packageTypePackageSmall' => $this->helper->getGeneralConfig('delivery_titles/package_small_title') ?: __('packet_title'), - 'signatureTitle' => $this->helper->getGeneralConfig('delivery_titles/signature_title') ?: __('signature_title'), - 'onlyRecipientTitle' => $this->helper->getGeneralConfig('delivery_titles/only_recipient_title') ?: __('only_recipient_title'), - 'saturdayDeliveryTitle' => $this->helper->getGeneralConfig('delivery_titles/saturday_title') ?: __('saturday_delivery_title'), + 'deliveryTitle' => $this->configService->getGeneralConfig('delivery_titles/delivery_title') ?: __('delivery_title'), + 'deliveryStandardTitle' => $this->configService->getGeneralConfig('delivery_titles/standard_delivery_title') ?: __('standard_delivery'), + 'deliveryMorningTitle' => $this->configService->getGeneralConfig('delivery_titles/morning_title') ?: __('morning_title'), + 'deliveryEveningTitle' => $this->configService->getGeneralConfig('delivery_titles/evening_title') ?: __('evening_title'), + 'deliveryPickupTitle' => $this->configService->getGeneralConfig('delivery_titles/pickup_title') ?: __('pickup_title'), + 'pickupTitle' => $this->configService->getGeneralConfig('delivery_titles/pickup_title') ?: __('pickup_title'), + 'deliverySameDayTitle' => $this->configService->getGeneralConfig('delivery_titles/same_day_title') ?: __('same_day_title'), + 'hideSenderTitle' => $this->configService->getGeneralConfig('delivery_titles/hide_sender_title') ?: __('hide_sender_title'), + 'list' => $this->configService->getGeneralConfig('delivery_titles/pickup_list_button_title') ?: __('list_title'), + 'map' => $this->configService->getGeneralConfig('delivery_titles/pickup_map_button_title') ?: __('map_title'), + 'packageTypeMailbox' => $this->configService->getGeneralConfig('delivery_titles/mailbox_title') ?: __('mailbox_title'), + 'packageTypeDigitalStamp' => $this->configService->getGeneralConfig('delivery_titles/digital_stamp_title') ?: __('digital_stamp_title'), + 'packageTypePackageSmall' => $this->configService->getGeneralConfig('delivery_titles/package_small_title') ?: __('packet_title'), + 'signatureTitle' => $this->configService->getGeneralConfig('delivery_titles/signature_title') ?: __('signature_title'), + 'onlyRecipientTitle' => $this->configService->getGeneralConfig('delivery_titles/only_recipient_title') ?: __('only_recipient_title'), + 'saturdayDeliveryTitle' => $this->configService->getGeneralConfig('delivery_titles/saturday_title') ?: __('saturday_delivery_title'), 'wrongPostalCodeCity' => __('Postcode/city combination unknown'), 'addressNotFound' => __('Address details are not entered'), @@ -361,12 +363,12 @@ public function checkPackageType(string $carrier, ?string $country = null): stri try { $consignment = ConsignmentFactory::createByCarrierName($carrier); } catch (\Throwable $e) { - $this->helper->log(sprintf('checkPackageType: Could not create default consignment for %s', $carrier)); + $this->configService->log(sprintf('checkPackageType: Could not create default consignment for %s', $carrier)); return AbstractConsignment::DEFAULT_PACKAGE_TYPE_NAME; } - $carrierPath = Data::CARRIERS_XML_PATH_MAP[$carrier]; + $carrierPath = ConfigService::CARRIERS_XML_PATH_MAP[$carrier]; $products = $this->cart->getAllItems(); $country = $country ?? $this->country ?? $this->cart->getShippingAddress()->getCountryId(); $canHaveDigitalStamp = $consignment->canHavePackageType(AbstractConsignment::PACKAGE_TYPE_DIGITAL_STAMP_NAME); @@ -379,17 +381,17 @@ public function checkPackageType(string $carrier, ?string $country = null): stri if ($canHaveMailbox) { if (AbstractConsignment::CC_NL === $country) { - $this->package->setMailboxActive($this->helper->getBoolConfig($carrierPath, 'mailbox/active')); + $this->package->setMailboxActive($this->configService->getBoolConfig($carrierPath, 'mailbox/active')); } else { - $this->package->setMailboxActive($this->helper->getBoolConfig($carrierPath, 'mailbox/international_active')); + $this->package->setMailboxActive($this->configService->getBoolConfig($carrierPath, 'mailbox/international_active')); } } else { $this->package->setMailboxActive(false); } $this->package->setCurrentCountry($country); - $this->package->setDigitalStampActive($canHaveDigitalStamp && $this->helper->getBoolConfig($carrierPath, 'digital_stamp/active')); - $this->package->setPackageSmallActive($canHavePackageSmall && $this->helper->getBoolConfig($carrierPath, 'package_small/active')); + $this->package->setDigitalStampActive($canHaveDigitalStamp && $this->configService->getBoolConfig($carrierPath, 'digital_stamp/active')); + $this->package->setPackageSmallActive($canHavePackageSmall && $this->configService->getBoolConfig($carrierPath, 'package_small/active')); return $this->package->selectPackageType($products, $carrierPath); } @@ -418,7 +420,7 @@ public function getDropOffDelay(string $carrierPath, string $key): int $productDelay = $this->package->getProductDropOffDelay($products); if (! $productDelay) { - $productDelay = $this->helper->getIntegerConfig($carrierPath, $key); + $productDelay = $this->configService->getIntegerConfig($carrierPath, $key); } return (int) $productDelay; @@ -443,8 +445,8 @@ public function hideDeliveryOptionsForProduct() private function isPickupAllowed(string $carrier): bool { $isMailboxPackage = self::PACKAGE_TYPE_MAILBOX === $this->getPackageType(); - $pickupEnabled = $this->helper->getBoolConfig($carrier, 'pickup/active'); - $showPickupForMailbox = $this->helper->getBoolConfig($carrier, 'mailbox/pickup_mailbox'); + $pickupEnabled = $this->configService->getBoolConfig($carrier, 'pickup/active'); + $showPickupForMailbox = $this->configService->getBoolConfig($carrier, 'mailbox/pickup_mailbox'); $showPickup = ! $isMailboxPackage || $showPickupForMailbox; return ! $this->package->deliveryOptionsDisabled && $pickupEnabled && $showPickup; diff --git a/Model/Quote/SaveOrderBeforeSalesModelQuoteObserver.php b/Model/Quote/SaveOrderBeforeSalesModelQuoteObserver.php index 4322e06c..4029281c 100644 --- a/Model/Quote/SaveOrderBeforeSalesModelQuoteObserver.php +++ b/Model/Quote/SaveOrderBeforeSalesModelQuoteObserver.php @@ -24,9 +24,9 @@ use Magento\Framework\Event\ObserverInterface; use Magento\Quote\Model\Quote; use Magento\Sales\Model\Order; -use MyParcelNL\Magento\Helper\Checkout; use MyParcelNL\Magento\Model\Carrier\Carrier; use MyParcelNL\Magento\Model\Sales\Repository\DeliveryRepository; +use MyParcelNL\Magento\Service\Config\ConfigService; use MyParcelNL\Sdk\src\Helper\ValidatePostalCode; use MyParcelNL\Sdk\src\Helper\ValidateStreet; use MyParcelNL\Sdk\src\Model\Consignment\AbstractConsignment; @@ -46,15 +46,15 @@ class SaveOrderBeforeSalesModelQuoteObserver implements ObserverInterface /** * SaveOrderBeforeSalesModelQuoteObserver constructor. * - * @param DeliveryRepository $delivery - * @param Checkout $checkoutHelper + * @param DeliveryRepository $delivery + * @param ConfigService $configService */ public function __construct( DeliveryRepository $delivery, - Checkout $checkoutHelper + ConfigService $configService ) { $this->delivery = $delivery; - $this->parentMethods = explode(',', $checkoutHelper->getGeneralConfig('shipping_methods/methods') ?? ''); + $this->parentMethods = explode(',', $configService->getGeneralConfig('shipping_methods/methods') ?? ''); } /** @@ -65,6 +65,7 @@ public function __construct( */ public function execute(Observer $observer) { + throw new \Exception('Use the newer classes to handle this (Joeri)'); /* @var Quote $quote */ $quote = $observer->getEvent()->getData('quote'); @@ -80,24 +81,24 @@ public function execute(Observer $observer) $destinationCountry = $order->getShippingAddress()->getCountryId(); if (! ValidateStreet::validate($fullStreet, AbstractConsignment::CC_NL, $destinationCountry)) { - $order->setData(Checkout::FIELD_TRACK_STATUS, __('⚠️  Please check street')); + $order->setData(ConfigService::FIELD_TRACK_STATUS, __('⚠️  Please check street')); } if (! ValidatePostalCode::validate($postcode, $destinationCountry)) { - $order->setData(Checkout::FIELD_TRACK_STATUS, __('⚠️  Please check postal code')); + $order->setData(ConfigService::FIELD_TRACK_STATUS, __('⚠️  Please check postal code')); } - if ($quote->hasData(Checkout::FIELD_DELIVERY_OPTIONS) && $this->hasMyParcelDeliveryOptions($quote)) { - $jsonDeliveryOptions = $quote->getData(Checkout::FIELD_DELIVERY_OPTIONS) ?? ''; + if ($quote->hasData(ConfigService::FIELD_DELIVERY_OPTIONS) && $this->hasMyParcelDeliveryOptions($quote)) { + $jsonDeliveryOptions = $quote->getData(ConfigService::FIELD_DELIVERY_OPTIONS) ?? ''; $deliveryOptions = json_decode($jsonDeliveryOptions, true) ?? []; - $order->setData(Checkout::FIELD_DELIVERY_OPTIONS, $jsonDeliveryOptions); + $order->setData(ConfigService::FIELD_DELIVERY_OPTIONS, $jsonDeliveryOptions); $dropOffDay = $this->delivery->getDropOffDayFromDeliveryOptions($deliveryOptions); - $order->setData(Checkout::FIELD_DROP_OFF_DAY, $dropOffDay); + $order->setData(ConfigService::FIELD_DROP_OFF_DAY, $dropOffDay); $selectedCarrier = $this->delivery->getCarrierFromDeliveryOptions($deliveryOptions); - $order->setData(Checkout::FIELD_MYPARCEL_CARRIER, $selectedCarrier); + $order->setData(ConfigService::FIELD_MYPARCEL_CARRIER, $selectedCarrier); } return $this; diff --git a/Model/Rate/Result.php b/Model/Rate/Result.php index 098eb615..bfddfc7a 100755 --- a/Model/Rate/Result.php +++ b/Model/Rate/Result.php @@ -19,11 +19,14 @@ namespace MyParcelNL\Magento\Model\Rate; use Countable; +use Magento\Backend\Model\Session\Quote; use Magento\Checkout\Model\Session; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Exception\NoSuchEntityException; use Magento\Quote\Model\Quote\Address\RateResult\Method; -use MyParcelNL\Magento\Helper\Checkout; -use MyParcelNL\Magento\Helper\Data; +use Magento\Store\Model\StoreManagerInterface; use MyParcelNL\Magento\Model\Sales\Repository\PackageRepository; +use MyParcelNL\Magento\Service\Config\ConfigService; use MyParcelNL\Sdk\src\Model\Carrier\CarrierDHLForYou; use MyParcelNL\Sdk\src\Model\Carrier\CarrierDPD; use MyParcelNL\Sdk\src\Model\Carrier\CarrierPostNL; @@ -47,7 +50,7 @@ class Result extends \Magento\Shipping\Model\Rate\Result /** * @var Checkout */ - private $myParcelHelper; + private $configService; /** * @var \MyParcelNL\Magento\Model\Sales\Repository\PackageRepository @@ -72,29 +75,29 @@ class Result extends \Magento\Shipping\Model\Rate\Result /** * Result constructor. * - * @param \Magento\Store\Model\StoreManagerInterface $storeManager - * @param \Magento\Backend\Model\Session\Quote $quote - * @param Session $session - * @param Checkout $myParcelHelper - * @param PackageRepository $package + * @param StoreManagerInterface $storeManager + * @param Quote $quote + * @param Session $session + * @param ConfigService $configService + * @param PackageRepository $package * - * @throws \Magento\Framework\Exception\LocalizedException - * @throws \Magento\Framework\Exception\NoSuchEntityException + * @throws LocalizedException + * @throws NoSuchEntityException * @internal param \Magento\Checkout\Model\Session $session */ public function __construct( \Magento\Store\Model\StoreManagerInterface $storeManager, \Magento\Backend\Model\Session\Quote $quote, Session $session, - Checkout $myParcelHelper, + ConfigService $configService, PackageRepository $package ) { parent::__construct($storeManager); - - $this->myParcelHelper = $myParcelHelper; +throw new \Exception(' Result is everything '); + $this->configService = $configService; $this->session = $session; $this->quote = $quote; - $this->parentMethods = explode(',', $this->myParcelHelper->getGeneralConfig('shipping_methods/methods') ?? ''); + $this->parentMethods = explode(',', $this->configService->getGeneralConfig('shipping_methods/methods') ?? ''); $package->setCurrentCountry( $this->getQuoteFromCartOrSession() ->getShippingAddress() @@ -176,8 +179,8 @@ private function addMyParcelRates(Method $parentRate): void return; } - foreach (Data::CARRIERS_XML_PATH_MAP as $carrier => $carrierPath) { - if (! $this->myParcelHelper->getConfigValue("{$carrierPath}delivery/active")) { + foreach (ConfigService::CARRIERS_XML_PATH_MAP as $carrier => $carrierPath) { + if (! $this->configService->getConfigValue("{$carrierPath}delivery/active")) { continue; } @@ -261,7 +264,7 @@ private function isSettingActive(string $map, string $settingPath, string $separ $settingPathParts = explode("/", $settingPath ?? ''); $baseSetting = $settingPathParts[0]; - if (! $this->myParcelHelper->getConfigValue("{$map}{$baseSetting}/active")) { + if (! $this->configService->getConfigValue("{$map}{$baseSetting}/active")) { return false; } @@ -270,7 +273,7 @@ private function isSettingActive(string $map, string $settingPath, string $separ continue; } $fullPath = "{$map}delivery/{$option}{$separator}active"; - if (! $this->myParcelHelper->getConfigValue($fullPath)) { + if (! $this->configService->getConfigValue($fullPath)) { return false; } } @@ -315,7 +318,7 @@ private function isBaseSetting(string $settingPath): bool private function getShippingMethod(string $settingPath, Method $parentRate): Method { $method = clone $parentRate; - $this->myParcelHelper->setBasePrice($parentRate->getData('price')); + $this->configService->setBasePrice($parentRate->getData('price')); $title = $this->createTitle($settingPath); $price = $this->getPrice($settingPath); @@ -353,7 +356,8 @@ private function createTitle($settingPath) */ private function getPrice($settingPath): float { - $basePrice = $this->myParcelHelper->getBasePrice(); + throw new \Exception('You must get the price from the DeliveryCostsService'); + $basePrice = $this->configService->getBasePrice(); $settingFee = 0; // Explode settingPath like: myparcelnl_magento_postnl_settings/delivery/only_recipient/signature @@ -362,7 +366,7 @@ private function getPrice($settingPath): float // Check if the selected delivery options are delivery, only_recipient and signature // delivery/only_recipient/signature if (isset($settingPath[self::THIRD_PART], $settingPath[self::FOURTH_PART]) && 'delivery' === $settingPath[self::SECOND_PART]) { - $settingFee += (float) $this->myParcelHelper->getConfigValue( + $settingFee += (float) $this->configService->getConfigValue( sprintf( "%s/%s/%s_fee", $settingPath[self::FIRST_PART], @@ -370,7 +374,7 @@ private function getPrice($settingPath): float $settingPath[self::THIRD_PART] ) ); - $settingFee += (float) $this->myParcelHelper->getConfigValue( + $settingFee += (float) $this->configService->getConfigValue( sprintf( "%s/%s/%sfee", $settingPath[self::FIRST_PART], @@ -382,7 +386,7 @@ private function getPrice($settingPath): float // Check if the selected delivery is morning or evening and select the fee if (AbstractConsignment::DELIVERY_TYPE_MORNING_NAME === $settingPath[self::SECOND_PART] || AbstractConsignment::DELIVERY_TYPE_EVENING_NAME === $settingPath[self::SECOND_PART]) { - $settingFee = (float) $this->myParcelHelper->getConfigValue( + $settingFee = (float) $this->configService->getConfigValue( sprintf("%s/%s/fee", $settingPath[self::FIRST_PART], $settingPath[self::SECOND_PART]) ); @@ -394,14 +398,14 @@ private function getPrice($settingPath): float unset($settingPath[self::THIRD_PART]); } - $settingFee += (float) $this->myParcelHelper->getConfigValue(implode('/', $settingPath ?? []) . 'fee'); + $settingFee += (float) $this->configService->getConfigValue(implode('/', $settingPath ?? []) . 'fee'); // For mailbox and digital stamp the base price should not be calculated if (AbstractConsignment::PACKAGE_TYPE_MAILBOX_NAME === $settingPath[self::SECOND_PART]) { // for international mailbox, we have a different price :-) $cc = $this->session->getQuote()->getShippingAddress()->getCountryId(); if ($cc !== 'NL') { - $settingFee = (float) $this->myParcelHelper->getConfigValue( + $settingFee = (float) $this->configService->getConfigValue( sprintf("%s/%s/international_fee", $settingPath[self::FIRST_PART], $settingPath[self::SECOND_PART]) ); } diff --git a/Model/Sales/Delivery.php b/Model/Sales/Delivery.php deleted file mode 100755 index 79e8de85..00000000 --- a/Model/Sales/Delivery.php +++ /dev/null @@ -1,50 +0,0 @@ - - * @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 - * @since File available since Release 2.0.0 - */ - -namespace MyParcelNL\Magento\Model\Sales; - - -use Magento\Framework\Module\ModuleListInterface; -use MyParcelNL\Magento\Helper\Data; -use Magento\Framework\App\Helper\Context; -use Psr\Log\LoggerInterface; - -class Delivery extends Data implements DeliveryInterface -{ - /** - * @var int - */ - private $deliveryDateTime; - - /** - * @return int - */ - public function getDeliveryDateTime() - { - return $this->deliveryDateTime; - } - - /** - * @param int $deliveryDateTime - * @return int - */ - public function setDeliveryDateTime($deliveryDateTime) - { - $this->deliveryDateTime = $deliveryDateTime; - } -} diff --git a/Model/Sales/MagentoOrderCollection.php b/Model/Sales/MagentoOrderCollection.php index 376df205..1077c119 100755 --- a/Model/Sales/MagentoOrderCollection.php +++ b/Model/Sales/MagentoOrderCollection.php @@ -15,7 +15,7 @@ use MyParcelNL\Magento\Helper\CustomsDeclarationFromOrder; use MyParcelNL\Magento\Helper\ShipmentOptions; use MyParcelNL\Magento\Model\Source\DefaultOptions; -use MyParcelNL\Magento\Services\Normalizer\ConsignmentNormalizer; +use MyParcelNL\Magento\Service\Normalizer\ConsignmentNormalizer; use MyParcelNL\Sdk\src\Collection\Fulfilment\OrderCollection; use MyParcelNL\Sdk\src\Collection\Fulfilment\OrderNotesCollection; use MyParcelNL\Sdk\src\Factory\ConsignmentFactory; diff --git a/Model/Sales/Package.php b/Model/Sales/Package.php index 32d0fa2a..fe05b377 100755 --- a/Model/Sales/Package.php +++ b/Model/Sales/Package.php @@ -18,15 +18,10 @@ namespace MyParcelNL\Magento\Model\Sales; -use MyParcelNL\Magento\Helper\Data; +use MyParcelNL\Magento\Service\Config\ConfigService; -class Package extends Data implements PackageInterface +class Package extends ConfigService implements PackageInterface //used to extend MyParcelNL\Magento\Helper\Data; { - const PACKAGE_TYPE_NORMAL = 1; - const PACKAGE_TYPE_MAILBOX = 2; - const PACKAGE_TYPE_LETTER = 3; - const PACKAGE_TYPE_DIGITAL_STAMP = 4; - /** * @var int */ @@ -244,17 +239,6 @@ protected function setMaxPackageSmallWeight(float $maxWeight): void $this->maxPackageSmallWeight = $maxWeight; } - /** - * @param bool $allProductsFit - * @deprecated fit in what? use PackageRepository->selectPackageType() to get the relevant package type - */ - public function setAllProductsFit(bool $allProductsFit): void - { - if ($allProductsFit === false) { - $this->allProductsFit = $allProductsFit; - } - } - /** * @return int */ @@ -263,6 +247,7 @@ public function getPackageType(): int if (! isset($this->packageType)) { throw new \RuntimeException('Use setPackageType() before you can getPackageType()'); } + throw new \Exception('Please remove Package.php and PackageRepository.php and use a service'); return $this->packageType; } @@ -293,4 +278,9 @@ public function setCurrentCountry(?string $currentCountry): void $this->currentCountry = $currentCountry; } + + public function setAllProductsFit(bool $all_products_fit) + { + // TODO: Implement setAllProductsFit() method. + } } diff --git a/Model/Sales/Repository/DeliveryRepository.php b/Model/Sales/Repository/DeliveryRepository.php index 4c089c7e..dc8fd205 100755 --- a/Model/Sales/Repository/DeliveryRepository.php +++ b/Model/Sales/Repository/DeliveryRepository.php @@ -18,10 +18,33 @@ namespace MyParcelNL\Magento\Model\Sales\Repository; -use MyParcelNL\Magento\Model\Sales\Delivery; +use MyParcelNL\Magento\Model\Sales\DeliveryInterface; +use MyParcelNL\Magento\Service\Config\ConfigService; -class DeliveryRepository extends Delivery +class DeliveryRepository extends ConfigService implements DeliveryInterface // used to extend MyParcelNL\Magento\Helper\Data; { + /** + * @var int + */ + private int $deliveryDateTime; + + /** + * @return int + */ + public function getDeliveryDateTime() + { + return $this->deliveryDateTime; + } + + /** + * @param int $deliveryDateTime + * @return int + */ + public function setDeliveryDateTime($deliveryDateTime) + { + $this->deliveryDateTime = $deliveryDateTime; + } + /** * Get drop off day with chosen options from checkout * diff --git a/Model/Sales/TrackTraceHolder.php b/Model/Sales/TrackTraceHolder.php index 3e2d7498..e755b042 100755 --- a/Model/Sales/TrackTraceHolder.php +++ b/Model/Sales/TrackTraceHolder.php @@ -23,10 +23,12 @@ use Magento\Sales\Model\Order\Shipment; use Magento\Sales\Model\Order\Shipment\Track; use MyParcelNL\Magento\Adapter\DeliveryOptionsFromOrderAdapter; -use MyParcelNL\Magento\Helper\Data; use MyParcelNL\Magento\Helper\ShipmentOptions; use MyParcelNL\Magento\Model\Source\DefaultOptions; -use MyParcelNL\Magento\Services\Normalizer\ConsignmentNormalizer; +use MyParcelNL\Magento\Service\Config\ConfigService; +use MyParcelNL\Magento\Service\Costs\DeliveryCostsService; +use MyParcelNL\Magento\Service\Normalizer\ConsignmentNormalizer; +use MyParcelNL\Magento\Service\Weight\WeightService; use MyParcelNL\Magento\Ui\Component\Listing\Column\TrackAndTrace; use MyParcelNL\Sdk\src\Exception\MissingFieldException; use MyParcelNL\Sdk\src\Factory\ConsignmentFactory; @@ -79,7 +81,7 @@ class TrackTraceHolder /** * @var \MyParcelNL\Magento\Helper\Data */ - private $dataHelper; + private $configService; /** * @var ObjectManagerInterface @@ -90,38 +92,37 @@ class TrackTraceHolder * @var \MyParcelNL\Magento\Helper\ShipmentOptions */ private $shipmentOptionsHelper; + private WeightService $weightService; + private DeliveryCostsService $deliveryCostsService; /** * TrackTraceHolder constructor. * - * @param ObjectManagerInterface $objectManager - * @param Data $helper - * @param \Magento\Sales\Model\Order $order + * @param ObjectManagerInterface $objectManager + * @param ConfigService $configService + * @param WeightService $weightService + * @param DeliveryCostsService $deliveryCostsService + * @param Order $order */ public function __construct( ObjectManagerInterface $objectManager, - Data $helper, + ConfigService $configService, + WeightService $weightService, + DeliveryCostsService $deliveryCostsService, Order $order ) { $this->objectManager = $objectManager; - $this->dataHelper = $helper; + $this->configService = $configService; + $this->weightService = $weightService; + $this->deliveryCostsService = $deliveryCostsService; $this->messageManager = $this->objectManager->create('Magento\Framework\Message\ManagerInterface'); self::$defaultOptions = new DefaultOptions( $order, - $this->dataHelper + $configService, + $weightService ); } - /** - * @param float $price - * - * @return int - */ - public static function getCentsByPrice(float $price): int - { - return (int) $price * 100; - } - /** * Set all data to MyParcel object * @@ -134,6 +135,7 @@ public static function getCentsByPrice(float $price): int */ public function convertDataFromMagentoToApi(Track $magentoTrack, array $options): self { + throw new \Exception('refactor completely joeri'); $shipment = $magentoTrack->getShipment(); $address = $shipment->getShippingAddress(); $order = $shipment->getOrder(); @@ -157,7 +159,7 @@ public function convertDataFromMagentoToApi(Track $magentoTrack, array $options) } $pickupLocationAdapter = $deliveryOptionsAdapter->getPickupLocation(); - $apiKey = $this->dataHelper->getGeneralConfig( + $apiKey = $this->configService->getGeneralConfig( 'api/key', $order->getStoreId() ); @@ -166,7 +168,7 @@ public function convertDataFromMagentoToApi(Track $magentoTrack, array $options) $this->carrier = $deliveryOptionsAdapter->getCarrier(); $this->shipmentOptionsHelper = new ShipmentOptions( self::$defaultOptions, - $this->dataHelper, + $this->configService, $order, $this->objectManager, $this->carrier, @@ -195,16 +197,16 @@ public function convertDataFromMagentoToApi(Track $magentoTrack, array $options) $this->objectManager->get('Psr\Log\LoggerInterface') ->critical($errorHuman . '-' . $e); - $this->dataHelper->setOrderStatus($magentoTrack->getOrderId(), Order::STATE_NEW); + $this->configService->setOrderStatus($magentoTrack->getOrderId(), Order::STATE_NEW); } if (isset($deliveryOptions['packageType'])) { $options['package_type'] = $deliveryOptions['packageType']; } $packageType = $this->getPackageType($options, $magentoTrack, $address); - $dropOffPoint = $this->dataHelper->getDropOffPoint( - CarrierFactory::createFromName($deliveryOptionsAdapter->getCarrier()) - ); +// $dropOffPoint = $this->configService->getDropOffPoint( +// CarrierFactory::createFromName($deliveryOptionsAdapter->getCarrier()) +// ); $regionCode = $address->getRegionCode(); $state = $regionCode && strlen($regionCode) === 2 ? $regionCode : null; @@ -215,8 +217,8 @@ public function convertDataFromMagentoToApi(Track $magentoTrack, array $options) ->setPhone($address->getTelephone()) ->setEmail($address->getEmail()) ->setLabelDescription($this->shipmentOptionsHelper->getLabelDescription()) - ->setDeliveryDate($this->dataHelper->convertDeliveryDate($deliveryOptionsAdapter->getDate())) - ->setDeliveryType($this->dataHelper->checkDeliveryType($deliveryOptionsAdapter->getDeliveryTypeId())) + ->setDeliveryDate($this->configService->convertDeliveryDate($deliveryOptionsAdapter->getDate())) + ->setDeliveryType($this->configService->checkDeliveryType($deliveryOptionsAdapter->getDeliveryTypeId())) ->setPackageType($packageType) ->setDropOffPoint($dropOffPoint) ->setOnlyRecipient($this->shipmentOptionsHelper->hasOnlyRecipient()) @@ -300,7 +302,7 @@ public function getCountryOfOrigin(int $product_id): string return $productCountryOfManufacture; } - return $this->dataHelper->getGeneralConfig('print/country_of_origin'); + return $this->configService->getGeneralConfig('print/country_of_origin'); } /** @@ -359,7 +361,7 @@ private function calculateTotalWeight(Track $magentoTrack, int $totalWeight = 0) $totalWeight += $shipmentItem['weight'] * $shipmentItem['qty']; } - $totalWeight = $this->dataHelper->convertToGrams($totalWeight); + $totalWeight = $this->weightService->convertToGrams($totalWeight); if (0 === $totalWeight) { throw new RuntimeException( @@ -400,8 +402,8 @@ private function convertDataForCdCountry(Track $magentoTrack) $myParcelProduct = (new MyParcelCustomsItem()) ->setDescription($product->getName()) ->setAmount($product->getQty()) - ->setWeight($this->dataHelper->convertToGrams($product->getWeight()) ?: 1) - ->setItemValue($this->getCentsByPrice($product->getPrice())) + ->setWeight($this->weightService->convertToGrams($product->getWeight()) ?: 1) + ->setItemValue($this->deliveryCostsService->getCentsByPrice($product->getPrice())) ->setClassification( (int) $this->getAttributeValue( 'catalog_product_entity_int', @@ -419,7 +421,7 @@ private function convertDataForCdCountry(Track $magentoTrack) $myParcelProduct = (new MyParcelCustomsItem()) ->setDescription($item->getName()) ->setAmount($item->getQty()) - ->setWeight($this->dataHelper->convertToGrams($item->getWeight() * $item->getQty())) + ->setWeight($this->weightService->convertToGrams($item->getWeight() * $item->getQty())) ->setItemValue($item->getPrice() * 100) ->setClassification( (int) $this->getAttributeValue( diff --git a/Model/Source/AgeCheckNo.php b/Model/Source/AgeCheckNo.php index 77ab06a8..b2d18bbe 100755 --- a/Model/Source/AgeCheckNo.php +++ b/Model/Source/AgeCheckNo.php @@ -18,6 +18,7 @@ use Magento\Framework\Data\OptionSourceInterface; use Magento\Sales\Model\Order; use MyParcelNL\Magento\Helper\Data; +use MyParcelNL\Magento\Service\Config\ConfigService; use MyParcelNL\Sdk\src\Model\Carrier\CarrierPostNL; /** @@ -32,14 +33,11 @@ class AgeCheckNo implements OptionSourceInterface static private $helper; /** - * Insurance constructor. - * - * @param $order Order - * @param $helper Data + * @param ConfigService $configService */ - public function __construct(Data $helper) + public function __construct(ConfigService $configService) { - self::$helper = $helper; + self::$configService = $configService; } /** @@ -49,7 +47,8 @@ public function __construct(Data $helper) */ public function getDefault($option) { - $settings = self::$helper->getStandardConfig(CarrierPostNL::NAME, 'default_options'); + throw new \Exception('this is not really a default'); + $settings = self::$configService->getCarrierConfig(CarrierPostNL::NAME, 'default_options'); return (bool) $settings[$option . '_active']; } diff --git a/Model/Source/AgeCheckYes.php b/Model/Source/AgeCheckYes.php index 064c47a0..192f817d 100755 --- a/Model/Source/AgeCheckYes.php +++ b/Model/Source/AgeCheckYes.php @@ -18,6 +18,7 @@ use Magento\Framework\Data\OptionSourceInterface; use Magento\Sales\Model\Order; use MyParcelNL\Magento\Helper\Data; +use MyParcelNL\Magento\Service\Config\ConfigService; use MyParcelNL\Sdk\src\Model\Carrier\CarrierPostNL; /** @@ -29,7 +30,7 @@ class AgeCheckYes implements OptionSourceInterface /** * @var Data */ - static private $helper; + static private $configService; /** * Insurance constructor. @@ -37,9 +38,9 @@ class AgeCheckYes implements OptionSourceInterface * @param $order Order * @param $helper Data */ - public function __construct(Data $helper) + public function __construct(ConfigService $configService) { - self::$helper = $helper; + self::$configService = $configService; } /** @@ -49,7 +50,8 @@ public function __construct(Data $helper) */ public function hasDefault($option): bool { - $settings = self::$helper->getStandardConfig(CarrierPostNL::NAME, 'default_options'); + throw new \Exception('this is not really a default option'); + $settings = self::$configService->getCarrierConfig(CarrierPostNL::NAME, 'default_options'); return (bool) $settings[$option . '_active']; } diff --git a/Model/Source/DefaultOptions.php b/Model/Source/DefaultOptions.php index 71349428..7b7808d6 100755 --- a/Model/Source/DefaultOptions.php +++ b/Model/Source/DefaultOptions.php @@ -13,12 +13,11 @@ namespace MyParcelNL\Magento\Model\Source; -use BadMethodCallException; use Exception; use Magento\Sales\Model\Order; -use MyParcelNL\Magento\Helper\Checkout; -use MyParcelNL\Magento\Helper\Data; use MyParcelNL\Magento\Model\Sales\Repository\PackageRepository; +use MyParcelNL\Magento\Service\Config\ConfigService; +use MyParcelNL\Magento\Service\Weight\WeightService; use MyParcelNL\Sdk\src\Factory\ConsignmentFactory; use MyParcelNL\Sdk\src\Factory\DeliveryOptionsAdapterFactory; use MyParcelNL\Sdk\src\Model\Carrier\AbstractCarrier; @@ -53,34 +52,24 @@ class DefaultOptions private const INSURANCE_PERCENTAGE = 'insurance_percentage'; public const DEFAULT_OPTION_VALUE = 'default'; - /** - * @var Data - */ - private static $helper; - - /** - * @var Order - */ - private static $order; - - /** - * @var array - */ - private static $chosenOptions; + private static ConfigService $configService; + private static Order $order; + private static array $chosenOptions; + private static WeightService $weightService; /** - * Insurance constructor. - * - * @param Order $order - * @param Data $helper + * @param Order $order + * @param ConfigService $configService + * @param WeightService $weightService */ - public function __construct(Order $order, Data $helper) + public function __construct(Order $order, ConfigService $configService, WeightService $weightService) { - self::$helper = $helper; + self::$configService = $configService; + self::$weightService = $weightService; self::$order = $order; try { self::$chosenOptions = DeliveryOptionsAdapterFactory::create( - (array) json_decode($order->getData(Checkout::FIELD_DELIVERY_OPTIONS), true) + (array) json_decode($order->getData(ConfigService::FIELD_DELIVERY_OPTIONS), true) )->toArray(); } catch (Exception $e) { self::$chosenOptions = []; @@ -138,9 +127,9 @@ public function getMaxCompanyName(?string $company): ?string public function hasDefaultLargeFormat(string $carrier, string $option): bool { $price = self::$order->getGrandTotal(); - $weight = self::$helper->convertToGrams(self::$order->getWeight()); + $weight = self::$weightService->convertToGrams(self::$order->getWeight()); - $settings = self::$helper->getStandardConfig($carrier, 'default_options'); + $settings = self::$configService->getCarrierConfig($carrier, 'default_options'); $activeKey = "{$option}_active"; if (isset($settings[$activeKey]) && @@ -168,7 +157,7 @@ public function hasDefaultLargeFormat(string $carrier, string $option): bool */ public function hasDefaultOptionsWithoutPrice(string $carrier, string $option): bool { - $settings = self::$helper->getStandardConfig($carrier, 'default_options'); + $settings = self::$configService->getCarrierConfig($carrier, 'default_options'); return '1' === ($settings[$option . '_active'] ?? null); } @@ -207,7 +196,7 @@ public function getDefaultInsurance(string $carrier): int private function getInsurance(string $carrierName, string $priceKey, string $shippingCountry): int { $total = self::$order->getGrandTotal(); - $settings = self::$helper->getStandardConfig($carrierName, 'default_options'); + $settings = self::$configService->getCarrierConfig($carrierName, 'default_options'); $totalAfterPercentage = $total * (($settings[self::INSURANCE_PERCENTAGE] ?? 0) / 100); if (! isset($settings[$priceKey]) @@ -241,7 +230,7 @@ private function getInsurance(string $carrierName, string $priceKey, string $shi */ public function getDigitalStampDefaultWeight(): string { - return self::$helper->getCarrierConfig('digital_stamp/default_weight', 'myparcelnl_magento_postnl_settings/'); + return self::$configService->getConfigValue('myparcelnl_magento_postnl_settings/digital_stamp/default_weight'); } /** @@ -280,17 +269,6 @@ public function getCarrier(): string return CarrierPostNL::NAME; } - /** - * Get package type name as a string by default - * - * @return string - */ - public function getPackageTypeName(): string - { - $packageTypesMap = array_flip(AbstractConsignment::PACKAGE_TYPES_NAMES_IDS_MAP); - return $packageTypesMap[$this->getPackageType()]; - } - /** * TODO: In the future, when multiple carriers will be available for Rest of World shipments, replace PostNL with a setting for default carrier * diff --git a/Model/Source/DigitalStampWeightOptions.php b/Model/Source/DigitalStampWeightOptions.php index 50d648e3..66e5a452 100755 --- a/Model/Source/DigitalStampWeightOptions.php +++ b/Model/Source/DigitalStampWeightOptions.php @@ -18,6 +18,7 @@ use Magento\Framework\Data\OptionSourceInterface; use Magento\Sales\Model\Order; use MyParcelNL\Magento\Helper\Data; +use MyParcelNL\Magento\Service\Config\ConfigService; use MyParcelNL\Sdk\src\Model\Carrier\CarrierPostNL; /** @@ -29,17 +30,14 @@ class DigitalStampWeightOptions implements OptionSourceInterface /** * @var Data */ - static private $helper; + static private $configService; /** - * Insurance constructor. - * - * @param $order Order - * @param $helper Data + * @param $configService ConfigService */ - public function __construct(Data $helper) + public function __construct(ConfigService $configService) { - self::$helper = $helper; + self::$configService = $configService; } /** @@ -49,7 +47,8 @@ public function __construct(Data $helper) */ public function getDefault($option): bool { - $settings = self::$helper->getStandardConfig(CarrierPostNL::NAME, 'options'); + throw new \Exception('again, not really a default'); + $settings = self::$configService->getCarrierConfig(CarrierPostNL::NAME, 'options'); return (bool) $settings[$option . '_active']; } diff --git a/Service/Config/ConfigService.php b/Service/Config/ConfigService.php new file mode 100644 index 00000000..65eecea7 --- /dev/null +++ b/Service/Config/ConfigService.php @@ -0,0 +1,204 @@ + self::XML_PATH_POSTNL_SETTINGS, + CarrierDHLForYou::NAME => self::XML_PATH_DHLFORYOU_SETTINGS, + CarrierDHLEuroplus::NAME => self::XML_PATH_DHLEUROPLUS_SETTINGS, + CarrierDHLParcelConnect::NAME => self::XML_PATH_DHLPARCELCONNECT_SETTINGS, + CarrierUPS::NAME => self::XML_PATH_UPS_SETTINGS, + CarrierDPD::NAME => self::XML_PATH_DPD_SETTINGS, + ]; + + /** + * @var ModuleListInterface + */ + private $moduleList; + /** + * @var CheckApiKeyWebService + */ + private $checkApiKeyWebService; + + /** + * @param Context $context + * @param ModuleListInterface $moduleList + * @param CheckApiKeyWebService $checkApiKeyWebService + */ + public function __construct( + Context $context, + ModuleListInterface $moduleList, + CheckApiKeyWebService $checkApiKeyWebService + ) + { + parent::__construct($context); + $this->moduleList = $moduleList; + $this->checkApiKeyWebService = $checkApiKeyWebService; + } + + /** + * Get settings by field + * + * @param $field + * @param null $storeId + * + * @return mixed + */ + public function getConfigValue($field, $storeId = null) + { + return $this->scopeConfig->getValue($field, ScopeInterface::SCOPE_STORE, $storeId); + } + + + /** + * Get setting for carrier + * + * @param string $carrier + * @param string $code + * @param null $storeId + * + * @return mixed + */ + public function getCarrierConfig(string $carrier, string $code = '', $storeId = null) + { + return $this->getConfigValue(self::CARRIERS_XML_PATH_MAP[$carrier] . $code, $storeId); + } + + + /** + * Get general settings + * + * @param string $code + * @param null|int $storeId + * + * @return mixed + */ + public function getGeneralConfig(string $code = '', int $storeId = null) + { + return $this->getConfigValue(self::XML_PATH_GENERAL . $code, $storeId); + } + + /** + * @return string|null + */ + public function getExportMode(): ?string + { + return $this->getGeneralConfig('print/export_mode'); + } + + // TODO everything below here must be refactored out + /** + * Get the version number of the installed module + * + * @return string + */ + public function getVersion(): string + { + $moduleCode = self::MODULE_NAME; + $moduleInfo = $this->moduleList->getOne($moduleCode); + + return (string) $moduleInfo['setup_version']; + } + + /** + * Check if api key is correct + */ + public function apiKeyIsCorrect(): bool + { + $apiKey = $this->getApiKey(); + + return $this->checkApiKeyService->setApiKey($apiKey) + ->apiKeyIsCorrect(); + } + + /** + * @return null|string + */ + public function getApiKey(): ?string + { + return $this->getGeneralConfig('api/key'); + } + + /** + * Check if global API Key isset + * + * @return bool + */ + public function hasApiKey(): bool + { + $apiKey = $this->getApiKey(); + + return isset($apiKey); + } + + /** + * Get date in YYYY-MM-DD HH:MM:SS format + * + * @param string|null $date + * + * @return string|null + */ + public function convertDeliveryDate(?string $date): ?string + { + if (! $date) { + return null; + } + + $checkoutDate = json_decode($date, true)['date'] ?? substr($date, 0, 10); + $deliveryDate = strtotime(date('Y-m-d', strtotime($checkoutDate))); + $currentDate = strtotime(date('Y-m-d')); + + if ($deliveryDate <= $currentDate) { + return date('Y-m-d H:i:s', strtotime('now +1 day')); + } + + return $checkoutDate; + } + + /** + * @param int $orderId + * @param string $status + */ + public function setOrderStatus(int $orderId, string $status): void + { + $order = ObjectManager::getInstance() + ->create('\Magento\Sales\Model\Order') + ->load($orderId); + $order->setState($status) + ->setStatus($status); + $order->save(); + } +} diff --git a/Service/Costs/DeliveryCostsService.php b/Service/Costs/DeliveryCostsService.php new file mode 100644 index 00000000..8cdb4a4f --- /dev/null +++ b/Service/Costs/DeliveryCostsService.php @@ -0,0 +1,23 @@ +$configService = $configService; + } + /** + * Get the correct weight type + * + * @param null|float $weight + * + * @return int + */ + public function convertToGrams(?float $weight): int + { + $weightType = $this->configService->getGeneralConfig('print/weight_indication'); + + if ('kilo' === $weightType) { + return (int) ($weight * 1000); + } + + return (int) $weight ?: self::DEFAULT_WEIGHT; + } +} From d3222c4fd5fe1ee45f3a10f71beb7a8e9a150abb Mon Sep 17 00:00:00 2001 From: Joeri van Veen Date: Thu, 26 Sep 2024 17:25:33 +0200 Subject: [PATCH 03/29] wip --- Helper/Checkout.php | 23 - Model/Carrier/Carrier.php | 40 +- Model/Quote/Checkout.php | 22 +- ...SaveOrderBeforeSalesModelQuoteObserver.php | 13 +- Model/Rate/Result.php | 440 ------------------ Service/Config/ConfigService.php | 55 ++- Service/Costs/DeliveryCostsService.php | 29 ++ etc/di.xml | 2 - 8 files changed, 109 insertions(+), 515 deletions(-) delete mode 100755 Model/Rate/Result.php diff --git a/Helper/Checkout.php b/Helper/Checkout.php index 8e48505d..d92bcd31 100755 --- a/Helper/Checkout.php +++ b/Helper/Checkout.php @@ -184,29 +184,6 @@ private function getEstimatedAddress( return $address; } - /** - * Get MyParcel method/option price. - * Check if total shipping price is not below 0 euro - * - * @param string $carrier - * @param string $key - * @param bool $addBasePrice - * - * @return float - */ - public function getMethodPrice(string $carrier, string $key, bool $addBasePrice = true): float - { - $value = (float) $this->getConfigValue("$carrier$key"); - $showTotalPrice = $this->getConfigValue(Data::XML_PATH_GENERAL . 'shipping_methods/delivery_options_prices') === PriceDeliveryOptionsView::TOTAL; - - if ($showTotalPrice && $addBasePrice) { - // Calculate value - $value = (float) $this->getBasePrice() + $value; - } - - return $value; - } - /** * Get bool of setting * diff --git a/Model/Carrier/Carrier.php b/Model/Carrier/Carrier.php index aad7e737..e9528098 100644 --- a/Model/Carrier/Carrier.php +++ b/Model/Carrier/Carrier.php @@ -189,30 +189,30 @@ public static function getMethods() * * @return array */ - public function getAllowedMethods() + public function getAllowedMethods(): array { return self::getMethods(); } - /** - * @param \Magento\Quote\Model\Quote\Address\RateRequest $result - * @return mixed - */ - private function addShippingMethods($result) - { - $this->package->setDigitalStampSettings(); - $this->package->setMailboxSettings(); - - foreach ($this->getAllowedMethods() as $alias => $settingPath) { - $active = $this->configService->getConfigValue(ConfigService::XML_PATH_POSTNL_SETTINGS . $settingPath . 'active') === '1'; - if ($active) { - $method = $this->getShippingMethod($alias, $settingPath); - $result->append($method); - } - } - - return $result; - } +// /** +// * @param \Magento\Quote\Model\Quote\Address\RateRequest $result +// * @return mixed +// */ +// private function addShippingMethods($result) +// { +// $this->package->setDigitalStampSettings(); +// $this->package->setMailboxSettings(); +// +// foreach ($this->getAllowedMethods() as $alias => $settingPath) { +// $active = $this->configService->getConfigValue(ConfigService::XML_PATH_POSTNL_SETTINGS . $settingPath . 'active') === '1'; +// if ($active) { +// $method = $this->getShippingMethod($alias, $settingPath); +// $result->append($method); +// } +// } +// +// return $result; +// } /** * @param $alias diff --git a/Model/Quote/Checkout.php b/Model/Quote/Checkout.php index 8e5a56cd..7e119d4c 100644 --- a/Model/Quote/Checkout.php +++ b/Model/Quote/Checkout.php @@ -200,19 +200,19 @@ private function getDeliveryData(?string $packageType = null): array if ($canHaveMailbox) { $cc = $this->country ?? $this->cart->getShippingAddress()->getCountryId() ?? AbstractConsignment::CC_NL; if (AbstractConsignment::CC_NL === $cc) { - $mailboxFee = $this->configService->getMethodPrice($carrierPath, 'mailbox/fee', false); + $mailboxFee = $this->deliveryCostsService->getMethodPrice($carrierPath, 'mailbox/fee', false); } else { - $mailboxFee = $this->configService->getMethodPrice($carrierPath, 'mailbox/international_fee', false); + $mailboxFee = $this->deliveryCostsService->getMethodPrice($carrierPath, 'mailbox/international_fee', false); } } $basePrice = $this->deliveryCostsService->getBasePrice($consignment); - $mondayFee = $canHaveMonday ? $this->configService->getMethodPrice($carrierPath, 'delivery/monday_fee') : 0; - $morningFee = $canHaveMorning ? $this->configService->getMethodPrice($carrierPath, 'morning/fee') : 0; - $eveningFee = $canHaveEvening ? $this->configService->getMethodPrice($carrierPath, 'evening/fee') : 0; - $sameDayFee = $canHaveSameDay ? (int) $this->configService->getMethodPrice($carrierPath, 'delivery/same_day_delivery_fee') : 0; - $signatureFee = $canHaveSignature ? $this->configService->getMethodPrice($carrierPath, 'delivery/signature_fee', false) : 0; - $onlyRecipientFee = $canHaveOnlyRecipient ? $this->configService->getMethodPrice($carrierPath, 'delivery/only_recipient_fee', false) : 0; + $mondayFee = $canHaveMonday ? $this->deliveryCostsService->getMethodPrice($carrierPath, 'delivery/monday_fee') : 0; + $morningFee = $canHaveMorning ? $this->deliveryCostsService->getMethodPrice($carrierPath, 'morning/fee') : 0; + $eveningFee = $canHaveEvening ? $this->deliveryCostsService->getMethodPrice($carrierPath, 'evening/fee') : 0; + $sameDayFee = $canHaveSameDay ? (int) $this->deliveryCostsService->getMethodPrice($carrierPath, 'delivery/same_day_delivery_fee') : 0; + $signatureFee = $canHaveSignature ? $this->deliveryCostsService->getMethodPrice($carrierPath, 'delivery/signature_fee', false) : 0; + $onlyRecipientFee = $canHaveOnlyRecipient ? $this->deliveryCostsService->getMethodPrice($carrierPath, 'delivery/only_recipient_fee', false) : 0; $isAgeCheckActive = $canHaveAgeCheck && $this->isAgeCheckActive($carrierPath); $allowPickup = $this->configService->getBoolConfig($carrierPath, 'pickup/active'); @@ -254,10 +254,10 @@ private function getDeliveryData(?string $packageType = null): array 'priceEveningSignature' => ($eveningFee + $signatureFee), 'priceSignatureAndOnlyRecipient' => ($basePrice + $signatureFee + $onlyRecipientFee), - 'pricePickup' => $canHavePickup ? $this->configService->getMethodPrice($carrierPath, 'pickup/fee') : 0, + 'pricePickup' => $canHavePickup ? $this->deliveryCostsService->getMethodPrice($carrierPath, 'pickup/fee') : 0, 'pricePackageTypeMailbox' => $mailboxFee, - 'pricePackageTypeDigitalStamp' => $canHaveDigitalStamp ? $this->configService->getMethodPrice($carrierPath, 'digital_stamp/fee', false) : 0, - 'pricePackageTypePackageSmall' => $canHavePackageSmall ? $this->configService->getMethodPrice($carrierPath, 'package_small/fee', false) : 0, + 'pricePackageTypeDigitalStamp' => $canHaveDigitalStamp ? $this->deliveryCostsService->getMethodPrice($carrierPath, 'digital_stamp/fee', false) : 0, + 'pricePackageTypePackageSmall' => $canHavePackageSmall ? $this->deliveryCostsService->getMethodPrice($carrierPath, 'package_small/fee', false) : 0, ]; } diff --git a/Model/Quote/SaveOrderBeforeSalesModelQuoteObserver.php b/Model/Quote/SaveOrderBeforeSalesModelQuoteObserver.php index 4029281c..4cabef03 100644 --- a/Model/Quote/SaveOrderBeforeSalesModelQuoteObserver.php +++ b/Model/Quote/SaveOrderBeforeSalesModelQuoteObserver.php @@ -65,7 +65,6 @@ public function __construct( */ public function execute(Observer $observer) { - throw new \Exception('Use the newer classes to handle this (Joeri)'); /* @var Quote $quote */ $quote = $observer->getEvent()->getData('quote'); @@ -111,18 +110,12 @@ public function execute(Observer $observer) */ private function hasMyParcelDeliveryOptions(Quote $quote): bool { - $myParcelMethods = array_keys(Carrier::getMethods()); $shippingMethod = $quote->getShippingAddress()->getShippingMethod(); - if ($this->isMyParcelRelated($shippingMethod, $myParcelMethods)) { - return true; - } - - if ($this->isMyParcelRelated($shippingMethod, $this->parentMethods)) { - return true; - } + // TODO JOERI get the _code and stuff not hardcoded string + if ('myparcelnl_delivery_MyParcel' === $shippingMethod) return true; - return array_key_exists('myparcel_delivery_options', $quote->getData()); + return array_key_exists(ConfigService::FIELD_DELIVERY_OPTIONS, $quote->getData()); } /** diff --git a/Model/Rate/Result.php b/Model/Rate/Result.php deleted file mode 100755 index bfddfc7a..00000000 --- a/Model/Rate/Result.php +++ /dev/null @@ -1,440 +0,0 @@ - - * @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 2.0.0 - */ - -namespace MyParcelNL\Magento\Model\Rate; - -use Countable; -use Magento\Backend\Model\Session\Quote; -use Magento\Checkout\Model\Session; -use Magento\Framework\Exception\LocalizedException; -use Magento\Framework\Exception\NoSuchEntityException; -use Magento\Quote\Model\Quote\Address\RateResult\Method; -use Magento\Store\Model\StoreManagerInterface; -use MyParcelNL\Magento\Model\Sales\Repository\PackageRepository; -use MyParcelNL\Magento\Service\Config\ConfigService; -use MyParcelNL\Sdk\src\Model\Carrier\CarrierDHLForYou; -use MyParcelNL\Sdk\src\Model\Carrier\CarrierDPD; -use MyParcelNL\Sdk\src\Model\Carrier\CarrierPostNL; -use MyParcelNL\Sdk\src\Model\Consignment\AbstractConsignment; - -class Result extends \Magento\Shipping\Model\Rate\Result -{ - private const FIRST_PART = 0; - private const SECOND_PART = 1; - private const THIRD_PART = 2; - private const FOURTH_PART = 3; - private const CARRIERS_WITH_MAILBOX = [ - CarrierPostNL::NAME, - CarrierDHLForYou::NAME, - CarrierDPD::NAME, - ]; - public const CARRIERS_WITH_DIGITAL_STAMP = [ - CarrierPostNL::NAME, - ]; - - /** - * @var Checkout - */ - private $configService; - - /** - * @var \MyParcelNL\Magento\Model\Sales\Repository\PackageRepository - */ - private $package; - - /** - * @var array - */ - private $parentMethods; - - /** - * @var Session - */ - private $session; - - /** - * @var \Magento\Backend\Model\Session\Quote - */ - private $quote; - - /** - * Result constructor. - * - * @param StoreManagerInterface $storeManager - * @param Quote $quote - * @param Session $session - * @param ConfigService $configService - * @param PackageRepository $package - * - * @throws LocalizedException - * @throws NoSuchEntityException - * @internal param \Magento\Checkout\Model\Session $session - */ - public function __construct( - \Magento\Store\Model\StoreManagerInterface $storeManager, - \Magento\Backend\Model\Session\Quote $quote, - Session $session, - ConfigService $configService, - PackageRepository $package - ) { - parent::__construct($storeManager); -throw new \Exception(' Result is everything '); - $this->configService = $configService; - $this->session = $session; - $this->quote = $quote; - $this->parentMethods = explode(',', $this->configService->getGeneralConfig('shipping_methods/methods') ?? ''); - $package->setCurrentCountry( - $this->getQuoteFromCartOrSession() - ->getShippingAddress() - ->getCountryId() - ); - $this->package = $package; - } - - /** - * Add a rate to the result - * - * @param \Magento\Quote\Model\Quote\Address\RateResult\AbstractResult|\Magento\Shipping\Model\Rate\Result $result - * - * @return $this - * @throws \Magento\Framework\Exception\LocalizedException - * @throws \Magento\Framework\Exception\NoSuchEntityException - */ - public function append($result) - { - if ($result instanceof \Magento\Quote\Model\Quote\Address\RateResult\Error) { - $this->setError(true); - } - if ($result instanceof \Magento\Quote\Model\Quote\Address\RateResult\Method) { - $this->_rates[] = $result; - $this->addMyParcelRates($result); - } elseif ($result instanceof \Magento\Quote\Model\Quote\Address\RateResult\AbstractResult) { - $this->_rates[] = $result; - } elseif ($result instanceof \Magento\Shipping\Model\Rate\Result) { - $rates = $result->getAllRates(); - foreach ($rates as $rate) { - $this->append($rate); - $this->addMyParcelRates($rate); - } - } - - return $this; - } - - /** - * Get allowed shipping methods - * - * @return array - */ - public static function getMethods(): array - { - return [ - 'pickup' => 'pickup', - 'standard' => 'delivery', - 'standard_signature' => 'delivery/signature', - 'standard_only_recipient' => 'delivery/only_recipient', - 'standard_only_recipient_signature' => 'delivery/only_recipient/signature', - 'morning' => 'morning', - 'morning_only_recipient' => 'morning/only_recipient', - 'morning_only_recipient_signature' => 'morning/only_recipient/signature', - 'evening' => 'evening', - 'evening_only_recipient' => 'evening/only_recipient', - 'evening_only_recipient_signature' => 'evening/only_recipient/signature', - 'mailbox' => 'mailbox', - 'digital_stamp' => 'digital_stamp', - 'same_day_delivery' => 'delivery/same_day_delivery', - 'same_day_delivery_only_recipient' => 'delivery/only_recipient/same_day_delivery', - ]; - } - - /** - * Add MyParcel shipping rates - * - * @param \Magento\Quote\Model\Quote\Address\RateResult\Method $parentRate - * - * @return void - * @throws \Magento\Framework\Exception\NoSuchEntityException - * @throws \Magento\Framework\Exception\LocalizedException - */ - private function addMyParcelRates(Method $parentRate): void - { - return;//todo joeri - $parentShippingMethod = $parentRate->getData('carrier'); - if (! in_array($parentShippingMethod, $this->parentMethods, true)) { - return; - } - - foreach (ConfigService::CARRIERS_XML_PATH_MAP as $carrier => $carrierPath) { - if (! $this->configService->getConfigValue("{$carrierPath}delivery/active")) { - continue; - } - - if (in_array($carrier, self::CARRIERS_WITH_MAILBOX)) { - $this->package->setMailboxSettings($carrierPath); - } - - if (in_array($carrier, self::CARRIERS_WITH_DIGITAL_STAMP)) { - $this->package->setDigitalStampSettings($carrierPath); - } - - $packageType = $this->package->selectPackageType( - $this->getQuoteFromCartOrSession()->getAllItems(), - $carrierPath - ); - - foreach (self::getMethods() as $settingPath) { - $fullPath = $this->getFullSettingPath($carrierPath, $settingPath); - $separator = $this->isBaseSetting($settingPath) ? '/' : '_'; - $pathParts = explode('/', $settingPath ?? ''); - - if (! $fullPath - || ! $this->isRelevantOption($packageType, $pathParts[0]) - || ! $this->isSettingActive($carrierPath, $settingPath, $separator) - ) { - continue; - } - - $this->_rates[] = $this->getShippingMethod( - $fullPath, - $parentRate - ); - } - } - } - - /** - * @param string $packageType - * @param string $fromOptionPath - * - * @return bool - */ - private function isRelevantOption(string $packageType, string $fromOptionPath): bool - { - switch ($packageType) { - - case AbstractConsignment::PACKAGE_TYPE_LETTER_NAME: - return false; - - case AbstractConsignment::PACKAGE_TYPE_DIGITAL_STAMP_NAME: - return AbstractConsignment::PACKAGE_TYPE_DIGITAL_STAMP_NAME === $fromOptionPath; - - case AbstractConsignment::PACKAGE_TYPE_MAILBOX_NAME: - if (AbstractConsignment::DELIVERY_TYPE_PICKUP_NAME === $fromOptionPath) { - return $this->package->isPickupMailboxActive(); - } - return AbstractConsignment::PACKAGE_TYPE_MAILBOX_NAME === $fromOptionPath; - - default: - return ! in_array($fromOptionPath, - [ - AbstractConsignment::PACKAGE_TYPE_MAILBOX_NAME, - AbstractConsignment::PACKAGE_TYPE_DIGITAL_STAMP_NAME, - ] - ); - } - } - - /** - * Check if a given map/setting combination is active. If the setting is not a top level setting its parent group - * will be checked for an "active" setting. If this is disabled this will return false; - * - * @param string $map - * @param string $settingPath - * @param string $separator - * - * @return bool - */ - private function isSettingActive(string $map, string $settingPath, string $separator): bool - { - $settingPathParts = explode("/", $settingPath ?? ''); - $baseSetting = $settingPathParts[0]; - - if (! $this->configService->getConfigValue("{$map}{$baseSetting}/active")) { - return false; - } - - foreach ($settingPathParts as $index => $option) { - if (0 === $index) { - continue; - } - $fullPath = "{$map}delivery/{$option}{$separator}active"; - if (! $this->configService->getConfigValue($fullPath)) { - return false; - } - } - - return true; - } - - /** - * @param string $map - * @param string $settingPath - * - * @return string|null - */ - private function getFullSettingPath(string $map, string $settingPath): ?string - { - $separator = $this->isBaseSetting($settingPath) ? '/' : '_'; - $settingActive = $this->isSettingActive($map, $settingPath, $separator); - - if ($settingActive) { - return $map . $settingPath . $separator; - } - - return null; - } - - /** - * @param string $settingPath - * - * @return bool - */ - private function isBaseSetting(string $settingPath): bool - { - return strpos($settingPath, '/') === false; - } - - /** - * @param string|null $settingPath - * @param Method|null $parentRate - * - * @return Method - */ - private function getShippingMethod(string $settingPath, Method $parentRate): Method - { - $method = clone $parentRate; - $this->configService->setBasePrice($parentRate->getData('price')); - - $title = $this->createTitle($settingPath); - $price = $this->getPrice($settingPath); - - $method->setData('cost', 0); - // Trim the separator off the end of the settings path - $method->setData('method', substr($settingPath, 0, -1)); - $method->setData('method_title', $title); - $method->setPrice($price); - - return $method; - } - - /** - * Create title for method - * If no title isset in config, get title from translation - * - * @param $settingPath - * - * @return \Magento\Framework\Phrase|mixed - */ - private function createTitle($settingPath) - { - return __(substr($settingPath, 0, -1)); - } - - /** - * Create price - * Calculate price if multiple options are chosen - * - * @param $settingPath - * - * @return float - * @todo: Several improvements are possible within this method - */ - private function getPrice($settingPath): float - { - throw new \Exception('You must get the price from the DeliveryCostsService'); - $basePrice = $this->configService->getBasePrice(); - $settingFee = 0; - - // Explode settingPath like: myparcelnl_magento_postnl_settings/delivery/only_recipient/signature - $settingPath = explode('/', $settingPath ?? ''); - - // Check if the selected delivery options are delivery, only_recipient and signature - // delivery/only_recipient/signature - if (isset($settingPath[self::THIRD_PART], $settingPath[self::FOURTH_PART]) && 'delivery' === $settingPath[self::SECOND_PART]) { - $settingFee += (float) $this->configService->getConfigValue( - sprintf( - "%s/%s/%s_fee", - $settingPath[self::FIRST_PART], - $settingPath[self::SECOND_PART], - $settingPath[self::THIRD_PART] - ) - ); - $settingFee += (float) $this->configService->getConfigValue( - sprintf( - "%s/%s/%sfee", - $settingPath[self::FIRST_PART], - $settingPath[self::SECOND_PART], - $settingPath[self::FOURTH_PART] - ) - ); - } - - // Check if the selected delivery is morning or evening and select the fee - if (AbstractConsignment::DELIVERY_TYPE_MORNING_NAME === $settingPath[self::SECOND_PART] || AbstractConsignment::DELIVERY_TYPE_EVENING_NAME === $settingPath[self::SECOND_PART]) { - $settingFee = (float) $this->configService->getConfigValue( - sprintf("%s/%s/fee", $settingPath[self::FIRST_PART], $settingPath[self::SECOND_PART]) - ); - - // change delivery type if there is a signature selected - if (isset($settingPath[self::FOURTH_PART])) { - $settingPath[self::SECOND_PART] = 'delivery'; - } - // Unset only_recipient to select the correct price - unset($settingPath[self::THIRD_PART]); - } - - $settingFee += (float) $this->configService->getConfigValue(implode('/', $settingPath ?? []) . 'fee'); - - // For mailbox and digital stamp the base price should not be calculated - if (AbstractConsignment::PACKAGE_TYPE_MAILBOX_NAME === $settingPath[self::SECOND_PART]) { - // for international mailbox, we have a different price :-) - $cc = $this->session->getQuote()->getShippingAddress()->getCountryId(); - if ($cc !== 'NL') { - $settingFee = (float) $this->configService->getConfigValue( - sprintf("%s/%s/international_fee", $settingPath[self::FIRST_PART], $settingPath[self::SECOND_PART]) - ); - } - return min($settingFee, $basePrice); - } - if (AbstractConsignment::PACKAGE_TYPE_DIGITAL_STAMP_NAME === $settingPath[self::SECOND_PART]){ - return min($settingFee, $basePrice); - } - - return $basePrice + $settingFee; - } - - /** - * Can't get quote from session\Magento\Checkout\Model\Session::getQuote() - * To fix a conflict with buckeroo, use \Magento\Checkout\Model\Cart::getQuote() like the following - * - * @return \Magento\Quote\Model\Quote - * @throws \Magento\Framework\Exception\LocalizedException - * @throws \Magento\Framework\Exception\NoSuchEntityException - */ - private function getQuoteFromCartOrSession() - { - if ($this->quote->getQuoteId() != null && $this->quote->getQuote() - && $this->quote->getQuote() instanceof Countable - && count($this->quote->getQuote()) - ) { - return $this->quote->getQuote(); - } - - return $this->session->getQuote(); - } -} diff --git a/Service/Config/ConfigService.php b/Service/Config/ConfigService.php index 65eecea7..862e4e28 100644 --- a/Service/Config/ConfigService.php +++ b/Service/Config/ConfigService.php @@ -29,11 +29,11 @@ class ConfigService extends AbstractHelper public const XML_PATH_UPS_SETTINGS = 'myparcelnl_magento_ups_settings/'; public const XML_PATH_DPD_SETTINGS = 'myparcelnl_magento_dpd_settings/'; public const XML_PATH_LOCALE_WEIGHT_UNIT = 'general/locale/weight_unit'; - public const FIELD_DROP_OFF_DAY = 'drop_off_day'; + public const FIELD_DROP_OFF_DAY = 'drop_off_day'; public const FIELD_MYPARCEL_CARRIER = 'myparcel_carrier'; public const FIELD_DELIVERY_OPTIONS = 'myparcel_delivery_options'; - public const FIELD_TRACK_STATUS = 'track_status'; - public const DEFAULT_COUNTRY_CODE = 'NL'; + public const FIELD_TRACK_STATUS = 'track_status'; + public const DEFAULT_COUNTRY_CODE = 'NL'; public const CARRIERS_XML_PATH_MAP = [ CarrierPostNL::NAME => self::XML_PATH_POSTNL_SETTINGS, @@ -82,6 +82,42 @@ public function getConfigValue($field, $storeId = null) return $this->scopeConfig->getValue($field, ScopeInterface::SCOPE_STORE, $storeId); } + /** + * @param string $path + * @param string $key + * @return bool + */ + public function getBoolConfig(string $path, string $key): bool + { + return '1' === $this->getConfigValue("$path$key"); + } + + public function getFloatConfig($path, $key): float + { + return (float)$this->getConfigValue("$path$key"); + } + + public function getTimeConfig(string $carrier, string $key): string + { + $timeAsString = str_replace(',', ':', (string) $this->getConfigValue("$carrier$key")); + $timeComponents = explode(':', $timeAsString ?? ''); + if (count($timeComponents) >= 3) { + [$hours, $minutes] = $timeComponents; + $timeAsString = $hours . ':' . $minutes; + } + + return $timeAsString; + } + + /** + * @param $path + * @param $key + * @return int + */ + public function getIntegerConfig($path, $key): int + { + return (int)$this->getConfigValue("$path$key"); + } /** * Get setting for carrier @@ -120,6 +156,7 @@ public function getExportMode(): ?string } // TODO everything below here must be refactored out + /** * Get the version number of the installed module * @@ -130,7 +167,7 @@ public function getVersion(): string $moduleCode = self::MODULE_NAME; $moduleInfo = $this->moduleList->getOne($moduleCode); - return (string) $moduleInfo['setup_version']; + return (string)$moduleInfo['setup_version']; } /** @@ -167,19 +204,19 @@ public function hasApiKey(): bool /** * Get date in YYYY-MM-DD HH:MM:SS format * - * @param string|null $date + * @param string|null $date * * @return string|null */ public function convertDeliveryDate(?string $date): ?string { - if (! $date) { + if (!$date) { return null; } $checkoutDate = json_decode($date, true)['date'] ?? substr($date, 0, 10); $deliveryDate = strtotime(date('Y-m-d', strtotime($checkoutDate))); - $currentDate = strtotime(date('Y-m-d')); + $currentDate = strtotime(date('Y-m-d')); if ($deliveryDate <= $currentDate) { return date('Y-m-d H:i:s', strtotime('now +1 day')); @@ -189,8 +226,8 @@ public function convertDeliveryDate(?string $date): ?string } /** - * @param int $orderId - * @param string $status + * @param int $orderId + * @param string $status */ public function setOrderStatus(int $orderId, string $status): void { diff --git a/Service/Costs/DeliveryCostsService.php b/Service/Costs/DeliveryCostsService.php index 8cdb4a4f..ae3d14ce 100644 --- a/Service/Costs/DeliveryCostsService.php +++ b/Service/Costs/DeliveryCostsService.php @@ -4,8 +4,37 @@ namespace MyParcelNL\Magento\Service\Costs; +use Magento\Framework\App\Helper\Context; +use MyParcelNL\Magento\Model\Source\PriceDeliveryOptionsView; +use MyParcelNL\Magento\Service\Config\ConfigService; + class DeliveryCostsService { + private ConfigService $configService; + + public function __construct(ConfigService $configService) + { + $this->configService = $configService; + } + + /** + * @param string $carrier + * @param string $key + * @param bool $addBasePrice + * @return float + */ + public function getMethodPrice(string $carrier, string $key, bool $addBasePrice = true): float + { + $value = $this->configService->getFloatConfig($carrier,$key); + $showTotalPrice = $this->configService->getConfigValue(ConfigService::XML_PATH_GENERAL . 'shipping_methods/delivery_options_prices') === PriceDeliveryOptionsView::TOTAL; + + if ($showTotalPrice && $addBasePrice) { + $value = $this->getBasePrice() + $value; + } + + return $value; + } + // todo: accept country, weight, packagetype, carrier, deliverytype etc. Or maybe a consignment then? public function getBasePrice(): float { diff --git a/etc/di.xml b/etc/di.xml index 90ce5dfa..279a4052 100755 --- a/etc/di.xml +++ b/etc/di.xml @@ -40,8 +40,6 @@ - - From e64f0b0cae8c965383a08b898992f191513149ef Mon Sep 17 00:00:00 2001 From: Joeri van Veen Date: Thu, 26 Sep 2024 17:42:05 +0200 Subject: [PATCH 04/29] wip --- Helper/CustomsDeclarationFromOrder.php | 5 +++-- Model/Sales/MagentoCollection.php | 22 +++++++++++++------- Model/Sales/MagentoOrderCollection.php | 8 +++---- Model/Sales/TrackTraceHolder.php | 17 +++++---------- Service/Config/ConfigService.php | 4 ++++ Ui/Component/Listing/Column/TrackActions.php | 14 ++++++------- 6 files changed, 36 insertions(+), 34 deletions(-) diff --git a/Helper/CustomsDeclarationFromOrder.php b/Helper/CustomsDeclarationFromOrder.php index 55b11425..736927fd 100644 --- a/Helper/CustomsDeclarationFromOrder.php +++ b/Helper/CustomsDeclarationFromOrder.php @@ -38,8 +38,9 @@ class CustomsDeclarationFromOrder private $WeightService; /** - * @param \Magento\Sales\Model\Order $order - * @param \Magento\Framework\ObjectManagerInterface $objectManager + * @param Order $order + * @param ObjectManagerInterface $objectManager + * @param WeightService $WeightService */ public function __construct(Order $order, ObjectManagerInterface $objectManager, WeightService $WeightService) { diff --git a/Model/Sales/MagentoCollection.php b/Model/Sales/MagentoCollection.php index eca7b02f..5cad61a0 100755 --- a/Model/Sales/MagentoCollection.php +++ b/Model/Sales/MagentoCollection.php @@ -21,6 +21,8 @@ use MyParcelNL\Magento\Model\Source\ReturnInTheBox; use MyParcelNL\Magento\Model\Source\SourceItem; use MyParcelNL\Magento\Observer\NewShipment; +use MyParcelNL\Magento\Service\Config\ConfigService; +use MyParcelNL\Magento\Service\Weight\WeightService; use MyParcelNL\Magento\Ui\Component\Listing\Column\TrackAndTrace; use MyParcelNL\Sdk\src\Helper\MyParcelCollection; use MyParcelNL\Sdk\src\Model\Carrier\CarrierPostNL; @@ -94,7 +96,7 @@ abstract class MagentoCollection implements MagentoCollectionInterface /** * @var \MyParcelNL\Magento\Helper\Data */ - protected $helper; + protected $configService; /** * @var array @@ -116,6 +118,10 @@ abstract class MagentoCollection implements MagentoCollectionInterface 'return_in_the_box' => false, 'same_day_delivery' => false, ]; + /** + * @var mixed + */ + private $weightService; /** * @param ObjectManagerInterface $objectManager @@ -138,11 +144,12 @@ public function __construct( $this->trackSender = $this->objectManager->get( 'MyParcelNL\Magento\Model\Order\Email\Sender\TrackSender' ); - $this->helper = $objectManager->create(self::PATH_HELPER_DATA); + $this->configService = $objectManager->create(ConfigService::class); + $this->weightService = $objectManager->create(WeightService::class); $this->modelTrack = $objectManager->create(self::PATH_ORDER_TRACK); $this->messageManager = $objectManager->create(self::PATH_MANAGER_INTERFACE); $this->myParcelCollection = (new MyParcelCollection())->setUserAgents( - ['Magento2' => $this->helper->getVersion()] + ['Magento2' => $this->configService->getVersion()] ); $this->setSourceItemWhenInventoryApiEnabled(); @@ -189,7 +196,7 @@ public function setOptionsFromParameters() $this->options['create_track_if_one_already_exist'] = false; } - $returnInTheBox = $this->helper->getGeneralConfig('print/return_in_the_box'); + $returnInTheBox = $this->configService->getGeneralConfig('print/return_in_the_box'); if (ReturnInTheBox::NO_OPTIONS === $returnInTheBox || ReturnInTheBox::EQUAL_TO_SHIPMENT === $returnInTheBox) { $this->options['return_in_the_box'] = $returnInTheBox; } @@ -239,7 +246,7 @@ public function addConsignment(BaseConsignment $consignment) */ public function getApiKey(): string { - return $this->helper->getApiKey(); + return $this->configService->getApiKey(); } /** @@ -247,7 +254,7 @@ public function getApiKey(): string */ public function getExportMode(): ?string { - return $this->helper->getExportMode(); + return $this->configService->getExportMode(); } /** @@ -255,7 +262,7 @@ public function getExportMode(): ?string */ public function apiKeyIsCorrect(): bool { - return $this->helper->apiKeyIsCorrect(); + return $this->configService->apiKeyIsCorrect(); } /** @@ -375,7 +382,6 @@ protected function createConsignmentAndGetTrackTraceHolder($magentoTrack): Track { $trackTraceHolder = new TrackTraceHolder( $this->objectManager, - $this->helper, $magentoTrack->getShipment()->getOrder() ); $trackTraceHolder->convertDataFromMagentoToApi($magentoTrack, $this->options); diff --git a/Model/Sales/MagentoOrderCollection.php b/Model/Sales/MagentoOrderCollection.php index 1077c119..4f47d545 100755 --- a/Model/Sales/MagentoOrderCollection.php +++ b/Model/Sales/MagentoOrderCollection.php @@ -166,13 +166,13 @@ public function setFulfilment(): self $orderLines = new Collection(); foreach ($this->getOrders() as $magentoOrder) { - $defaultOptions = new DefaultOptions($magentoOrder, $this->helper); + $defaultOptions = new DefaultOptions($magentoOrder, $this->configService); $myparcelDeliveryOptions = $magentoOrder['myparcel_delivery_options'] ?? ''; $deliveryOptions = json_decode($myparcelDeliveryOptions, true); $selectedCarrier = $deliveryOptions['carrier'] ?? $this->options['carrier'] ?? CarrierPostNL::NAME; $shipmentOptionsHelper = new ShipmentOptions( $defaultOptions, - $this->helper, + $this->configService, $magentoOrder, $this->objectManager, $selectedCarrier, @@ -208,7 +208,7 @@ public function setFulfilment(): self ->setOrderDate($this->getLocalCreatedAtDate()) ->setExternalIdentifier($this->order->getIncrementId()) ->setDropOffPoint( - $this->helper->getDropOffPoint( + $this->configService->getDropOffPoint( CarrierFactory::createFromName($deliveryOptionsAdapter->getCarrier()) ) ); @@ -351,7 +351,7 @@ private function getTotalWeight(): int $totalWeight += $product->getWeight() * $item->getQtyOrdered(); } - return $this->helper->convertToGrams($totalWeight); + return $this->configService->convertToGrams($totalWeight); } /** diff --git a/Model/Sales/TrackTraceHolder.php b/Model/Sales/TrackTraceHolder.php index e755b042..6f59edba 100755 --- a/Model/Sales/TrackTraceHolder.php +++ b/Model/Sales/TrackTraceHolder.php @@ -33,7 +33,6 @@ use MyParcelNL\Sdk\src\Exception\MissingFieldException; use MyParcelNL\Sdk\src\Factory\ConsignmentFactory; use MyParcelNL\Sdk\src\Factory\DeliveryOptionsAdapterFactory; -use MyParcelNL\Sdk\src\Model\Carrier\CarrierFactory; use MyParcelNL\Sdk\src\Model\Consignment\AbstractConsignment; use MyParcelNL\Sdk\src\Model\MyParcelCustomsItem; use RuntimeException; @@ -99,27 +98,21 @@ class TrackTraceHolder * TrackTraceHolder constructor. * * @param ObjectManagerInterface $objectManager - * @param ConfigService $configService - * @param WeightService $weightService - * @param DeliveryCostsService $deliveryCostsService * @param Order $order */ public function __construct( ObjectManagerInterface $objectManager, - ConfigService $configService, - WeightService $weightService, - DeliveryCostsService $deliveryCostsService, Order $order ) { $this->objectManager = $objectManager; - $this->configService = $configService; - $this->weightService = $weightService; - $this->deliveryCostsService = $deliveryCostsService; + $this->configService = $objectManager->create(ConfigService::class); + $this->weightService = $objectManager->create(WeightService::class); + $this->deliveryCostsService = $objectManager->create(DeliveryCostsService::class); $this->messageManager = $this->objectManager->create('Magento\Framework\Message\ManagerInterface'); self::$defaultOptions = new DefaultOptions( $order, - $configService, - $weightService + $this->configService, + $this->weightService ); } diff --git a/Service/Config/ConfigService.php b/Service/Config/ConfigService.php index 862e4e28..275676a8 100644 --- a/Service/Config/ConfigService.php +++ b/Service/Config/ConfigService.php @@ -34,6 +34,10 @@ class ConfigService extends AbstractHelper public const FIELD_DELIVERY_OPTIONS = 'myparcel_delivery_options'; public const FIELD_TRACK_STATUS = 'track_status'; public const DEFAULT_COUNTRY_CODE = 'NL'; + 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 CARRIERS_XML_PATH_MAP = [ CarrierPostNL::NAME => self::XML_PATH_POSTNL_SETTINGS, diff --git a/Ui/Component/Listing/Column/TrackActions.php b/Ui/Component/Listing/Column/TrackActions.php index 5a6b1920..323eb6d1 100755 --- a/Ui/Component/Listing/Column/TrackActions.php +++ b/Ui/Component/Listing/Column/TrackActions.php @@ -8,8 +8,7 @@ use Magento\Framework\View\Element\UiComponent\ContextInterface; use Magento\Framework\View\Element\UiComponentFactory; use Magento\Ui\Component\Listing\Columns\Column; -use MyParcelNL\Magento\Helper\Data; -use MyParcelNL\Magento\Model\Sales\TrackTraceHolder; +use MyParcelNL\Magento\Service\Config\ConfigService; /** * Class DepartmentActions @@ -21,7 +20,7 @@ class TrackActions extends Column /** * @var \MyParcelNL\Magento\Helper\Data */ - private $helper; + private $configService; /** * @var UrlInterface @@ -32,7 +31,6 @@ class TrackActions extends Column * @param ContextInterface $context * @param UiComponentFactory $uiComponentFactory * @param UrlInterface $urlBuilder - * @param \MyParcelNL\Magento\Helper\Data $helper * @param array $components * @param array $data */ @@ -45,7 +43,7 @@ public function __construct( ) { $this->urlBuilder = $urlBuilder; $objectManager = ObjectManager::getInstance(); - $this->helper = $objectManager->create(Data::class); + $this->configService = $objectManager->create(ConfigService::class); parent::__construct($context, $uiComponentFactory, $components, $data); } @@ -63,10 +61,10 @@ public function prepareDataSource(array $dataSource) return $dataSource; } - $orderManagementActivated = TrackTraceHolder::EXPORT_MODE_PPS === $this->helper->getExportMode(); + $orderManagementActivated = ConfigService::EXPORT_MODE_PPS === $this->configService->getExportMode(); foreach ($dataSource['data']['items'] as &$item) { - if (! key_exists(ShippingStatus::NAME, $item)) { + if (! array_key_exists(ShippingStatus::NAME, $item)) { throw new LocalizedException( __( 'Note that the installation of the extension was not successful. Some columns have not been added to the database. The installation should be reversed. Use the following command to reinstall the module: DELETE FROM `setup_module` WHERE `setup_module`.`module` = \'MyParcelNL_Magento\'' @@ -76,7 +74,7 @@ public function prepareDataSource(array $dataSource) } if (! isset($item[ShippingStatus::NAME])) { - if (TrackTraceHolder::EXPORT_MODE_PPS === $this->helper->getExportMode()) { + if (ConfigService::EXPORT_MODE_PPS === $this->configService->getExportMode()) { $item[$this->getData('name')]['action-create_concept'] = [ 'href' => $this->urlBuilder->getUrl( 'myparcel/order/CreateAndPrintMyParcelTrack', From 1352c8c6138495a63e24e3c386a206b772a00b0f Mon Sep 17 00:00:00 2001 From: Joeri van Veen Date: Fri, 27 Sep 2024 14:58:05 +0200 Subject: [PATCH 05/29] wip --- Block/Sales/NewShipment.php | 15 +- Block/Sales/OrdersAction.php | 27 +-- Block/Sales/ShipmentsAction.php | 13 +- .../Form/AbstractDefaultDropOffPoint.php | 35 +-- .../Order/CreateAndPrintMyParcelTrack.php | 29 +-- .../Order/SendMyParcelReturnMail.php | 13 +- .../Settings/CarrierConfigurationImport.php | 28 +-- .../Shipment/CreateAndPrintMyParcelTrack.php | 9 +- Cron/UpdateStatus.php | 94 ++++---- Model/Sales/MagentoCollection.php | 205 +++++++----------- Model/Sales/MagentoOrderCollection.php | 8 +- Model/Sales/TrackTraceHolder.php | 24 +- Model/Settings/AccountSettings.php | 67 +++--- Model/Source/AgeCheckNo.php | 7 +- Model/Source/AgeCheckYes.php | 6 +- Model/Source/DefaultOptions.php | 10 +- Model/Source/DigitalStampWeightOptions.php | 9 +- Model/Source/LargeFormatOptions.php | 17 +- Observer/CreateConceptAfterInvoice.php | 29 +-- Observer/NewShipment.php | 12 +- Observer/SalesOrderStatusHistoryObserver.php | 19 +- Service/Config/ConfigService.php | 2 +- Service/Weight/WeightService.php | 9 +- Setup/UpgradeData.php | 4 +- Ui/Component/Listing/Column/TrackActions.php | 2 +- 25 files changed, 273 insertions(+), 420 deletions(-) diff --git a/Block/Sales/NewShipment.php b/Block/Sales/NewShipment.php index 7610e1ad..9c36bf66 100755 --- a/Block/Sales/NewShipment.php +++ b/Block/Sales/NewShipment.php @@ -22,7 +22,6 @@ use Magento\Sales\Block\Adminhtml\Items\AbstractItems; use MyParcelNL\Magento\Model\Sales\MagentoOrderCollection; use MyParcelNL\Magento\Model\Source\DefaultOptions; -use MyParcelNL\Magento\Helper\Data; use MyParcelNL\Magento\Model\Sales\TrackTraceHolder; use MyParcelNL\Magento\Service\Config\ConfigService; use MyParcelNL\Magento\Service\Weight\WeightService; @@ -53,29 +52,23 @@ class NewShipment extends AbstractItems /** * @param Context $context - * @param WeightService $weightService * @param StockRegistryInterface $stockRegistry * @param StockConfigurationInterface $stockConfiguration * @param Registry $registry - * @param ConfigService $configService */ public function __construct( Context $context, - WeightService $weightService, StockRegistryInterface $stockRegistry, StockConfigurationInterface $stockConfiguration, Registry $registry, ObjectManagerInterface $objectManager ) { $this->order = $registry->registry('current_shipment')->getOrder(); - $this->weightService = $weightService; + $this->weightService = $objectManager->get(WeightService::class); + $this->configService = $objectManager->get(ConfigService::class); $this->form = new NewShipmentForm(); - $this->defaultOptions = new DefaultOptions( - $this->order, - $objectManager->get(ConfigService::class), - $weightService - ); + $this->defaultOptions = new DefaultOptions($this->order); $request = $objectManager->get('Magento\Framework\App\RequestInterface'); $this->orderCollection = new MagentoOrderCollection($objectManager, $request); @@ -191,6 +184,6 @@ public function getNewShipmentForm(): NewShipmentForm */ public function isOrderManagementEnabled(): bool { - return TrackTraceHolder::EXPORT_MODE_PPS === $this->orderCollection->getExportMode(); + return ConfigService::EXPORT_MODE_PPS === $this->configService->getExportMode(); } } diff --git a/Block/Sales/OrdersAction.php b/Block/Sales/OrdersAction.php index a3bc4f9c..30ad0938 100755 --- a/Block/Sales/OrdersAction.php +++ b/Block/Sales/OrdersAction.php @@ -17,30 +17,23 @@ use Magento\Backend\Block\Template; use Magento\Backend\Block\Template\Context; use Magento\Framework\App\ObjectManager; -use MyParcelNL\Magento\Helper\Data; +use MyParcelNL\Magento\Service\Config\ConfigService; class OrdersAction extends Template { - /** - * @var \Magento\Framework\ObjectManagerInterface - */ - private $objectManager; - - /** - * @var \MyParcelNL\Magento\Helper\Data - */ - private $helper; + private ConfigService $configService; /** * @param Context $context - * @param array $data + * @param array $data */ public function __construct( Context $context, - array $data = [] - ) { - $this->objectManager = ObjectManager::getInstance(); - $this->helper = $this->objectManager->get(Data::class); + array $data = [] + ) + { + $objectManager = ObjectManager::getInstance(); + $this->configService = $objectManager->get(ConfigService::class); parent::__construct($context, $data); } @@ -51,7 +44,7 @@ public function __construct( */ public function hasApiKey(): bool { - return $this->helper->hasApiKey(); + return $this->configService->hasApiKey(); } /** @@ -91,7 +84,7 @@ public function getAjaxUrlSendReturnMail(): string */ public function getPrintSettings() { - $settings = $this->helper->getGeneralConfig('print'); + $settings = $this->configService->getGeneralConfig('print'); return json_encode($settings); } diff --git a/Block/Sales/ShipmentsAction.php b/Block/Sales/ShipmentsAction.php index c169a8f6..35568888 100755 --- a/Block/Sales/ShipmentsAction.php +++ b/Block/Sales/ShipmentsAction.php @@ -17,14 +17,11 @@ use Magento\Backend\Block\Template; use Magento\Backend\Block\Template\Context; use Magento\Framework\App\ObjectManager; -use MyParcelNL\Magento\Helper\Data; +use MyParcelNL\Magento\Service\Config\ConfigService; class ShipmentsAction extends Template { - /** - * @var \MyParcelNL\Magento\Helper\Data - */ - private $helper; + private ConfigService $configService; /** * @param Context $context @@ -35,7 +32,7 @@ public function __construct( array $data = [] ) { $objectManager = ObjectManager::getInstance(); - $this->helper = $objectManager->get(Data::class); + $this->configService = $objectManager->get(ConfigService::class); parent::__construct($context, $data); } @@ -46,7 +43,7 @@ public function __construct( */ public function hasApiKey(): bool { - return $this->helper->hasApiKey(); + return $this->configService->hasApiKey(); } /** @@ -86,7 +83,7 @@ public function getAjaxUrlSendReturnMail(): string */ public function getPrintSettings(): string { - $settings = $this->helper->getGeneralConfig('print'); + $settings = $this->configService->getGeneralConfig('print'); return json_encode($settings); } diff --git a/Block/System/Config/Form/AbstractDefaultDropOffPoint.php b/Block/System/Config/Form/AbstractDefaultDropOffPoint.php index e1b8627a..2f11154f 100644 --- a/Block/System/Config/Form/AbstractDefaultDropOffPoint.php +++ b/Block/System/Config/Form/AbstractDefaultDropOffPoint.php @@ -9,7 +9,8 @@ use Magento\Config\Block\System\Config\Form\Field; use Magento\Framework\App\ObjectManager; use Magento\Framework\Data\Form\Element\AbstractElement; -use MyParcelNL\Magento\Helper\Data; +use MyParcelNL\Magento\Model\Settings\AccountSettings; +use MyParcelNL\Magento\Service\Config\ConfigService; use MyParcelNL\Sdk\src\Model\Carrier\CarrierFactory; abstract class AbstractDefaultDropOffPoint extends Field @@ -31,9 +32,7 @@ abstract class AbstractDefaultDropOffPoint extends Field */ public function __construct(Context $context, array $data = []) { - $objectManager = ObjectManager::getInstance(); - $helper = $objectManager->get(Data::class); - $dropOffPoint = $helper->getDropOffPoint(CarrierFactory::createFromId($this->getCarrierId())); + $dropOffPoint = AccountSettings::getInstance()->getDropOffPoint(CarrierFactory::createFromId($this->getCarrierId())); $this->dropOffPoint = $dropOffPoint; parent::__construct($context, $data); } @@ -46,7 +45,7 @@ abstract public function getCarrierId(): int; /** * Retrieve HTML markup for given form element * - * @param \Magento\Framework\Data\Form\Element\AbstractElement $element + * @param \Magento\Framework\Data\Form\Element\AbstractElement $element * * @return string */ @@ -61,7 +60,7 @@ public function render(AbstractElement $element): string /** * Retrieve element HTML markup * - * @param \Magento\Framework\Data\Form\Element\AbstractElement $element + * @param \Magento\Framework\Data\Form\Element\AbstractElement $element * * @return string */ @@ -75,14 +74,20 @@ protected function _getElementHtml(AbstractElement $element): string */ public function getDropOffPointDetails(): ?array { - return $this->dropOffPoint ? [ - 'location_name' => $this->dropOffPoint->getLocationName(), - 'city' => $this->dropOffPoint->getCity(), - 'street' => $this->dropOffPoint->getStreet(), - 'number' => $this->dropOffPoint->getNumber(), - 'number_suffix' => $this->dropOffPoint->getNumberSuffix(), - 'postal_code' => $this->dropOffPoint->getPostalCode(), - ] : null; + if (!$this->dropOffPoint) { + return null; + } + + $dropOffPoint = $this->dropOffPoint; + + return [ + 'location_name' => $dropOffPoint->getLocationName(), + 'city' => $dropOffPoint->getCity(), + 'street' => $dropOffPoint->getStreet(), + 'number' => $dropOffPoint->getNumber(), + 'number_suffix' => $dropOffPoint->getNumberSuffix(), + 'postal_code' => $dropOffPoint->getPostalCode(), + ]; } /** @@ -106,7 +111,7 @@ public function getButtonHtml(): string $button = $this->getLayout() ->createBlock(Button::class) ->setData([ - 'id' => 'settings-button', + 'id' => 'settings-button', 'label' => __('Import'), ]); return $button->toHtml(); diff --git a/Controller/Adminhtml/Order/CreateAndPrintMyParcelTrack.php b/Controller/Adminhtml/Order/CreateAndPrintMyParcelTrack.php index fa124595..e5c78b86 100755 --- a/Controller/Adminhtml/Order/CreateAndPrintMyParcelTrack.php +++ b/Controller/Adminhtml/Order/CreateAndPrintMyParcelTrack.php @@ -11,6 +11,7 @@ use MyParcelNL\Magento\Model\Sales\MagentoCollection; use MyParcelNL\Magento\Model\Sales\MagentoOrderCollection; use MyParcelNL\Magento\Model\Sales\TrackTraceHolder; +use MyParcelNL\Magento\Service\Config\ConfigService; use MyParcelNL\Magento\Ui\Component\Listing\Column\TrackAndTrace; use MyParcelNL\Sdk\src\Exception\ApiException; use MyParcelNL\Sdk\src\Exception\MissingFieldException; @@ -36,15 +37,9 @@ class CreateAndPrintMyParcelTrack extends \Magento\Framework\App\Action\Action const PATH_MODEL_ORDER = 'Magento\Sales\Model\Order'; const PATH_URI_ORDER_INDEX = 'sales/order/index'; - /** - * @var \Magento\Backend\App\Action\Context - */ - private $context; - /** - * @var MagentoOrderCollection - */ - private $orderCollection; + private MagentoOrderCollection $orderCollection; + private ConfigService $configService; /** * CreateAndPrintMyParcelTrack constructor. @@ -53,12 +48,13 @@ class CreateAndPrintMyParcelTrack extends \Magento\Framework\App\Action\Action */ public function __construct(Context $context) { - $this->context = $context; - parent::__construct($this->context); + // TODO joeri don’t use deprecated action + parent::__construct($context); - $this->resultRedirectFactory = $this->context->getResultRedirectFactory(); + $this->configService = $this->_objectManager->get(ConfigService::class); + $this->resultRedirectFactory = $context->getResultRedirectFactory(); $this->orderCollection = new MagentoOrderCollection( - $context->getObjectManager(), + $this->_objectManager, $this->getRequest(), null ); @@ -92,7 +88,7 @@ public function execute() */ private function massAction() { - if (! $this->orderCollection->apiKeyIsCorrect()) { + if (! $this->configService->apiKeyIsCorrect()) { $message = 'You not have entered the correct API key. To get your personal API credentials you should contact MyParcel.'; $this->messageManager->addErrorMessage(__($message)); $this->_objectManager->get('Psr\Log\LoggerInterface')->critical($message); @@ -115,7 +111,7 @@ private function massAction() $orderIds = $this->filterCorrectAddress($orderIds); $this->addOrdersToCollection($orderIds); - if (TrackTraceHolder::EXPORT_MODE_PPS === $this->orderCollection->getExportMode()) { + if (ConfigService::EXPORT_MODE_PPS === $this->configService->getExportMode()) { $this->orderCollection->setFulfilment(); return $this; @@ -163,7 +159,7 @@ private function addOrdersToCollection($orderIds) /** * @var \Magento\Sales\Model\ResourceModel\Order\Collection $collection */ - $collection = $this->_objectManager->get(MagentoOrderCollection::PATH_MODEL_ORDER); + $collection = $this->_objectManager->get(MagentoOrderCollection::PATH_MODEL_ORDER_COLLECTION); $collection->addAttributeToFilter('entity_id', ['in' => $orderIds]); $this->orderCollection->setOrderCollection($collection); } @@ -175,8 +171,7 @@ private function addOrdersToCollection($orderIds) */ private function filterCorrectAddress(array $orderIds): array { - $objectManager = ObjectManager::getInstance(); - $order = $objectManager->get(Order::class); + $order = $this->_objectManager->get(Order::class); // Go through the selected orders and check if the address details are correct foreach ($orderIds as $orderId) { $order->load($orderId); diff --git a/Controller/Adminhtml/Order/SendMyParcelReturnMail.php b/Controller/Adminhtml/Order/SendMyParcelReturnMail.php index 5bfabb5e..98b11176 100755 --- a/Controller/Adminhtml/Order/SendMyParcelReturnMail.php +++ b/Controller/Adminhtml/Order/SendMyParcelReturnMail.php @@ -6,6 +6,7 @@ use Magento\Backend\App\Action\Context; use Magento\Framework\Exception\LocalizedException; use MyParcelNL\Magento\Model\Sales\MagentoOrderCollection; +use MyParcelNL\Magento\Service\Config\ConfigService; /** * Action to send mails with a return label @@ -21,13 +22,10 @@ */ class SendMyParcelReturnMail extends \Magento\Framework\App\Action\Action { - const PATH_MODEL_ORDER = 'Magento\Sales\Model\Order'; const PATH_URI_ORDER_INDEX = 'sales/order/index'; - /** - * @var MagentoOrderCollection - */ - private $orderCollection; + private MagentoOrderCollection $orderCollection; + private ConfigService $configService; /** * CreateAndPrintMyParcelTrack constructor. @@ -38,6 +36,7 @@ public function __construct(Context $context) { parent::__construct($context); + $this->configService = $context->getObjectManager()->get(ConfigService::class); $this->resultRedirectFactory = $context->getResultRedirectFactory(); $this->orderCollection = new MagentoOrderCollection( $context->getObjectManager(), @@ -69,7 +68,7 @@ private function sendReturnMail() { error_reporting(E_ALL); ini_set('display_errors', 1); - if ($this->orderCollection->apiKeyIsCorrect() !== true) { + if ($this->configService->apiKeyIsCorrect() !== true) { $message = 'You not have entered the correct API key. Go to the general settings in the back office of MyParcel to generate the API Key.'; $this->messageManager->addErrorMessage(__($message)); $this->_objectManager->get('Psr\Log\LoggerInterface')->critical($message); @@ -123,7 +122,7 @@ private function addOrdersToCollection($orderIds) /** * @var \Magento\Sales\Model\ResourceModel\Order\Collection $collection */ - $collection = $this->_objectManager->get(MagentoOrderCollection::PATH_MODEL_ORDER); + $collection = $this->_objectManager->get(MagentoOrderCollection::PATH_MODEL_ORDER_COLLECTION); $collection->addAttributeToFilter('entity_id', ['in' => $orderIds]); $this->orderCollection->setOrderCollection($collection); } diff --git a/Controller/Adminhtml/Settings/CarrierConfigurationImport.php b/Controller/Adminhtml/Settings/CarrierConfigurationImport.php index 64408dd1..61379be3 100644 --- a/Controller/Adminhtml/Settings/CarrierConfigurationImport.php +++ b/Controller/Adminhtml/Settings/CarrierConfigurationImport.php @@ -12,11 +12,8 @@ use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\App\ObjectManager; use Magento\Framework\Controller\Result\JsonFactory; -use Magento\Framework\Message\ManagerInterface; -use Magento\Framework\Message\MessageInterface; use Magento\Framework\Model\ResourceModel\Db\Context as DbContext; -use MyParcelNL\Magento\Helper\Data; -use MyParcelNL\Magento\Model\Sales\MagentoOrderCollection; +use MyParcelNL\Magento\Service\Config\ConfigService; use MyParcelNL\Sdk\src\Model\Account\CarrierConfiguration; use MyParcelNL\Sdk\src\Model\Account\CarrierOptions; use MyParcelNL\Sdk\src\Support\Collection; @@ -26,15 +23,9 @@ class CarrierConfigurationImport extends Action { - /** - * @var string - */ - private $apiKey; - - /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface - */ - private $config; + private string $apiKey; + private ScopeConfigInterface $config; + private Pool $pool; /** * @var mixed @@ -46,11 +37,6 @@ class CarrierConfigurationImport extends Action */ private $typeListInterface; - /** - * @var Pool - */ - private $pool; - /** * @param \Magento\Framework\Controller\Result\JsonFactory $resultFactory * @param \Magento\Backend\App\Action\Context $context @@ -70,7 +56,7 @@ public function __construct( parent::__construct($context); $this->resultFactory = $resultFactory; $this->config = $config; - $this->apiKey = $this->config->getValue(Data::XML_PATH_GENERAL . 'api/key'); + $this->apiKey = $this->config->getValue(ConfigService::XML_PATH_GENERAL . 'api/key'); $this->context = $dbContext; $this->typeListInterface = $typeListInterface; $this->pool = $pool; @@ -84,7 +70,7 @@ public function __construct( public function execute() { $config = new Config($this->context); - $path = Data::XML_PATH_GENERAL . 'account_settings'; + $path = ConfigService::XML_PATH_GENERAL . 'account_settings'; $configuration = $this->fetchConfigurations(); $config->saveConfig($path, json_encode($this->createArray($configuration))); @@ -134,7 +120,7 @@ public static function getAccountSettings(): ?Collection { $objectManager = ObjectManager::getInstance(); $accountSettings = $objectManager->get(ScopeConfigInterface::class) - ->getValue(Data::XML_PATH_GENERAL . 'account_settings'); + ->getValue(ConfigService::XML_PATH_GENERAL . 'account_settings'); if (! $accountSettings) { return null; diff --git a/Controller/Adminhtml/Shipment/CreateAndPrintMyParcelTrack.php b/Controller/Adminhtml/Shipment/CreateAndPrintMyParcelTrack.php index b6f99838..a2938488 100755 --- a/Controller/Adminhtml/Shipment/CreateAndPrintMyParcelTrack.php +++ b/Controller/Adminhtml/Shipment/CreateAndPrintMyParcelTrack.php @@ -6,7 +6,9 @@ use Magento\Framework\App\ResponseInterface; use Magento\Framework\Controller\ResultInterface; use Magento\Framework\Exception\LocalizedException; +use MyParcelNL\Magento\Model\Sales\MagentoCollection; use MyParcelNL\Magento\Model\Sales\MagentoShipmentCollection; +use MyParcelNL\Magento\Service\Config\ConfigService; /** * Action to create and print MyParcel Track @@ -22,13 +24,13 @@ */ class CreateAndPrintMyParcelTrack extends \Magento\Framework\App\Action\Action { - const PATH_MODEL_ORDER = 'Magento\Sales\Model\Order'; const PATH_URI_SHIPMENT_INDEX = 'sales/shipment/index'; /** * @var MagentoShipmentCollection */ private $shipmentCollection; + private ConfigService $configService; /** * CreateAndPrintMyParcelTrack constructor. @@ -39,6 +41,7 @@ public function __construct(Context $context) { parent::__construct($context); + $this->configService = $context->getObjectManager()->get(ConfigService::class); $this->resultRedirectFactory = $context->getResultRedirectFactory(); $this->shipmentCollection = new MagentoShipmentCollection( $context->getObjectManager(), @@ -73,7 +76,7 @@ public function execute() */ private function massAction() { - if (! $this->shipmentCollection->apiKeyIsCorrect()) { + if (! $this->configService->apiKeyIsCorrect()) { $message = 'You not have entered the correct API key. Go to the general settings in the back office of MyParcel to generate the API Key.'; $this->messageManager->addErrorMessage(__($message)); $this->_objectManager->get('Psr\Log\LoggerInterface')->critical($message); @@ -126,7 +129,7 @@ private function addShipmentsToCollection($shipmentIds) /** * @var \Magento\Sales\Model\ResourceModel\Order\Shipment\Collection $collection */ - $collection = $this->_objectManager->get(MagentoShipmentCollection::PATH_MODEL_SHIPMENT); + $collection = $this->_objectManager->get(MagentoCollection::PATH_MODEL_SHIPMENT_COLLECTION); $collection->addAttributeToFilter('entity_id', ['in' => $shipmentIds]); $this->shipmentCollection->setShipmentCollection($collection); } diff --git a/Cron/UpdateStatus.php b/Cron/UpdateStatus.php index e0b18e21..ab96a907 100755 --- a/Cron/UpdateStatus.php +++ b/Cron/UpdateStatus.php @@ -25,44 +25,32 @@ use Magento\Sales\Api\Data\ShipmentTrackInterface; use Magento\Sales\Model\Order; use MyParcelNL\Magento\Api\ShipmentStatus; +use MyParcelNL\Magento\Model\Sales\MagentoCollection; use MyParcelNL\Magento\Model\Sales\MagentoOrderCollection; use MyParcelNL\Magento\Model\Sales\TrackTraceHolder; +use MyParcelNL\Magento\Service\Config\ConfigService; use MyParcelNL\Magento\Ui\Component\Listing\Column\TrackAndTrace; use MyParcelNL\Sdk\src\Collection\Fulfilment\OrderCollection; use Magento\Sales\Model\ResourceModel\Order\Shipment\Track\Collection; class UpdateStatus { - public const ORDER_ID_NOT_TO_PROCESS = '000000000'; - public const ORDER_STATUS_EXPORTED = 'Exported'; - public const PATH_MODEL_ORDER_TRACK = Collection::class; - public const PATH_MODEL_ORDER = \Magento\Sales\Model\ResourceModel\Order\Collection::class; + public const ORDER_ID_NOT_TO_PROCESS = '000000000'; + public const ORDER_STATUS_EXPORTED = 'Exported'; + public const PATH_MODEL_ORDER_TRACK = Collection::class; - /** - * @var \Psr\Log\LoggerInterface - */ - private $logger; - /** - * @var ObjectManager - */ - private $objectManager; - - /** - * @var \Magento\Sales\Model\ResourceModel\Order - */ - private $orderResource; - - /** - * @var \MyParcelNL\Magento\Model\Sales\MagentoOrderCollection - */ - private $orderCollection; + private \Psr\Log\LoggerInterface $logger; + private ObjectManager $objectManager; + private \Magento\Sales\Model\ResourceModel\Order $orderResource; + private MagentoOrderCollection $orderCollection; + private ConfigService $configService; /** * UpdateStatus constructor. * - * @param \Magento\Framework\App\AreaList $areaList - * @param \Psr\Log\LoggerInterface $logger + * @param \Magento\Framework\App\AreaList $areaList + * @param \Psr\Log\LoggerInterface $logger * @param \Magento\Sales\Model\ResourceModel\Order $orderResource * * @todo; Adjust if there is a solution to the following problem: https://github.com/magento/magento2/pull/8413 @@ -71,11 +59,13 @@ public function __construct( \Magento\Framework\App\AreaList $areaList, \Psr\Log\LoggerInterface $logger, \Magento\Sales\Model\ResourceModel\Order $orderResource - ) { - $this->objectManager = ObjectManager::getInstance(); + ) + { + $this->objectManager = $objectManager = ObjectManager::getInstance(); + $this->configService = $objectManager->get(ConfigService::class); $this->orderCollection = new MagentoOrderCollection($this->objectManager, null, $areaList); - $this->logger = $logger; - $this->orderResource = $orderResource; + $this->logger = $logger; + $this->orderResource = $orderResource; } /** @@ -87,14 +77,14 @@ public function __construct( */ public function execute(): self { - if (TrackTraceHolder::EXPORT_MODE_PPS === $this->orderCollection->getExportMode()) { - return $this->updateStatusOrderbeheer(); + if (ConfigService::EXPORT_MODE_PPS === $this->configService->getExportMode()) { + return $this->updateStatusPPS(); } return $this->updateStatusShipments(); } /** - * Handles orders exported using Orderbeheer setting. + * Handles orders exported using Orderbeheer (PPS) setting. * Gets (max 300) orders from Magento that are eligible, gets the most recently updated orders from the api. * When the api order is one of the eligible Magento orders and it is shipped, adds the shipment in Magento. * @@ -113,12 +103,12 @@ public function execute(): self * @throws \MyParcelNL\Sdk\src\Exception\MissingFieldException * @throws \Exception */ - private function updateStatusOrderbeheer(): self + private function updateStatusPPS(): self { /** * @var \Magento\Sales\Model\ResourceModel\Order\Collection $magentoOrders */ - $magentoOrders = $this->objectManager->get(self::PATH_MODEL_ORDER); + $magentoOrders = $this->objectManager->get(MagentoCollection::PATH_MODEL_ORDER_COLLECTION); $magentoOrders ->addFieldToSelect('increment_id') ->addFieldToSelect('entity_id') @@ -128,31 +118,31 @@ private function updateStatusOrderbeheer(): self ->setOrder('increment_id', 'DESC'); $orderIdsToCheck = array_unique(array_column($magentoOrders->getData(), 'increment_id')); - $apiOrders = OrderCollection::query($this->orderCollection->getApiKey()); - $orderIdsDone = []; + $apiOrders = OrderCollection::query($this->configService->getApiKey()); + $orderIdsDone = []; foreach ($apiOrders->getIterator() as $apiOrder) { $incrementId = $apiOrder->getExternalIdentifier(); - $shipment = $apiOrder->getOrderShipments()[0]['shipment'] ?? null; + $shipment = $apiOrder->getOrderShipments()[0]['shipment'] ?? null; - if (! $incrementId - || ! $shipment + if (!$incrementId + || !$shipment || isset($orderIdsDone[$incrementId]) - || ! array_contains($orderIdsToCheck, $incrementId)) { + || !array_contains($orderIdsToCheck, $incrementId)) { continue; } $orderIdsDone[$incrementId] = $incrementId; - $barcode = $shipment['external_identifier'] ?? TrackAndTrace::VALUE_PRINTED; + $barcode = $shipment['external_identifier'] ?? TrackAndTrace::VALUE_PRINTED; - if (! $this->apiShipmentIsShipped($shipment)) { + if (!$this->apiShipmentIsShipped($shipment)) { continue; } $magentoOrder = $this->objectManager->create('Magento\Sales\Model\Order') ->loadByIncrementId($incrementId); - if (! $magentoOrder->canShip()) { + if (!$magentoOrder->canShip()) { $orderIdsDone[$incrementId] = self::ORDER_ID_NOT_TO_PROCESS; $this->logger->notice('Order is shipped from backoffice but Magento will not create a shipment.'); @@ -160,32 +150,32 @@ private function updateStatusOrderbeheer(): self } } - if (! $orderIdsDone) { - $this->logger->notice('Orderbeheer: no orders updated'); + if (!$orderIdsDone) { + $this->logger->notice('PPS: no orders updated'); return $this; } $orderIncrementIds = array_unique(array_values($orderIdsDone)); - $index = array_search(self::ORDER_ID_NOT_TO_PROCESS, $orderIncrementIds); + $index = array_search(self::ORDER_ID_NOT_TO_PROCESS, $orderIncrementIds); if (false !== $index) { unset($orderIncrementIds[$index]); } - $orderEntityIds = []; + $orderEntityIds = []; $arrayWithIdsArray = $magentoOrders->getData(); foreach ($arrayWithIdsArray as $arrayWithIds) { - if (! in_array($arrayWithIds['increment_id'], $orderIncrementIds)) { + if (!in_array($arrayWithIds['increment_id'], $orderIncrementIds)) { continue; } $orderEntityIds[] = $arrayWithIds['entity_id']; } - if (! $orderEntityIds) { + if (!$orderEntityIds) { return $this; } - $this->logger->notice(sprintf('Orderbeheer: update orders %s', implode(', ', $orderIncrementIds ?? []))); + $this->logger->notice(sprintf('PPS: update orders %s', implode(', ', $orderIncrementIds ?? []))); $this->addOrdersToCollection($orderEntityIds); $this->orderCollection->setNewMagentoShipment(false) @@ -241,7 +231,7 @@ private function apiShipmentIsShipped(array $shipment): bool $status = $shipment['status'] ?? null; return $status >= ShipmentStatus::PRINTED_MINIMUM - && (! in_array($status, [ShipmentStatus::CREDITED, ShipmentStatus::CANCELLED])); + && (!in_array($status, [ShipmentStatus::CREDITED, ShipmentStatus::CANCELLED], true)); } /** @@ -274,7 +264,7 @@ private function getOrderIdFromTrackToUpdate() ->addFieldToSelect('order_id') ->addAttributeToFilter('myparcel_status', [1, 2, 3, 4, 5, 6, 8]) ->addAttributeToFilter('myparcel_consignment_id', ['notnull' => true]) - ->addAttributeToFilter(ShipmentTrackInterface::CARRIER_CODE, TrackTraceHolder::MYPARCEL_CARRIER_CODE) + ->addAttributeToFilter(ShipmentTrackInterface::CARRIER_CODE, ConfigService::MYPARCEL_CARRIER_CODE) ->setPageSize(300) ->setOrder('order_id', 'DESC'); @@ -292,7 +282,7 @@ private function addOrdersToCollection(array $orderIds): void * @var \Magento\Sales\Model\ResourceModel\Order\Collection $collection */ $now = new \DateTime('now -14 day'); - $collection = $this->objectManager->get(MagentoOrderCollection::PATH_MODEL_ORDER); + $collection = $this->objectManager->get(MagentoCollection::PATH_MODEL_ORDER_COLLECTION); $collection ->addAttributeToFilter('entity_id', ['in' => $orderIds]) ->addFieldToFilter('created_at', ['gteq' => $now->format('Y-m-d H:i:s')]); diff --git a/Model/Sales/MagentoCollection.php b/Model/Sales/MagentoCollection.php index 5cad61a0..1e5f3768 100755 --- a/Model/Sales/MagentoCollection.php +++ b/Model/Sales/MagentoCollection.php @@ -14,9 +14,14 @@ namespace MyParcelNL\Magento\Model\Sales; +use Magento\Framework\App\AreaList; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Message\ManagerInterface; use Magento\Framework\Module\Manager; use Magento\Framework\ObjectManagerInterface; use Magento\Sales\Model\Order; +use Magento\Sales\Model\ResourceModel\Order\Collection as OrderCollection; +use Magento\Sales\Model\ResourceModel\Order\Shipment\Collection as ShipmentCollection; use MyParcelNL\Magento\Model\Order\Email\Sender\TrackSender; use MyParcelNL\Magento\Model\Source\ReturnInTheBox; use MyParcelNL\Magento\Model\Source\SourceItem; @@ -37,86 +42,47 @@ */ abstract class MagentoCollection implements MagentoCollectionInterface { - public const PATH_HELPER_DATA = '\MyParcelNL\Magento\Helper\Data'; - public const PATH_MODEL_ORDER = '\Magento\Sales\Model\ResourceModel\Order\Collection'; - public const PATH_MODEL_SHIPMENT = '\Magento\Sales\Model\ResourceModel\Order\Shipment\Collection'; - public const ERROR_ORDER_HAS_NO_SHIPMENT = 'No shipment can be made with this order. Shipments can not be created if the status is On Hold or if the product is digital.'; - public const ERROR_ORDER_HAS_NO_SOURCE = 'Creating shipments via bulk actions is not possible for orders without a source. Go to the details of the order and process the shipment manually.'; - public const DEFAULT_ERROR_ORDER_HAS_NO_SOURCE = 'Source item not found by source code'; - - private const PATH_ORDER_TRACK = '\Magento\Sales\Model\Order\Shipment\Track'; - private const PATH_MANAGER_INTERFACE = '\Magento\Framework\Message\ManagerInterface'; + public const PATH_MODEL_ORDER_COLLECTION = OrderCollection::class; + public const PATH_MODEL_SHIPMENT_COLLECTION = ShipmentCollection::class; + public const ERROR_ORDER_HAS_NO_SHIPMENT = 'No shipment can be made with this order. Shipments can not be created if the status is On Hold or if the product is digital.'; + public const ERROR_ORDER_HAS_NO_SOURCE = 'Creating shipments via bulk actions is not possible for orders without a source. Go to the details of the order and process the shipment manually.'; + public const DEFAULT_ERROR_ORDER_HAS_NO_SOURCE = 'Source item not found by source code'; + + private const PATH_ORDER_TRACK = '\Magento\Sales\Model\Order\Shipment\Track'; + private const PATH_MANAGER_INTERFACE = '\Magento\Framework\Message\ManagerInterface'; private const PATH_ORDER_TRACK_COLLECTION = '\Magento\Sales\Model\ResourceModel\Order\Shipment\Track\Collection'; - /** - * @var MyParcelCollection - */ - public $myParcelCollection; - - /** - * @var \Magento\Framework\Module\Manager - */ - protected $moduleManager; - - /** - * @var \MyParcelNL\Magento\Model\Source\SourceItem - */ - protected $sourceItem; - - /** - * @var \Magento\Framework\App\RequestInterface - */ - public $request = null; - - /** - * @var TrackSender - */ - protected $trackSender; - - /** - * @var ObjectManagerInterface - */ - protected $objectManager; - - /** - * @var Order\Shipment\Track - */ - protected $modelTrack; - - /** - * @var \Magento\Framework\App\AreaList - */ - protected $areaList; - /** - * @var \Magento\Framework\Message\ManagerInterface $messageManager - */ - protected $messageManager; - - /** - * @var \MyParcelNL\Magento\Helper\Data - */ - protected $configService; + public MyParcelCollection $myParcelCollection; + public ?RequestInterface $request = null; + protected Manager $moduleManager; + protected SourceItem $sourceItem; + protected TrackSender $trackSender; + protected ObjectManagerInterface $objectManager; + protected Order\Shipment\Track $modelTrack; + protected AreaList $areaList; + protected ManagerInterface $messageManager; + protected ConfigService $configService; /** * @var array */ protected $options = [ 'create_track_if_one_already_exist' => true, - 'request_type' => 'download', - 'package_type' => 'default', - 'carrier' => 'postnl', - 'positions' => null, - 'signature' => null, - 'only_recipient' => null, - 'return' => null, - 'large_format' => null, - 'age_check' => null, - 'insurance' => null, - 'label_amount' => NewShipment::DEFAULT_LABEL_AMOUNT, - 'digital_stamp_weight' => null, - 'return_in_the_box' => false, - 'same_day_delivery' => false, + 'request_type' => 'download', + 'package_type' => 'default', + 'carrier' => 'postnl', + 'positions' => null, + 'signature' => null, + 'only_recipient' => null, + 'return' => null, + 'large_format' => null, + 'age_check' => null, + 'insurance' => null, + 'label_amount' => NewShipment::DEFAULT_LABEL_AMOUNT, + 'digital_stamp_weight' => null, + 'return_in_the_box' => false, + 'same_day_delivery' => false, ]; /** * @var mixed @@ -125,29 +91,28 @@ abstract class MagentoCollection implements MagentoCollectionInterface /** * @param ObjectManagerInterface $objectManager - * @param null $request - * @param null $areaList + * @param null $request + * @param null $areaList */ public function __construct( ObjectManagerInterface $objectManager, $request = null, $areaList = null - ) { + ) + { // @todo; Adjust if there is a solution to the following problem: https://github.com/magento/magento2/pull/8413 if ($areaList) { $this->areaList = $areaList; } - $this->objectManager = $objectManager; - $this->moduleManager = $objectManager->get(Manager::class); - $this->request = $request; - $this->trackSender = $this->objectManager->get( - 'MyParcelNL\Magento\Model\Order\Email\Sender\TrackSender' - ); - $this->configService = $objectManager->create(ConfigService::class); - $this->weightService = $objectManager->create(WeightService::class); - $this->modelTrack = $objectManager->create(self::PATH_ORDER_TRACK); - $this->messageManager = $objectManager->create(self::PATH_MANAGER_INTERFACE); + $this->objectManager = $objectManager; + $this->moduleManager = $objectManager->get(Manager::class); + $this->request = $request; + $this->trackSender = $this->objectManager->get(TrackSender::class); + $this->configService = $objectManager->get(ConfigService::class); + $this->weightService = $objectManager->get(WeightService::class); + $this->modelTrack = $objectManager->create(self::PATH_ORDER_TRACK); + $this->messageManager = $objectManager->create(self::PATH_MANAGER_INTERFACE); $this->myParcelCollection = (new MyParcelCollection())->setUserAgents( ['Magento2' => $this->configService->getVersion()] ); @@ -241,30 +206,6 @@ public function addConsignment(BaseConsignment $consignment) return $this; } - /** - * @return string - */ - public function getApiKey(): string - { - return $this->configService->getApiKey(); - } - - /** - * @return string|null - */ - public function getExportMode(): ?string - { - return $this->configService->getExportMode(); - } - - /** - * @return bool - */ - public function apiKeyIsCorrect(): bool - { - return $this->configService->apiKeyIsCorrect(); - } - /** * Update sales_order table * @@ -278,7 +219,7 @@ public function getHtmlForGridColumns($orderId) * @todo; Adjust if there is a solution to the following problem: https://github.com/magento/magento2/pull/8413 */ // Temporarily fix to translate in cronjob - if (! empty($this->areaList)) { + if (!empty($this->areaList)) { $areaObject = $this->areaList->getArea(\Magento\Framework\App\Area::AREA_ADMINHTML); $areaObject->load(\Magento\Framework\App\Area::PART_TRANSLATE); } @@ -293,7 +234,7 @@ public function getHtmlForGridColumns($orderId) */ public function getHtmlForGridColumnsByTracks($tracks): array { - $data = ['track_status' => [], 'track_number' => []]; + $data = ['track_status' => [], 'track_number' => []]; $columnHtml = ['track_status' => '', 'track_number' => '']; foreach ($tracks as $track) { @@ -344,8 +285,8 @@ protected function setNewMagentoTrack($shipment) $track ->setOrderId($shipment->getOrderId()) ->setShipment($shipment) - ->setCarrierCode(TrackTraceHolder::MYPARCEL_CARRIER_CODE) - ->setTitle(TrackTraceHolder::MYPARCEL_TRACK_TITLE) + ->setCarrierCode(ConfigService::MYPARCEL_CARRIER_CODE) + ->setTitle(ConfigService::MYPARCEL_TRACK_TITLE) ->setQty($shipment->getTotalQty()) ->setTrackNumber(TrackAndTrace::VALUE_EMPTY) ->save(); @@ -399,7 +340,7 @@ public function syncMagentoToMyparcel(): self try { $this->myParcelCollection->addConsignmentByConsignmentIds( $consignmentIds, - $this->getApiKey() + $this->configService->getApiKey() ); } catch (\Exception $e) { $this->messageManager->addErrorMessage($e->getMessage()); @@ -416,7 +357,7 @@ public function syncMagentoToMyparcel(): self */ public function createMyParcelConcepts(): self { - if (! count($this->myParcelCollection)) { + if (!count($this->myParcelCollection)) { $this->messageManager->addWarningMessage(__('myparcelnl_magento_error_no_shipments_to_process')); return $this; } @@ -445,7 +386,7 @@ public function setNewMyParcelTracks(): self $multiColloConsignments = []; /** - * @var Order\Shipment $shipment + * @var Order\Shipment $shipment * @var Order\Shipment\Track $magentoTrack */ foreach ($shipments as $shipment) { @@ -468,7 +409,7 @@ public function setNewMyParcelTracks(): self $multiColloConsignments[$parentId] = [ 'consignment' => $consignment, - 'colli' => 1, + 'colli' => 1, ]; } } @@ -485,7 +426,7 @@ protected function addGroupedConsignments(array $multiColloConsignments): self { foreach ($multiColloConsignments as $multiColloConsignment) { $consignment = $multiColloConsignment['consignment']; - $quantity = $multiColloConsignment['colli']; + $quantity = $multiColloConsignment['colli']; if (1 < $quantity && $this->canUseMultiCollo($consignment)) { $this->myParcelCollection->addMultiCollo($consignment, $quantity); @@ -500,7 +441,7 @@ protected function addGroupedConsignments(array $multiColloConsignments): self /** * @param \MyParcelNL\Sdk\src\Model\Consignment\AbstractConsignment $consignment - * @param int $quantity + * @param int $quantity * * @throws \MyParcelNL\Sdk\src\Exception\MissingFieldException */ @@ -562,7 +503,7 @@ public function updateMagentoTrack(): self $shipments = $this->getShipmentsCollection(); foreach ($shipments as $shipment) { - $consignments = $this->myParcelCollection->getConsignmentsByReferenceId($shipment->getEntityId()); + $consignments = $this->myParcelCollection->getConsignmentsByReferenceId($shipment->getEntityId()); $trackCollection = $this->getTrackByShipment($shipment)->getItems(); foreach ($trackCollection as $magentoTrack) { @@ -570,13 +511,13 @@ public function updateMagentoTrack(): self $magentoTrack->getData('myparcel_consignment_id') ); - if (! $myParcelTrack) { + if (!$myParcelTrack) { if ($consignments->isEmpty()) { continue; } $myParcelTrack = $consignments->pop(); - if (! $myParcelTrack->getConsignmentId()) { + if (!$myParcelTrack->getConsignmentId()) { continue; } $magentoTrack->setData('myparcel_consignment_id', $myParcelTrack->getConsignmentId()); @@ -621,12 +562,12 @@ protected function updateOrderGrid(): self { $shipments = $this->getShipmentsCollection(); - if (! $shipments) { + if (!$shipments) { return $this; } foreach ($shipments as $shipment) { - if (! $shipment || ! method_exists($shipment, 'getOrder')) { + if (!$shipment || !method_exists($shipment, 'getOrder')) { continue; } @@ -645,7 +586,7 @@ protected function updateOrderGrid(): self return $this; } - abstract protected function getShipmentsCollection(): \Magento\Sales\Model\ResourceModel\Order\Shipment\Collection; + abstract protected function getShipmentsCollection(): ShipmentCollection; /** * @param $orderId @@ -656,12 +597,12 @@ private function getTracksCollectionByOrderId($orderId): array { /** @var \Magento\Framework\App\ResourceConnection $connection */ $connection = $this->objectManager->create(ResourceConnection::class); - $conn = $connection->getConnection(); - $select = $conn->select() - ->from( - ['main_table' => $connection->getTableName('sales_shipment_track')] - ) - ->where('main_table.order_id=?', $orderId); + $conn = $connection->getConnection(); + $select = $conn->select() + ->from( + ['main_table' => $connection->getTableName('sales_shipment_track')] + ) + ->where('main_table.order_id=?', $orderId); return $conn->fetchAll($select); } @@ -677,7 +618,7 @@ protected function getMyparcelConsignmentIdsForShipments(): array foreach ($shipments as $shipment) { $trackCollection = $shipment->getAllTracks(); foreach ($trackCollection as $magentoTrack) { - $consignmentId = (int) $magentoTrack->getData('myparcel_consignment_id'); + $consignmentId = (int)$magentoTrack->getData('myparcel_consignment_id'); if ($consignmentId) { $consignmentIds[] = $consignmentId; } @@ -711,7 +652,7 @@ public function canUseMultiCollo(AbstractConsignment $consignment): bool */ private function setSourceItemWhenInventoryApiEnabled(): void { - if (! $this->moduleManager->isEnabled('Magento_InventoryApi')) { + if (!$this->moduleManager->isEnabled('Magento_InventoryApi')) { return; } $this->sourceItem = $this->objectManager->get(SourceItem::class); diff --git a/Model/Sales/MagentoOrderCollection.php b/Model/Sales/MagentoOrderCollection.php index 4f47d545..0d198476 100755 --- a/Model/Sales/MagentoOrderCollection.php +++ b/Model/Sales/MagentoOrderCollection.php @@ -161,12 +161,12 @@ public function setMagentoTrack(): MagentoOrderCollection */ public function setFulfilment(): self { - $apiKey = $this->getApiKey(); + $apiKey = $this->configService->getApiKey(); $orderCollection = (new OrderCollection())->setApiKey($apiKey); $orderLines = new Collection(); foreach ($this->getOrders() as $magentoOrder) { - $defaultOptions = new DefaultOptions($magentoOrder, $this->configService); + $defaultOptions = new DefaultOptions($magentoOrder); $myparcelDeliveryOptions = $magentoOrder['myparcel_delivery_options'] ?? ''; $deliveryOptions = json_decode($myparcelDeliveryOptions, true); $selectedCarrier = $deliveryOptions['carrier'] ?? $this->options['carrier'] ?? CarrierPostNL::NAME; @@ -269,7 +269,7 @@ public function setFulfilment(): self */ private function saveOrderNotes(): void { - $notes = (new OrderNotesCollection())->setApiKey($this->getApiKey()); + $notes = (new OrderNotesCollection())->setApiKey($this->configService->getApiKey()); $this->myParcelCollection->each(function(FulfilmentOrder $order) use ($notes) { @@ -551,7 +551,7 @@ protected function getShipmentsCollection(): \Magento\Sales\Model\ResourceModel\ $orderIds[] = $order->getEntityId(); } - $shipmentsCollection = $this->objectManager->get(MagentoShipmentCollection::PATH_MODEL_SHIPMENT); + $shipmentsCollection = $this->objectManager->get(MagentoShipmentCollection::PATH_MODEL_SHIPMENT_COLLECTION); $shipmentsCollection->addAttributeToFilter('order_id', ['in' => $orderIds]); return $shipmentsCollection; diff --git a/Model/Sales/TrackTraceHolder.php b/Model/Sales/TrackTraceHolder.php index 6f59edba..5ed3c181 100755 --- a/Model/Sales/TrackTraceHolder.php +++ b/Model/Sales/TrackTraceHolder.php @@ -44,14 +44,6 @@ */ 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'; - /** * @var \MyParcelNL\Magento\Model\Source\DefaultOptions */ @@ -105,15 +97,11 @@ public function __construct( Order $order ) { $this->objectManager = $objectManager; - $this->configService = $objectManager->create(ConfigService::class); - $this->weightService = $objectManager->create(WeightService::class); - $this->deliveryCostsService = $objectManager->create(DeliveryCostsService::class); + $this->configService = $objectManager->get(ConfigService::class); + $this->weightService = $objectManager->get(WeightService::class); + $this->deliveryCostsService = $objectManager->get(DeliveryCostsService::class); $this->messageManager = $this->objectManager->create('Magento\Framework\Message\ManagerInterface'); - self::$defaultOptions = new DefaultOptions( - $order, - $this->configService, - $this->weightService - ); + self::$defaultOptions = new DefaultOptions($order); } /** @@ -269,8 +257,8 @@ public function createTrackTraceFromShipment(Shipment $shipment) $this->mageTrack ->setOrderId($shipment->getOrderId()) ->setShipment($shipment) - ->setCarrierCode(self::MYPARCEL_CARRIER_CODE) - ->setTitle(self::MYPARCEL_TRACK_TITLE) + ->setCarrierCode(ConfigService::MYPARCEL_CARRIER_CODE) + ->setTitle(ConfigService::MYPARCEL_TRACK_TITLE) ->setQty($shipment->getTotalQty()) ->setTrackNumber(TrackAndTrace::VALUE_EMPTY); diff --git a/Model/Settings/AccountSettings.php b/Model/Settings/AccountSettings.php index 4ebba166..15c5de6b 100644 --- a/Model/Settings/AccountSettings.php +++ b/Model/Settings/AccountSettings.php @@ -12,35 +12,16 @@ use MyParcelNL\Sdk\src\Model\Account\Shop; use MyParcelNL\Sdk\src\Model\BaseModel; use MyParcelNL\Sdk\src\Model\Carrier\AbstractCarrier; +use MyParcelNL\Sdk\src\Model\Consignment\DropOffPoint; use MyParcelNL\Sdk\src\Support\Collection; class AccountSettings extends BaseModel { - - /** - * @var - */ - protected $shop; - - /** - * @var - */ - protected $account; - - /** - * @var - */ - protected $carrier_options; - - /** - * @var - */ - protected $carrier_configurations; - - /** - * @var self - */ - private static $instance; + protected Shop $shop; + protected Account $account; + protected Collection $carrier_options; + protected Collection $carrier_configurations; + private static self $instance; /** * @throws \MyParcelNL\Sdk\src\Exception\ApiException @@ -60,7 +41,7 @@ public function __construct() } /** - * @return null|\MyParcelNL\Sdk\src\Model\Account\Account + * @return null|Account */ public function getAccount(): ?Account { @@ -68,9 +49,9 @@ public function getAccount(): ?Account } /** - * @param \MyParcelNL\Sdk\src\Model\Carrier\AbstractCarrier $carrier + * @param AbstractCarrier $carrier * - * @return null|\MyParcelNL\Sdk\src\Model\Account\CarrierConfiguration + * @return null|CarrierConfiguration */ public function getCarrierConfigurationByCarrier(AbstractCarrier $carrier): ?CarrierConfiguration { @@ -87,7 +68,7 @@ static function (CarrierConfiguration $carrierConfiguration) use ($carrier) { } /** - * @return \MyParcelNL\Sdk\src\Model\Account\CarrierConfiguration[]|\MyParcelNL\Sdk\src\Support\Collection + * @return CarrierConfiguration[]|Collection */ public function getCarrierConfigurations(): Collection { @@ -96,7 +77,7 @@ public function getCarrierConfigurations(): Collection /** c * - * @return \MyParcelNL\Sdk\src\Model\Account\CarrierOptions[]|\MyParcelNL\Sdk\src\Support\Collection + * @return \MyParcelNL\Sdk\src\Model\Account\CarrierOptions[]|Collection */ public function getCarrierOptions(): Collection { @@ -104,7 +85,7 @@ public function getCarrierOptions(): Collection } /** - * @param \MyParcelNL\Sdk\src\Model\Carrier\AbstractCarrier $carrier + * @param AbstractCarrier $carrier * * @return null|\MyParcelNL\Sdk\src\Model\Account\CarrierOptions */ @@ -123,7 +104,7 @@ static function (CarrierOptions $carrierOptions) use ($carrier) { } /** - * @return null|\MyParcelNL\Sdk\src\Model\Account\Shop + * @return null|Shop */ public function getShop(): ?Shop { @@ -131,7 +112,27 @@ public function getShop(): ?Shop } /** - * @param \MyParcelNL\Sdk\src\Support\Collection $settings + * @throws \Exception + */ + public function getDropOffPoint(AbstractCarrier $carrier): ?DropOffPoint + { + $carrierConfiguration = $this->getCarrierConfigurationByCarrier($carrier); + + if (! $carrierConfiguration) { + return null; + } + + $dropOffPoint = $carrierConfiguration->getDefaultDropOffPoint(); + + if ($dropOffPoint && null === $dropOffPoint->getNumberSuffix()) { + $dropOffPoint->setNumberSuffix(''); + } + + return $dropOffPoint; + } + + /** + * @param Collection $settings * * @return void */ diff --git a/Model/Source/AgeCheckNo.php b/Model/Source/AgeCheckNo.php index b2d18bbe..c48e9759 100755 --- a/Model/Source/AgeCheckNo.php +++ b/Model/Source/AgeCheckNo.php @@ -16,8 +16,6 @@ namespace MyParcelNL\Magento\Model\Source; use Magento\Framework\Data\OptionSourceInterface; -use Magento\Sales\Model\Order; -use MyParcelNL\Magento\Helper\Data; use MyParcelNL\Magento\Service\Config\ConfigService; use MyParcelNL\Sdk\src\Model\Carrier\CarrierPostNL; @@ -27,10 +25,7 @@ */ class AgeCheckNo implements OptionSourceInterface { - /** - * @var Data - */ - static private $helper; + static private ConfigService $configService; /** * @param ConfigService $configService diff --git a/Model/Source/AgeCheckYes.php b/Model/Source/AgeCheckYes.php index 192f817d..519f113f 100755 --- a/Model/Source/AgeCheckYes.php +++ b/Model/Source/AgeCheckYes.php @@ -17,7 +17,6 @@ use Magento\Framework\Data\OptionSourceInterface; use Magento\Sales\Model\Order; -use MyParcelNL\Magento\Helper\Data; use MyParcelNL\Magento\Service\Config\ConfigService; use MyParcelNL\Sdk\src\Model\Carrier\CarrierPostNL; @@ -27,10 +26,7 @@ */ class AgeCheckYes implements OptionSourceInterface { - /** - * @var Data - */ - static private $configService; + static private ConfigService $configService; /** * Insurance constructor. diff --git a/Model/Source/DefaultOptions.php b/Model/Source/DefaultOptions.php index 7b7808d6..df00f77e 100755 --- a/Model/Source/DefaultOptions.php +++ b/Model/Source/DefaultOptions.php @@ -14,6 +14,7 @@ namespace MyParcelNL\Magento\Model\Source; use Exception; +use Magento\Framework\App\ObjectManager; use Magento\Sales\Model\Order; use MyParcelNL\Magento\Model\Sales\Repository\PackageRepository; use MyParcelNL\Magento\Service\Config\ConfigService; @@ -59,13 +60,12 @@ class DefaultOptions /** * @param Order $order - * @param ConfigService $configService - * @param WeightService $weightService */ - public function __construct(Order $order, ConfigService $configService, WeightService $weightService) + public function __construct(Order $order) { - self::$configService = $configService; - self::$weightService = $weightService; + $objectManager = ObjectManager::getInstance(); + self::$configService = $objectManager->get(ConfigService::class); + self::$weightService = $objectManager->get(WeightService::class); self::$order = $order; try { self::$chosenOptions = DeliveryOptionsAdapterFactory::create( diff --git a/Model/Source/DigitalStampWeightOptions.php b/Model/Source/DigitalStampWeightOptions.php index 66e5a452..6fecca4a 100755 --- a/Model/Source/DigitalStampWeightOptions.php +++ b/Model/Source/DigitalStampWeightOptions.php @@ -16,8 +16,6 @@ namespace MyParcelNL\Magento\Model\Source; use Magento\Framework\Data\OptionSourceInterface; -use Magento\Sales\Model\Order; -use MyParcelNL\Magento\Helper\Data; use MyParcelNL\Magento\Service\Config\ConfigService; use MyParcelNL\Sdk\src\Model\Carrier\CarrierPostNL; @@ -27,9 +25,6 @@ */ class DigitalStampWeightOptions implements OptionSourceInterface { - /** - * @var Data - */ static private $configService; /** @@ -60,14 +55,12 @@ public function getDefault($option): bool */ public function toOptionArray() { - $digitalStampOptions = [ + return [ ['value' => 0, 'label' => __('No standard weight')], ['value' => 20, 'label' => __('0 - 20 gram')], ['value' => 50, 'label' => __('20 - 50 gram')], ['value' => 200, 'label' => __('50 - 350 gram')], ['value' => 2000, 'label' => __('350 - 2000 gram')] ]; - - return $digitalStampOptions; } } diff --git a/Model/Source/LargeFormatOptions.php b/Model/Source/LargeFormatOptions.php index 65a6d235..544a121e 100755 --- a/Model/Source/LargeFormatOptions.php +++ b/Model/Source/LargeFormatOptions.php @@ -5,25 +5,18 @@ namespace MyParcelNL\Magento\Model\Source; use Magento\Framework\Data\OptionSourceInterface; -use Magento\Sales\Model\Order; -use MyParcelNL\Magento\Helper\Data; +use MyParcelNL\Magento\Service\Config\ConfigService; class LargeFormatOptions implements OptionSourceInterface { - /** - * @var Data - */ - static private $helper; + static private ConfigService $configService; /** - * Insurance constructor. - * - * @param $order Order - * @param $helper Data + * @param $configService ConfigService */ - public function __construct(Data $helper) + public function __construct(ConfigService $configService) { - self::$helper = $helper; + self::$configService = $configService; } /** diff --git a/Observer/CreateConceptAfterInvoice.php b/Observer/CreateConceptAfterInvoice.php index 8327ecaf..ce37c60b 100644 --- a/Observer/CreateConceptAfterInvoice.php +++ b/Observer/CreateConceptAfterInvoice.php @@ -23,17 +23,15 @@ use Magento\Framework\Model\AbstractModel; use Magento\Sales\Model\Order\Shipment\Track; use Magento\Sales\Model\ResourceModel\Order\Collection; -use MyParcelNL\Magento\Helper\Data; +use MyParcelNL\Magento\Model\Sales\MagentoCollection; use MyParcelNL\Magento\Model\Sales\MagentoOrderCollection; use MyParcelNL\Magento\Model\Sales\MagentoShipmentCollection; -use MyParcelNL\Magento\Model\Sales\TrackTraceHolder; +use MyParcelNL\Magento\Service\Config\ConfigService; use MyParcelNL\Sdk\src\Exception\ApiException; use MyParcelNL\Sdk\src\Exception\MissingFieldException; class CreateConceptAfterInvoice implements ObserverInterface { - const DEFAULT_LABEL_AMOUNT = 1; - protected $orderFactory; /** @@ -56,10 +54,7 @@ class CreateConceptAfterInvoice implements ObserverInterface */ private $orderCollection; - /** - * @var Data - */ - private $helper; + private ConfigService $configService; /** * @var MagentoShipmentCollection @@ -78,12 +73,12 @@ class CreateConceptAfterInvoice implements ObserverInterface */ public function __construct(MagentoOrderCollection $orderCollection = null) { - $this->objectManager = ObjectManager::getInstance(); - $this->request = $this->objectManager->get('Magento\Framework\App\RequestInterface'); + $objectManager = ObjectManager::getInstance(); + //$this->request = $objectManager->get('Magento\Framework\App\RequestInterface'); $this->orderCollection = $orderCollection ?? new MagentoOrderCollection($this->objectManager, $this->request); - $this->helper = $this->objectManager->get('MyParcelNL\Magento\Helper\Data'); - $this->modelTrack = $this->objectManager->create('Magento\Sales\Model\Order\Shipment\Track'); - $this->orderFactory = $this->objectManager->get('\Magento\Sales\Model\Order'); + $this->configService = $objectManager->get(ConfigService::class); + //$this->modelTrack = $objectManager->create('Magento\Sales\Model\Order\Shipment\Track'); + //$this->orderFactory = $objectManager->get('\Magento\Sales\Model\Order'); } /** @@ -96,7 +91,7 @@ public function __construct(MagentoOrderCollection $orderCollection = null) */ public function execute(Observer $observer): self { - if ($this->helper->getGeneralConfig('print/create_concept_after_invoice')) { + if ($this->configService->getGeneralConfig('print/create_concept_after_invoice')) { $order = $observer ->getEvent() ->getInvoice() @@ -133,7 +128,7 @@ private function exportAccordingToMode($orderIds) ->setOptionsFromParameters() ->setNewMagentoShipment(); - if (TrackTraceHolder::EXPORT_MODE_PPS === $this->orderCollection->getExportMode()) { + if (ConfigService::EXPORT_MODE_PPS === $this->configService->getExportMode()) { $this->orderCollection->setFulfilment(); return $this; @@ -151,12 +146,12 @@ private function exportAccordingToMode($orderIds) /** * @param $orderIds int[] */ - private function addOrdersToCollection($orderIds) + private function addOrdersToCollection($orderIds): void { /** * @var Collection $collection */ - $collection = $this->objectManager->get(MagentoOrderCollection::PATH_MODEL_ORDER); + $collection = $this->objectManager->get(MagentoCollection::PATH_MODEL_ORDER_COLLECTION); $collection->addAttributeToFilter('entity_id', ['in' => $orderIds]); $this->orderCollection->setOrderCollection($collection); } diff --git a/Observer/NewShipment.php b/Observer/NewShipment.php index 351eb09e..fd3f6460 100755 --- a/Observer/NewShipment.php +++ b/Observer/NewShipment.php @@ -20,6 +20,7 @@ use Magento\Sales\Model\Order\Shipment; use MyParcelNL\Magento\Model\Sales\MagentoOrderCollection; use MyParcelNL\Magento\Model\Sales\TrackTraceHolder; +use MyParcelNL\Magento\Service\Config\ConfigService; class NewShipment implements ObserverInterface { @@ -58,7 +59,7 @@ class NewShipment implements ObserverInterface /** * @var \MyParcelNL\Magento\Helper\Data */ - private $helper; + private $configService; /** * NewShipment constructor. @@ -72,8 +73,7 @@ public function __construct(MagentoOrderCollection $orderCollection = null) $this->redirectFactory = $this->objectManager->get('Magento\Framework\Controller\Result\RedirectFactory'); $this->messageManager = $this->objectManager->get('Magento\Framework\Message\Manager'); $this->orderCollection = $orderCollection ?? new MagentoOrderCollection($this->objectManager, $this->request); - $this->helper = $this->objectManager->get('MyParcelNL\Magento\Helper\Data'); - $this->modelTrack = $this->objectManager->create('Magento\Sales\Model\Order\Shipment\Track'); + $this->configService = $this->objectManager->get(ConfigService::class); } /** @@ -127,7 +127,7 @@ private function setMagentoAndMyParcelTrack(Shipment $shipment): void while ($i <= $amount) { // Set MyParcel options - $trackTraceHolder = (new TrackTraceHolder($this->objectManager, $this->helper, $shipment->getOrder())) + $trackTraceHolder = (new TrackTraceHolder($this->objectManager, $shipment->getOrder())) ->createTrackTraceFromShipment($shipment); $trackTraceHolder->convertDataFromMagentoToApi($trackTraceHolder->mageTrack, $options); @@ -151,7 +151,7 @@ private function setMagentoAndMyParcelTrack(Shipment $shipment): void ); } - if (TrackTraceHolder::EXPORT_MODE_PPS === $this->orderCollection->getExportMode()) { + if (ConfigService::EXPORT_MODE_PPS === $this->configService->getExportMode()) { $this->exportEntireOrder($shipment); $this->updateTrackGrid($shipment, true); @@ -186,7 +186,7 @@ private function exportEntireOrder($shipment): void /** * @var \Magento\Sales\Model\ResourceModel\Order\Collection $collection */ - $collection = $this->objectManager->get(MagentoOrderCollection::PATH_MODEL_ORDER); + $collection = $this->objectManager->get(MagentoOrderCollection::PATH_MODEL_ORDER_COLLECTION); $collection->addAttributeToFilter('entity_id', ['in' => $orderId]); $this->orderCollection->setOrderCollection($collection); $this->orderCollection->setFulfilment(); diff --git a/Observer/SalesOrderStatusHistoryObserver.php b/Observer/SalesOrderStatusHistoryObserver.php index d879e961..82746f78 100644 --- a/Observer/SalesOrderStatusHistoryObserver.php +++ b/Observer/SalesOrderStatusHistoryObserver.php @@ -9,25 +9,18 @@ use Magento\Framework\Event\ObserverInterface; use Magento\Sales\Model\Order; use Magento\Sales\Model\Order\Status\History; +use MyParcelNL\Magento\Service\Config\ConfigService; use MyParcelNL\Sdk\src\Collection\Fulfilment\OrderNotesCollection; use MyParcelNL\Sdk\src\Model\Fulfilment\OrderNote; -use MyParcelNL\Magento\Helper\Data; class SalesOrderStatusHistoryObserver implements ObserverInterface { - /** - * @var \MyParcelNL\Magento\Helper\Data - */ - private $helper; - - /** - * @var \Magento\Framework\App\ObjectManager - */ - private $objectManager; + private ConfigService $configService; + private ObjectManager $objectManager; public function __construct() { - $this->objectManager = ObjectManager::getInstance(); - $this->helper = $this->objectManager->get(Data::class); + $this->objectManager = ObjectManager::getInstance(); + $this->configService = $this->objectManager->get(ConfigService::class); } /** @@ -57,7 +50,7 @@ public function execute(Observer $observer): self return $this; } - (new OrderNotesCollection())->setApiKey($this->helper->getApiKey()) + (new OrderNotesCollection())->setApiKey($this->configService->getApiKey()) ->push( new OrderNote([ 'orderUuid' => $uuid, diff --git a/Service/Config/ConfigService.php b/Service/Config/ConfigService.php index 275676a8..a155e1eb 100644 --- a/Service/Config/ConfigService.php +++ b/Service/Config/ConfigService.php @@ -181,7 +181,7 @@ public function apiKeyIsCorrect(): bool { $apiKey = $this->getApiKey(); - return $this->checkApiKeyService->setApiKey($apiKey) + return $this->checkApiKeyWebService->setApiKey($apiKey) ->apiKeyIsCorrect(); } diff --git a/Service/Weight/WeightService.php b/Service/Weight/WeightService.php index 0dd28e24..3a317d55 100644 --- a/Service/Weight/WeightService.php +++ b/Service/Weight/WeightService.php @@ -8,16 +8,13 @@ class WeightService { - public const DEFAULT_WEIGHT = 1000; + public const DEFAULT_WEIGHT = 1000; - /** - * @var ConfigService - */ - private $configService; + private ConfigService $configService; public function __construct(ConfigService $configService) { - $this->$configService = $configService; + $this->configService = $configService; } /** * Get the correct weight type diff --git a/Setup/UpgradeData.php b/Setup/UpgradeData.php index 326d0990..22975925 100644 --- a/Setup/UpgradeData.php +++ b/Setup/UpgradeData.php @@ -26,7 +26,7 @@ use Magento\Framework\Setup\ModuleContextInterface; use Magento\Framework\Setup\ModuleDataSetupInterface; use Magento\Framework\Setup\UpgradeDataInterface; -use MyParcelNL\Magento\Helper\Data; +use MyParcelNL\Magento\Service\Config\ConfigService; use MyParcelNL\Magento\Setup\Migrations\ReplaceDpzRange; use MyParcelNL\Magento\Setup\Migrations\ReplaceFitInMailbox; use MyParcelNL\Magento\Setup\Migrations\ReplaceDisableCheckout; @@ -777,7 +777,7 @@ public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface continue; } - foreach (Data::CARRIERS_XML_PATH_MAP as $carrierName => $carrierPath) { + foreach (ConfigService::CARRIERS_XML_PATH_MAP as $carrierName => $carrierPath) { echo "\nMigrating $carrierName for scope $scope ($scopeId)"; /** * update the carrier specific date settings to a single setting for later diff --git a/Ui/Component/Listing/Column/TrackActions.php b/Ui/Component/Listing/Column/TrackActions.php index 323eb6d1..d9b18349 100755 --- a/Ui/Component/Listing/Column/TrackActions.php +++ b/Ui/Component/Listing/Column/TrackActions.php @@ -43,7 +43,7 @@ public function __construct( ) { $this->urlBuilder = $urlBuilder; $objectManager = ObjectManager::getInstance(); - $this->configService = $objectManager->create(ConfigService::class); + $this->configService = $objectManager->get(ConfigService::class); parent::__construct($context, $uiComponentFactory, $components, $data); } From 17d298dc3b6df6663f369023611cdd6d1feb40bd Mon Sep 17 00:00:00 2001 From: Joeri van Veen Date: Fri, 27 Sep 2024 15:49:17 +0200 Subject: [PATCH 06/29] wip --- Helper/CustomsDeclarationFromOrder.php | 14 +++++++------- Model/Sales/MagentoOrderCollection.php | 5 +++-- Model/Sales/TrackTraceHolder.php | 17 ++++++++--------- Model/Settings/AccountSettings.php | 16 ++++++++-------- 4 files changed, 26 insertions(+), 26 deletions(-) diff --git a/Helper/CustomsDeclarationFromOrder.php b/Helper/CustomsDeclarationFromOrder.php index 736927fd..65335d16 100644 --- a/Helper/CustomsDeclarationFromOrder.php +++ b/Helper/CustomsDeclarationFromOrder.php @@ -3,6 +3,7 @@ namespace MyParcelNL\Magento\Helper; use Magento\Catalog\Model\Product; +use Magento\Framework\App\ObjectManager; use Magento\Framework\ObjectManagerInterface; use Magento\Sales\Model\Order; use MyParcelNL\Magento\Service\Costs\DeliveryCostsService; @@ -35,18 +36,17 @@ class CustomsDeclarationFromOrder /** * @var WeightService */ - private $WeightService; + private $weightService; /** * @param Order $order - * @param ObjectManagerInterface $objectManager - * @param WeightService $WeightService */ - public function __construct(Order $order, ObjectManagerInterface $objectManager, WeightService $WeightService) + public function __construct(Order $order) { + $objectManager = ObjectManager::getInstance(); $this->order = $order; $this->objectManager = $objectManager; - $this->WeightService = $WeightService; + $this->weightService = $objectManager->get(WeightService::class); } /** @@ -67,13 +67,13 @@ public function createCustomsDeclaration(): CustomsDeclaration } $amount = (float) $item->getQtyShipped() ? $item->getQtyShipped() : $item->getQtyOrdered(); - $totalWeight += $this->WeightService->convertToGrams($product->getWeight() * $amount); + $totalWeight += $this->weightService->convertToGrams($product->getWeight() * $amount); $description = Str::limit($product->getName(), AbstractConsignment::DESCRIPTION_MAX_LENGTH); $customsItem = (new MyParcelCustomsItem()) ->setDescription($description) ->setAmount($amount) - ->setWeight($this->WeightService->convertToGrams($product->getWeight())) + ->setWeight($this->weightService->convertToGrams($product->getWeight())) ->setItemValueArray([ 'amount' => DeliveryCostsService::getCentsByPrice($product->getPrice()), 'currency' => $this->order->getOrderCurrency()->getCode() ?? self::CURRENCY_EURO, diff --git a/Model/Sales/MagentoOrderCollection.php b/Model/Sales/MagentoOrderCollection.php index 0d198476..a48ea778 100755 --- a/Model/Sales/MagentoOrderCollection.php +++ b/Model/Sales/MagentoOrderCollection.php @@ -15,6 +15,7 @@ use MyParcelNL\Magento\Helper\CustomsDeclarationFromOrder; use MyParcelNL\Magento\Helper\ShipmentOptions; use MyParcelNL\Magento\Model\Source\DefaultOptions; +use MyParcelNL\Magento\Service\Config\ConfigService; use MyParcelNL\Magento\Service\Normalizer\ConsignmentNormalizer; use MyParcelNL\Sdk\src\Collection\Fulfilment\OrderCollection; use MyParcelNL\Sdk\src\Collection\Fulfilment\OrderNotesCollection; @@ -167,7 +168,7 @@ public function setFulfilment(): self foreach ($this->getOrders() as $magentoOrder) { $defaultOptions = new DefaultOptions($magentoOrder); - $myparcelDeliveryOptions = $magentoOrder['myparcel_delivery_options'] ?? ''; + $myparcelDeliveryOptions = $magentoOrder[ConfigService::FIELD_DELIVERY_OPTIONS] ?? ''; $deliveryOptions = json_decode($myparcelDeliveryOptions, true); $selectedCarrier = $deliveryOptions['carrier'] ?? $this->options['carrier'] ?? CarrierPostNL::NAME; $shipmentOptionsHelper = new ShipmentOptions( @@ -237,7 +238,7 @@ public function setFulfilment(): self $order->setOrderLines($orderLines); if (! in_array($this->shippingRecipient->getCc(), AbstractConsignment::EURO_COUNTRIES, true)) { - $customsDeclarationAdapter = new CustomsDeclarationFromOrder($this->order, $this->objectManager); + $customsDeclarationAdapter = new CustomsDeclarationFromOrder($this->order); $customsDeclaration = $customsDeclarationAdapter->createCustomsDeclaration(); $order->setCustomsDeclaration($customsDeclaration); } diff --git a/Model/Sales/TrackTraceHolder.php b/Model/Sales/TrackTraceHolder.php index 5ed3c181..ac5794e1 100755 --- a/Model/Sales/TrackTraceHolder.php +++ b/Model/Sales/TrackTraceHolder.php @@ -24,6 +24,7 @@ use Magento\Sales\Model\Order\Shipment\Track; use MyParcelNL\Magento\Adapter\DeliveryOptionsFromOrderAdapter; use MyParcelNL\Magento\Helper\ShipmentOptions; +use MyParcelNL\Magento\Model\Settings\AccountSettings; use MyParcelNL\Magento\Model\Source\DefaultOptions; use MyParcelNL\Magento\Service\Config\ConfigService; use MyParcelNL\Magento\Service\Costs\DeliveryCostsService; @@ -33,6 +34,7 @@ use MyParcelNL\Sdk\src\Exception\MissingFieldException; use MyParcelNL\Sdk\src\Factory\ConsignmentFactory; use MyParcelNL\Sdk\src\Factory\DeliveryOptionsAdapterFactory; +use MyParcelNL\Sdk\src\Model\Carrier\CarrierFactory; use MyParcelNL\Sdk\src\Model\Consignment\AbstractConsignment; use MyParcelNL\Sdk\src\Model\MyParcelCustomsItem; use RuntimeException; @@ -116,7 +118,6 @@ public function __construct( */ public function convertDataFromMagentoToApi(Track $magentoTrack, array $options): self { - throw new \Exception('refactor completely joeri'); $shipment = $magentoTrack->getShipment(); $address = $shipment->getShippingAddress(); $order = $shipment->getOrder(); @@ -135,8 +136,7 @@ public function convertDataFromMagentoToApi(Track $magentoTrack, array $options) $deliveryOptionsAdapter = DeliveryOptionsAdapterFactory::create((array) $deliveryOptions); } catch (BadMethodCallException $e) { // create new instance from unknown json data - $deliveryOptions = (new ConsignmentNormalizer((array) $deliveryOptions + $options))->normalize(); - $deliveryOptionsAdapter = new DeliveryOptionsFromOrderAdapter($deliveryOptions); + $deliveryOptionsAdapter = new DeliveryOptionsFromOrderAdapter((array) $deliveryOptions + $options); } $pickupLocationAdapter = $deliveryOptionsAdapter->getPickupLocation(); @@ -185,9 +185,9 @@ public function convertDataFromMagentoToApi(Track $magentoTrack, array $options) $options['package_type'] = $deliveryOptions['packageType']; } $packageType = $this->getPackageType($options, $magentoTrack, $address); -// $dropOffPoint = $this->configService->getDropOffPoint( -// CarrierFactory::createFromName($deliveryOptionsAdapter->getCarrier()) -// ); + $dropOffPoint = AccountSettings::getInstance()->getDropOffPoint( + CarrierFactory::createFromName($deliveryOptionsAdapter->getCarrier()) + ); $regionCode = $address->getRegionCode(); $state = $regionCode && strlen($regionCode) === 2 ? $regionCode : null; @@ -199,7 +199,7 @@ public function convertDataFromMagentoToApi(Track $magentoTrack, array $options) ->setEmail($address->getEmail()) ->setLabelDescription($this->shipmentOptionsHelper->getLabelDescription()) ->setDeliveryDate($this->configService->convertDeliveryDate($deliveryOptionsAdapter->getDate())) - ->setDeliveryType($this->configService->checkDeliveryType($deliveryOptionsAdapter->getDeliveryTypeId())) + ->setDeliveryType($deliveryOptionsAdapter->getDeliveryTypeId() ?? AbstractConsignment::DELIVERY_TYPE_STANDARD) ->setPackageType($packageType) ->setDropOffPoint($dropOffPoint) ->setOnlyRecipient($this->shipmentOptionsHelper->hasOnlyRecipient()) @@ -216,7 +216,7 @@ public function convertDataFromMagentoToApi(Track $magentoTrack, array $options) ) ->setSaveRecipientAddress(false); - if ($deliveryOptionsAdapter->isPickup() && $pickupLocationAdapter) { + if ($pickupLocationAdapter && $deliveryOptionsAdapter->isPickup()) { $this->consignment ->setPickupPostalCode($pickupLocationAdapter->getPostalCode()) ->setPickupStreet($pickupLocationAdapter->getStreet()) @@ -225,7 +225,6 @@ public function convertDataFromMagentoToApi(Track $magentoTrack, array $options) ->setPickupCountry($pickupLocationAdapter->getCountry()) ->setPickupLocationName($pickupLocationAdapter->getLocationName()) ->setPickupLocationCode($pickupLocationAdapter->getLocationCode()) - ->setPickupNetworkId($pickupLocationAdapter->getPickupNetworkId()) ->setReturn(false); if ($pickupLocationAdapter->getRetailNetworkId()) { diff --git a/Model/Settings/AccountSettings.php b/Model/Settings/AccountSettings.php index 15c5de6b..14a4c965 100644 --- a/Model/Settings/AccountSettings.php +++ b/Model/Settings/AccountSettings.php @@ -19,8 +19,8 @@ class AccountSettings extends BaseModel { protected Shop $shop; protected Account $account; - protected Collection $carrier_options; - protected Collection $carrier_configurations; + protected Collection $carrierOptions; + protected Collection $carrierConfigurations; private static self $instance; /** @@ -72,7 +72,7 @@ static function (CarrierConfiguration $carrierConfiguration) use ($carrier) { */ public function getCarrierConfigurations(): Collection { - return $this->carrier_configurations ?? new Collection(); + return $this->carrierConfigurations ?? new Collection(); } /** c @@ -81,7 +81,7 @@ public function getCarrierConfigurations(): Collection */ public function getCarrierOptions(): Collection { - return $this->carrier_options ?? new Collection(); + return $this->carrierOptions ?? new Collection(); } /** @@ -145,8 +145,8 @@ private function fillProperties(Collection $settings): void $this->shop = new Shop($shop); $account['shops'] = [$shop]; $this->account = new Account($account); - $this->carrier_options = (new Collection($carrierOptions))->mapInto(CarrierOptions::class); - $this->carrier_configurations = (new Collection($carrierConfigurations))->map(function (array $data) { + $this->carrierOptions = (new Collection($carrierOptions))->mapInto(CarrierOptions::class); + $this->carrierConfigurations = (new Collection($carrierConfigurations))->map(function (array $data) { return CarrierConfigurationFactory::create($data); }); } @@ -154,11 +154,11 @@ private function fillProperties(Collection $settings): void /** * Get the one instance of this class that is loaded or can be loaded. * - * @return \MyParcelNL\Magento\Model\Settings\AccountSettings + * @return AccountSettings */ public static function getInstance(): self { - if (null === static::$instance) { + if (!isset(static::$instance)) { static::$instance = new static(); } From 8d216bedfc82d12f78ebbe34e5e1b959f8b1951f Mon Sep 17 00:00:00 2001 From: Joeri van Veen Date: Fri, 27 Sep 2024 18:34:20 +0200 Subject: [PATCH 07/29] wip --- Helper/ShipmentOptions.php | 126 ++++++------- Model/Carrier/Carrier.php | 140 +++++++-------- Model/Sales/MagentoOrderCollection.php | 154 ++++++++-------- Model/Sales/TrackTraceHolder.php | 179 ++++++++++--------- Model/Settings/AccountSettings.php | 42 ++--- Service/Config/ConfigService.php | 67 ++----- Service/Date/DatingService.php | 40 +++++ Service/Normalizer/ConsignmentNormalizer.php | 31 ---- Ui/Component/Listing/Column/TrackActions.php | 67 +++---- 9 files changed, 417 insertions(+), 429 deletions(-) create mode 100644 Service/Date/DatingService.php delete mode 100644 Service/Normalizer/ConsignmentNormalizer.php diff --git a/Helper/ShipmentOptions.php b/Helper/ShipmentOptions.php index 002ca72e..68200ce0 100644 --- a/Helper/ShipmentOptions.php +++ b/Helper/ShipmentOptions.php @@ -4,27 +4,29 @@ use Magento\Framework\App\ObjectManager; use Magento\Framework\ObjectManagerInterface; +use Magento\Sales\Model\Order; use MyParcelNL\Magento\Model\Source\DefaultOptions; use MyParcelNL\Magento\Service\Config\ConfigService; +use MyParcelNL\Magento\Service\Date\DatingService; use MyParcelNL\Sdk\src\Model\Consignment\AbstractConsignment; use Magento\Framework\App\ResourceConnection; class ShipmentOptions { - private const INSURANCE = 'insurance'; - private const ONLY_RECIPIENT = 'only_recipient'; + private const INSURANCE = 'insurance'; + private const ONLY_RECIPIENT = 'only_recipient'; private const SAME_DAY_DELIVERY = 'same_day_delivery'; - private const SIGNATURE = 'signature'; - private const RETURN = 'return'; - private const AGE_CHECK = 'age_check'; - private const LARGE_FORMAT = 'large_format'; - private const HIDE_SENDER = 'hide_sender'; + private const SIGNATURE = 'signature'; + private const RETURN = 'return'; + private const AGE_CHECK = 'age_check'; + private const LARGE_FORMAT = 'large_format'; + private const HIDE_SENDER = 'hide_sender'; private const LABEL_DESCRIPTION = 'label_description'; - private const ORDER_NUMBER = '%order_nr%'; - private const DELIVERY_DATE = '%delivery_date%'; - private const PRODUCT_ID = '%product_id%'; - private const PRODUCT_NAME = '%product_name%'; - private const PRODUCT_QTY = '%product_qty%'; + private const ORDER_NUMBER = '%order_nr%'; + private const DELIVERY_DATE = '%delivery_date%'; + private const PRODUCT_ID = '%product_id%'; + private const PRODUCT_NAME = '%product_name%'; + private const PRODUCT_QTY = '%product_qty%'; /** * @var string @@ -32,12 +34,12 @@ class ShipmentOptions private $carrier; /** - * @var \MyParcelNL\Magento\Model\Source\DefaultOptions + * @var DefaultOptions */ private static $defaultOptions; /** - * @var \Magento\Framework\ObjectManagerInterface + * @var ObjectManagerInterface */ private $objectManager; @@ -47,38 +49,39 @@ class ShipmentOptions private $options; /** - * @var \MyParcelNL\Magento\Helper\Data + * @var Data */ private $configService; /** - * @var \Magento\Sales\Model\Order + * @var Order */ private $order; /** * @var string|null */ - private $cc; + private ?string $cc; + private DatingService $datingService; /** - * @param \MyParcelNL\Magento\Model\Source\DefaultOptions $defaultOptions - * @param \MyParcelNL\Magento\Helper\ConfigService $configService - * @param \Magento\Sales\Model\Order $order - * @param \Magento\Framework\ObjectManagerInterface $objectManager - * @param string $carrier - * @param array $options + * @param DefaultOptions $defaultOptions + * @param Order $order + * @param ObjectManagerInterface $objectManager + * @param string $carrier + * @param array $options */ public function __construct( - DefaultOptions $defaultOptions, - ConfigService $configService, - \Magento\Sales\Model\Order $order, - ObjectManagerInterface $objectManager, - string $carrier, - array $options = [] - ) { + DefaultOptions $defaultOptions, + Order $order, + ObjectManagerInterface $objectManager, + string $carrier, + array $options = [] + ) + { self::$defaultOptions = $defaultOptions; - $this->configService = $configService; + $this->configService = $objectManager->get(ConfigService::class); + $this->datingService = $objectManager->get(DatingService::class); $this->order = $order; $this->objectManager = $objectManager; $this->carrier = $carrier; @@ -177,7 +180,7 @@ public static function getAgeCheckFromProduct($products): ?bool 'age_check' ); - if (! isset($productAgeCheck) || '' === $productAgeCheck) { + if (!isset($productAgeCheck) || '' === $productAgeCheck) { $hasAgeCheck = null; } elseif ('1' === $productAgeCheck) { return true; @@ -188,9 +191,9 @@ public static function getAgeCheckFromProduct($products): ?bool } /** - * @param string $tableName - * @param string $entityId - * @param string $column + * @param string $tableName + * @param string $entityId + * @param string $column * * @return null|string */ @@ -215,8 +218,8 @@ public static function getAttributeValue(string $tableName, string $entityId, st /** * @param $connection - * @param string $tableName - * @param string $databaseColumn + * @param string $tableName + * @param string $databaseColumn * * @return mixed */ @@ -231,10 +234,10 @@ public static function getAttributeId($connection, string $tableName, string $da } /** - * @param object $connection - * @param string $tableName - * @param string $attributeId - * @param string $entityId + * @param object $connection + * @param string $tableName + * @param string $attributeId + * @param string $entityId * * @return string|null */ @@ -243,7 +246,8 @@ public static function getValueFromAttribute( string $tableName, string $attributeId, string $entityId - ): ?string { + ): ?string + { $sql = $connection ->select() ->from($tableName, ['value']) @@ -254,18 +258,18 @@ public static function getValueFromAttribute( } /** - * @param string $key - * @param array $options + * @param string $key + * @param array $options * * @return bool|null boolean value of the option named $key, or null when not set in $options */ public static function getValueOfOptionWhenSet(string $key, array $options): ?bool { - if (! isset($options[$key])) { + if (!isset($options[$key])) { return null; } - return (bool) $options[$key]; + return (bool)$options[$key]; } /** @@ -273,7 +277,7 @@ public static function getValueOfOptionWhenSet(string $key, array $options): ?bo */ public function hasLargeFormat(): bool { - if (! in_array($this->cc, AbstractConsignment::EURO_COUNTRIES)) { + if (!in_array($this->cc, AbstractConsignment::EURO_COUNTRIES)) { return false; } @@ -288,18 +292,18 @@ public function hasLargeFormat(): bool */ public function getLabelDescription(): string { - $checkoutData = $this->order->getData('myparcel_delivery_options'); $labelDescription = $this->configService->getGeneralConfig( 'print/label_description', $this->order->getStoreId() ); - if (! $labelDescription) { + if (!$labelDescription) { return ''; } + $deliveryOptions = $this->order->getData(ConfigService::FIELD_DELIVERY_OPTIONS); + $checkoutDate = json_decode($deliveryOptions, true)['date'] ?? null; $productInfo = $this->getItemsCollectionByShipmentId($this->order->getId()); - $deliveryDate = $checkoutData ? date('d-m-Y', strtotime($this->configService->convertDeliveryDate($checkoutData))) : null; $labelDescription = str_replace( [ self::ORDER_NUMBER, @@ -310,7 +314,7 @@ public function getLabelDescription(): string ], [ $this->order->getIncrementId(), - $this->configService->convertDeliveryDate($checkoutData) ? $deliveryDate : '', + $this->datingService->convertDeliveryDate($checkoutDate, 'd-m-Y') ?: '', $this->getProductInfo($productInfo, 'product_id'), $this->getProductInfo($productInfo, 'name'), $productInfo ? round($this->getProductInfo($productInfo, 'qty')) : null, @@ -318,12 +322,12 @@ public function getLabelDescription(): string $labelDescription ); - return (string) $labelDescription; + return (string)$labelDescription; } /** - * @param array $productInfo - * @param string $field + * @param array $productInfo + * @param string $field * * @return string|null */ @@ -343,14 +347,14 @@ private function getProductInfo(array $productInfo, string $field): ?string */ public function getItemsCollectionByShipmentId($shipmentId): array { - /** @var \Magento\Framework\App\ResourceConnection $connection */ + /** @var ResourceConnection $connection */ $connection = $this->objectManager->create(ResourceConnection::class); $conn = $connection->getConnection(); $select = $conn->select() - ->from( - ['main_table' => $connection->getTableName('sales_shipment_item')] - ) - ->where('main_table.parent_id=?', $shipmentId); + ->from( + ['main_table' => $connection->getTableName('sales_shipment_item')] + ) + ->where('main_table.parent_id=?', $shipmentId); return $conn->fetchAll($select); } @@ -364,11 +368,11 @@ public function getItemsCollectionByShipmentId($shipmentId): array */ private function optionIsEnabled($optionKey): bool { - if (! isset($this->options[$optionKey])) { + if (!isset($this->options[$optionKey])) { return self::$defaultOptions->hasDefault($optionKey, $this->carrier); } - return (bool) $this->options[$optionKey]; + return (bool)$this->options[$optionKey]; } /** diff --git a/Model/Carrier/Carrier.php b/Model/Carrier/Carrier.php index e9528098..4b0f9270 100644 --- a/Model/Carrier/Carrier.php +++ b/Model/Carrier/Carrier.php @@ -19,20 +19,35 @@ namespace MyParcelNL\Magento\Model\Carrier; use Composer\Config; +use Magento\CatalogInventory\Api\StockRegistryInterface; use Magento\Checkout\Model\Session; +use Magento\Directory\Helper\Data; +use Magento\Directory\Model\CountryFactory; +use Magento\Directory\Model\CurrencyFactory; +use Magento\Directory\Model\RegionFactory; use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\DataObject; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Framework\Phrase; use Magento\Framework\Xml\Security; +use Magento\OfflineShipping\Model\Carrier\Freeshipping; use Magento\Quote\Model\Quote\Address\RateRequest; +use Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory; +use Magento\Quote\Model\Quote\Address\RateResult\Method; use Magento\Quote\Model\Quote\Address\RateResult\MethodFactory; use Magento\Shipping\Model\Carrier\AbstractCarrier; use Magento\Shipping\Model\Carrier\CarrierInterface; +use Magento\Shipping\Model\Rate\ResultFactory; +use Magento\Shipping\Model\Simplexml\ElementFactory; +use Magento\Shipping\Model\Tracking\Result\StatusFactory; use MyParcelNL\Magento\Model\Sales\Repository\PackageRepository; use MyParcelNL\Magento\Service\Config\ConfigService; use MyParcelNL\Magento\Service\Costs\DeliveryCostsService; use MyParcelNL\Sdk\src\Adapter\DeliveryOptions\DeliveryOptionsV3Adapter; use MyParcelNL\Sdk\src\Factory\DeliveryOptionsAdapterFactory; use Psr\Log\LoggerInterface; +use Throwable; class Carrier extends AbstractCarrier implements CarrierInterface { @@ -50,41 +65,42 @@ class Carrier extends AbstractCarrier implements CarrierInterface /** * Carrier constructor. * - * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig - * @param \Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory $rateErrorFactory - * @param \Psr\Log\LoggerInterface $logger - * @param Security $xmlSecurity - * @param \Magento\Shipping\Model\Simplexml\ElementFactory $xmlElFactory - * @param \Magento\Shipping\Model\Rate\ResultFactory $rateFactory - * @param \Magento\Quote\Model\Quote\Address\RateResult\MethodFactory $rateMethodFactory - * @param \Magento\Shipping\Model\Tracking\ResultFactory $trackFactory - * @param \Magento\Shipping\Model\Tracking\Result\ErrorFactory $trackErrorFactory - * @param \Magento\Shipping\Model\Tracking\Result\StatusFactory $trackStatusFactory - * @param \Magento\Directory\Model\RegionFactory $regionFactory - * @param \Magento\Directory\Model\CountryFactory $countryFactory - * @param \Magento\Directory\Model\CurrencyFactory $currencyFactory - * @param \Magento\Directory\Helper\Data $directoryData - * @param \Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry - * @param \Magento\Checkout\Model\Session $session - * @param PackageRepository $package - * @param array $data + * @param ScopeConfigInterface $scopeConfig + * @param ErrorFactory $rateErrorFactory + * @param LoggerInterface $logger + * @param Security $xmlSecurity + * @param ElementFactory $xmlElFactory + * @param ResultFactory $rateFactory + * @param MethodFactory $rateMethodFactory + * @param \Magento\Shipping\Model\Tracking\ResultFactory $trackFactory + * @param \Magento\Shipping\Model\Tracking\Result\ErrorFactory $trackErrorFactory + * @param StatusFactory $trackStatusFactory + * @param RegionFactory $regionFactory + * @param CountryFactory $countryFactory + * @param CurrencyFactory $currencyFactory + * @param Data $directoryData + * @param StockRegistryInterface $stockRegistry + * @param Session $session + * @param PackageRepository $package + * @param array $data * - * @throws \Magento\Framework\Exception\LocalizedException - * @throws \Magento\Framework\Exception\NoSuchEntityException + * @throws LocalizedException + * @throws NoSuchEntityException */ public function __construct( ScopeConfigInterface $scopeConfig, - \Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory $rateErrorFactory, - LoggerInterface $logger, - ConfigService $configService, + ErrorFactory $rateErrorFactory, + LoggerInterface $logger, + ConfigService $configService, DeliveryCostsService $deliveryCostsService, - \Magento\Shipping\Model\Rate\ResultFactory $rateFactory, - MethodFactory $rateMethodFactory, - Session $session, - PackageRepository $package, - \Magento\OfflineShipping\Model\Carrier\Freeshipping $freeShipping, - array $data = [] - ) { + ResultFactory $rateFactory, + MethodFactory $rateMethodFactory, + Session $session, + PackageRepository $package, + Freeshipping $freeShipping, + array $data = [] + ) + { parent::__construct( $scopeConfig, $rateErrorFactory, @@ -94,14 +110,14 @@ public function __construct( //$this->quote = $session->getQuote(); try { $this->deliveryOptions = DeliveryOptionsAdapterFactory::create(json_decode($session->getQuote()->getData('myparcel_delivery_options'), true)); - } catch (\Throwable $e) { + } catch (Throwable $e) { $this->deliveryOptions = DeliveryOptionsAdapterFactory::create(DeliveryOptionsV3Adapter::DEFAULTS); } - $this->package = $package; - $this->rateResultFactory = $rateFactory; - $this->rateMethodFactory = $rateMethodFactory; - $this->_freeShipping = $freeShipping; - $this->configService = $configService; + $this->package = $package; + $this->rateResultFactory = $rateFactory; + $this->rateMethodFactory = $rateMethodFactory; + $this->_freeShipping = $freeShipping; + $this->configService = $configService; $this->deliveryCostsService = $deliveryCostsService; } @@ -122,26 +138,27 @@ public function collectRates(RateRequest $request) $method->setCarrierTitle('MyParcel'); $method->setMethod('MyParcel'); $method->setMethodTitle($this->getMethodTitle()); - $method->setPrice((string) $this->getMethodAmount()); + $method->setPrice((string)$this->getMethodAmount()); $result->append($method); return $result; } - private function getMethodAmount(): float { - $path = ConfigService::CARRIERS_XML_PATH_MAP[$this->deliveryOptions->getCarrier()]??''; + private function getMethodAmount(): float + { + $path = ConfigService::CARRIERS_XML_PATH_MAP[$this->deliveryOptions->getCarrier()] ?? ''; $dinges = [ - "{$this->deliveryOptions->getDeliveryType()}/fee"=>true, - "{$this->deliveryOptions->getPackageType()}/fee"=>true, - 'delivery/signature_fee'=> $this->deliveryOptions->getShipmentOptions()->hasSignature(), - 'delivery/only_recipient_fee'=> $this->deliveryOptions->getShipmentOptions()->hasOnlyRecipient(), + "{$this->deliveryOptions->getDeliveryType()}/fee" => true, + "{$this->deliveryOptions->getPackageType()}/fee" => true, + 'delivery/signature_fee' => $this->deliveryOptions->getShipmentOptions()->hasSignature(), + 'delivery/only_recipient_fee' => $this->deliveryOptions->getShipmentOptions()->hasOnlyRecipient(), ]; $amount = $this->deliveryCostsService->getBasePrice(); - foreach ($dinges as $key=>$value) { + foreach ($dinges as $key => $value) { //echo $key, ' ', $value, ': ',$this->myParcelHelper->getCarrierConfig($key, $path), PHP_EOL; - if (! $value) continue; - $amount += (float) $this->configService->getConfigValue("$path$key"); + if (!$value) continue; + $amount += (float)$this->configService->getConfigValue("$path$key"); } //$bla = $this->myParcelHelper->getCarrierConfig('evening/fee', $path); return $amount; @@ -150,10 +167,11 @@ private function getMethodAmount(): float { $freeShippingIsAvailable = false; // todo // $this->_freeShipping->getConfigData('active') // todo: get actual price based on chosen and possible options for this quote / cart $amount = $freeShippingIsAvailable ? 0.00 : 10.00; -return $amount; + return $amount; } - private function getMethodTitle(): string { + private function getMethodTitle(): string + { // todo make a nice title from the options return var_export($this->deliveryOptions, true); } @@ -194,31 +212,11 @@ public function getAllowedMethods(): array return self::getMethods(); } -// /** -// * @param \Magento\Quote\Model\Quote\Address\RateRequest $result -// * @return mixed -// */ -// private function addShippingMethods($result) -// { -// $this->package->setDigitalStampSettings(); -// $this->package->setMailboxSettings(); -// -// foreach ($this->getAllowedMethods() as $alias => $settingPath) { -// $active = $this->configService->getConfigValue(ConfigService::XML_PATH_POSTNL_SETTINGS . $settingPath . 'active') === '1'; -// if ($active) { -// $method = $this->getShippingMethod($alias, $settingPath); -// $result->append($method); -// } -// } -// -// return $result; -// } - /** * @param $alias - * @param string $settingPath + * @param string $settingPath * - * @return \Magento\Quote\Model\Quote\Address\RateResult\Method + * @return Method */ private function getShippingMethod($alias, string $settingPath) { @@ -240,7 +238,7 @@ private function getShippingMethod($alias, string $settingPath) * If no title isset in config, get title from translation * * @param $settingPath - * @return \Magento\Framework\Phrase|mixed + * @return Phrase|mixed */ private function createTitle($settingPath) { diff --git a/Model/Sales/MagentoOrderCollection.php b/Model/Sales/MagentoOrderCollection.php index a48ea778..04a6a377 100755 --- a/Model/Sales/MagentoOrderCollection.php +++ b/Model/Sales/MagentoOrderCollection.php @@ -4,9 +4,16 @@ namespace MyParcelNL\Magento\Model\Sales; +use BadMethodCallException; +use DateTime; +use DateTimeZone; +use Exception; use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\App\ObjectManager; +use Magento\Framework\Exception\AlreadyExistsException; use Magento\Framework\Exception\LocalizedException; use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Shipment; use Magento\Sales\Model\ResourceModel\Order as OrderResource; use Magento\Sales\Model\ResourceModel\Order\Shipment as ShipmentResource; use Magento\Store\Model\ScopeInterface; @@ -19,12 +26,16 @@ use MyParcelNL\Magento\Service\Normalizer\ConsignmentNormalizer; use MyParcelNL\Sdk\src\Collection\Fulfilment\OrderCollection; use MyParcelNL\Sdk\src\Collection\Fulfilment\OrderNotesCollection; +use MyParcelNL\Sdk\src\Exception\AccountNotActiveException; +use MyParcelNL\Sdk\src\Exception\ApiException; +use MyParcelNL\Sdk\src\Exception\MissingFieldException; use MyParcelNL\Sdk\src\Factory\ConsignmentFactory; use MyParcelNL\Sdk\src\Factory\DeliveryOptionsAdapterFactory; use MyParcelNL\Sdk\src\Helper\SplitStreet; use MyParcelNL\Sdk\src\Model\Carrier\CarrierFactory; use MyParcelNL\Sdk\src\Model\Carrier\CarrierPostNL; use MyParcelNL\Sdk\src\Model\Consignment\AbstractConsignment; +use MyParcelNL\Sdk\src\Model\Consignment\PostNLConsignment; use MyParcelNL\Sdk\src\Model\Fulfilment\Order as FulfilmentOrder; use MyParcelNL\Sdk\src\Model\Fulfilment\OrderNote; use MyParcelNL\Sdk\src\Model\PickupLocation; @@ -40,29 +51,29 @@ class MagentoOrderCollection extends MagentoCollection { /** - * @var \Magento\Sales\Model\ResourceModel\Order\Collection + * @var OrderResource\Collection */ private $orders = null; /** - * @var \Magento\Sales\Model\Order + * @var Order */ private $order; /** - * @var \MyParcelNL\Sdk\src\Model\Recipient + * @var Recipient */ private $billingRecipient; /** - * @var \MyParcelNL\Sdk\src\Model\Recipient + * @var Recipient */ private $shippingRecipient; /** * Get all Magento orders * - * @return \Magento\Sales\Model\ResourceModel\Order\Collection + * @return OrderResource\Collection */ public function getOrders() { @@ -72,7 +83,7 @@ public function getOrders() /** * Set Magento collection * - * @param \Magento\Sales\Model\ResourceModel\Order\Collection|Order[] $orderCollection + * @param OrderResource\Collection|Order[] $orderCollection * * @return $this */ @@ -94,7 +105,7 @@ public function reload(): self $orders = []; foreach ($ids as $orderId) { - $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); + $objectManager = ObjectManager::getInstance(); $orders[] = $objectManager->create(Order::class)->load($orderId); } @@ -106,13 +117,13 @@ public function reload(): self /** * Set existing or create new Magento Track and set API consignment to collection * - * @throws \Exception + * @throws Exception * @throws LocalizedException */ public function setNewMagentoShipment(bool $notifyClientsByEmail = true): MagentoOrderCollection { /** @var Order $order */ - /** @var Order\Shipment $shipment */ + /** @var Shipment $shipment */ foreach ($this->getOrders() as $order) { if ($order->canShip()) { $this->createMagentoShipment($order, $notifyClientsByEmail); @@ -128,13 +139,13 @@ public function setNewMagentoShipment(bool $notifyClientsByEmail = true): Magent * Create new Magento Track and save order * * @return $this - * @throws \Exception + * @throws Exception */ public function setMagentoTrack(): MagentoOrderCollection { /** - * @var Order $order - * @var Order\Shipment $shipment + * @var Order $order + * @var Shipment $shipment */ foreach ($this->getShipmentsCollection() as $shipment) { $i = 1; @@ -157,7 +168,7 @@ public function setMagentoTrack(): MagentoOrderCollection /** * @return $this - * @throws \Exception + * @throws Exception * */ public function setFulfilment(): self @@ -173,7 +184,6 @@ public function setFulfilment(): self $selectedCarrier = $deliveryOptions['carrier'] ?? $this->options['carrier'] ?? CarrierPostNL::NAME; $shipmentOptionsHelper = new ShipmentOptions( $defaultOptions, - $this->configService, $magentoOrder, $this->objectManager, $selectedCarrier, @@ -185,16 +195,16 @@ public function setFulfilment(): self } $deliveryOptions['shipmentOptions'] = $shipmentOptionsHelper->getShipmentOptions(); + $deliveryOptions['carrier'] = $selectedCarrier; try { // create new instance from known json - $deliveryOptions['carrier'] = $selectedCarrier; - $deliveryOptionsAdapter = DeliveryOptionsAdapterFactory::create((array) $deliveryOptions); - } catch (\BadMethodCallException $e) { + $deliveryOptionsAdapter = DeliveryOptionsAdapterFactory::create((array)$deliveryOptions); + } catch (BadMethodCallException $e) { // create new instance from unknown json data - $deliveryOptions = (new ConsignmentNormalizer((array) $deliveryOptions))->normalize(); - $deliveryOptions['packageType'] = $deliveryOptions['packageType'] ?? AbstractConsignment::PACKAGE_TYPE_PACKAGE_NAME; - $deliveryOptionsAdapter = DeliveryOptionsAdapterFactory::create($deliveryOptions); + $deliveryOptions['packageType'] = $deliveryOptions['packageType'] ?? AbstractConsignment::PACKAGE_TYPE_PACKAGE_NAME; + $deliveryOptions['deliveryType'] = $deliveryOptions['deliveryType'] ?? AbstractConsignment::DELIVERY_TYPE_STANDARD_NAME; + $deliveryOptionsAdapter = DeliveryOptionsAdapterFactory::create($deliveryOptions); } $this->order = $magentoOrder; @@ -217,15 +227,15 @@ public function setFulfilment(): self if ($deliveryOptionsAdapter->isPickup()) { $pickupData = $deliveryOptionsAdapter->getPickupLocation(); $pickupLocation = new PickupLocation([ - 'cc' => $pickupData->getCountry(), - 'city' => $pickupData->getCity(), - 'postal_code' => $pickupData->getPostalCode(), - 'street' => $pickupData->getStreet(), - 'number' => $pickupData->getNumber(), - 'location_name' => $pickupData->getLocationName(), - 'location_code' => $pickupData->getLocationCode(), - 'retail_network_id' => $pickupData->getRetailNetworkId(), - ]); + 'cc' => $pickupData->getCountry(), + 'city' => $pickupData->getCity(), + 'postal_code' => $pickupData->getPostalCode(), + 'street' => $pickupData->getStreet(), + 'number' => $pickupData->getNumber(), + 'location_name' => $pickupData->getLocationName(), + 'location_code' => $pickupData->getLocationCode(), + 'retail_network_id' => $pickupData->getRetailNetworkId(), + ]); $order->setPickupLocation($pickupLocation); } @@ -237,7 +247,7 @@ public function setFulfilment(): self $order->setOrderLines($orderLines); - if (! in_array($this->shippingRecipient->getCc(), AbstractConsignment::EURO_COUNTRIES, true)) { + if (!in_array($this->shippingRecipient->getCc(), AbstractConsignment::EURO_COUNTRIES, true)) { $customsDeclarationAdapter = new CustomsDeclarationFromOrder($this->order); $customsDeclaration = $customsDeclarationAdapter->createCustomsDeclaration(); $order->setCustomsDeclaration($customsDeclaration); @@ -250,13 +260,13 @@ public function setFulfilment(): self try { $this->myParcelCollection = $orderCollection->save(); $this->setMagentoOrdersAsExported(); - } catch (\Exception $e) { + } catch (Exception $e) { $this->messageManager->addErrorMessage($e->getMessage()); } try { $this->saveOrderNotes(); - } catch(\Exception $e) { + } catch (Exception $e) { $this->messageManager->addErrorMessage($e->getMessage()); } @@ -264,21 +274,21 @@ public function setFulfilment(): self } /** - * @throws \MyParcelNL\Sdk\src\Exception\AccountNotActiveException - * @throws \MyParcelNL\Sdk\src\Exception\ApiException - * @throws \MyParcelNL\Sdk\src\Exception\MissingFieldException + * @throws AccountNotActiveException + * @throws ApiException + * @throws MissingFieldException */ private function saveOrderNotes(): void { $notes = (new OrderNotesCollection())->setApiKey($this->configService->getApiKey()); - $this->myParcelCollection->each(function(FulfilmentOrder $order) use ($notes) { + $this->myParcelCollection->each(function (FulfilmentOrder $order) use ($notes) { - $this->getAllNotesForOrder($order)->each(function(OrderNote $note) use ($notes) { + $this->getAllNotesForOrder($order)->each(function (OrderNote $note) use ($notes) { try { $note->validate(); $notes->push($note); - } catch (\Exception $e) { + } catch (Exception $e) { $this->messageManager->addWarningMessage( sprintf( 'Note `%s` not exported. %s', @@ -298,19 +308,19 @@ private function getAllNotesForOrder(FulfilmentOrder $fulfilmentOrder): OrderNot $notes = new OrderNotesCollection(); $orderUuid = $fulfilmentOrder->getUuid(); $magentoOrder = $this->objectManager->create(Order::class) - ->loadByIncrementId($fulfilmentOrder->getExternalIdentifier()); + ->loadByIncrementId($fulfilmentOrder->getExternalIdentifier()); foreach ($magentoOrder->getStatusHistoryCollection() as $status) { - if (! $status->getComment()) { + if (!$status->getComment()) { continue; } $notes->push( new OrderNote([ - 'orderUuid' => $orderUuid, - 'note' => $status->getComment(), - 'author' => 'webshop', - ]) + 'orderUuid' => $orderUuid, + 'note' => $status->getComment(), + 'author' => 'webshop', + ]) ); } @@ -322,7 +332,7 @@ private function setMagentoOrdersAsExported(): void foreach ($this->getOrders() as $magentoOrder) { $magentoOrder->setData('track_status', UpdateStatus::ORDER_STATUS_EXPORTED); - $fulfilmentOrder = $this->myParcelCollection->first(function(FulfilmentOrder $order) use ($magentoOrder){ + $fulfilmentOrder = $this->myParcelCollection->first(function (FulfilmentOrder $order) use ($magentoOrder) { return $order->getExternalIdentifier() === $magentoOrder->getIncrementId(); }); @@ -345,7 +355,7 @@ private function getTotalWeight(): int foreach ($this->order->getItems() as $item) { $product = $item->getProduct(); - if (! $product) { + if (!$product) { continue; } @@ -356,14 +366,14 @@ private function getTotalWeight(): int } /** - * @param string $format + * @param string $format * * @return string */ public function getLocalCreatedAtDate(string $format = 'Y-m-d H:i:s'): string { $scopeConfig = $this->objectManager->create(ScopeConfigInterface::class); - $datetime = \DateTime::createFromFormat('Y-m-d H:i:s', $this->order->getCreatedAt()); + $datetime = DateTime::createFromFormat('Y-m-d H:i:s', $this->order->getCreatedAt()); $timezone = $scopeConfig->getValue( 'general/locale/timezone', ScopeInterface::SCOPE_STORE, @@ -371,7 +381,7 @@ public function getLocalCreatedAtDate(string $format = 'Y-m-d H:i:s'): string ); if ($timezone) { - $storeTime = new \DateTimeZone($timezone); + $storeTime = new DateTimeZone($timezone); $datetime->setTimezone($storeTime); } @@ -397,7 +407,7 @@ public function setBillingRecipient(): self } /** - * @return \MyParcelNL\Sdk\src\Model\Recipient|null + * @return Recipient|null */ public function getBillingRecipient(): ?Recipient { @@ -406,15 +416,15 @@ public function getBillingRecipient(): ?Recipient /** * @return self - * @throws \Exception + * @throws Exception */ public function setShippingRecipient(): self { - $carrier = ConsignmentFactory::createByCarrierName(CarrierPostNL::NAME); - $street = implode( + $carrier = ConsignmentFactory::createByCarrierName(CarrierPostNL::NAME); + $street = implode( ' ', $this->order->getShippingAddress() - ->getStreet() ?? [] + ->getStreet() ?? [] ); $country = $this->order->getShippingAddress()->getCountryId(); @@ -428,16 +438,16 @@ public function setShippingRecipient(): self ->setPerson($this->getFullCustomerName()) ->setPostalCode($this->order->getShippingAddress()->getPostcode()) ->setStreet($streetParts->getStreet()) - ->setNumber((string) $streetParts->getNumber()) - ->setNumberSuffix((string) $streetParts->getNumberSuffix()) - ->setBoxNumber((string) $streetParts->getBoxNumber()) + ->setNumber((string)$streetParts->getNumber()) + ->setNumberSuffix((string)$streetParts->getNumberSuffix()) + ->setBoxNumber((string)$streetParts->getBoxNumber()) ->setPhone($this->order->getShippingAddress()->getTelephone()); return $this; } /** - * @return \MyParcelNL\Sdk\src\Model\Recipient|null + * @return Recipient|null */ public function getShippingRecipient(): ?Recipient { @@ -460,7 +470,7 @@ public function getFullCustomerName(): string * Set PDF content and convert status 'Concept' to 'Registered' * * @return $this - * @throws \Exception + * @throws Exception */ public function setPdfOfLabels(): self { @@ -473,7 +483,7 @@ public function setPdfOfLabels(): self * Download PDF directly * * @return $this - * @throws \Exception + * @throws Exception */ public function downloadPdfOfLabels(): self { @@ -487,7 +497,7 @@ public function downloadPdfOfLabels(): self * Update MyParcel collection * * @return $this - * @throws \Exception + * @throws Exception */ public function setLatestData(): self { @@ -502,8 +512,8 @@ public function setLatestData(): self /** * @return $this - * @throws \MyParcelNL\Sdk\src\Exception\ApiException - * @throws \MyParcelNL\Sdk\src\Exception\MissingFieldException|\MyParcelNL\Sdk\src\Exception\AccountNotActiveException + * @throws ApiException + * @throws MissingFieldException|AccountNotActiveException */ public function sendReturnLabelMails() { @@ -543,9 +553,9 @@ public function hasShipment(): bool } /** - * @return \Magento\Sales\Model\ResourceModel\Order\Shipment\Collection + * @return ShipmentResource\Collection */ - protected function getShipmentsCollection(): \Magento\Sales\Model\ResourceModel\Order\Shipment\Collection + protected function getShipmentsCollection(): ShipmentResource\Collection { $orderIds = []; foreach ($this->getOrders() as $order) { @@ -571,14 +581,14 @@ private function save(): void /** * Send shipment email with Track and trace variable * - * @param \Magento\Sales\Model\Order $order + * @param Order $order * * @return $this */ private function sendTrackEmailFromOrder(Order $order): self { /** - * @var \Magento\Sales\Model\Order\Shipment $shipment + * @var Shipment $shipment */ if ($this->trackSender->isEnabled() == false) { return $this; @@ -594,7 +604,7 @@ private function sendTrackEmailFromOrder(Order $order): self } /** - * @throws \Magento\Framework\Exception\AlreadyExistsException + * @throws AlreadyExistsException */ public function createMagentoShipment(Order $order, bool $notifyClientByEmail = true): void { @@ -609,11 +619,11 @@ public function createMagentoShipment(Order $order, bool $notifyClientByEmail = } foreach ($order->getAllItems() as $orderItem) { - if (! $orderItem->getQtyToShip() || $orderItem->getIsVirtual()) { + if (!$orderItem->getQtyToShip() || $orderItem->getIsVirtual()) { continue; } - $qtyShipped = $orderItem->getQtyToShip(); + $qtyShipped = $orderItem->getQtyToShip(); $shipmentItem = $convertOrder->itemToShipmentItem($orderItem)->setQty($qtyShipped); $shipment->addItem($shipmentItem); } @@ -624,7 +634,7 @@ public function createMagentoShipment(Order $order, bool $notifyClientByEmail = try { $this->objectManager->get(ShipmentResource::class)->save($shipment); $this->objectManager->get(OrderResource::class)->save($shipment->getOrder()); - } catch (\Exception $e) { + } catch (Exception $e) { if (preg_match('/' . MagentoOrderCollection::DEFAULT_ERROR_ORDER_HAS_NO_SOURCE . '/', $e->getMessage())) { $this->messageManager->addErrorMessage(__(MagentoOrderCollection::ERROR_ORDER_HAS_NO_SOURCE)); } else { @@ -636,7 +646,7 @@ public function createMagentoShipment(Order $order, bool $notifyClientByEmail = if ($notifyClientByEmail) { $this->objectManager->create('Magento\Shipping\Model\ShipmentNotifier') - ->notify($shipment); + ->notify($shipment); } } } diff --git a/Model/Sales/TrackTraceHolder.php b/Model/Sales/TrackTraceHolder.php index ac5794e1..f213ea22 100755 --- a/Model/Sales/TrackTraceHolder.php +++ b/Model/Sales/TrackTraceHolder.php @@ -18,6 +18,7 @@ use Magento\Framework\App\ObjectManager; use Magento\Framework\App\ResourceConnection; use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Message\ManagerInterface; use Magento\Framework\ObjectManagerInterface; use Magento\Sales\Model\Order; use Magento\Sales\Model\Order\Shipment; @@ -28,7 +29,7 @@ use MyParcelNL\Magento\Model\Source\DefaultOptions; use MyParcelNL\Magento\Service\Config\ConfigService; use MyParcelNL\Magento\Service\Costs\DeliveryCostsService; -use MyParcelNL\Magento\Service\Normalizer\ConsignmentNormalizer; +use MyParcelNL\Magento\Service\Date\DatingService; use MyParcelNL\Magento\Service\Weight\WeightService; use MyParcelNL\Magento\Ui\Component\Listing\Column\TrackAndTrace; use MyParcelNL\Sdk\src\Exception\MissingFieldException; @@ -47,12 +48,12 @@ class TrackTraceHolder { /** - * @var \MyParcelNL\Magento\Model\Source\DefaultOptions + * @var DefaultOptions */ private static $defaultOptions; /** - * @var \MyParcelNL\Sdk\src\Model\Consignment\AbstractConsignment|null + * @var AbstractConsignment|null */ public $consignment; @@ -62,7 +63,7 @@ class TrackTraceHolder public $mageTrack; /** - * @var \Magento\Framework\Message\ManagerInterface + * @var ManagerInterface */ protected $messageManager; @@ -71,10 +72,7 @@ class TrackTraceHolder */ private $carrier; - /** - * @var \MyParcelNL\Magento\Helper\Data - */ - private $configService; + private ConfigService $configService; /** * @var ObjectManagerInterface @@ -82,7 +80,7 @@ class TrackTraceHolder private $objectManager; /** - * @var \MyParcelNL\Magento\Helper\ShipmentOptions + * @var ShipmentOptions */ private $shipmentOptionsHelper; private WeightService $weightService; @@ -97,46 +95,48 @@ class TrackTraceHolder public function __construct( ObjectManagerInterface $objectManager, Order $order - ) { - $this->objectManager = $objectManager; - $this->configService = $objectManager->get(ConfigService::class); - $this->weightService = $objectManager->get(WeightService::class); + ) + { + $this->objectManager = $objectManager; + $this->configService = $objectManager->get(ConfigService::class); + $this->weightService = $objectManager->get(WeightService::class); + $this->datingService = $objectManager->get(DatingService::class); $this->deliveryCostsService = $objectManager->get(DeliveryCostsService::class); - $this->messageManager = $this->objectManager->create('Magento\Framework\Message\ManagerInterface'); - self::$defaultOptions = new DefaultOptions($order); + $this->messageManager = $this->objectManager->create('Magento\Framework\Message\ManagerInterface'); + self::$defaultOptions = new DefaultOptions($order); } /** * 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 + * @throws Exception * @throws LocalizedException */ public function convertDataFromMagentoToApi(Track $magentoTrack, array $options): self { - $shipment = $magentoTrack->getShipment(); - $address = $shipment->getShippingAddress(); - $order = $shipment->getOrder(); - $checkoutData = $order->getData('myparcel_delivery_options') ?? ''; - $deliveryOptions = json_decode($checkoutData, true) ?? []; - $deliveryOptions['carrier'] = $this->getCarrierFromOptions($options) + $shipment = $magentoTrack->getShipment(); + $address = $shipment->getShippingAddress(); + $order = $shipment->getOrder(); + $checkoutData = $order->getData('myparcel_delivery_options') ?? ''; + $deliveryOptions = json_decode($checkoutData, true) ?? []; + $deliveryOptions['carrier'] = $this->getCarrierFromOptions($options) ?? $deliveryOptions['carrier'] ?? DefaultOptions::getDefaultCarrier() - ->getName(); + ->getName(); - $totalWeight = $options['digital_stamp_weight'] !== null ? (int) $options['digital_stamp_weight'] - : (int) self::$defaultOptions->getDigitalStampDefaultWeight(); + $totalWeight = $options['digital_stamp_weight'] !== null ? (int)$options['digital_stamp_weight'] + : (int)self::$defaultOptions->getDigitalStampDefaultWeight(); try { // create new instance from known json - $deliveryOptionsAdapter = DeliveryOptionsAdapterFactory::create((array) $deliveryOptions); + $deliveryOptionsAdapter = DeliveryOptionsAdapterFactory::create((array)$deliveryOptions); } catch (BadMethodCallException $e) { // create new instance from unknown json data - $deliveryOptionsAdapter = new DeliveryOptionsFromOrderAdapter((array) $deliveryOptions + $options); + $deliveryOptionsAdapter = new DeliveryOptionsFromOrderAdapter((array)$deliveryOptions + $options); } $pickupLocationAdapter = $deliveryOptionsAdapter->getPickupLocation(); @@ -149,7 +149,6 @@ public function convertDataFromMagentoToApi(Track $magentoTrack, array $options) $this->carrier = $deliveryOptionsAdapter->getCarrier(); $this->shipmentOptionsHelper = new ShipmentOptions( self::$defaultOptions, - $this->configService, $order, $this->objectManager, $this->carrier, @@ -169,16 +168,16 @@ public function convertDataFromMagentoToApi(Track $magentoTrack, array $options) ->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() - ); + $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); + ->critical($errorHuman . '-' . $e); - $this->configService->setOrderStatus($magentoTrack->getOrderId(), Order::STATE_NEW); + $this->setOrderStatus($magentoTrack->getOrderId(), Order::STATE_NEW); } if (isset($deliveryOptions['packageType'])) { @@ -190,7 +189,7 @@ public function convertDataFromMagentoToApi(Track $magentoTrack, array $options) ); $regionCode = $address->getRegionCode(); - $state = $regionCode && strlen($regionCode) === 2 ? $regionCode : null; + $state = $regionCode && strlen($regionCode) === 2 ? $regionCode : null; $this->consignment ->setCity($address->getCity()) @@ -198,7 +197,7 @@ public function convertDataFromMagentoToApi(Track $magentoTrack, array $options) ->setPhone($address->getTelephone()) ->setEmail($address->getEmail()) ->setLabelDescription($this->shipmentOptionsHelper->getLabelDescription()) - ->setDeliveryDate($this->configService->convertDeliveryDate($deliveryOptionsAdapter->getDate())) + ->setDeliveryDate($this->datingService->convertDeliveryDate($deliveryOptionsAdapter->getDate())) ->setDeliveryType($deliveryOptionsAdapter->getDeliveryTypeId() ?? AbstractConsignment::DELIVERY_TYPE_STANDARD) ->setPackageType($packageType) ->setDropOffPoint($dropOffPoint) @@ -234,7 +233,7 @@ public function convertDataFromMagentoToApi(Track $magentoTrack, array $options) try { $this->convertDataForCdCountry($magentoTrack) - ->calculateTotalWeight($magentoTrack, $totalWeight); + ->calculateTotalWeight($magentoTrack, $totalWeight); } catch (Exception $e) { $this->messageManager->addErrorMessage($e->getMessage()); return $this; @@ -246,7 +245,7 @@ public function convertDataFromMagentoToApi(Track $magentoTrack, array $options) /** * Create Magento Track from Magento shipment * - * @param \Magento\Sales\Model\Order\Shipment $shipment + * @param Shipment $shipment * * @return $this */ @@ -264,6 +263,20 @@ public function createTrackTraceFromShipment(Shipment $shipment) return $this; } + /** + * @param int $orderId + * @param string $status + */ + private function setOrderStatus(int $orderId, string $status): void + { + $order = ObjectManager::getInstance() + ->create('\Magento\Sales\Model\Order') + ->load($orderId); + $order->setState($status) + ->setStatus($status); + $order->save(); + } + /** * Get country of origin from product settings or, if they are not found, from the MyParcel settings. * @@ -273,9 +286,9 @@ public function createTrackTraceFromShipment(Shipment $shipment) */ public function getCountryOfOrigin(int $product_id): string { - $product = - $this->objectManager->get('Magento\Catalog\Api\ProductRepositoryInterface') - ->getById($product_id); + $product + = $this->objectManager->get('Magento\Catalog\Api\ProductRepositoryInterface') + ->getById($product_id); $productCountryOfManufacture = $product->getCountryOfManufacture(); if ($productCountryOfManufacture) { @@ -288,10 +301,10 @@ public function getCountryOfOrigin(int $product_id): string /** * Override to check if key isset * - * @param null|string $apiKey + * @param null|string $apiKey * * @return $this - * @throws \Magento\Framework\Exception\LocalizedException + * @throws LocalizedException */ public function validateApiKey(?string $apiKey): self { @@ -307,12 +320,12 @@ public function validateApiKey(?string $apiKey): self } /** - * @param Order\Shipment\Track $magentoTrack - * @param int $totalWeight + * @param Order\Shipment\Track $magentoTrack + * @param int $totalWeight * * @return TrackTraceHolder * @throws LocalizedException - * @throws \Exception + * @throws Exception */ private function calculateTotalWeight(Track $magentoTrack, int $totalWeight = 0): self { @@ -326,16 +339,16 @@ private function calculateTotalWeight(Track $magentoTrack, int $totalWeight = 0) return $this; } - $weightFromSettings = (int) self::$defaultOptions->getDigitalStampDefaultWeight(); + $weightFromSettings = (int)self::$defaultOptions->getDigitalStampDefaultWeight(); if ($weightFromSettings) { $this->consignment->setPhysicalProperties(["weight" => $weightFromSettings]); return $this; } - $shipmentItems = - $magentoTrack->getShipment() - ->getItems(); + $shipmentItems + = $magentoTrack->getShipment() + ->getItems(); foreach ($shipmentItems as $shipmentItem) { $totalWeight += $shipmentItem['weight'] * $shipmentItem['qty']; @@ -348,36 +361,36 @@ private function calculateTotalWeight(Track $magentoTrack, int $totalWeight = 0) sprintf( 'Order %s can not be exported as digital stamp, no weights have been entered.', $magentoTrack->getShipment() - ->getOrder() - ->getIncrementId() + ->getOrder() + ->getIncrementId() ) ); } $this->consignment->setPhysicalProperties([ - 'weight' => $totalWeight, - ]); + 'weight' => $totalWeight, + ]); return $this; } /** - * @param Order\Shipment\Track $magentoTrack + * @param Order\Shipment\Track $magentoTrack * * @return $this * @throws LocalizedException * @throws MissingFieldException - * @throws \Exception + * @throws Exception */ private function convertDataForCdCountry(Track $magentoTrack) { - if (! $this->consignment->isCdCountry()) { + if (!$this->consignment->isCdCountry()) { return $this; } - if ($products = - $magentoTrack->getShipment() - ->getData('items')) { + if ($products + = $magentoTrack->getShipment() + ->getData('items')) { foreach ($products as $product) { $myParcelProduct = (new MyParcelCustomsItem()) ->setDescription($product->getName()) @@ -385,7 +398,7 @@ private function convertDataForCdCountry(Track $magentoTrack) ->setWeight($this->weightService->convertToGrams($product->getWeight()) ?: 1) ->setItemValue($this->deliveryCostsService->getCentsByPrice($product->getPrice())) ->setClassification( - (int) $this->getAttributeValue( + (int)$this->getAttributeValue( 'catalog_product_entity_int', $product['product_id'], 'classification' @@ -397,14 +410,14 @@ private function convertDataForCdCountry(Track $magentoTrack) } foreach ($magentoTrack->getShipment() - ->getItems() as $item) { + ->getItems() as $item) { $myParcelProduct = (new MyParcelCustomsItem()) ->setDescription($item->getName()) ->setAmount($item->getQty()) ->setWeight($this->weightService->convertToGrams($item->getWeight() * $item->getQty())) ->setItemValue($item->getPrice() * 100) ->setClassification( - (int) $this->getAttributeValue( + (int)$this->getAttributeValue( 'catalog_product_entity_int', $item->getProductId(), 'classification' @@ -419,12 +432,12 @@ private function convertDataForCdCountry(Track $magentoTrack) } /** - * @param Order\Shipment\Track $magentoTrack - * @param object $address - * @param array $options + * @param Order\Shipment\Track $magentoTrack + * @param object $address + * @param array $options * * @return bool - * @throws \Magento\Framework\Exception\LocalizedException + * @throws LocalizedException */ private function getAgeCheck(Track $magentoTrack, $address, array $options = []): bool { @@ -440,9 +453,9 @@ private function getAgeCheck(Track $magentoTrack, $address, array $options = []) } /** - * @param string $tableName - * @param string $entityId - * @param string $column + * @param string $tableName + * @param string $entityId + * @param string $column * * @return string|null */ @@ -466,7 +479,7 @@ private function getAttributeValue(string $tableName, string $entityId, string $ } /** - * @param array $options + * @param array $options * * @return null|string */ @@ -475,22 +488,22 @@ private function getCarrierFromOptions(array $options): ?string $carrier = null; if (array_key_exists('carrier', $options) && $options['carrier']) { - $carrier = - DefaultOptions::DEFAULT_OPTION_VALUE === $options['carrier'] ? self::$defaultOptions->getCarrier() - : $options['carrier']; + $carrier + = DefaultOptions::DEFAULT_OPTION_VALUE === $options['carrier'] ? self::$defaultOptions->getCarrier() + : $options['carrier']; } return $carrier; } /** - * @param array $options - * @param string $packageType - * @param Order\Shipment\Track $magentoTrack - * @param object $address + * @param array $options + * @param string $packageType + * @param Order\Shipment\Track $magentoTrack + * @param object $address * * @return int - * @throws \Magento\Framework\Exception\LocalizedException + * @throws LocalizedException */ private function getPackageType(array $options, Track $magentoTrack, $address): int { @@ -504,7 +517,7 @@ private function getPackageType(array $options, Track $magentoTrack, $address): $packageType = self::$defaultOptions->getPackageType(); } - if (! is_numeric($packageType)) { + if (!is_numeric($packageType)) { $packageType = AbstractConsignment::PACKAGE_TYPES_NAMES_IDS_MAP[$packageType] ?? self::$defaultOptions->getPackageType(); } diff --git a/Model/Settings/AccountSettings.php b/Model/Settings/AccountSettings.php index 14a4c965..cb1429e4 100644 --- a/Model/Settings/AccountSettings.php +++ b/Model/Settings/AccountSettings.php @@ -4,7 +4,11 @@ namespace MyParcelNL\Magento\Model\Settings; +use Exception; use MyParcelNL\Magento\Controller\Adminhtml\Settings\CarrierConfigurationImport; +use MyParcelNL\Sdk\src\Exception\AccountNotActiveException; +use MyParcelNL\Sdk\src\Exception\ApiException; +use MyParcelNL\Sdk\src\Exception\MissingFieldException; use MyParcelNL\Sdk\src\Factory\Account\CarrierConfigurationFactory; use MyParcelNL\Sdk\src\Model\Account\Account; use MyParcelNL\Sdk\src\Model\Account\CarrierConfiguration; @@ -24,16 +28,16 @@ class AccountSettings extends BaseModel private static self $instance; /** - * @throws \MyParcelNL\Sdk\src\Exception\ApiException - * @throws \MyParcelNL\Sdk\src\Exception\AccountNotActiveException - * @throws \MyParcelNL\Sdk\src\Exception\MissingFieldException - * @throws \Exception + * @throws ApiException + * @throws AccountNotActiveException + * @throws MissingFieldException + * @throws Exception */ public function __construct() { $settings = CarrierConfigurationImport::getAccountSettings(); - if (! $settings) { + if (!$settings) { return; } @@ -60,8 +64,7 @@ public function getCarrierConfigurationByCarrier(AbstractCarrier $carrier): ?Car return $carrierConfigurations ->filter( static function (CarrierConfiguration $carrierConfiguration) use ($carrier) { - return $carrier->getId() === $carrierConfiguration->getCarrier() - ->getId(); + return $carrier->getId() === $carrierConfiguration->getCarrier()->getId(); } ) ->first(); @@ -77,7 +80,7 @@ public function getCarrierConfigurations(): Collection /** c * - * @return \MyParcelNL\Sdk\src\Model\Account\CarrierOptions[]|Collection + * @return CarrierOptions[]|Collection */ public function getCarrierOptions(): Collection { @@ -87,7 +90,7 @@ public function getCarrierOptions(): Collection /** * @param AbstractCarrier $carrier * - * @return null|\MyParcelNL\Sdk\src\Model\Account\CarrierOptions + * @return null|CarrierOptions */ public function getCarrierOptionsByCarrier(AbstractCarrier $carrier): ?CarrierOptions { @@ -96,8 +99,7 @@ public function getCarrierOptionsByCarrier(AbstractCarrier $carrier): ?CarrierOp return $carrierOptions ->filter( static function (CarrierOptions $carrierOptions) use ($carrier) { - return $carrier->getId() === $carrierOptions->getCarrier() - ->getId(); + return $carrier->getId() === $carrierOptions->getCarrier()->getId(); } ) ->first(); @@ -112,13 +114,13 @@ public function getShop(): ?Shop } /** - * @throws \Exception + * @throws Exception */ public function getDropOffPoint(AbstractCarrier $carrier): ?DropOffPoint { $carrierConfiguration = $this->getCarrierConfigurationByCarrier($carrier); - if (! $carrierConfiguration) { + if (!$carrierConfiguration) { return null; } @@ -138,13 +140,13 @@ public function getDropOffPoint(AbstractCarrier $carrier): ?DropOffPoint */ private function fillProperties(Collection $settings): void { - $shop = $settings->get('shop'); - $account = $settings->get('account'); - $carrierOptions = $settings->get('carrier_options'); - $carrierConfigurations = $settings->get('carrier_configurations'); - $this->shop = new Shop($shop); - $account['shops'] = [$shop]; - $this->account = new Account($account); + $shop = $settings->get('shop'); + $account = $settings->get('account'); + $carrierOptions = $settings->get('carrier_options'); + $carrierConfigurations = $settings->get('carrier_configurations'); + $this->shop = new Shop($shop); + $account['shops'] = [$shop]; + $this->account = new Account($account); $this->carrierOptions = (new Collection($carrierOptions))->mapInto(CarrierOptions::class); $this->carrierConfigurations = (new Collection($carrierConfigurations))->map(function (array $data) { return CarrierConfigurationFactory::create($data); diff --git a/Service/Config/ConfigService.php b/Service/Config/ConfigService.php index a155e1eb..f5b5c5c2 100644 --- a/Service/Config/ConfigService.php +++ b/Service/Config/ConfigService.php @@ -6,7 +6,6 @@ use Magento\Framework\App\Helper\AbstractHelper; use Magento\Framework\App\Helper\Context; -use Magento\Framework\App\ObjectManager; use Magento\Framework\Module\ModuleListInterface; use Magento\Store\Model\ScopeInterface; use MyParcelNL\Sdk\src\Model\Carrier\CarrierDHLEuroplus; @@ -15,7 +14,6 @@ use MyParcelNL\Sdk\src\Model\Carrier\CarrierDPD; use MyParcelNL\Sdk\src\Model\Carrier\CarrierPostNL; use MyParcelNL\Sdk\src\Model\Carrier\CarrierUPS; -use MyParcelNL\Sdk\src\Services\CheckApiKeyService; use MyParcelNL\Sdk\src\Services\Web\CheckApiKeyWebService; class ConfigService extends AbstractHelper @@ -34,19 +32,20 @@ class ConfigService extends AbstractHelper public const FIELD_DELIVERY_OPTIONS = 'myparcel_delivery_options'; public const FIELD_TRACK_STATUS = 'track_status'; public const DEFAULT_COUNTRY_CODE = 'NL'; - public const MYPARCEL_TRACK_TITLE = 'MyParcel'; + public const MYPARCEL_TRACK_TITLE = 'MyParcel'; public const MYPARCEL_CARRIER_CODE = 'myparcel'; - public const EXPORT_MODE_PPS = 'pps'; + public const EXPORT_MODE_PPS = 'pps'; public const EXPORT_MODE_SHIPMENTS = 'shipments'; - public const CARRIERS_XML_PATH_MAP = [ - CarrierPostNL::NAME => self::XML_PATH_POSTNL_SETTINGS, - CarrierDHLForYou::NAME => self::XML_PATH_DHLFORYOU_SETTINGS, - CarrierDHLEuroplus::NAME => self::XML_PATH_DHLEUROPLUS_SETTINGS, - CarrierDHLParcelConnect::NAME => self::XML_PATH_DHLPARCELCONNECT_SETTINGS, - CarrierUPS::NAME => self::XML_PATH_UPS_SETTINGS, - CarrierDPD::NAME => self::XML_PATH_DPD_SETTINGS, - ]; + public const CARRIERS_XML_PATH_MAP + = [ + CarrierPostNL::NAME => self::XML_PATH_POSTNL_SETTINGS, + CarrierDHLForYou::NAME => self::XML_PATH_DHLFORYOU_SETTINGS, + CarrierDHLEuroplus::NAME => self::XML_PATH_DHLEUROPLUS_SETTINGS, + CarrierDHLParcelConnect::NAME => self::XML_PATH_DHLPARCELCONNECT_SETTINGS, + CarrierUPS::NAME => self::XML_PATH_UPS_SETTINGS, + CarrierDPD::NAME => self::XML_PATH_DPD_SETTINGS, + ]; /** * @var ModuleListInterface @@ -69,7 +68,7 @@ public function __construct( ) { parent::__construct($context); - $this->moduleList = $moduleList; + $this->moduleList = $moduleList; $this->checkApiKeyWebService = $checkApiKeyWebService; } @@ -103,7 +102,7 @@ public function getFloatConfig($path, $key): float public function getTimeConfig(string $carrier, string $key): string { - $timeAsString = str_replace(',', ':', (string) $this->getConfigValue("$carrier$key")); + $timeAsString = str_replace(',', ':', (string)$this->getConfigValue("$carrier$key")); $timeComponents = explode(':', $timeAsString ?? ''); if (count($timeComponents) >= 3) { [$hours, $minutes] = $timeComponents; @@ -182,7 +181,7 @@ public function apiKeyIsCorrect(): bool $apiKey = $this->getApiKey(); return $this->checkApiKeyWebService->setApiKey($apiKey) - ->apiKeyIsCorrect(); + ->apiKeyIsCorrect(); } /** @@ -204,42 +203,4 @@ public function hasApiKey(): bool return isset($apiKey); } - - /** - * Get date in YYYY-MM-DD HH:MM:SS format - * - * @param string|null $date - * - * @return string|null - */ - public function convertDeliveryDate(?string $date): ?string - { - if (!$date) { - return null; - } - - $checkoutDate = json_decode($date, true)['date'] ?? substr($date, 0, 10); - $deliveryDate = strtotime(date('Y-m-d', strtotime($checkoutDate))); - $currentDate = strtotime(date('Y-m-d')); - - if ($deliveryDate <= $currentDate) { - return date('Y-m-d H:i:s', strtotime('now +1 day')); - } - - return $checkoutDate; - } - - /** - * @param int $orderId - * @param string $status - */ - public function setOrderStatus(int $orderId, string $status): void - { - $order = ObjectManager::getInstance() - ->create('\Magento\Sales\Model\Order') - ->load($orderId); - $order->setState($status) - ->setStatus($status); - $order->save(); - } } diff --git a/Service/Date/DatingService.php b/Service/Date/DatingService.php new file mode 100644 index 00000000..a494c5d3 --- /dev/null +++ b/Service/Date/DatingService.php @@ -0,0 +1,40 @@ +format('Y-m-d')); + } catch (Exception $e) { + return null; + } + + $currentDate = strtotime(date('Y-m-d')); + + if ($deliveryDate <= $currentDate) { + return date($format, strtotime('now +1 day')); + } + + return date($format, $deliveryDate); + } + +} diff --git a/Service/Normalizer/ConsignmentNormalizer.php b/Service/Normalizer/ConsignmentNormalizer.php deleted file mode 100644 index 5719fcd9..00000000 --- a/Service/Normalizer/ConsignmentNormalizer.php +++ /dev/null @@ -1,31 +0,0 @@ -data = $data; - } - - public function normalize(): array - { - $data = $this->data; - $data['carrier'] = $data['carrier'] ?? PostNLConsignment::CARRIER_NAME; - $data['deliveryType'] = $data['deliveryType'] ?? AbstractConsignment::DELIVERY_TYPE_STANDARD_NAME; - $data['package_type'] = $data['package_type'] ?? AbstractConsignment::PACKAGE_TYPE_PACKAGE_NAME; - - return $data; - } -} diff --git a/Ui/Component/Listing/Column/TrackActions.php b/Ui/Component/Listing/Column/TrackActions.php index d9b18349..874125c2 100755 --- a/Ui/Component/Listing/Column/TrackActions.php +++ b/Ui/Component/Listing/Column/TrackActions.php @@ -10,40 +10,31 @@ use Magento\Ui\Component\Listing\Columns\Column; use MyParcelNL\Magento\Service\Config\ConfigService; -/** - * Class DepartmentActions - */ class TrackActions extends Column { - const NAME = 'track_actions'; + public const NAME = 'track_actions'; - /** - * @var \MyParcelNL\Magento\Helper\Data - */ - private $configService; + private ConfigService $configService; + private UrlInterface $urlBuilder; /** - * @var UrlInterface - */ - private $urlBuilder; - - /** - * @param ContextInterface $context - * @param UiComponentFactory $uiComponentFactory - * @param UrlInterface $urlBuilder - * @param array $components - * @param array $data + * @param ContextInterface $context + * @param UiComponentFactory $uiComponentFactory + * @param UrlInterface $urlBuilder + * @param array $components + * @param array $data */ public function __construct( - ContextInterface $context, + ContextInterface $context, UiComponentFactory $uiComponentFactory, - UrlInterface $urlBuilder, - array $components = [], - array $data = [] - ) { - $this->urlBuilder = $urlBuilder; - $objectManager = ObjectManager::getInstance(); - $this->configService = $objectManager->get(ConfigService::class); + UrlInterface $urlBuilder, + array $components = [], + array $data = [] + ) + { + $this->urlBuilder = $urlBuilder; + $objectManager = ObjectManager::getInstance(); + $this->configService = $objectManager->get(ConfigService::class); parent::__construct($context, $uiComponentFactory, $components, $data); } @@ -57,14 +48,14 @@ public function __construct( */ public function prepareDataSource(array $dataSource) { - if (! isset($dataSource['data']['items'])) { + if (!isset($dataSource['data']['items'])) { return $dataSource; } $orderManagementActivated = ConfigService::EXPORT_MODE_PPS === $this->configService->getExportMode(); foreach ($dataSource['data']['items'] as &$item) { - if (! array_key_exists(ShippingStatus::NAME, $item)) { + if (!array_key_exists(ShippingStatus::NAME, $item)) { throw new LocalizedException( __( 'Note that the installation of the extension was not successful. Some columns have not been added to the database. The installation should be reversed. Use the following command to reinstall the module: DELETE FROM `setup_module` WHERE `setup_module`.`module` = \'MyParcelNL_Magento\'' @@ -73,7 +64,7 @@ public function prepareDataSource(array $dataSource) continue; } - if (! isset($item[ShippingStatus::NAME])) { + if (!isset($item[ShippingStatus::NAME])) { if (ConfigService::EXPORT_MODE_PPS === $this->configService->getExportMode()) { $item[$this->getData('name')]['action-create_concept'] = [ 'href' => $this->urlBuilder->getUrl( @@ -84,10 +75,10 @@ public function prepareDataSource(array $dataSource) ] ), 'label' => __('Export to MyParcel'), - 'hidden' => ! $orderManagementActivated, + 'hidden' => !$orderManagementActivated, ]; } else { - $item[$this->getData('name')]['action-download_package_label'] = [ + $item[$this->getData('name')]['action-download_package_label'] = [ 'href' => $this->urlBuilder->getUrl( 'myparcel/order/CreateAndPrintMyParcelTrack', [ @@ -123,7 +114,7 @@ public function prepareDataSource(array $dataSource) 'label' => __('Download digital stamp label'), 'hidden' => $orderManagementActivated, ]; - $item[$this->getData('name')]['action-download_mailbox_label'] = [ + $item[$this->getData('name')]['action-download_mailbox_label'] = [ 'href' => $this->urlBuilder->getUrl( 'myparcel/order/CreateAndPrintMyParcelTrack', [ @@ -135,7 +126,7 @@ public function prepareDataSource(array $dataSource) 'label' => __('Download mailbox label'), 'hidden' => $orderManagementActivated, ]; - $item[$this->getData('name')]['action-download_letter_label'] = [ + $item[$this->getData('name')]['action-download_letter_label'] = [ 'href' => $this->urlBuilder->getUrl( 'myparcel/order/CreateAndPrintMyParcelTrack', [ @@ -147,7 +138,7 @@ public function prepareDataSource(array $dataSource) 'label' => __('Download letter label'), 'hidden' => $orderManagementActivated, ]; - $item[$this->getData('name')]['action-create_concept'] = [ + $item[$this->getData('name')]['action-create_concept'] = [ 'href' => $this->urlBuilder->getUrl( 'myparcel/order/CreateAndPrintMyParcelTrack', [ @@ -158,7 +149,7 @@ public function prepareDataSource(array $dataSource) 'label' => __('Create new concept'), 'hidden' => $orderManagementActivated, ]; - $item[$this->getData('name')]['action-ship_direct'] = [ + $item[$this->getData('name')]['action-ship_direct'] = [ 'href' => $this->urlBuilder->getUrl( 'adminhtml/order_shipment/start', [ @@ -172,7 +163,7 @@ public function prepareDataSource(array $dataSource) } if (isset($item[ShippingStatus::NAME])) { - $item[$this->getData('name')]['action-create_concept'] = [ + $item[$this->getData('name')]['action-create_concept'] = [ 'href' => $this->urlBuilder->getUrl( 'myparcel/order/CreateAndPrintMyParcelTrack', [ @@ -181,9 +172,9 @@ public function prepareDataSource(array $dataSource) ] ), 'label' => __('Already exported'), - 'hidden' => ! $orderManagementActivated, + 'hidden' => !$orderManagementActivated, ]; - $item[$this->getData('name')]['action-download_package_label'] = [ + $item[$this->getData('name')]['action-download_package_label'] = [ 'href' => $this->urlBuilder->getUrl( 'myparcel/order/CreateAndPrintMyParcelTrack', [ From ec2cc8dc5da7f91c49459644df54d90b68aec5d8 Mon Sep 17 00:00:00 2001 From: Joeri van Veen Date: Tue, 8 Oct 2024 11:13:12 +0200 Subject: [PATCH 08/29] fix: prevent delivery date for small package outside nl --- Model/Sales/TrackTraceHolder.php | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Model/Sales/TrackTraceHolder.php b/Model/Sales/TrackTraceHolder.php index f213ea22..a47aa996 100755 --- a/Model/Sales/TrackTraceHolder.php +++ b/Model/Sales/TrackTraceHolder.php @@ -184,6 +184,10 @@ public function convertDataFromMagentoToApi(Track $magentoTrack, array $options) $options['package_type'] = $deliveryOptions['packageType']; } $packageType = $this->getPackageType($options, $magentoTrack, $address); + $deliveryDate = ( + AbstractConsignment::PACKAGE_TYPE_PACKAGE_SMALL === $packageType + && 'NL' !== $address->getCountryId() + ) ? null : $this->datingService->convertDeliveryDate($deliveryOptionsAdapter->getDate()); $dropOffPoint = AccountSettings::getInstance()->getDropOffPoint( CarrierFactory::createFromName($deliveryOptionsAdapter->getCarrier()) ); @@ -197,8 +201,8 @@ public function convertDataFromMagentoToApi(Track $magentoTrack, array $options) ->setPhone($address->getTelephone()) ->setEmail($address->getEmail()) ->setLabelDescription($this->shipmentOptionsHelper->getLabelDescription()) - ->setDeliveryDate($this->datingService->convertDeliveryDate($deliveryOptionsAdapter->getDate())) ->setDeliveryType($deliveryOptionsAdapter->getDeliveryTypeId() ?? AbstractConsignment::DELIVERY_TYPE_STANDARD) + ->setDeliveryDate($deliveryDate) ->setPackageType($packageType) ->setDropOffPoint($dropOffPoint) ->setOnlyRecipient($this->shipmentOptionsHelper->hasOnlyRecipient()) From 4cc6ad2f9e5839d2edcb390f381d1d5d3dcfc0f6 Mon Sep 17 00:00:00 2001 From: Joeri van Veen Date: Thu, 10 Oct 2024 11:57:02 +0200 Subject: [PATCH 09/29] wip --- Block/Sales/View.php | 28 ++++++------ Model/Carrier/Carrier.php | 43 ++++++++----------- ...SaveOrderBeforeSalesModelQuoteObserver.php | 37 +++++----------- Model/Source/ExportMode.php | 9 ++-- Service/Costs/DeliveryCostsService.php | 12 +++--- etc/config.xml | 11 ++--- 6 files changed, 63 insertions(+), 77 deletions(-) diff --git a/Block/Sales/View.php b/Block/Sales/View.php index a0a523c3..70586376 100755 --- a/Block/Sales/View.php +++ b/Block/Sales/View.php @@ -19,11 +19,13 @@ namespace MyParcelNL\Magento\Block\Sales; use DateTime; -use Magento\Framework\App\ObjectManager; +use Exception; +use Magento\Framework\Exception\LocalizedException; use Magento\Sales\Block\Adminhtml\Order\AbstractOrder; -use MyParcelNL\Magento\Helper\Checkout as CheckoutHelper; +use MyParcelNL\Magento\Service\Config\ConfigService; use MyParcelNL\Sdk\src\Adapter\DeliveryOptions\AbstractDeliveryOptionsAdapter; use MyParcelNL\Sdk\src\Factory\DeliveryOptionsAdapterFactory; +use Throwable; class View extends AbstractOrder { @@ -31,21 +33,21 @@ class View extends AbstractOrder * Collect options selected at checkout and calculate type consignment * * @return string - * @throws \Magento\Framework\Exception\LocalizedException - * @throws \Exception + * @throws LocalizedException + * @throws Exception */ public function getCheckoutOptionsHtml(): string { $order = $this->getOrder(); /** @var object $data Data from checkout */ - $data = $order->getData(CheckoutHelper::FIELD_DELIVERY_OPTIONS) !== null ? json_decode($order->getData(CheckoutHelper::FIELD_DELIVERY_OPTIONS), true) : null; + $data = json_decode($order->getData(ConfigService::FIELD_DELIVERY_OPTIONS) ?? null, true); - if (! is_array($data)) { + if (!is_array($data)) { return ''; } - $deliveryOptions = DeliveryOptionsAdapterFactory::create((array) $data); + $deliveryOptions = DeliveryOptionsAdapterFactory::create((array)$data); $returnString = ''; try { @@ -56,8 +58,8 @@ public function getCheckoutOptionsHtml(): string if ($deliveryOptions->getDate()) { $returnString = htmlentities($this->getCheckoutOptionsDeliveryHtml($deliveryOptions)); } - } catch (\Throwable $e) { - ObjectManager::getInstance()->get(CheckoutHelper::class)->log($e->getMessage()); + } catch (Throwable $e) { + $this->_logger->critical($e->getMessage()); $returnString = __('MyParcel options data not found'); } @@ -68,7 +70,8 @@ public function getCheckoutOptionsHtml(): string * @param AbstractDeliveryOptionsAdapter $deliveryOptions * @return string */ - private function getCheckoutOptionsPickupHtml(AbstractDeliveryOptionsAdapter $deliveryOptions): string { + private function getCheckoutOptionsPickupHtml(AbstractDeliveryOptionsAdapter $deliveryOptions): string + { ob_start(); echo __("{$deliveryOptions->getCarrier()} location:"), ' '; @@ -90,9 +93,10 @@ private function getCheckoutOptionsPickupHtml(AbstractDeliveryOptionsAdapter $de /** * @param AbstractDeliveryOptionsAdapter $deliveryOptions * @return string - * @throws \Exception + * @throws Exception */ - private function getCheckoutOptionsDeliveryHtml(AbstractDeliveryOptionsAdapter $deliveryOptions): string { + private function getCheckoutOptionsDeliveryHtml(AbstractDeliveryOptionsAdapter $deliveryOptions): string + { ob_start(); if ($deliveryOptions->getPackageType()) { diff --git a/Model/Carrier/Carrier.php b/Model/Carrier/Carrier.php index 4b0f9270..29d70bfc 100644 --- a/Model/Carrier/Carrier.php +++ b/Model/Carrier/Carrier.php @@ -18,7 +18,7 @@ namespace MyParcelNL\Magento\Model\Carrier; -use Composer\Config; +use Exception; use Magento\CatalogInventory\Api\StockRegistryInterface; use Magento\Checkout\Model\Session; use Magento\Directory\Helper\Data; @@ -45,15 +45,16 @@ use MyParcelNL\Magento\Service\Config\ConfigService; use MyParcelNL\Magento\Service\Costs\DeliveryCostsService; use MyParcelNL\Sdk\src\Adapter\DeliveryOptions\DeliveryOptionsV3Adapter; +use MyParcelNL\Sdk\src\Adapter\DeliveryOptions\ShipmentOptionsV3Adapter; use MyParcelNL\Sdk\src\Factory\DeliveryOptionsAdapterFactory; use Psr\Log\LoggerInterface; use Throwable; class Carrier extends AbstractCarrier implements CarrierInterface { - const CODE = 'myparcelnl_delivery'; + public const CODE = 'myparcel'; // same as in /etc/config.xml - protected $_code = self::CODE; // $_code is a mandatory property for Magento carrier + protected $_code = self::CODE; // $_code is a mandatory property for a Magento carrier protected $_freeShipping; @@ -68,24 +69,16 @@ class Carrier extends AbstractCarrier implements CarrierInterface * @param ScopeConfigInterface $scopeConfig * @param ErrorFactory $rateErrorFactory * @param LoggerInterface $logger - * @param Security $xmlSecurity - * @param ElementFactory $xmlElFactory + * @param ConfigService $configService + * @param DeliveryCostsService $deliveryCostsService * @param ResultFactory $rateFactory * @param MethodFactory $rateMethodFactory - * @param \Magento\Shipping\Model\Tracking\ResultFactory $trackFactory - * @param \Magento\Shipping\Model\Tracking\Result\ErrorFactory $trackErrorFactory - * @param StatusFactory $trackStatusFactory - * @param RegionFactory $regionFactory - * @param CountryFactory $countryFactory - * @param CurrencyFactory $currencyFactory - * @param Data $directoryData - * @param StockRegistryInterface $stockRegistry * @param Session $session * @param PackageRepository $package + * @param Freeshipping $freeShipping * @param array $data * - * @throws LocalizedException - * @throws NoSuchEntityException + * @throws Exception */ public function __construct( ScopeConfigInterface $scopeConfig, @@ -109,7 +102,7 @@ public function __construct( ); //$this->quote = $session->getQuote(); try { - $this->deliveryOptions = DeliveryOptionsAdapterFactory::create(json_decode($session->getQuote()->getData('myparcel_delivery_options'), true)); + $this->deliveryOptions = DeliveryOptionsAdapterFactory::create(json_decode($session->getQuote()->getData(ConfigService::FIELD_DELIVERY_OPTIONS), true)); } catch (Throwable $e) { $this->deliveryOptions = DeliveryOptionsAdapterFactory::create(DeliveryOptionsV3Adapter::DEFAULTS); } @@ -147,18 +140,20 @@ public function collectRates(RateRequest $request) private function getMethodAmount(): float { - $path = ConfigService::CARRIERS_XML_PATH_MAP[$this->deliveryOptions->getCarrier()] ?? ''; - $dinges = [ + $configPath = ConfigService::CARRIERS_XML_PATH_MAP[$this->deliveryOptions->getCarrier()] ?? ''; + $shipmentOptions = $this->deliveryOptions->getShipmentOptions() ?? new ShipmentOptionsV3Adapter([]); + $dinges = [ "{$this->deliveryOptions->getDeliveryType()}/fee" => true, "{$this->deliveryOptions->getPackageType()}/fee" => true, - 'delivery/signature_fee' => $this->deliveryOptions->getShipmentOptions()->hasSignature(), - 'delivery/only_recipient_fee' => $this->deliveryOptions->getShipmentOptions()->hasOnlyRecipient(), + 'delivery/signature_fee' => $shipmentOptions->hasSignature(), + 'delivery/only_recipient_fee' => $shipmentOptions->hasOnlyRecipient(), ]; - $amount = $this->deliveryCostsService->getBasePrice(); + $amount = $this->deliveryCostsService->getBasePrice(); foreach ($dinges as $key => $value) { - //echo $key, ' ', $value, ': ',$this->myParcelHelper->getCarrierConfig($key, $path), PHP_EOL; - if (!$value) continue; - $amount += (float)$this->configService->getConfigValue("$path$key"); + if (!$value) { + continue; + } + $amount += (float)$this->configService->getConfigValue("$configPath$key"); } //$bla = $this->myParcelHelper->getCarrierConfig('evening/fee', $path); return $amount; diff --git a/Model/Quote/SaveOrderBeforeSalesModelQuoteObserver.php b/Model/Quote/SaveOrderBeforeSalesModelQuoteObserver.php index 4cabef03..f8502b6e 100644 --- a/Model/Quote/SaveOrderBeforeSalesModelQuoteObserver.php +++ b/Model/Quote/SaveOrderBeforeSalesModelQuoteObserver.php @@ -51,8 +51,9 @@ class SaveOrderBeforeSalesModelQuoteObserver implements ObserverInterface */ public function __construct( DeliveryRepository $delivery, - ConfigService $configService - ) { + ConfigService $configService + ) + { $this->delivery = $delivery; $this->parentMethods = explode(',', $configService->getGeneralConfig('shipping_methods/methods') ?? ''); } @@ -79,11 +80,11 @@ public function execute(Observer $observer) $postcode = $order->getShippingAddress()->getPostcode(); $destinationCountry = $order->getShippingAddress()->getCountryId(); - if (! ValidateStreet::validate($fullStreet, AbstractConsignment::CC_NL, $destinationCountry)) { + if (!ValidateStreet::validate($fullStreet, AbstractConsignment::CC_NL, $destinationCountry)) { $order->setData(ConfigService::FIELD_TRACK_STATUS, __('⚠️  Please check street')); } - if (! ValidatePostalCode::validate($postcode, $destinationCountry)) { + if (!ValidatePostalCode::validate($postcode, $destinationCountry)) { $order->setData(ConfigService::FIELD_TRACK_STATUS, __('⚠️  Please check postal code')); } @@ -104,35 +105,19 @@ public function execute(Observer $observer) } /** - * @param Quote $quote + * @param Quote $quote * * @return bool */ private function hasMyParcelDeliveryOptions(Quote $quote): bool { - $shippingMethod = $quote->getShippingAddress()->getShippingMethod(); + $shippingMethod = $quote->getShippingAddress()->getShippingMethod(); + $myparcelMethod = Carrier::CODE . '_MyParcel';// TODO JOERI get the _code and stuff not hardcoded string - // TODO JOERI get the _code and stuff not hardcoded string - if ('myparcelnl_delivery_MyParcel' === $shippingMethod) return true; + if ($myparcelMethod === $shippingMethod) { + return true; + } return array_key_exists(ConfigService::FIELD_DELIVERY_OPTIONS, $quote->getData()); } - - /** - * @param string $input - * @param array $data - * - * @return bool - */ - private function isMyParcelRelated(string $input, array $data): bool - { - $result = array_filter( - $data, - static function ($item) use ($input) { - return stripos($input, $item) !== false; - } - ); - - return count($result) > 0; - } } diff --git a/Model/Source/ExportMode.php b/Model/Source/ExportMode.php index e7578374..9496a415 100755 --- a/Model/Source/ExportMode.php +++ b/Model/Source/ExportMode.php @@ -6,6 +6,7 @@ use Magento\Framework\Data\OptionSourceInterface; use MyParcelNL\Magento\Model\Sales\TrackTraceHolder; +use MyParcelNL\Magento\Service\Config\ConfigService; class ExportMode implements OptionSourceInterface { @@ -16,11 +17,11 @@ public function toOptionArray(): array { return [ [ - 'value' => TrackTraceHolder::EXPORT_MODE_SHIPMENTS, + 'value' => ConfigService::EXPORT_MODE_SHIPMENTS, 'label' => __('Export shipping details only') ], [ - 'value' => TrackTraceHolder::EXPORT_MODE_PPS, + 'value' => ConfigService::EXPORT_MODE_PPS, 'label' => __('Export entire order') ] ]; @@ -32,8 +33,8 @@ public function toOptionArray(): array public function toArray(): array { return [ - 'shipments' => __(TrackTraceHolder::EXPORT_MODE_SHIPMENTS), - 'pps' => __(TrackTraceHolder::EXPORT_MODE_PPS) + 'shipments' => __(ConfigService::EXPORT_MODE_SHIPMENTS), + 'pps' => __(ConfigService::EXPORT_MODE_PPS) ]; } } diff --git a/Service/Costs/DeliveryCostsService.php b/Service/Costs/DeliveryCostsService.php index ae3d14ce..f12f70bb 100644 --- a/Service/Costs/DeliveryCostsService.php +++ b/Service/Costs/DeliveryCostsService.php @@ -4,7 +4,6 @@ namespace MyParcelNL\Magento\Service\Costs; -use Magento\Framework\App\Helper\Context; use MyParcelNL\Magento\Model\Source\PriceDeliveryOptionsView; use MyParcelNL\Magento\Service\Config\ConfigService; @@ -18,14 +17,14 @@ public function __construct(ConfigService $configService) } /** - * @param string $carrier - * @param string $key - * @param bool $addBasePrice + * @param string $carrier + * @param string $key + * @param bool $addBasePrice * @return float */ public function getMethodPrice(string $carrier, string $key, bool $addBasePrice = true): float { - $value = $this->configService->getFloatConfig($carrier,$key); + $value = $this->configService->getFloatConfig($carrier, $key); $showTotalPrice = $this->configService->getConfigValue(ConfigService::XML_PATH_GENERAL . 'shipping_methods/delivery_options_prices') === PriceDeliveryOptionsView::TOTAL; if ($showTotalPrice && $addBasePrice) { @@ -40,8 +39,9 @@ public function getBasePrice(): float { return 5; } + /** - * @param float $price + * @param float $price * * @return int */ diff --git a/etc/config.xml b/etc/config.xml index 422f0426..342a5cec 100755 --- a/etc/config.xml +++ b/etc/config.xml @@ -5,7 +5,8 @@ * See COPYING.txt for license details. */ --> - + @@ -246,15 +247,15 @@ - + 1 - Custom Shipping Title - Custom Shipping Method Name + MyParcel + MyParcel 10 0 15 MyparcelNL\Magento\Model\Carrier\Carrier - + From 3dbeef7918418e88ff556156160401840a6ba04c Mon Sep 17 00:00:00 2001 From: Joeri van Veen Date: Thu, 10 Oct 2024 14:45:59 +0200 Subject: [PATCH 10/29] wip --- Cron/UpdateStatus.php | 81 +++++---- Model/Carrier/Carrier.php | 12 +- Model/Quote/Checkout.php | 162 ++++++++---------- ...SaveOrderBeforeSalesModelQuoteObserver.php | 4 +- Model/Sales/MagentoCollection.php | 153 +++++++++-------- Model/Sales/TrackTraceHolder.php | 3 +- Service/Config/ConfigService.php | 2 +- 7 files changed, 217 insertions(+), 200 deletions(-) diff --git a/Cron/UpdateStatus.php b/Cron/UpdateStatus.php index ab96a907..9a44045e 100755 --- a/Cron/UpdateStatus.php +++ b/Cron/UpdateStatus.php @@ -21,17 +21,26 @@ namespace MyParcelNL\Magento\Cron; +use DateTime; +use Exception; +use Magento\Framework\App\AreaList; use Magento\Framework\App\ObjectManager; +use Magento\Framework\Exception\AlreadyExistsException; +use Magento\Framework\Exception\LocalizedException; use Magento\Sales\Api\Data\ShipmentTrackInterface; use Magento\Sales\Model\Order; +use Magento\Sales\Model\ResourceModel\Order\Shipment\Track\Collection; use MyParcelNL\Magento\Api\ShipmentStatus; +use MyParcelNL\Magento\Model\Carrier\Carrier; use MyParcelNL\Magento\Model\Sales\MagentoCollection; use MyParcelNL\Magento\Model\Sales\MagentoOrderCollection; -use MyParcelNL\Magento\Model\Sales\TrackTraceHolder; use MyParcelNL\Magento\Service\Config\ConfigService; use MyParcelNL\Magento\Ui\Component\Listing\Column\TrackAndTrace; use MyParcelNL\Sdk\src\Collection\Fulfilment\OrderCollection; -use Magento\Sales\Model\ResourceModel\Order\Shipment\Track\Collection; +use MyParcelNL\Sdk\src\Exception\AccountNotActiveException; +use MyParcelNL\Sdk\src\Exception\ApiException; +use MyParcelNL\Sdk\src\Exception\MissingFieldException; +use Psr\Log\LoggerInterface; class UpdateStatus { @@ -40,7 +49,7 @@ class UpdateStatus public const PATH_MODEL_ORDER_TRACK = Collection::class; - private \Psr\Log\LoggerInterface $logger; + private LoggerInterface $logger; private ObjectManager $objectManager; private \Magento\Sales\Model\ResourceModel\Order $orderResource; private MagentoOrderCollection $orderCollection; @@ -49,31 +58,31 @@ class UpdateStatus /** * UpdateStatus constructor. * - * @param \Magento\Framework\App\AreaList $areaList - * @param \Psr\Log\LoggerInterface $logger + * @param AreaList $areaList + * @param LoggerInterface $logger * @param \Magento\Sales\Model\ResourceModel\Order $orderResource * * @todo; Adjust if there is a solution to the following problem: https://github.com/magento/magento2/pull/8413 */ public function __construct( - \Magento\Framework\App\AreaList $areaList, - \Psr\Log\LoggerInterface $logger, + AreaList $areaList, + LoggerInterface $logger, \Magento\Sales\Model\ResourceModel\Order $orderResource ) { - $this->objectManager = $objectManager = ObjectManager::getInstance(); - $this->configService = $objectManager->get(ConfigService::class); + $this->objectManager = $objectManager = ObjectManager::getInstance(); + $this->configService = $objectManager->get(ConfigService::class); $this->orderCollection = new MagentoOrderCollection($this->objectManager, null, $areaList); - $this->logger = $logger; - $this->orderResource = $orderResource; + $this->logger = $logger; + $this->orderResource = $orderResource; } /** * Run the cron job * * @return $this - * @throws \Magento\Framework\Exception\LocalizedException - * @throws \Exception + * @throws LocalizedException + * @throws Exception */ public function execute(): self { @@ -97,11 +106,11 @@ public function execute(): self * this means only on the following run the track_number is updated because the order cannot be shipped anymore. * * @return $this - * @throws \Magento\Framework\Exception\AlreadyExistsException - * @throws \MyParcelNL\Sdk\src\Exception\AccountNotActiveException - * @throws \MyParcelNL\Sdk\src\Exception\ApiException - * @throws \MyParcelNL\Sdk\src\Exception\MissingFieldException - * @throws \Exception + * @throws AlreadyExistsException + * @throws AccountNotActiveException + * @throws ApiException + * @throws MissingFieldException + * @throws Exception */ private function updateStatusPPS(): self { @@ -118,12 +127,12 @@ private function updateStatusPPS(): self ->setOrder('increment_id', 'DESC'); $orderIdsToCheck = array_unique(array_column($magentoOrders->getData(), 'increment_id')); - $apiOrders = OrderCollection::query($this->configService->getApiKey()); - $orderIdsDone = []; + $apiOrders = OrderCollection::query($this->configService->getApiKey()); + $orderIdsDone = []; foreach ($apiOrders->getIterator() as $apiOrder) { $incrementId = $apiOrder->getExternalIdentifier(); - $shipment = $apiOrder->getOrderShipments()[0]['shipment'] ?? null; + $shipment = $apiOrder->getOrderShipments()[0]['shipment'] ?? null; if (!$incrementId || !$shipment @@ -133,14 +142,14 @@ private function updateStatusPPS(): self } $orderIdsDone[$incrementId] = $incrementId; - $barcode = $shipment['external_identifier'] ?? TrackAndTrace::VALUE_PRINTED; + $barcode = $shipment['external_identifier'] ?? TrackAndTrace::VALUE_PRINTED; if (!$this->apiShipmentIsShipped($shipment)) { continue; } $magentoOrder = $this->objectManager->create('Magento\Sales\Model\Order') - ->loadByIncrementId($incrementId); + ->loadByIncrementId($incrementId); if (!$magentoOrder->canShip()) { $orderIdsDone[$incrementId] = self::ORDER_ID_NOT_TO_PROCESS; @@ -157,11 +166,11 @@ private function updateStatusPPS(): self } $orderIncrementIds = array_unique(array_values($orderIdsDone)); - $index = array_search(self::ORDER_ID_NOT_TO_PROCESS, $orderIncrementIds); + $index = array_search(self::ORDER_ID_NOT_TO_PROCESS, $orderIncrementIds); if (false !== $index) { unset($orderIncrementIds[$index]); } - $orderEntityIds = []; + $orderEntityIds = []; $arrayWithIdsArray = $magentoOrders->getData(); foreach ($arrayWithIdsArray as $arrayWithIds) { @@ -179,10 +188,10 @@ private function updateStatusPPS(): self $this->addOrdersToCollection($orderEntityIds); $this->orderCollection->setNewMagentoShipment(false) - ->setMagentoTrack() - ->setNewMyParcelTracks() - ->setLatestData() - ->updateMagentoTrack(); + ->setMagentoTrack() + ->setNewMyParcelTracks() + ->setLatestData() + ->updateMagentoTrack(); return $this; } @@ -190,8 +199,8 @@ private function updateStatusPPS(): self /** * Handles orders that have regular shipments, first removes any lingering orders in $this->orderCollection * - * @throws \Magento\Framework\Exception\LocalizedException - * @throws \Exception + * @throws LocalizedException + * @throws Exception */ private function updateStatusShipments(): self { @@ -206,7 +215,7 @@ private function updateStatusShipments(): self } /** - * @throws \Magento\Framework\Exception\AlreadyExistsException + * @throws AlreadyExistsException */ private function setShippedWithoutShipment(Order $magentoOrder, string $barcode): void { @@ -237,7 +246,7 @@ private function apiShipmentIsShipped(array $shipment): bool /** * Get all order to update the data * - * @throws \Magento\Framework\Exception\LocalizedException + * @throws LocalizedException */ private function setOrdersToUpdate() { @@ -257,14 +266,14 @@ private function getOrderIdFromTrackToUpdate() { /** * @var $magentoTrack Order\Shipment\Track - * @var \Magento\Sales\Model\ResourceModel\Order\Shipment\Track\Collection $trackCollection + * @var Collection $trackCollection */ $trackCollection = $this->objectManager->get(self::PATH_MODEL_ORDER_TRACK); $trackCollection ->addFieldToSelect('order_id') ->addAttributeToFilter('myparcel_status', [1, 2, 3, 4, 5, 6, 8]) ->addAttributeToFilter('myparcel_consignment_id', ['notnull' => true]) - ->addAttributeToFilter(ShipmentTrackInterface::CARRIER_CODE, ConfigService::MYPARCEL_CARRIER_CODE) + ->addAttributeToFilter(ShipmentTrackInterface::CARRIER_CODE, Carrier::CODE) ->setPageSize(300) ->setOrder('order_id', 'DESC'); @@ -281,7 +290,7 @@ private function addOrdersToCollection(array $orderIds): void /** * @var \Magento\Sales\Model\ResourceModel\Order\Collection $collection */ - $now = new \DateTime('now -14 day'); + $now = new DateTime('now -14 day'); $collection = $this->objectManager->get(MagentoCollection::PATH_MODEL_ORDER_COLLECTION); $collection ->addAttributeToFilter('entity_id', ['in' => $orderIds]) diff --git a/Model/Carrier/Carrier.php b/Model/Carrier/Carrier.php index 29d70bfc..7adf5210 100644 --- a/Model/Carrier/Carrier.php +++ b/Model/Carrier/Carrier.php @@ -55,6 +55,8 @@ class Carrier extends AbstractCarrier implements CarrierInterface public const CODE = 'myparcel'; // same as in /etc/config.xml protected $_code = self::CODE; // $_code is a mandatory property for a Magento carrier + protected $_name; + protected $_title; protected $_freeShipping; @@ -100,12 +102,16 @@ public function __construct( $logger, $data, ); - //$this->quote = $session->getQuote(); + + $this->_name = $configService->getConfigValue('carriers/myparcel_delivery/name') ?: self::CODE; + $this->_title = $configService->getConfigValue('carriers/myparcel_delivery/title') ?: self::CODE; + try { $this->deliveryOptions = DeliveryOptionsAdapterFactory::create(json_decode($session->getQuote()->getData(ConfigService::FIELD_DELIVERY_OPTIONS), true)); } catch (Throwable $e) { $this->deliveryOptions = DeliveryOptionsAdapterFactory::create(DeliveryOptionsV3Adapter::DEFAULTS); } + $this->package = $package; $this->rateResultFactory = $rateFactory; $this->rateMethodFactory = $rateMethodFactory; @@ -128,8 +134,8 @@ public function collectRates(RateRequest $request) $method = $this->rateMethodFactory->create(); $method->setCarrier($this->_code); - $method->setCarrierTitle('MyParcel'); - $method->setMethod('MyParcel'); + $method->setCarrierTitle($this->_title); + $method->setMethod($this->_name); $method->setMethodTitle($this->getMethodTitle()); $method->setPrice((string)$this->getMethodAmount()); diff --git a/Model/Quote/Checkout.php b/Model/Quote/Checkout.php index 7e119d4c..6eb570e8 100644 --- a/Model/Quote/Checkout.php +++ b/Model/Quote/Checkout.php @@ -4,6 +4,9 @@ use Magento\Checkout\Model\Cart; use Magento\Checkout\Model\Session; +use Magento\Eav\Model\Entity\Collection\AbstractCollection; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Exception\NoSuchEntityException; use Magento\Store\Model\StoreManagerInterface; use MyParcelNL\Magento\Model\Sales\Repository\PackageRepository; use MyParcelNL\Magento\Model\Source\PriceDeliveryOptionsView; @@ -11,34 +14,21 @@ use MyParcelNL\Magento\Service\Costs\DeliveryCostsService; use MyParcelNL\Sdk\src\Factory\ConsignmentFactory; use MyParcelNL\Sdk\src\Model\Consignment\AbstractConsignment; +use Throwable; class Checkout { - private const PLATFORM = 'myparcel'; - private const PACKAGE_TYPE_MAILBOX = 'mailbox'; - - /** - * @var \MyParcelNL\Magento\Helper\Checkout - */ - private $configService; - - /** - * @var \Magento\Quote\Model\Quote - */ - private $quoteId; - - /** - * @var PackageRepository - */ - private $package; + private ConfigService $configService; + private DeliveryCostsService $deliveryCostsService; + private PackageRepository $package; /** - * @var \Magento\Eav\Model\Entity\Collection\AbstractCollection[] + * @var AbstractCollection[] */ private $cart; /** - * @var \Magento\Store\Model\StoreManagerInterface + * @var StoreManagerInterface */ private $currency; @@ -46,7 +36,6 @@ class Checkout * @var mixed */ private $country; - private DeliveryCostsService $deliveryCostsService; /** * Checkout constructor. @@ -58,19 +47,19 @@ class Checkout * @param StoreManagerInterface $currency */ public function __construct( - Session $session, - Cart $cart, - ConfigService $configService, - DeliveryCostsService $deliveryCostsService, - PackageRepository $package, + Session $session, + Cart $cart, + ConfigService $configService, + DeliveryCostsService $deliveryCostsService, + PackageRepository $package, StoreManagerInterface $currency - ) { - $this->configService = $configService; - $this->deliveryCostsService= $deliveryCostsService; - $this->quoteId = $session->getQuoteId(); - $this->cart = $cart->getQuote(); - $this->package = $package; - $this->currency = $currency; + ) + { + $this->configService = $configService; + $this->deliveryCostsService = $deliveryCostsService; + $this->cart = $cart->getQuote(); + $this->package = $package; + $this->currency = $currency; } /** @@ -79,7 +68,7 @@ public function __construct( * @param array $forAddress associative array holding the latest address from the client * * @return array - * @throws \Magento\Framework\Exception\NoSuchEntityException + * @throws NoSuchEntityException */ public function getDeliveryOptions(array $forAddress = []): array { @@ -115,13 +104,13 @@ public function getDeliveryOptions(array $forAddress = []): array * Get general data * * @return array) - * @throws \Magento\Framework\Exception\NoSuchEntityException + * @throws NoSuchEntityException|LocalizedException */ private function getGeneralData() { return [ 'allowRetry' => true, - 'platform' => self::PLATFORM, + 'platform' => ConfigService::PLATFORM, 'carriers' => $this->getActiveCarriers(), 'currency' => $this->currency->getStore()->getCurrentCurrency()->getCode(), 'allowShowDeliveryDate' => $this->configService->getBoolConfig(ConfigService::XML_PATH_GENERAL, 'date_settings/allow_show_delivery_date'), @@ -179,7 +168,7 @@ private function getDeliveryData(?string $packageType = null): array try { $consignment = ConsignmentFactory::createByCarrierName($carrier); $consignment->setPackageType(AbstractConsignment::PACKAGE_TYPE_PACKAGE); - } catch (\Throwable $ex) { + } catch (Throwable $ex) { $this->configService->log(sprintf('getDeliveryData: Could not create default consignment for %s', $carrier)); continue; } @@ -210,16 +199,16 @@ private function getDeliveryData(?string $packageType = null): array $mondayFee = $canHaveMonday ? $this->deliveryCostsService->getMethodPrice($carrierPath, 'delivery/monday_fee') : 0; $morningFee = $canHaveMorning ? $this->deliveryCostsService->getMethodPrice($carrierPath, 'morning/fee') : 0; $eveningFee = $canHaveEvening ? $this->deliveryCostsService->getMethodPrice($carrierPath, 'evening/fee') : 0; - $sameDayFee = $canHaveSameDay ? (int) $this->deliveryCostsService->getMethodPrice($carrierPath, 'delivery/same_day_delivery_fee') : 0; + $sameDayFee = $canHaveSameDay ? (int)$this->deliveryCostsService->getMethodPrice($carrierPath, 'delivery/same_day_delivery_fee') : 0; $signatureFee = $canHaveSignature ? $this->deliveryCostsService->getMethodPrice($carrierPath, 'delivery/signature_fee', false) : 0; $onlyRecipientFee = $canHaveOnlyRecipient ? $this->deliveryCostsService->getMethodPrice($carrierPath, 'delivery/only_recipient_fee', false) : 0; $isAgeCheckActive = $canHaveAgeCheck && $this->isAgeCheckActive($carrierPath); $allowPickup = $this->configService->getBoolConfig($carrierPath, 'pickup/active'); $allowStandardDelivery = $this->configService->getBoolConfig($carrierPath, 'delivery/active'); - $allowMorningDelivery = ! $isAgeCheckActive && $canHaveMorning && $this->configService->getBoolConfig($carrierPath, 'morning/active'); - $allowEveningDelivery = ! $isAgeCheckActive && $canHaveEvening && $this->configService->getBoolConfig($carrierPath, 'evening/active'); - $allowDeliveryOptions = ! $this->package->deliveryOptionsDisabled + $allowMorningDelivery = !$isAgeCheckActive && $canHaveMorning && $this->configService->getBoolConfig($carrierPath, 'morning/active'); + $allowEveningDelivery = !$isAgeCheckActive && $canHaveEvening && $this->configService->getBoolConfig($carrierPath, 'evening/active'); + $allowDeliveryOptions = !$this->package->deliveryOptionsDisabled && ($allowPickup || $allowStandardDelivery || $allowMorningDelivery || $allowEveningDelivery); if ($allowDeliveryOptions && $packageType === AbstractConsignment::PACKAGE_TYPE_MAILBOX_NAME) { @@ -239,7 +228,7 @@ private function getDeliveryData(?string $packageType = null): array 'allowMondayDelivery' => $canHaveMonday && $this->configService->getBoolConfig($carrierPath, 'delivery/monday_active'), 'allowSameDayDelivery' => $canHaveSameDay && $this->configService->getBoolConfig($carrierPath, 'delivery/same_day_delivery_active'), - 'dropOffDays' => $this->getDropOffDays($carrierPath), + 'dropOffDays' => $this->getDropOffDays($carrierPath), 'priceSignature' => $signatureFee, 'priceOnlyRecipient' => $onlyRecipientFee, @@ -283,16 +272,20 @@ public function getActiveCarriers(): array return $carriers; } - private function getDropOffDays(string $carrierPath): array { + private function getDropOffDays(string $carrierPath): array + { $dropOffDays = []; for ($weekday = 0; $weekday < 7; $weekday++) { $cutoffTimeSameDay = $this->configService->getTimeConfig($carrierPath, "drop_off_days/cutoff_time_same_day_$weekday"); - $sameDayTimeEntry = $cutoffTimeSameDay ? ['cutoffTimeSameDay' => $cutoffTimeSameDay] : []; + $sameDayTimeEntry = $cutoffTimeSameDay ? ['cutoffTimeSameDay' => $cutoffTimeSameDay] : []; if ($this->configService->getBoolConfig($carrierPath, "drop_off_days/day_{$weekday}_active")) { - $dropOffDays[] = (object) array_merge([ - 'weekday' => $weekday, - 'cutoffTime' => $this->configService->getTimeConfig($carrierPath, "drop_off_days/cutoff_time_$weekday"), - ], $sameDayTimeEntry); + $dropOffDays[] = (object)array_merge( + [ + 'weekday' => $weekday, + 'cutoffTime' => $this->configService->getTimeConfig($carrierPath, "drop_off_days/cutoff_time_$weekday"), + ], + $sameDayTimeEntry + ); } } @@ -307,22 +300,22 @@ private function getDropOffDays(string $carrierPath): array { private function getDeliveryOptionsStrings(): array { return [ - 'deliveryTitle' => $this->configService->getGeneralConfig('delivery_titles/delivery_title') ?: __('delivery_title'), - 'deliveryStandardTitle' => $this->configService->getGeneralConfig('delivery_titles/standard_delivery_title') ?: __('standard_delivery'), - 'deliveryMorningTitle' => $this->configService->getGeneralConfig('delivery_titles/morning_title') ?: __('morning_title'), - 'deliveryEveningTitle' => $this->configService->getGeneralConfig('delivery_titles/evening_title') ?: __('evening_title'), - 'deliveryPickupTitle' => $this->configService->getGeneralConfig('delivery_titles/pickup_title') ?: __('pickup_title'), - 'pickupTitle' => $this->configService->getGeneralConfig('delivery_titles/pickup_title') ?: __('pickup_title'), - 'deliverySameDayTitle' => $this->configService->getGeneralConfig('delivery_titles/same_day_title') ?: __('same_day_title'), - 'hideSenderTitle' => $this->configService->getGeneralConfig('delivery_titles/hide_sender_title') ?: __('hide_sender_title'), - 'list' => $this->configService->getGeneralConfig('delivery_titles/pickup_list_button_title') ?: __('list_title'), - 'map' => $this->configService->getGeneralConfig('delivery_titles/pickup_map_button_title') ?: __('map_title'), - 'packageTypeMailbox' => $this->configService->getGeneralConfig('delivery_titles/mailbox_title') ?: __('mailbox_title'), - 'packageTypeDigitalStamp' => $this->configService->getGeneralConfig('delivery_titles/digital_stamp_title') ?: __('digital_stamp_title'), - 'packageTypePackageSmall' => $this->configService->getGeneralConfig('delivery_titles/package_small_title') ?: __('packet_title'), - 'signatureTitle' => $this->configService->getGeneralConfig('delivery_titles/signature_title') ?: __('signature_title'), - 'onlyRecipientTitle' => $this->configService->getGeneralConfig('delivery_titles/only_recipient_title') ?: __('only_recipient_title'), - 'saturdayDeliveryTitle' => $this->configService->getGeneralConfig('delivery_titles/saturday_title') ?: __('saturday_delivery_title'), + 'deliveryTitle' => $this->configService->getGeneralConfig('delivery_titles/delivery_title') ?: __('delivery_title'), + 'deliveryStandardTitle' => $this->configService->getGeneralConfig('delivery_titles/standard_delivery_title') ?: __('standard_delivery'), + 'deliveryMorningTitle' => $this->configService->getGeneralConfig('delivery_titles/morning_title') ?: __('morning_title'), + 'deliveryEveningTitle' => $this->configService->getGeneralConfig('delivery_titles/evening_title') ?: __('evening_title'), + 'deliveryPickupTitle' => $this->configService->getGeneralConfig('delivery_titles/pickup_title') ?: __('pickup_title'), + 'pickupTitle' => $this->configService->getGeneralConfig('delivery_titles/pickup_title') ?: __('pickup_title'), + 'deliverySameDayTitle' => $this->configService->getGeneralConfig('delivery_titles/same_day_title') ?: __('same_day_title'), + 'hideSenderTitle' => $this->configService->getGeneralConfig('delivery_titles/hide_sender_title') ?: __('hide_sender_title'), + 'list' => $this->configService->getGeneralConfig('delivery_titles/pickup_list_button_title') ?: __('list_title'), + 'map' => $this->configService->getGeneralConfig('delivery_titles/pickup_map_button_title') ?: __('map_title'), + 'packageTypeMailbox' => $this->configService->getGeneralConfig('delivery_titles/mailbox_title') ?: __('mailbox_title'), + 'packageTypeDigitalStamp' => $this->configService->getGeneralConfig('delivery_titles/digital_stamp_title') ?: __('digital_stamp_title'), + 'packageTypePackageSmall' => $this->configService->getGeneralConfig('delivery_titles/package_small_title') ?: __('packet_title'), + 'signatureTitle' => $this->configService->getGeneralConfig('delivery_titles/signature_title') ?: __('signature_title'), + 'onlyRecipientTitle' => $this->configService->getGeneralConfig('delivery_titles/only_recipient_title') ?: __('only_recipient_title'), + 'saturdayDeliveryTitle' => $this->configService->getGeneralConfig('delivery_titles/saturday_title') ?: __('saturday_delivery_title'), 'wrongPostalCodeCity' => __('Postcode/city combination unknown'), 'addressNotFound' => __('Address details are not entered'), @@ -338,22 +331,22 @@ private function getDeliveryOptionsStrings(): array 'showMoreHours' => __('Show more opening hours'), 'showMoreLocations' => __('Show more locations'), - 'error3212' => __('{field} is required.'), - 'error3501' => __('Address not found.'), - 'error3505' => __('Postal code is invalid for the current country.'), - - 'cityText' => __('City'), - 'city' => __('City'), - 'cc' => __('Country'), - 'houseNumber' => __('House number'), - 'numberText' => __('House number'), - 'postalCode' => __('Postal code'), - 'street' => __('Street'), + 'error3212' => __('{field} is required.'), + 'error3501' => __('Address not found.'), + 'error3505' => __('Postal code is invalid for the current country.'), + + 'cityText' => __('City'), + 'city' => __('City'), + 'cc' => __('Country'), + 'houseNumber' => __('House number'), + 'numberText' => __('House number'), + 'postalCode' => __('Postal code'), + 'street' => __('Street'), ]; } /** - * @param string $carrier + * @param string $carrier * @param string|null $country * * @return string @@ -362,7 +355,7 @@ public function checkPackageType(string $carrier, ?string $country = null): stri { try { $consignment = ConsignmentFactory::createByCarrierName($carrier); - } catch (\Throwable $e) { + } catch (Throwable $e) { $this->configService->log(sprintf('checkPackageType: Could not create default consignment for %s', $carrier)); return AbstractConsignment::DEFAULT_PACKAGE_TYPE_NAME; @@ -417,13 +410,10 @@ public function isAgeCheckActive(string $carrierPath): bool public function getDropOffDelay(string $carrierPath, string $key): int { $products = $this->cart->getAllItems(); - $productDelay = $this->package->getProductDropOffDelay($products); - - if (! $productDelay) { - $productDelay = $this->configService->getIntegerConfig($carrierPath, $key); - } + $productDelay = (int)$this->package->getProductDropOffDelay($products); + $configDelay = $this->configService->getIntegerConfig($carrierPath, $key); - return (int) $productDelay; + return max($productDelay, $configDelay); } /** @@ -438,17 +428,17 @@ public function hideDeliveryOptionsForProduct() } /** - * @param string $carrier + * @param string $carrier * * @return bool */ private function isPickupAllowed(string $carrier): bool { - $isMailboxPackage = self::PACKAGE_TYPE_MAILBOX === $this->getPackageType(); + $isMailboxPackage = AbstractConsignment::PACKAGE_TYPE_MAILBOX_NAME === $this->getPackageType(); $pickupEnabled = $this->configService->getBoolConfig($carrier, 'pickup/active'); $showPickupForMailbox = $this->configService->getBoolConfig($carrier, 'mailbox/pickup_mailbox'); - $showPickup = ! $isMailboxPackage || $showPickupForMailbox; + $showPickup = !$isMailboxPackage || $showPickupForMailbox; - return ! $this->package->deliveryOptionsDisabled && $pickupEnabled && $showPickup; + return !$this->package->deliveryOptionsDisabled && $pickupEnabled && $showPickup; } } diff --git a/Model/Quote/SaveOrderBeforeSalesModelQuoteObserver.php b/Model/Quote/SaveOrderBeforeSalesModelQuoteObserver.php index f8502b6e..ba537c08 100644 --- a/Model/Quote/SaveOrderBeforeSalesModelQuoteObserver.php +++ b/Model/Quote/SaveOrderBeforeSalesModelQuoteObserver.php @@ -30,6 +30,7 @@ use MyParcelNL\Sdk\src\Helper\ValidatePostalCode; use MyParcelNL\Sdk\src\Helper\ValidateStreet; use MyParcelNL\Sdk\src\Model\Consignment\AbstractConsignment; +use MyParcelNL\Sdk\src\Support\Str; class SaveOrderBeforeSalesModelQuoteObserver implements ObserverInterface { @@ -112,9 +113,8 @@ public function execute(Observer $observer) private function hasMyParcelDeliveryOptions(Quote $quote): bool { $shippingMethod = $quote->getShippingAddress()->getShippingMethod(); - $myparcelMethod = Carrier::CODE . '_MyParcel';// TODO JOERI get the _code and stuff not hardcoded string - if ($myparcelMethod === $shippingMethod) { + if (Str::startswith($shippingMethod, Carrier::CODE)) { return true; } diff --git a/Model/Sales/MagentoCollection.php b/Model/Sales/MagentoCollection.php index 1e5f3768..81a5ae8e 100755 --- a/Model/Sales/MagentoCollection.php +++ b/Model/Sales/MagentoCollection.php @@ -14,14 +14,22 @@ namespace MyParcelNL\Magento\Model\Sales; +use Exception; +use Magento\Framework\App\Area; use Magento\Framework\App\AreaList; use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Message\ManagerInterface; use Magento\Framework\Module\Manager; use Magento\Framework\ObjectManagerInterface; use Magento\Sales\Model\Order; +use Magento\Sales\Model\Order\Shipment\Track; use Magento\Sales\Model\ResourceModel\Order\Collection as OrderCollection; +use Magento\Sales\Model\ResourceModel\Order\Shipment; use Magento\Sales\Model\ResourceModel\Order\Shipment\Collection as ShipmentCollection; +use Magento\Sales\Model\ResourceModel\Order\Shipment\Track\Collection; +use MyParcelNL\Magento\Model\Carrier\Carrier; use MyParcelNL\Magento\Model\Order\Email\Sender\TrackSender; use MyParcelNL\Magento\Model\Source\ReturnInTheBox; use MyParcelNL\Magento\Model\Source\SourceItem; @@ -29,11 +37,13 @@ use MyParcelNL\Magento\Service\Config\ConfigService; use MyParcelNL\Magento\Service\Weight\WeightService; use MyParcelNL\Magento\Ui\Component\Listing\Column\TrackAndTrace; +use MyParcelNL\Sdk\src\Exception\AccountNotActiveException; +use MyParcelNL\Sdk\src\Exception\ApiException; +use MyParcelNL\Sdk\src\Exception\MissingFieldException; use MyParcelNL\Sdk\src\Helper\MyParcelCollection; use MyParcelNL\Sdk\src\Model\Carrier\CarrierPostNL; use MyParcelNL\Sdk\src\Model\Consignment\AbstractConsignment; use MyParcelNL\Sdk\src\Model\Consignment\BaseConsignment; -use Magento\Framework\App\ResourceConnection; /** * Class MagentoOrderCollection @@ -59,7 +69,7 @@ abstract class MagentoCollection implements MagentoCollectionInterface protected SourceItem $sourceItem; protected TrackSender $trackSender; protected ObjectManagerInterface $objectManager; - protected Order\Shipment\Track $modelTrack; + protected Track $modelTrack; protected AreaList $areaList; protected ManagerInterface $messageManager; protected ConfigService $configService; @@ -67,23 +77,24 @@ abstract class MagentoCollection implements MagentoCollectionInterface /** * @var array */ - protected $options = [ - 'create_track_if_one_already_exist' => true, - 'request_type' => 'download', - 'package_type' => 'default', - 'carrier' => 'postnl', - 'positions' => null, - 'signature' => null, - 'only_recipient' => null, - 'return' => null, - 'large_format' => null, - 'age_check' => null, - 'insurance' => null, - 'label_amount' => NewShipment::DEFAULT_LABEL_AMOUNT, - 'digital_stamp_weight' => null, - 'return_in_the_box' => false, - 'same_day_delivery' => false, - ]; + protected $options + = [ + 'create_track_if_one_already_exist' => true, + 'request_type' => 'download', + 'package_type' => 'default', + 'carrier' => 'postnl', + 'positions' => null, + 'signature' => null, + 'only_recipient' => null, + 'return' => null, + 'large_format' => null, + 'age_check' => null, + 'insurance' => null, + 'label_amount' => NewShipment::DEFAULT_LABEL_AMOUNT, + 'digital_stamp_weight' => null, + 'return_in_the_box' => false, + 'same_day_delivery' => false, + ]; /** * @var mixed */ @@ -105,14 +116,14 @@ public function __construct( $this->areaList = $areaList; } - $this->objectManager = $objectManager; - $this->moduleManager = $objectManager->get(Manager::class); - $this->request = $request; - $this->trackSender = $this->objectManager->get(TrackSender::class); - $this->configService = $objectManager->get(ConfigService::class); - $this->weightService = $objectManager->get(WeightService::class); - $this->modelTrack = $objectManager->create(self::PATH_ORDER_TRACK); - $this->messageManager = $objectManager->create(self::PATH_MANAGER_INTERFACE); + $this->objectManager = $objectManager; + $this->moduleManager = $objectManager->get(Manager::class); + $this->request = $request; + $this->trackSender = $this->objectManager->get(TrackSender::class); + $this->configService = $objectManager->get(ConfigService::class); + $this->weightService = $objectManager->get(WeightService::class); + $this->modelTrack = $objectManager->create(self::PATH_ORDER_TRACK); + $this->messageManager = $objectManager->create(self::PATH_MANAGER_INTERFACE); $this->myParcelCollection = (new MyParcelCollection())->setUserAgents( ['Magento2' => $this->configService->getVersion()] ); @@ -197,7 +208,7 @@ public function getOption($option) * @param $consignment BaseConsignment * * @return $this - * @throws \Exception + * @throws Exception */ public function addConsignment(BaseConsignment $consignment) { @@ -220,21 +231,21 @@ public function getHtmlForGridColumns($orderId) */ // Temporarily fix to translate in cronjob if (!empty($this->areaList)) { - $areaObject = $this->areaList->getArea(\Magento\Framework\App\Area::AREA_ADMINHTML); - $areaObject->load(\Magento\Framework\App\Area::PART_TRANSLATE); + $areaObject = $this->areaList->getArea(Area::AREA_ADMINHTML); + $areaObject->load(Area::PART_TRANSLATE); } return $this->getHtmlForGridColumnsByTracks($this->getTracksCollectionByOrderId($orderId)); } /** - * @param Order\Shipment\Track[]|\Magento\Sales\Model\ResourceModel\Order\Shipment\Track\Collection $tracks + * @param Track[]|Collection $tracks * * @return string[] */ public function getHtmlForGridColumnsByTracks($tracks): array { - $data = ['track_status' => [], 'track_number' => []]; + $data = ['track_status' => [], 'track_number' => []]; $columnHtml = ['track_status' => '', 'track_number' => '']; foreach ($tracks as $track) { @@ -261,7 +272,7 @@ public function getHtmlForGridColumnsByTracks($tracks): array /** * Check if track already exists * - * @param \Magento\Sales\Model\ResourceModel\Order\Shipment $shipment + * @param Shipment $shipment * * @return bool */ @@ -275,17 +286,17 @@ protected function shipmentHasTrack($shipment) * * @param Order\Shipment $shipment * - * @return \Magento\Sales\Model\Order\Shipment\Track - * @throws \Exception + * @return Track + * @throws Exception */ protected function setNewMagentoTrack($shipment) { - /** @var \Magento\Sales\Model\Order\Shipment\Track $track */ - $track = $this->objectManager->create('Magento\Sales\Model\Order\Shipment\Track'); + /** @var Track $track */ + $track = $this->objectManager->create(Track::class); $track ->setOrderId($shipment->getOrderId()) ->setShipment($shipment) - ->setCarrierCode(ConfigService::MYPARCEL_CARRIER_CODE) + ->setCarrierCode(Carrier::CODE) ->setTitle(ConfigService::MYPARCEL_TRACK_TITLE) ->setQty($shipment->getTotalQty()) ->setTrackNumber(TrackAndTrace::VALUE_EMPTY) @@ -297,13 +308,13 @@ protected function setNewMagentoTrack($shipment) /** * Get all tracks * - * @param \Magento\Sales\Model\ResourceModel\Order\Shipment $shipment + * @param Shipment $shipment * - * @return \Magento\Sales\Model\ResourceModel\Order\Shipment\Track\Collection + * @return Collection */ protected function getTrackByShipment($shipment) { - /* @var \Magento\Sales\Model\ResourceModel\Order\Shipment\Track\Collection $collection */ + /* @var Collection $collection */ $collection = $this->objectManager->create(self::PATH_ORDER_TRACK_COLLECTION); $collection ->addAttributeToFilter('parent_id', $shipment->getId()); @@ -314,10 +325,10 @@ protected function getTrackByShipment($shipment) /** * Get MyParcel Track from Magento Track * - * @param Order\Shipment\Track $magentoTrack + * @param Track $magentoTrack * * @return TrackTraceHolder $myParcelTrack - * @throws \Magento\Framework\Exception\LocalizedException + * @throws LocalizedException */ protected function createConsignmentAndGetTrackTraceHolder($magentoTrack): TrackTraceHolder { @@ -342,7 +353,7 @@ public function syncMagentoToMyparcel(): self $consignmentIds, $this->configService->getApiKey() ); - } catch (\Exception $e) { + } catch (Exception $e) { $this->messageManager->addErrorMessage($e->getMessage()); } @@ -351,9 +362,9 @@ public function syncMagentoToMyparcel(): self /** * @return $this - * @throws \MyParcelNL\Sdk\src\Exception\ApiException - * @throws \MyParcelNL\Sdk\src\Exception\MissingFieldException - * @throws \Exception + * @throws ApiException + * @throws MissingFieldException + * @throws Exception */ public function createMyParcelConcepts(): self { @@ -364,7 +375,7 @@ public function createMyParcelConcepts(): self try { $this->myParcelCollection->createConcepts(); - } catch (\Exception $e) { + } catch (Exception $e) { $this->messageManager->addErrorMessage($e->getMessage()); return $this; } @@ -378,7 +389,7 @@ public function createMyParcelConcepts(): self * Add MyParcel Track from Magento Track * * @return $this - * @throws \Exception + * @throws Exception */ public function setNewMyParcelTracks(): self { @@ -387,7 +398,7 @@ public function setNewMyParcelTracks(): self $multiColloConsignments = []; /** * @var Order\Shipment $shipment - * @var Order\Shipment\Track $magentoTrack + * @var Track $magentoTrack */ foreach ($shipments as $shipment) { $magentoTracks = $this->getTrackByShipment($shipment)->getItems(); @@ -409,7 +420,7 @@ public function setNewMyParcelTracks(): self $multiColloConsignments[$parentId] = [ 'consignment' => $consignment, - 'colli' => 1, + 'colli' => 1, ]; } } @@ -426,7 +437,7 @@ protected function addGroupedConsignments(array $multiColloConsignments): self { foreach ($multiColloConsignments as $multiColloConsignment) { $consignment = $multiColloConsignment['consignment']; - $quantity = $multiColloConsignment['colli']; + $quantity = $multiColloConsignment['colli']; if (1 < $quantity && $this->canUseMultiCollo($consignment)) { $this->myParcelCollection->addMultiCollo($consignment, $quantity); @@ -440,10 +451,10 @@ protected function addGroupedConsignments(array $multiColloConsignments): self } /** - * @param \MyParcelNL\Sdk\src\Model\Consignment\AbstractConsignment $consignment + * @param AbstractConsignment $consignment * @param int $quantity * - * @throws \MyParcelNL\Sdk\src\Exception\MissingFieldException + * @throws MissingFieldException */ protected function addConsignmentMultipleTimes(AbstractConsignment $consignment, int $quantity): void { @@ -452,7 +463,7 @@ protected function addConsignmentMultipleTimes(AbstractConsignment $consignment, while ($i < $quantity) { try { $this->myParcelCollection->addConsignment($consignment); - } catch (\Exception $e) { + } catch (Exception $e) { return; } @@ -461,9 +472,9 @@ protected function addConsignmentMultipleTimes(AbstractConsignment $consignment, } /** - * @throws \MyParcelNL\Sdk\src\Exception\AccountNotActiveException - * @throws \MyParcelNL\Sdk\src\Exception\ApiException - * @throws \MyParcelNL\Sdk\src\Exception\MissingFieldException + * @throws AccountNotActiveException + * @throws ApiException + * @throws MissingFieldException */ public function addReturnInTheBox(string $returnOptions): void { @@ -496,14 +507,14 @@ function ( /** * @return $this - * @throws \Exception + * @throws Exception */ public function updateMagentoTrack(): self { $shipments = $this->getShipmentsCollection(); foreach ($shipments as $shipment) { - $consignments = $this->myParcelCollection->getConsignmentsByReferenceId($shipment->getEntityId()); + $consignments = $this->myParcelCollection->getConsignmentsByReferenceId($shipment->getEntityId()); $trackCollection = $this->getTrackByShipment($shipment)->getItems(); foreach ($trackCollection as $magentoTrack) { @@ -540,9 +551,9 @@ public function updateMagentoTrack(): self /** * @return $this - * @throws \MyParcelNL\Sdk\src\Exception\AccountNotActiveException - * @throws \MyParcelNL\Sdk\src\Exception\ApiException - * @throws \MyParcelNL\Sdk\src\Exception\MissingFieldException + * @throws AccountNotActiveException + * @throws ApiException + * @throws MissingFieldException */ public function addReturnShipments(): self { @@ -595,14 +606,14 @@ abstract protected function getShipmentsCollection(): ShipmentCollection; */ private function getTracksCollectionByOrderId($orderId): array { - /** @var \Magento\Framework\App\ResourceConnection $connection */ + /** @var ResourceConnection $connection */ $connection = $this->objectManager->create(ResourceConnection::class); - $conn = $connection->getConnection(); - $select = $conn->select() - ->from( - ['main_table' => $connection->getTableName('sales_shipment_track')] - ) - ->where('main_table.order_id=?', $orderId); + $conn = $connection->getConnection(); + $select = $conn->select() + ->from( + ['main_table' => $connection->getTableName('sales_shipment_track')] + ) + ->where('main_table.order_id=?', $orderId); return $conn->fetchAll($select); } @@ -628,7 +639,7 @@ protected function getMyparcelConsignmentIdsForShipments(): array } /** - * @param \MyParcelNL\Sdk\src\Model\Consignment\AbstractConsignment $consignment + * @param AbstractConsignment $consignment * * @return bool whether $consignment properties allow for multicollo shipments */ diff --git a/Model/Sales/TrackTraceHolder.php b/Model/Sales/TrackTraceHolder.php index a47aa996..02dbcff8 100755 --- a/Model/Sales/TrackTraceHolder.php +++ b/Model/Sales/TrackTraceHolder.php @@ -25,6 +25,7 @@ use Magento\Sales\Model\Order\Shipment\Track; use MyParcelNL\Magento\Adapter\DeliveryOptionsFromOrderAdapter; use MyParcelNL\Magento\Helper\ShipmentOptions; +use MyParcelNL\Magento\Model\Carrier\Carrier; use MyParcelNL\Magento\Model\Settings\AccountSettings; use MyParcelNL\Magento\Model\Source\DefaultOptions; use MyParcelNL\Magento\Service\Config\ConfigService; @@ -259,7 +260,7 @@ public function createTrackTraceFromShipment(Shipment $shipment) $this->mageTrack ->setOrderId($shipment->getOrderId()) ->setShipment($shipment) - ->setCarrierCode(ConfigService::MYPARCEL_CARRIER_CODE) + ->setCarrierCode(Carrier::CODE) ->setTitle(ConfigService::MYPARCEL_TRACK_TITLE) ->setQty($shipment->getTotalQty()) ->setTrackNumber(TrackAndTrace::VALUE_EMPTY); diff --git a/Service/Config/ConfigService.php b/Service/Config/ConfigService.php index f5b5c5c2..1cdeb7ca 100644 --- a/Service/Config/ConfigService.php +++ b/Service/Config/ConfigService.php @@ -19,6 +19,7 @@ class ConfigService extends AbstractHelper { public const MODULE_NAME = 'MyParcelNL_Magento'; + public const PLATFORM = 'myparcel'; public const XML_PATH_GENERAL = 'myparcelnl_magento_general/'; public const XML_PATH_POSTNL_SETTINGS = 'myparcelnl_magento_postnl_settings/'; public const XML_PATH_DHLFORYOU_SETTINGS = 'myparcelnl_magento_dhlforyou_settings/'; @@ -33,7 +34,6 @@ class ConfigService extends AbstractHelper public const FIELD_TRACK_STATUS = 'track_status'; public const DEFAULT_COUNTRY_CODE = 'NL'; public const MYPARCEL_TRACK_TITLE = 'MyParcel'; - public const MYPARCEL_CARRIER_CODE = 'myparcel'; public const EXPORT_MODE_PPS = 'pps'; public const EXPORT_MODE_SHIPMENTS = 'shipments'; From 8a90232fd6ce65dbcf2daec3b6b4f10ba9780810 Mon Sep 17 00:00:00 2001 From: Joeri van Veen Date: Mon, 14 Oct 2024 11:26:22 +0200 Subject: [PATCH 11/29] wip --- Block/Sales/View.php | 3 +- Cron/UpdateStatus.php | 14 ++-- Facade/Facade.php | 25 +++++++ Facade/Logger.php | 27 +++++++ Helper/Checkout.php | 98 ++++++++++++-------------- Helper/CustomsDeclarationFromOrder.php | 31 ++++---- Model/Carrier/Carrier.php | 67 +++++++----------- Model/Quote/Checkout.php | 53 +++++++------- Model/Sales/TrackTraceHolder.php | 2 +- Service/Costs/DeliveryCostsService.php | 40 ++++------- Service/Weight/WeightService.php | 51 ++++++++++++-- 11 files changed, 238 insertions(+), 173 deletions(-) create mode 100644 Facade/Facade.php create mode 100644 Facade/Logger.php diff --git a/Block/Sales/View.php b/Block/Sales/View.php index 70586376..ce8e82b9 100755 --- a/Block/Sales/View.php +++ b/Block/Sales/View.php @@ -22,6 +22,7 @@ use Exception; use Magento\Framework\Exception\LocalizedException; use Magento\Sales\Block\Adminhtml\Order\AbstractOrder; +use MyParcelNL\Magento\Facade\Logger; use MyParcelNL\Magento\Service\Config\ConfigService; use MyParcelNL\Sdk\src\Adapter\DeliveryOptions\AbstractDeliveryOptionsAdapter; use MyParcelNL\Sdk\src\Factory\DeliveryOptionsAdapterFactory; @@ -59,7 +60,7 @@ public function getCheckoutOptionsHtml(): string $returnString = htmlentities($this->getCheckoutOptionsDeliveryHtml($deliveryOptions)); } } catch (Throwable $e) { - $this->_logger->critical($e->getMessage()); + Logger::critical($e->getMessage()); $returnString = __('MyParcel options data not found'); } diff --git a/Cron/UpdateStatus.php b/Cron/UpdateStatus.php index 9a44045e..a6b9758f 100755 --- a/Cron/UpdateStatus.php +++ b/Cron/UpdateStatus.php @@ -31,6 +31,7 @@ use Magento\Sales\Model\Order; use Magento\Sales\Model\ResourceModel\Order\Shipment\Track\Collection; use MyParcelNL\Magento\Api\ShipmentStatus; +use MyParcelNL\Magento\Facade\Logger; use MyParcelNL\Magento\Model\Carrier\Carrier; use MyParcelNL\Magento\Model\Sales\MagentoCollection; use MyParcelNL\Magento\Model\Sales\MagentoOrderCollection; @@ -59,21 +60,18 @@ class UpdateStatus * UpdateStatus constructor. * * @param AreaList $areaList - * @param LoggerInterface $logger * @param \Magento\Sales\Model\ResourceModel\Order $orderResource * * @todo; Adjust if there is a solution to the following problem: https://github.com/magento/magento2/pull/8413 */ public function __construct( - AreaList $areaList, - LoggerInterface $logger, + AreaList $areaList, \Magento\Sales\Model\ResourceModel\Order $orderResource ) { $this->objectManager = $objectManager = ObjectManager::getInstance(); $this->configService = $objectManager->get(ConfigService::class); $this->orderCollection = new MagentoOrderCollection($this->objectManager, null, $areaList); - $this->logger = $logger; $this->orderResource = $orderResource; } @@ -154,13 +152,13 @@ private function updateStatusPPS(): self if (!$magentoOrder->canShip()) { $orderIdsDone[$incrementId] = self::ORDER_ID_NOT_TO_PROCESS; - $this->logger->notice('Order is shipped from backoffice but Magento will not create a shipment.'); + Logger::notice('Order is shipped from backoffice but Magento will not create a shipment.'); $this->setShippedWithoutShipment($magentoOrder, $barcode); } } if (!$orderIdsDone) { - $this->logger->notice('PPS: no orders updated'); + Logger::notice('PPS: no orders updated'); return $this; } @@ -184,7 +182,7 @@ private function updateStatusPPS(): self return $this; } - $this->logger->notice(sprintf('PPS: update orders %s', implode(', ', $orderIncrementIds ?? []))); + Logger::notice(sprintf('PPS: update orders %s', implode(', ', $orderIncrementIds ?? []))); $this->addOrdersToCollection($orderEntityIds); $this->orderCollection->setNewMagentoShipment(false) @@ -219,7 +217,7 @@ private function updateStatusShipments(): self */ private function setShippedWithoutShipment(Order $magentoOrder, string $barcode): void { - $this->logger->notice( + Logger::notice( sprintf( 'Order %s set to shipped without shipment', $magentoOrder->getIncrementId() diff --git a/Facade/Facade.php b/Facade/Facade.php new file mode 100644 index 00000000..d14d77c2 --- /dev/null +++ b/Facade/Facade.php @@ -0,0 +1,25 @@ +$method( + ...$args + ); + } + + protected static function getFacadeRoot() + { + return ObjectManager::getInstance()->get(static::getFacadeAccessor()); + } + + abstract public static function getFacadeAccessor(); +} diff --git a/Facade/Logger.php b/Facade/Logger.php new file mode 100644 index 00000000..f97241f9 --- /dev/null +++ b/Facade/Logger.php @@ -0,0 +1,27 @@ +shippingMethodManagement = $shippingMethodManagement; $this->estimatedAddressFactory = $estimatedAddressFactory; @@ -90,16 +96,6 @@ public function getBasePrice() return $this->base_price; } - /** - * @param string $message - * - * @return void - */ - public function log(string $message): void - { - $this->_logger->critical($message); - } - /** * @param float $base_price */ @@ -120,7 +116,7 @@ public function setBasePriceFromQuote(int $quoteId, array $forAddress = []): Che $method = $this->getParentRateFromQuote($quoteId, $forAddress); $price = ($method) ? $method->getPriceInclTax() : 0; - $this->setBasePrice((double) $price); + $this->setBasePrice((double)$price); return $this; } @@ -132,22 +128,22 @@ public function setBasePriceFromQuote(int $quoteId, array $forAddress = []): Che */ public function getParentRateFromQuote(int $quoteId, array $forAddress = []) { - $parentCarriers = explode(',', $this->getGeneralConfig('shipping_methods/methods') ?? ''); + $parentCarriers = explode(',', $this->getGeneralConfig('shipping_methods/methods') ?? ''); /** - * @var \Magento\Quote\Api\Data\EstimateAddressInterface $estimatedAddress - * @var \Magento\Quote\Model\Cart\ShippingMethod[] $methods + * @var EstimateAddressInterface $estimatedAddress + * @var ShippingMethod[] $methods */ $estimatedAddress = $this->getEstimatedAddress($forAddress, $this->quote->getShippingAddress()); - $magentoMethods = $this->shippingMethodManagement->estimateByAddress($quoteId, $estimatedAddress); - $myParcelMethods = array_keys(Result::getMethods()); + $magentoMethods = $this->shippingMethodManagement->estimateByAddress($quoteId, $estimatedAddress); + $myParcelMethods = array_keys(Result::getMethods()); foreach ($magentoMethods as $method) { $methodCode = explode('/', $method->getMethodCode() ?? ''); $latestMethodCode = array_pop($methodCode); if ( - ! in_array($latestMethodCode, $myParcelMethods, true) + !in_array($latestMethodCode, $myParcelMethods, true) && in_array($method->getCarrierCode(), $parentCarriers, true) ) { return $method; @@ -158,22 +154,22 @@ public function getParentRateFromQuote(int $quoteId, array $forAddress = []) } /** - * @param array $fromClient - * @param \Magento\Quote\Model\Quote\Address $fromQuote + * @param array $fromClient + * @param Address $fromQuote * - * @return \Magento\Quote\Api\Data\EstimateAddressInterface + * @return EstimateAddressInterface */ private function getEstimatedAddress( - array $fromClient, - \Magento\Quote\Model\Quote\Address $fromQuote - ): \Magento\Quote\Api\Data\EstimateAddressInterface + array $fromClient, + Address $fromQuote + ): EstimateAddressInterface { $address = $this->estimatedAddressFactory->create(); if (isset($fromClient['countryId'])) { $address->setCountryId($fromClient['countryId']); - $address->setPostcode($fromClient['postcode'] ?? ''); - $address->setRegion($fromClient['region'] ?? ''); + $address->setPostcode($fromClient['postcode'] ?? ''); + $address->setRegion($fromClient['region'] ?? ''); } else { $address->setCountryId($fromQuote->getCountryId() ?? self::DEFAULT_COUNTRY_CODE); $address->setPostcode($fromQuote->getPostcode() ?? ''); @@ -187,8 +183,8 @@ private function getEstimatedAddress( /** * Get bool of setting * - * @param string $carrier - * @param string $key + * @param string $carrier + * @param string $key * * @return bool */ @@ -207,7 +203,7 @@ public function getBoolConfig(string $carrier, string $key): bool */ public function getTimeConfig(string $carrier, string $key): string { - $timeAsString = str_replace(',', ':', (string) $this->getConfigValue("$carrier$key")); + $timeAsString = str_replace(',', ':', (string)$this->getConfigValue("$carrier$key")); $timeComponents = explode(':', $timeAsString ?? ''); if (count($timeComponents) >= 3) { [$hours, $minutes] = $timeComponents; @@ -227,9 +223,9 @@ public function getTimeConfig(string $carrier, string $key): string */ public function getArrayConfig(string $carrier, string $key): array { - return array_map(static function($val) { - return is_numeric($val) ? (int) $val : $val; - }, explode(',', (string) ($this->getConfigValue("$carrier$key") ?? ''))); + return array_map(static function ($val) { + return is_numeric($val) ? (int)$val : $val; + }, explode(',', (string)($this->getConfigValue("$carrier$key") ?? ''))); } /** @@ -242,6 +238,6 @@ public function getArrayConfig(string $carrier, string $key): array */ public function getIntegerConfig($carrier, $key) { - return (float) $this->getConfigValue("$carrier$key"); + return (float)$this->getConfigValue("$carrier$key"); } } diff --git a/Helper/CustomsDeclarationFromOrder.php b/Helper/CustomsDeclarationFromOrder.php index 65335d16..45798ec9 100644 --- a/Helper/CustomsDeclarationFromOrder.php +++ b/Helper/CustomsDeclarationFromOrder.php @@ -2,16 +2,17 @@ namespace MyParcelNL\Magento\Helper; +use Exception; +use Magento\Catalog\Api\ProductRepositoryInterface; use Magento\Catalog\Model\Product; use Magento\Framework\App\ObjectManager; -use Magento\Framework\ObjectManagerInterface; use Magento\Sales\Model\Order; use MyParcelNL\Magento\Service\Costs\DeliveryCostsService; use MyParcelNL\Magento\Service\Weight\WeightService; +use MyParcelNL\Sdk\src\Exception\MissingFieldException; use MyParcelNL\Sdk\src\Model\Consignment\AbstractConsignment; use MyParcelNL\Sdk\src\Model\CustomsDeclaration; use MyParcelNL\Sdk\src\Model\MyParcelCustomsItem; -use Magento\Catalog\Api\ProductRepositoryInterface; use MyParcelNL\Sdk\src\Support\Str; class CustomsDeclarationFromOrder @@ -24,12 +25,12 @@ class CustomsDeclarationFromOrder private $helper; /** - * @var \Magento\Framework\App\ObjectManager + * @var ObjectManager */ private $objectManager; /** - * @var \Magento\Sales\Model\Order + * @var Order */ private $order; @@ -50,9 +51,9 @@ public function __construct(Order $order) } /** - * @return \MyParcelNL\Sdk\src\Model\CustomsDeclaration - * @throws \MyParcelNL\Sdk\src\Exception\MissingFieldException - * @throws \Exception + * @return CustomsDeclaration + * @throws MissingFieldException + * @throws Exception */ public function createCustomsDeclaration(): CustomsDeclaration { @@ -62,11 +63,11 @@ public function createCustomsDeclaration(): CustomsDeclaration foreach ($this->order->getItems() as $item) { $product = $item->getProduct(); - if (! $product) { + if (!$product) { continue; } - $amount = (float) $item->getQtyShipped() ? $item->getQtyShipped() : $item->getQtyOrdered(); + $amount = (float)$item->getQtyShipped() ? $item->getQtyShipped() : $item->getQtyOrdered(); $totalWeight += $this->weightService->convertToGrams($product->getWeight() * $amount); $description = Str::limit($product->getName(), AbstractConsignment::DESCRIPTION_MAX_LENGTH); @@ -75,9 +76,9 @@ public function createCustomsDeclaration(): CustomsDeclaration ->setAmount($amount) ->setWeight($this->weightService->convertToGrams($product->getWeight())) ->setItemValueArray([ - 'amount' => DeliveryCostsService::getCentsByPrice($product->getPrice()), - 'currency' => $this->order->getOrderCurrency()->getCode() ?? self::CURRENCY_EURO, - ]) + 'amount' => DeliveryCostsService::getPriceInCents($product->getPrice()), + 'currency' => $this->order->getOrderCurrency()->getCode() ?? self::CURRENCY_EURO, + ]) ->setCountry($this->getCountryOfOrigin($product)) ->setClassification($this->getHsCode($product)); @@ -93,7 +94,7 @@ public function createCustomsDeclaration(): CustomsDeclaration } /** - * @param \Magento\Catalog\Model\Product $product + * @param Product $product * * @return string */ @@ -108,13 +109,13 @@ private function getCountryOfOrigin(Product $product): string } /** - * @param \Magento\Catalog\Model\Product $product + * @param Product $product * * @return int */ private function getHsCode(Product $product): int { - return (int) ShipmentOptions::getAttributeValue( + return (int)ShipmentOptions::getAttributeValue( 'catalog_product_entity_int', $product->getId(), 'classification' diff --git a/Model/Carrier/Carrier.php b/Model/Carrier/Carrier.php index 7adf5210..a170f1cf 100644 --- a/Model/Carrier/Carrier.php +++ b/Model/Carrier/Carrier.php @@ -19,19 +19,12 @@ namespace MyParcelNL\Magento\Model\Carrier; use Exception; -use Magento\CatalogInventory\Api\StockRegistryInterface; use Magento\Checkout\Model\Session; -use Magento\Directory\Helper\Data; -use Magento\Directory\Model\CountryFactory; -use Magento\Directory\Model\CurrencyFactory; -use Magento\Directory\Model\RegionFactory; use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\DataObject; -use Magento\Framework\Exception\LocalizedException; -use Magento\Framework\Exception\NoSuchEntityException; use Magento\Framework\Phrase; -use Magento\Framework\Xml\Security; use Magento\OfflineShipping\Model\Carrier\Freeshipping; +use Magento\Quote\Model\Quote; use Magento\Quote\Model\Quote\Address\RateRequest; use Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory; use Magento\Quote\Model\Quote\Address\RateResult\Method; @@ -39,8 +32,6 @@ use Magento\Shipping\Model\Carrier\AbstractCarrier; use Magento\Shipping\Model\Carrier\CarrierInterface; use Magento\Shipping\Model\Rate\ResultFactory; -use Magento\Shipping\Model\Simplexml\ElementFactory; -use Magento\Shipping\Model\Tracking\Result\StatusFactory; use MyParcelNL\Magento\Model\Sales\Repository\PackageRepository; use MyParcelNL\Magento\Service\Config\ConfigService; use MyParcelNL\Magento\Service\Costs\DeliveryCostsService; @@ -64,6 +55,7 @@ class Carrier extends AbstractCarrier implements CarrierInterface * @var PackageRepository */ private $package; + private Quote $quote; /** * Carrier constructor. @@ -106,8 +98,10 @@ public function __construct( $this->_name = $configService->getConfigValue('carriers/myparcel_delivery/name') ?: self::CODE; $this->_title = $configService->getConfigValue('carriers/myparcel_delivery/title') ?: self::CODE; + $this->quote = $session->getQuote(); + try { - $this->deliveryOptions = DeliveryOptionsAdapterFactory::create(json_decode($session->getQuote()->getData(ConfigService::FIELD_DELIVERY_OPTIONS), true)); + $this->deliveryOptions = DeliveryOptionsAdapterFactory::create(json_decode($this->quote->getData(ConfigService::FIELD_DELIVERY_OPTIONS), true)); } catch (Throwable $e) { $this->deliveryOptions = DeliveryOptionsAdapterFactory::create(DeliveryOptionsV3Adapter::DEFAULTS); } @@ -148,24 +142,23 @@ private function getMethodAmount(): float { $configPath = ConfigService::CARRIERS_XML_PATH_MAP[$this->deliveryOptions->getCarrier()] ?? ''; $shipmentOptions = $this->deliveryOptions->getShipmentOptions() ?? new ShipmentOptionsV3Adapter([]); - $dinges = [ + $shipmentFees = [ "{$this->deliveryOptions->getDeliveryType()}/fee" => true, - "{$this->deliveryOptions->getPackageType()}/fee" => true, + //"{$this->deliveryOptions->getPackageType()}/fee" => true, 'delivery/signature_fee' => $shipmentOptions->hasSignature(), 'delivery/only_recipient_fee' => $shipmentOptions->hasOnlyRecipient(), ]; - $amount = $this->deliveryCostsService->getBasePrice(); - foreach ($dinges as $key => $value) { + $amount = $this->deliveryCostsService->getBasePrice($this->quote); + foreach ($shipmentFees as $key => $value) { if (!$value) { continue; } $amount += (float)$this->configService->getConfigValue("$configPath$key"); } - //$bla = $this->myParcelHelper->getCarrierConfig('evening/fee', $path); + return $amount; - die(' weflweiuryfuhj'); //$this->configService->getMethodPrice(ConfigService::XML_PATH_POSTNL_SETTINGS . 'fee', $alias); - $freeShippingIsAvailable = false; // todo // $this->_freeShipping->getConfigData('active') + $freeShippingIsAvailable = false; // todo find out if this order has free shipping // $this->_freeShipping->getConfigData('active') // todo: get actual price based on chosen and possible options for this quote / cart $amount = $freeShippingIsAvailable ? 0.00 : 10.00; return $amount; @@ -173,8 +166,19 @@ private function getMethodAmount(): float private function getMethodTitle(): string { - // todo make a nice title from the options - return var_export($this->deliveryOptions, true); + $d = $this->deliveryOptions; + $s = $d->getShipmentOptions() ?? new ShipmentOptionsV3Adapter([]); + + ob_start(); + echo __("{$d->getDeliveryType()}_title"), ' '; + + foreach ($s->toArray() as $key => $value) { + if ($value) { + echo __("{$key}_title"), ' '; + } + } + + return ob_get_clean(); } public function proccessAdditionalValidation(DataObject $request) @@ -182,27 +186,6 @@ public function proccessAdditionalValidation(DataObject $request) return true; } - /** - * Get allowed shipping methods - * - * @return array - */ - public static function getMethods() - { - $methods = [ - 'signature_only_recip' => 'delivery/signature_and_only_recipient_', - 'morning' => 'morning/', - 'morning_signature' => 'morning_signature/', - 'evening' => 'evening/', - 'evening_signature' => 'evening_signature/', - 'pickup' => 'pickup/', - 'mailbox' => 'mailbox/', - 'digital_stamp' => 'digital_stamp/', - ]; - - return $methods; - } - /** * Get allowed shipping methods * @@ -210,7 +193,7 @@ public static function getMethods() */ public function getAllowedMethods(): array { - return self::getMethods(); + return [$this->_name]; } /** diff --git a/Model/Quote/Checkout.php b/Model/Quote/Checkout.php index 6eb570e8..dab376fc 100644 --- a/Model/Quote/Checkout.php +++ b/Model/Quote/Checkout.php @@ -8,6 +8,7 @@ use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Exception\NoSuchEntityException; use Magento\Store\Model\StoreManagerInterface; +use MyParcelNL\Magento\Facade\Logger; use MyParcelNL\Magento\Model\Sales\Repository\PackageRepository; use MyParcelNL\Magento\Model\Source\PriceDeliveryOptionsView; use MyParcelNL\Magento\Service\Config\ConfigService; @@ -25,7 +26,7 @@ class Checkout /** * @var AbstractCollection[] */ - private $cart; + private $quote; /** * @var StoreManagerInterface @@ -36,6 +37,7 @@ class Checkout * @var mixed */ private $country; + private Session $session; /** * Checkout constructor. @@ -55,9 +57,10 @@ public function __construct( StoreManagerInterface $currency ) { + $this->session = $session; $this->configService = $configService; $this->deliveryCostsService = $deliveryCostsService; - $this->cart = $cart->getQuote(); + $this->quote = $cart->getQuote(); $this->package = $package; $this->currency = $currency; } @@ -118,7 +121,7 @@ private function getGeneralData() 'dropOffDelay' => $this->getDropOffDelay(ConfigService::XML_PATH_GENERAL, 'date_settings/dropoff_delay'), 'pickupLocationsDefaultView' => $this->configService->getConfigValue(ConfigService::XML_PATH_GENERAL . 'shipping_methods/pickup_locations_view'), 'showPriceSurcharge' => $this->configService->getConfigValue(ConfigService::XML_PATH_GENERAL . 'shipping_methods/delivery_options_prices') === PriceDeliveryOptionsView::SURCHARGE, - 'basePrice' => $this->deliveryCostsService->getBasePrice(), + 'basePrice' => $this->deliveryCostsService->getBasePrice($this->quote), ]; } @@ -161,7 +164,6 @@ private function getDeliveryData(?string $packageType = null): array $activeCarriers = $this->getActiveCarriers(); $carrierPaths = ConfigService::CARRIERS_XML_PATH_MAP; $showTotalPrice = $this->configService->getConfigValue(ConfigService::XML_PATH_GENERAL . 'shipping_methods/delivery_options_prices') === PriceDeliveryOptionsView::TOTAL; - foreach ($activeCarriers as $carrier) { $carrierPath = $carrierPaths[$carrier]; @@ -169,7 +171,7 @@ private function getDeliveryData(?string $packageType = null): array $consignment = ConsignmentFactory::createByCarrierName($carrier); $consignment->setPackageType(AbstractConsignment::PACKAGE_TYPE_PACKAGE); } catch (Throwable $ex) { - $this->configService->log(sprintf('getDeliveryData: Could not create default consignment for %s', $carrier)); + Logger::info(sprintf('getDeliveryData: Could not create default consignment for %s', $carrier)); continue; } @@ -187,21 +189,22 @@ private function getDeliveryData(?string $packageType = null): array $mailboxFee = 0; if ($canHaveMailbox) { - $cc = $this->country ?? $this->cart->getShippingAddress()->getCountryId() ?? AbstractConsignment::CC_NL; + $cc = $this->country ?? $this->quote->getShippingAddress()->getCountryId() ?? AbstractConsignment::CC_NL; if (AbstractConsignment::CC_NL === $cc) { - $mailboxFee = $this->deliveryCostsService->getMethodPrice($carrierPath, 'mailbox/fee', false); + $mailboxFee = $this->configService->getFloatConfig($carrierPath, 'mailbox/fee'); } else { - $mailboxFee = $this->deliveryCostsService->getMethodPrice($carrierPath, 'mailbox/international_fee', false); + $mailboxFee = $this->configService->getFloatConfig($carrierPath, 'mailbox/international_fee'); } } - $basePrice = $this->deliveryCostsService->getBasePrice($consignment); - $mondayFee = $canHaveMonday ? $this->deliveryCostsService->getMethodPrice($carrierPath, 'delivery/monday_fee') : 0; - $morningFee = $canHaveMorning ? $this->deliveryCostsService->getMethodPrice($carrierPath, 'morning/fee') : 0; - $eveningFee = $canHaveEvening ? $this->deliveryCostsService->getMethodPrice($carrierPath, 'evening/fee') : 0; - $sameDayFee = $canHaveSameDay ? (int)$this->deliveryCostsService->getMethodPrice($carrierPath, 'delivery/same_day_delivery_fee') : 0; - $signatureFee = $canHaveSignature ? $this->deliveryCostsService->getMethodPrice($carrierPath, 'delivery/signature_fee', false) : 0; - $onlyRecipientFee = $canHaveOnlyRecipient ? $this->deliveryCostsService->getMethodPrice($carrierPath, 'delivery/only_recipient_fee', false) : 0; + $basePrice = $this->deliveryCostsService->getBasePrice($this->quote); + $addBasePrice = ($showTotalPrice) ? $basePrice : 0; + $mondayFee = $canHaveMonday ? $this->configService->getFloatConfig($carrierPath, 'delivery/monday_fee') + $addBasePrice : 0; + $morningFee = $canHaveMorning ? $this->configService->getFloatConfig($carrierPath, 'morning/fee') + $addBasePrice : 0; + $eveningFee = $canHaveEvening ? $this->configService->getFloatConfig($carrierPath, 'evening/fee') + $addBasePrice : 0; + $sameDayFee = $canHaveSameDay ? (int)$this->configService->getFloatConfig($carrierPath, 'delivery/same_day_delivery_fee') + $addBasePrice : 0; + $signatureFee = $canHaveSignature ? $this->configService->getFloatConfig($carrierPath, 'delivery/signature_fee') : 0; + $onlyRecipientFee = $canHaveOnlyRecipient ? $this->configService->getFloatConfig($carrierPath, 'delivery/only_recipient_fee') : 0; $isAgeCheckActive = $canHaveAgeCheck && $this->isAgeCheckActive($carrierPath); $allowPickup = $this->configService->getBoolConfig($carrierPath, 'pickup/active'); @@ -232,7 +235,7 @@ private function getDeliveryData(?string $packageType = null): array 'priceSignature' => $signatureFee, 'priceOnlyRecipient' => $onlyRecipientFee, - 'priceStandardDelivery' => $showTotalPrice ? $basePrice : 0, + 'priceStandardDelivery' => $addBasePrice, 'priceMondayDelivery' => $mondayFee, 'priceMorningDelivery' => $morningFee, 'priceEveningDelivery' => $eveningFee, @@ -243,10 +246,10 @@ private function getDeliveryData(?string $packageType = null): array 'priceEveningSignature' => ($eveningFee + $signatureFee), 'priceSignatureAndOnlyRecipient' => ($basePrice + $signatureFee + $onlyRecipientFee), - 'pricePickup' => $canHavePickup ? $this->deliveryCostsService->getMethodPrice($carrierPath, 'pickup/fee') : 0, + 'pricePickup' => $canHavePickup ? $this->configService->getFloatConfig($carrierPath, 'pickup/fee') + $basePrice : 0, 'pricePackageTypeMailbox' => $mailboxFee, - 'pricePackageTypeDigitalStamp' => $canHaveDigitalStamp ? $this->deliveryCostsService->getMethodPrice($carrierPath, 'digital_stamp/fee', false) : 0, - 'pricePackageTypePackageSmall' => $canHavePackageSmall ? $this->deliveryCostsService->getMethodPrice($carrierPath, 'package_small/fee', false) : 0, + 'pricePackageTypeDigitalStamp' => $canHaveDigitalStamp ? $this->configService->getFloatConfig($carrierPath, 'digital_stamp/fee') : 0, + 'pricePackageTypePackageSmall' => $canHavePackageSmall ? $this->configService->getFloatConfig($carrierPath, 'package_small/fee') : 0, ]; } @@ -356,14 +359,14 @@ public function checkPackageType(string $carrier, ?string $country = null): stri try { $consignment = ConsignmentFactory::createByCarrierName($carrier); } catch (Throwable $e) { - $this->configService->log(sprintf('checkPackageType: Could not create default consignment for %s', $carrier)); + Logger::critical(sprintf('checkPackageType: Could not create default consignment for %s', $carrier)); return AbstractConsignment::DEFAULT_PACKAGE_TYPE_NAME; } $carrierPath = ConfigService::CARRIERS_XML_PATH_MAP[$carrier]; - $products = $this->cart->getAllItems(); - $country = $country ?? $this->country ?? $this->cart->getShippingAddress()->getCountryId(); + $products = $this->quote->getAllItems(); + $country = $country ?? $this->country ?? $this->quote->getShippingAddress()->getCountryId(); $canHaveDigitalStamp = $consignment->canHavePackageType(AbstractConsignment::PACKAGE_TYPE_DIGITAL_STAMP_NAME); $canHaveMailbox = $consignment->canHavePackageType(AbstractConsignment::PACKAGE_TYPE_MAILBOX_NAME); $canHavePackageSmall = $consignment->canHavePackageType(AbstractConsignment::PACKAGE_TYPE_PACKAGE_SMALL_NAME); @@ -396,7 +399,7 @@ public function checkPackageType(string $carrier, ?string $country = null): stri */ public function isAgeCheckActive(string $carrierPath): bool { - $products = $this->cart->getAllItems(); + $products = $this->quote->getAllItems(); return $this->package->getAgeCheck($products, $carrierPath); } @@ -409,7 +412,7 @@ public function isAgeCheckActive(string $carrierPath): bool */ public function getDropOffDelay(string $carrierPath, string $key): int { - $products = $this->cart->getAllItems(); + $products = $this->quote->getAllItems(); $productDelay = (int)$this->package->getProductDropOffDelay($products); $configDelay = $this->configService->getIntegerConfig($carrierPath, $key); @@ -421,7 +424,7 @@ public function getDropOffDelay(string $carrierPath, string $key): int */ public function hideDeliveryOptionsForProduct() { - $products = $this->cart->getAllItems(); + $products = $this->quote->getAllItems(); $this->package->productWithoutDeliveryOptions($products); return $this; diff --git a/Model/Sales/TrackTraceHolder.php b/Model/Sales/TrackTraceHolder.php index 02dbcff8..f16e67a3 100755 --- a/Model/Sales/TrackTraceHolder.php +++ b/Model/Sales/TrackTraceHolder.php @@ -401,7 +401,7 @@ private function convertDataForCdCountry(Track $magentoTrack) ->setDescription($product->getName()) ->setAmount($product->getQty()) ->setWeight($this->weightService->convertToGrams($product->getWeight()) ?: 1) - ->setItemValue($this->deliveryCostsService->getCentsByPrice($product->getPrice())) + ->setItemValue($this->deliveryCostsService->getPriceInCents($product->getPrice())) ->setClassification( (int)$this->getAttributeValue( 'catalog_product_entity_int', diff --git a/Service/Costs/DeliveryCostsService.php b/Service/Costs/DeliveryCostsService.php index f12f70bb..84ee2713 100644 --- a/Service/Costs/DeliveryCostsService.php +++ b/Service/Costs/DeliveryCostsService.php @@ -4,39 +4,27 @@ namespace MyParcelNL\Magento\Service\Costs; -use MyParcelNL\Magento\Model\Source\PriceDeliveryOptionsView; -use MyParcelNL\Magento\Service\Config\ConfigService; +use Magento\Quote\Model\Quote; +use MyParcelNL\Magento\Service\Weight\WeightService; class DeliveryCostsService { - private ConfigService $configService; + private WeightService $weightService; - public function __construct(ConfigService $configService) + public function __construct(WeightService $weightService) { - $this->configService = $configService; + $this->weightService = $weightService; } - /** - * @param string $carrier - * @param string $key - * @param bool $addBasePrice - * @return float - */ - public function getMethodPrice(string $carrier, string $key, bool $addBasePrice = true): float + public function getBasePrice(Quote $quote): float { - $value = $this->configService->getFloatConfig($carrier, $key); - $showTotalPrice = $this->configService->getConfigValue(ConfigService::XML_PATH_GENERAL . 'shipping_methods/delivery_options_prices') === PriceDeliveryOptionsView::TOTAL; - - if ($showTotalPrice && $addBasePrice) { - $value = $this->getBasePrice() + $value; - } + $carrier = $quote->getShippingAddress()->getShippingMethod(); // todo get actual (chosen) carrier + $countryCode = $quote->getShippingAddress()->getCountryId(); + $packageType = 'package'; // todo get actual (chosen) package type + $weight = $this->weightService->getEmptyPackageWeightInGrams($packageType) + + $this->weightService->getQuoteWeightInGrams($quote); - return $value; - } - - // todo: accept country, weight, packagetype, carrier, deliverytype etc. Or maybe a consignment then? - public function getBasePrice(): float - { + // todo implement the actual logic based on configured multi dimensional object return 5; } @@ -45,8 +33,8 @@ public function getBasePrice(): float * * @return int */ - public function getCentsByPrice(float $price): int + public function getPriceInCents(float $price): int { - return (int)$price * 100; + return (int)($price * 100); } } diff --git a/Service/Weight/WeightService.php b/Service/Weight/WeightService.php index 3a317d55..067a17bd 100644 --- a/Service/Weight/WeightService.php +++ b/Service/Weight/WeightService.php @@ -4,7 +4,9 @@ namespace MyParcelNL\Magento\Service\Weight; +use Magento\Quote\Model\Quote; use MyParcelNL\Magento\Service\Config\ConfigService; +use MyParcelNL\Sdk\src\Model\Consignment\AbstractConsignment; class WeightService { @@ -16,10 +18,11 @@ public function __construct(ConfigService $configService) { $this->configService = $configService; } + /** - * Get the correct weight type + * Returns weight in grams based on configured weight indication, defaults to self::DEFAULT_WEIGHT * - * @param null|float $weight + * @param null|float $weight * * @return int */ @@ -28,9 +31,49 @@ public function convertToGrams(?float $weight): int $weightType = $this->configService->getGeneralConfig('print/weight_indication'); if ('kilo' === $weightType) { - return (int) ($weight * 1000); + return (int)($weight * 1000) ?: self::DEFAULT_WEIGHT; + } + + return (int)$weight ?: self::DEFAULT_WEIGHT; + } + + /** + * Returns configured empty weight in grams, defaults to 0 when not found or not set + * + * @param string $packageType + * @return int + */ + public function getEmptyPackageWeightInGrams(string $packageType): int + { + if (!in_array($packageType, AbstractConsignment::PACKAGE_TYPES_NAMES)) { + return 0; + } + + return $this->configService->getGeneralConfig("$packageType/empty_package_weight") ?: 0; + } + + /** + * Returns weight of products in Quote in grams, skips products with quantity < 1 or weight <= 0 + * + * @param Quote $quote + * @return int + */ + public function getQuoteWeightInGrams(Quote $quote): int + { + $products = $quote->getAllItems(); + $weight = 0; + + foreach ($products as $product) { + $productQty = (float)$product->getQty(); + $productWeight = (float)$product->getWeight(); + + if ($productQty < 1 || $productWeight <= 0) { + continue; + } + + $weight += $productWeight * $productQty; } - return (int) $weight ?: self::DEFAULT_WEIGHT; + return $this->convertToGrams($weight); } } From e8c83fea4e2681e022d2e15556e62020810057fa Mon Sep 17 00:00:00 2001 From: Joeri van Veen Date: Thu, 31 Oct 2024 16:50:21 +0100 Subject: [PATCH 12/29] fix: restore default options --- Block/Sales/NewShipment.php | 15 +--- Helper/ShipmentOptions.php | 18 ++--- Model/Sales/TrackTraceHolder.php | 22 +++--- Model/Source/DefaultOptions.php | 120 ++++++++++++++++--------------- 4 files changed, 84 insertions(+), 91 deletions(-) diff --git a/Block/Sales/NewShipment.php b/Block/Sales/NewShipment.php index 9c36bf66..ac0b9d31 100755 --- a/Block/Sales/NewShipment.php +++ b/Block/Sales/NewShipment.php @@ -84,20 +84,7 @@ public function __construct( */ public function hasDefaultOption(string $option, string $carrier): bool { - return $this->defaultOptions->hasDefault($option, $carrier); - } - - /** - * Get default value of age check - * - * @param string $carrier - * @param string $option - * - * @return bool - */ - public function hasDefaultOptionsWithoutPrice(string $carrier, string $option): bool - { - return $this->defaultOptions->hasDefaultOptionsWithoutPrice($carrier, $option); + return $this->defaultOptions->hasOptionSet($option, $carrier); } /** diff --git a/Helper/ShipmentOptions.php b/Helper/ShipmentOptions.php index 68200ce0..dfbcea3b 100644 --- a/Helper/ShipmentOptions.php +++ b/Helper/ShipmentOptions.php @@ -17,8 +17,8 @@ class ShipmentOptions private const ONLY_RECIPIENT = 'only_recipient'; private const SAME_DAY_DELIVERY = 'same_day_delivery'; private const SIGNATURE = 'signature'; - private const RETURN = 'return'; - private const AGE_CHECK = 'age_check'; + private const RETURN = 'return'; + public const AGE_CHECK = 'age_check'; private const LARGE_FORMAT = 'large_format'; private const HIDE_SENDER = 'hide_sender'; private const LABEL_DESCRIPTION = 'label_description'; @@ -36,7 +36,7 @@ class ShipmentOptions /** * @var DefaultOptions */ - private static $defaultOptions; + private $defaultOptions; /** * @var ObjectManagerInterface @@ -79,7 +79,7 @@ public function __construct( array $options = [] ) { - self::$defaultOptions = $defaultOptions; + $this->defaultOptions = $defaultOptions; $this->configService = $objectManager->get(ConfigService::class); $this->datingService = $objectManager->get(DatingService::class); $this->order = $order; @@ -94,7 +94,7 @@ public function __construct( */ public function getInsurance(): int { - return $this->options['insurance'] ?? self::$defaultOptions->getDefaultInsurance($this->carrier); + return $this->options['insurance'] ?? $this->defaultOptions->getDefaultInsurance($this->carrier); } /** @@ -152,7 +152,7 @@ public function hasAgeCheck(): bool $ageCheckFromOptions = self::getValueOfOptionWhenSet(self::AGE_CHECK, $this->options); $ageCheckOfProduct = self::getAgeCheckFromProduct($this->order->getItems()); - $ageCheckFromSettings = self::$defaultOptions->hasDefaultOptionsWithoutPrice($this->carrier, self::AGE_CHECK); + $ageCheckFromSettings = $this->defaultOptions->hasDefaultOption($this->carrier, self::AGE_CHECK); return $ageCheckFromOptions ?? $ageCheckOfProduct ?? $ageCheckFromSettings; } @@ -177,7 +177,7 @@ public static function getAgeCheckFromProduct($products): ?bool $productAgeCheck = self::getAttributeValue( 'catalog_product_entity_varchar', $product['product_id'], - 'age_check' + self::AGE_CHECK ); if (!isset($productAgeCheck) || '' === $productAgeCheck) { @@ -282,7 +282,7 @@ public function hasLargeFormat(): bool } $largeFormatFromOptions = self::getValueOfOptionWhenSet(self::LARGE_FORMAT, $this->options); - $largeFormatFromSettings = self::$defaultOptions->hasDefault(self::LARGE_FORMAT, $this->carrier); + $largeFormatFromSettings = $this->defaultOptions->hasOptionSet(self::LARGE_FORMAT, $this->carrier); return $largeFormatFromOptions ?? $largeFormatFromSettings; } @@ -369,7 +369,7 @@ public function getItemsCollectionByShipmentId($shipmentId): array private function optionIsEnabled($optionKey): bool { if (!isset($this->options[$optionKey])) { - return self::$defaultOptions->hasDefault($optionKey, $this->carrier); + return $this->defaultOptions->hasOptionSet($optionKey, $this->carrier); } return (bool)$this->options[$optionKey]; diff --git a/Model/Sales/TrackTraceHolder.php b/Model/Sales/TrackTraceHolder.php index f16e67a3..c27e7dcd 100755 --- a/Model/Sales/TrackTraceHolder.php +++ b/Model/Sales/TrackTraceHolder.php @@ -51,7 +51,7 @@ class TrackTraceHolder /** * @var DefaultOptions */ - private static $defaultOptions; + private $defaultOptions; /** * @var AbstractConsignment|null @@ -104,7 +104,7 @@ public function __construct( $this->datingService = $objectManager->get(DatingService::class); $this->deliveryCostsService = $objectManager->get(DeliveryCostsService::class); $this->messageManager = $this->objectManager->create('Magento\Framework\Message\ManagerInterface'); - self::$defaultOptions = new DefaultOptions($order); + $this->defaultOptions = new DefaultOptions($order); } /** @@ -130,7 +130,7 @@ public function convertDataFromMagentoToApi(Track $magentoTrack, array $options) ->getName(); $totalWeight = $options['digital_stamp_weight'] !== null ? (int)$options['digital_stamp_weight'] - : (int)self::$defaultOptions->getDigitalStampDefaultWeight(); + : (int)$this->defaultOptions->getDigitalStampDefaultWeight(); try { // create new instance from known json @@ -149,7 +149,7 @@ public function convertDataFromMagentoToApi(Track $magentoTrack, array $options) $this->validateApiKey($apiKey); $this->carrier = $deliveryOptionsAdapter->getCarrier(); $this->shipmentOptionsHelper = new ShipmentOptions( - self::$defaultOptions, + $this->defaultOptions, $order, $this->objectManager, $this->carrier, @@ -161,7 +161,7 @@ public function convertDataFromMagentoToApi(Track $magentoTrack, array $options) ->setReferenceIdentifier($shipment->getEntityId()) ->setConsignmentId($magentoTrack->getData('myparcel_consignment_id')) ->setCountry($address->getCountryId()) - ->setCompany(self::$defaultOptions->getMaxCompanyName($address->getCompany())) + ->setCompany($this->defaultOptions->getMaxCompanyName($address->getCompany())) ->setPerson($address->getName()); try { @@ -344,7 +344,7 @@ private function calculateTotalWeight(Track $magentoTrack, int $totalWeight = 0) return $this; } - $weightFromSettings = (int)self::$defaultOptions->getDigitalStampDefaultWeight(); + $weightFromSettings = (int)$this->defaultOptions->getDigitalStampDefaultWeight(); if ($weightFromSettings) { $this->consignment->setPhysicalProperties(["weight" => $weightFromSettings]); @@ -450,9 +450,9 @@ private function getAgeCheck(Track $magentoTrack, $address, array $options = []) return false; } - $ageCheckFromOptions = ShipmentOptions::getValueOfOptionWhenSet('age_check', $options); + $ageCheckFromOptions = ShipmentOptions::getValueOfOptionWhenSet(ShipmentOptions::AGE_CHECK, $options); $ageCheckOfProduct = ShipmentOptions::getAgeCheckFromProduct($magentoTrack); - $ageCheckFromSettings = self::$defaultOptions->hasDefaultOptionsWithoutPrice($this->carrier, 'age_check'); + $ageCheckFromSettings = $this->defaultOptions->hasDefaultOption($this->carrier, ShipmentOptions::AGE_CHECK); return $ageCheckFromOptions ?? $ageCheckOfProduct ?? $ageCheckFromSettings; } @@ -494,7 +494,7 @@ private function getCarrierFromOptions(array $options): ?string if (array_key_exists('carrier', $options) && $options['carrier']) { $carrier - = DefaultOptions::DEFAULT_OPTION_VALUE === $options['carrier'] ? self::$defaultOptions->getCarrier() + = DefaultOptions::DEFAULT_OPTION_VALUE === $options['carrier'] ? $this->defaultOptions->getCarrier() : $options['carrier']; } @@ -519,11 +519,11 @@ private function getPackageType(array $options, Track $magentoTrack, $address): // get package type from selected radio buttons and check if package type is set $packageType = $options['package_type'] ?? 'default'; if ('default' === $packageType) { - $packageType = self::$defaultOptions->getPackageType(); + $packageType = $this->defaultOptions->getPackageType(); } if (!is_numeric($packageType)) { - $packageType = AbstractConsignment::PACKAGE_TYPES_NAMES_IDS_MAP[$packageType] ?? self::$defaultOptions->getPackageType(); + $packageType = AbstractConsignment::PACKAGE_TYPES_NAMES_IDS_MAP[$packageType] ?? $this->defaultOptions->getPackageType(); } return $packageType; diff --git a/Model/Source/DefaultOptions.php b/Model/Source/DefaultOptions.php index df00f77e..3c835b6f 100755 --- a/Model/Source/DefaultOptions.php +++ b/Model/Source/DefaultOptions.php @@ -29,77 +29,76 @@ class DefaultOptions { // Maximum characters length of company name. - private const COMPANY_NAME_MAX_LENGTH = 50; + private const COMPANY_NAME_MAX_LENGTH = 50; /** @deprecated */ - private const INSURANCE_BELGIUM = 'insurance_belgium_custom'; + private const INSURANCE_BELGIUM = 'insurance_belgium_custom'; /** @deprecated */ - private const INSURANCE_EU_AMOUNT_50 = 'insurance_eu_50'; + private const INSURANCE_EU_AMOUNT_50 = 'insurance_eu_50'; /** @deprecated */ - private const INSURANCE_EU_AMOUNT_500 = 'insurance_eu_500'; + private const INSURANCE_EU_AMOUNT_500 = 'insurance_eu_500'; /** @deprecated */ - private const INSURANCE_AMOUNT_100 = 'insurance_100'; + private const INSURANCE_AMOUNT_100 = 'insurance_100'; /** @deprecated */ - private const INSURANCE_AMOUNT_250 = 'insurance_250'; + private const INSURANCE_AMOUNT_250 = 'insurance_250'; /** @deprecated */ - private const INSURANCE_AMOUNT_500 = 'insurance_500'; + private const INSURANCE_AMOUNT_500 = 'insurance_500'; /** @deprecated */ - private const INSURANCE_AMOUNT_CUSTOM = 'insurance_custom'; + private const INSURANCE_AMOUNT_CUSTOM = 'insurance_custom'; - private const INSURANCE_FROM_PRICE = 'insurance_from_price'; - private const INSURANCE_LOCAL_AMOUNT = 'insurance_local_amount'; - private const INSURANCE_BELGIUM_AMOUNT = 'insurance_belgium_amount'; - private const INSURANCE_EU_AMOUNT = 'insurance_eu_amount'; - private const INSURANCE_ROW_AMOUNT = 'insurance_row_amount'; - private const INSURANCE_PERCENTAGE = 'insurance_percentage'; - public const DEFAULT_OPTION_VALUE = 'default'; + private const INSURANCE_FROM_PRICE = 'insurance_from_price'; + private const INSURANCE_LOCAL_AMOUNT = 'insurance_local_amount'; + private const INSURANCE_BELGIUM_AMOUNT = 'insurance_belgium_amount'; + private const INSURANCE_EU_AMOUNT = 'insurance_eu_amount'; + private const INSURANCE_ROW_AMOUNT = 'insurance_row_amount'; + private const INSURANCE_PERCENTAGE = 'insurance_percentage'; + public const DEFAULT_OPTION_VALUE = 'default'; - private static ConfigService $configService; - private static Order $order; - private static array $chosenOptions; - private static WeightService $weightService; + private ConfigService $configService; + private Order $order; + private array $chosenOptions; + private WeightService $weightService; /** * @param Order $order */ public function __construct(Order $order) { - $objectManager = ObjectManager::getInstance(); - self::$configService = $objectManager->get(ConfigService::class); - self::$weightService = $objectManager->get(WeightService::class); - self::$order = $order; + $objectManager = ObjectManager::getInstance(); + $this->configService = $objectManager->get(ConfigService::class); + $this->weightService = $objectManager->get(WeightService::class); + $this->order = $order; try { - self::$chosenOptions = DeliveryOptionsAdapterFactory::create( + $this->chosenOptions = DeliveryOptionsAdapterFactory::create( (array) json_decode($order->getData(ConfigService::FIELD_DELIVERY_OPTIONS), true) )->toArray(); } catch (Exception $e) { - self::$chosenOptions = []; + $this->chosenOptions = []; } } /** * Get default of the option * - * @param string $option 'only_recipient'|'signature'|'return'|'large_format' - * @param string $carrier + * @param string $option 'only_recipient'|'signature'|'return'|'large_format' + * @param string $carrier * * @return bool */ - public function hasDefault(string $option, string $carrier): bool + public function hasOptionSet(string $option, string $carrier): bool { if (AbstractConsignment::SHIPMENT_OPTION_LARGE_FORMAT === $option) { return $this->hasDefaultLargeFormat($carrier, $option); } // Check that the customer has already chosen this option in the checkout - if (is_array(self::$chosenOptions) && - array_key_exists('shipmentOptions', self::$chosenOptions) && - array_key_exists($option, self::$chosenOptions['shipmentOptions']) && - self::$chosenOptions['shipmentOptions'][$option] + if (array_key_exists('shipmentOptions', $this->chosenOptions) && + array_key_exists($option, $this->chosenOptions['shipmentOptions']) && + $this->chosenOptions['shipmentOptions'][$option] ) { return true; } - return false; + return $this->hasDefaultOption($carrier, $option); } /** @@ -119,21 +118,21 @@ public function getMaxCompanyName(?string $company): ?string /** * Get default value of options without price check * - * @param string $carrier - * @param string $option + * @param string $carrier + * @param string $option * * @return bool */ public function hasDefaultLargeFormat(string $carrier, string $option): bool { - $price = self::$order->getGrandTotal(); - $weight = self::$weightService->convertToGrams(self::$order->getWeight()); + $price = $this->order->getGrandTotal(); + $weight = $this->weightService->convertToGrams($this->order->getWeight()); - $settings = self::$configService->getCarrierConfig($carrier, 'default_options'); + $settings = $this->configService->getCarrierConfig($carrier, 'default_options'); $activeKey = "{$option}_active"; if (isset($settings[$activeKey]) && - 'weight' === $settings[$activeKey] && + 'weight' === $settings[$activeKey] && $weight >= PackageRepository::DEFAULT_LARGE_FORMAT_WEIGHT ) { return true; @@ -150,16 +149,23 @@ public function hasDefaultLargeFormat(string $carrier, string $option): bool } /** - * @param string $carrier - * @param string $option + * @param string $carrier + * @param string $option * * @return bool */ - public function hasDefaultOptionsWithoutPrice(string $carrier, string $option): bool + public function hasDefaultOption(string $carrier, string $option): bool { - $settings = self::$configService->getCarrierConfig($carrier, 'default_options'); + $settings = $this->configService->getCarrierConfig($carrier, 'default_options'); + + if ('1' !== ($settings["{$option}_active"] ?? null)) { + return false; + } + + $fromPrice = $settings["{$option}_from_price"] ?? 0; + $orderAmount = $this->order->getGrandTotal() ?? 0.0; - return '1' === ($settings[$option . '_active'] ?? null); + return $fromPrice <= $orderAmount; } /** @@ -172,7 +178,7 @@ public function hasDefaultOptionsWithoutPrice(string $carrier, string $option): */ public function getDefaultInsurance(string $carrier): int { - $shippingAddress = self::$order->getShippingAddress(); + $shippingAddress = $this->order->getShippingAddress(); $shippingCountry = $shippingAddress ? $shippingAddress->getCountryId() : AbstractConsignment::CC_NL; if (AbstractConsignment::CC_NL === $shippingCountry) { @@ -195,17 +201,17 @@ public function getDefaultInsurance(string $carrier): int */ private function getInsurance(string $carrierName, string $priceKey, string $shippingCountry): int { - $total = self::$order->getGrandTotal(); - $settings = self::$configService->getCarrierConfig($carrierName, 'default_options'); + $total = $this->order->getGrandTotal(); + $settings = $this->configService->getCarrierConfig($carrierName, 'default_options'); $totalAfterPercentage = $total * (($settings[self::INSURANCE_PERCENTAGE] ?? 0) / 100); if (! isset($settings[$priceKey]) - || $settings[$priceKey] === 0 - || $totalAfterPercentage < $settings[self::INSURANCE_FROM_PRICE]) { + || (int) $settings[$priceKey] === 0 + || $totalAfterPercentage < (int) $settings[self::INSURANCE_FROM_PRICE]) { return 0; } - $carrier = ConsignmentFactory::createByCarrierName($carrierName); + $carrier = ConsignmentFactory::createByCarrierName($carrierName); $insuranceTiers = $carrier->getInsurancePossibilities($shippingCountry); sort($insuranceTiers); @@ -230,7 +236,7 @@ private function getInsurance(string $carrierName, string $priceKey, string $shi */ public function getDigitalStampDefaultWeight(): string { - return self::$configService->getConfigValue('myparcelnl_magento_postnl_settings/digital_stamp/default_weight'); + return $this->configService->getConfigValue('myparcelnl_magento_postnl_settings/digital_stamp/default_weight'); } /** @@ -240,11 +246,11 @@ public function getDigitalStampDefaultWeight(): string */ public function getPackageType(): int { - if (self::$chosenOptions) { - $keyIsPresent = array_key_exists('packageType', self::$chosenOptions); + if ($this->chosenOptions) { + $keyIsPresent = array_key_exists('packageType', $this->chosenOptions); if ($keyIsPresent) { - $packageType = self::$chosenOptions['packageType']; + $packageType = $this->chosenOptions['packageType']; return AbstractConsignment::PACKAGE_TYPES_NAMES_IDS_MAP[$packageType]; } @@ -258,11 +264,11 @@ public function getPackageType(): int */ public function getCarrier(): string { - if (self::$chosenOptions) { - $keyIsPresent = array_key_exists('carrier', self::$chosenOptions); + if ($this->chosenOptions) { + $keyIsPresent = array_key_exists('carrier', $this->chosenOptions); if ($keyIsPresent) { - return self::$chosenOptions['carrier']; + return $this->chosenOptions['carrier']; } } From a5c030200539ce2c65cf19ae266019b7549ac5ce Mon Sep 17 00:00:00 2001 From: Joeri van Veen Date: Thu, 31 Oct 2024 17:36:22 +0100 Subject: [PATCH 13/29] feat: add receipt code --- Adapter/ShipmentOptionsFromAdapter.php | 14 ++-- Block/Sales/NewShipment.php | 39 +++++++---- Block/Sales/NewShipmentForm.php | 23 ++++++- Helper/ShipmentOptions.php | 30 +++++++-- Model/Quote/Checkout.php | 42 +++++++----- Model/Sales/MagentoCollection.php | 73 +++++++++++---------- Model/Sales/TrackTraceHolder.php | 61 ++++++++--------- Model/Source/DefaultOptions.php | 9 +-- Observer/NewShipment.php | 22 +++---- composer.json | 2 +- etc/adminhtml/system.xml | 52 +++++++++++---- i18n/en_US.csv | 1 + i18n/fr_FR.csv | 4 ++ i18n/nl_NL.csv | 4 ++ view/adminhtml/templates/new_shipment.phtml | 7 ++ 15 files changed, 243 insertions(+), 140 deletions(-) diff --git a/Adapter/ShipmentOptionsFromAdapter.php b/Adapter/ShipmentOptionsFromAdapter.php index 956fd35f..cca2c0b1 100644 --- a/Adapter/ShipmentOptionsFromAdapter.php +++ b/Adapter/ShipmentOptionsFromAdapter.php @@ -4,6 +4,7 @@ namespace MyParcelNL\Magento\Adapter; +use MyParcelNL\Magento\Helper\ShipmentOptions; use MyParcelNL\Sdk\src\Adapter\DeliveryOptions\AbstractDeliveryOptionsAdapter; use MyParcelNL\Sdk\src\Adapter\DeliveryOptions\AbstractShipmentOptionsAdapter; @@ -17,11 +18,12 @@ class ShipmentOptionsFromAdapter extends AbstractShipmentOptionsAdapter public function __construct(array $inputData) { $options = $inputData ?? []; - $this->signature = (bool) ($options['signature'] ?? false); - $this->only_recipient = (bool) ($options['only_recipient'] ?? false); - $this->large_format = (bool) ($options['large_format'] ?? false); - $this->age_check = (bool) ($options['age_check'] ?? false); - $this->return = (bool) ($options['return'] ?? false); - $this->insurance = (int) ($options['insurance'] ?? self::DEFAULT_INSURANCE); + $this->signature = (bool) ($options[ShipmentOptions::SIGNATURE] ?? false); + $this->receipt_code = (bool) ($options[ShipmentOptions::RECEIPT_CODE] ?? false); + $this->only_recipient = (bool) ($options[ShipmentOptions::ONLY_RECIPIENT] ?? false); + $this->large_format = (bool) ($options[ShipmentOptions::LARGE_FORMAT] ?? false); + $this->age_check = (bool) ($options[ShipmentOptions::AGE_CHECK] ?? false); + $this->return = (bool) ($options[ShipmentOptions::RETURN] ?? false); + $this->insurance = (int) ($options[ShipmentOptions::INSURANCE] ?? self::DEFAULT_INSURANCE); } } diff --git a/Block/Sales/NewShipment.php b/Block/Sales/NewShipment.php index ac0b9d31..d6ab7146 100755 --- a/Block/Sales/NewShipment.php +++ b/Block/Sales/NewShipment.php @@ -14,12 +14,14 @@ namespace MyParcelNL\Magento\Block\Sales; +use Exception; use Magento\Backend\Block\Template\Context; use Magento\CatalogInventory\Api\StockConfigurationInterface; use Magento\CatalogInventory\Api\StockRegistryInterface; use Magento\Framework\ObjectManagerInterface; use Magento\Framework\Registry; use Magento\Sales\Block\Adminhtml\Items\AbstractItems; +use MyParcelNL\Magento\Helper\Checkout; use MyParcelNL\Magento\Model\Sales\MagentoOrderCollection; use MyParcelNL\Magento\Model\Source\DefaultOptions; use MyParcelNL\Magento\Model\Sales\TrackTraceHolder; @@ -51,18 +53,19 @@ class NewShipment extends AbstractItems private MagentoOrderCollection $orderCollection; /** - * @param Context $context - * @param StockRegistryInterface $stockRegistry + * @param Context $context + * @param StockRegistryInterface $stockRegistry * @param StockConfigurationInterface $stockConfiguration - * @param Registry $registry + * @param Registry $registry */ public function __construct( - Context $context, - StockRegistryInterface $stockRegistry, + Context $context, + StockRegistryInterface $stockRegistry, StockConfigurationInterface $stockConfiguration, - Registry $registry, - ObjectManagerInterface $objectManager - ) { + Registry $registry, + ObjectManagerInterface $objectManager + ) + { $this->order = $registry->registry('current_shipment')->getOrder(); $this->weightService = $objectManager->get(WeightService::class); $this->configService = $objectManager->get(ConfigService::class); @@ -70,15 +73,15 @@ public function __construct( $this->defaultOptions = new DefaultOptions($this->order); - $request = $objectManager->get('Magento\Framework\App\RequestInterface'); + $request = $objectManager->get('Magento\Framework\App\RequestInterface'); $this->orderCollection = new MagentoOrderCollection($objectManager, $request); parent::__construct($context, $stockRegistry, $stockConfiguration, $registry); } /** - * @param string $option 'signature', 'only_recipient' - * @param string $carrier + * @param string $option 'signature', 'only_recipient' + * @param string $carrier * * @return bool */ @@ -90,7 +93,7 @@ public function hasDefaultOption(string $option, string $carrier): bool /** * Get default value of insurance based on order grand total * - * @param string $carrier + * @param string $carrier * * @return int */ @@ -138,6 +141,18 @@ public function getCountry() return $this->order->getShippingAddress()->getCountryId(); } + public function getDeliveryType(): int + { + try { + $deliveryTypeName = json_decode($this->order->getData(Checkout::FIELD_DELIVERY_OPTIONS), true)['deliveryType']; + $deliveryType = AbstractConsignment::DELIVERY_TYPES_NAMES_IDS_MAP[$deliveryTypeName]; + } catch (Exception $e) { + $deliveryType = AbstractConsignment::DEFAULT_DELIVERY_TYPE; + } + + return $deliveryType; + } + public function consignmentHasShipmentOption(AbstractConsignment $consignment, string $shipmentOption): bool { /** diff --git a/Block/Sales/NewShipmentForm.php b/Block/Sales/NewShipmentForm.php index ec361cbd..3b610c7e 100644 --- a/Block/Sales/NewShipmentForm.php +++ b/Block/Sales/NewShipmentForm.php @@ -2,6 +2,7 @@ namespace MyParcelNL\Magento\Block\Sales; +use Exception; use MyParcelNL\Sdk\src\Factory\ConsignmentFactory; use MyParcelNL\Sdk\src\Model\Carrier\CarrierDHLEuroplus; use MyParcelNL\Sdk\src\Model\Carrier\CarrierDHLForYou; @@ -34,7 +35,12 @@ class NewShipmentForm /** * @var array */ - private $shipmentOptionsHumanMap; + private array $shipmentOptionsHumanMap; + + /** + * @var array + */ + private array $shipmentOptionsExplanation; public function __construct() @@ -48,10 +54,15 @@ public function __construct() AbstractConsignment::SHIPMENT_OPTION_RETURN => __('Return if no answer'), AbstractConsignment::SHIPMENT_OPTION_SAME_DAY_DELIVERY => __('Same day delivery'), ]; + + $this->shipmentOptionsExplanation = [ + AbstractConsignment::SHIPMENT_OPTION_RECEIPT_CODE => __('Insurance is mandatory and will be set. Other shipment options will be removed.'), + ]; } + /** * @return AbstractConsignment[] - * @throws \Exception + * @throws Exception */ public function getCarrierSpecificAbstractConsignments(): array { @@ -71,4 +82,12 @@ public function getShipmentOptionsHumanMap(): array { return $this->shipmentOptionsHumanMap; } + + /** + * @return array + */ + public function getShipmentOptionsExplanationMap(): array + { + return $this->shipmentOptionsExplanation; + } } diff --git a/Helper/ShipmentOptions.php b/Helper/ShipmentOptions.php index dfbcea3b..9a5561ca 100644 --- a/Helper/ShipmentOptions.php +++ b/Helper/ShipmentOptions.php @@ -8,18 +8,20 @@ use MyParcelNL\Magento\Model\Source\DefaultOptions; use MyParcelNL\Magento\Service\Config\ConfigService; use MyParcelNL\Magento\Service\Date\DatingService; +use MyParcelNL\Sdk\src\Model\Carrier\CarrierPostNL; use MyParcelNL\Sdk\src\Model\Consignment\AbstractConsignment; use Magento\Framework\App\ResourceConnection; class ShipmentOptions { - private const INSURANCE = 'insurance'; - private const ONLY_RECIPIENT = 'only_recipient'; + public const INSURANCE = 'insurance'; + public const ONLY_RECIPIENT = 'only_recipient'; private const SAME_DAY_DELIVERY = 'same_day_delivery'; - private const SIGNATURE = 'signature'; - private const RETURN = 'return'; - public const AGE_CHECK = 'age_check'; - private const LARGE_FORMAT = 'large_format'; + public const SIGNATURE = 'signature'; + public const RECEIPT_CODE = AbstractConsignment::SHIPMENT_OPTION_RECEIPT_CODE; + public const RETURN = 'return'; + public const AGE_CHECK = 'age_check'; + public const LARGE_FORMAT = 'large_format'; private const HIDE_SENDER = 'hide_sender'; private const LABEL_DESCRIPTION = 'label_description'; private const ORDER_NUMBER = '%order_nr%'; @@ -111,6 +113,21 @@ public function hasSignature(): bool return $signatureFromOptions ?? $this->optionIsEnabled(self::SIGNATURE); } + public function hasReceiptCode(): bool + { + $deliveryOptions = $this->order->getData(Checkout::FIELD_DELIVERY_OPTIONS) ?? []; + $deliveryType = $deliveryOptions['deliveryType'] ?? AbstractConsignment::DEFAULT_DELIVERY_TYPE; + + if (AbstractConsignment::CC_NL !== $this->cc + || CarrierPostNL::NAME !== $this->carrier + || AbstractConsignment::DELIVERY_TYPE_STANDARD !== $deliveryType + ) { + return false; + } + + return self::getValueOfOptionWhenSet(self::RECEIPT_CODE, $this->options) ?? $this->optionIsEnabled(self::RECEIPT_CODE); + } + /** * @return bool */ @@ -385,6 +402,7 @@ public function getShipmentOptions(): array self::RETURN => $this->hasReturn(), self::ONLY_RECIPIENT => $this->hasOnlyRecipient(), self::SIGNATURE => $this->hasSignature(), + self::RECEIPT_CODE => $this->hasReceiptCode(), self::AGE_CHECK => $this->hasAgeCheck(), self::LARGE_FORMAT => $this->hasLargeFormat(), self::LABEL_DESCRIPTION => $this->getLabelDescription(), diff --git a/Model/Quote/Checkout.php b/Model/Quote/Checkout.php index dab376fc..76de74c2 100644 --- a/Model/Quote/Checkout.php +++ b/Model/Quote/Checkout.php @@ -19,8 +19,12 @@ class Checkout { - private ConfigService $configService; + private ConfigService $configService; private DeliveryCostsService $deliveryCostsService; + + /** + * @var \MyParcelNL\Magento\Model\Sales\Repository\PackageRepository + */ private PackageRepository $package; /** @@ -36,16 +40,16 @@ class Checkout /** * @var mixed */ - private $country; + private $country; private Session $session; /** * Checkout constructor. * - * @param Session $session - * @param Cart $cart - * @param ConfigService $configService - * @param PackageRepository $package + * @param Session $session + * @param Cart $cart + * @param ConfigService $configService + * @param PackageRepository $package * @param StoreManagerInterface $currency */ public function __construct( @@ -106,7 +110,7 @@ public function getDeliveryOptions(array $forAddress = []): array /** * Get general data * - * @return array) + * @return array * @throws NoSuchEntityException|LocalizedException */ private function getGeneralData() @@ -183,6 +187,7 @@ private function getDeliveryData(?string $packageType = null): array $canHaveMorning = $consignment->canHaveDeliveryType(AbstractConsignment::DELIVERY_TYPE_MORNING_NAME); $canHaveEvening = $consignment->canHaveDeliveryType(AbstractConsignment::DELIVERY_TYPE_EVENING_NAME); $canHaveSignature = $consignment->canHaveShipmentOption(AbstractConsignment::SHIPMENT_OPTION_SIGNATURE); + $canHaveReceiptCode = $consignment->canHaveShipmentOption(AbstractConsignment::SHIPMENT_OPTION_RECEIPT_CODE); $canHaveOnlyRecipient = $consignment->canHaveShipmentOption(AbstractConsignment::SHIPMENT_OPTION_ONLY_RECIPIENT); $canHaveAgeCheck = $consignment->canHaveShipmentOption(AbstractConsignment::SHIPMENT_OPTION_AGE_CHECK); $canHavePickup = $consignment->canHaveDeliveryType(AbstractConsignment::DELIVERY_TYPE_PICKUP_NAME); @@ -202,16 +207,17 @@ private function getDeliveryData(?string $packageType = null): array $mondayFee = $canHaveMonday ? $this->configService->getFloatConfig($carrierPath, 'delivery/monday_fee') + $addBasePrice : 0; $morningFee = $canHaveMorning ? $this->configService->getFloatConfig($carrierPath, 'morning/fee') + $addBasePrice : 0; $eveningFee = $canHaveEvening ? $this->configService->getFloatConfig($carrierPath, 'evening/fee') + $addBasePrice : 0; - $sameDayFee = $canHaveSameDay ? (int)$this->configService->getFloatConfig($carrierPath, 'delivery/same_day_delivery_fee') + $addBasePrice : 0; + $sameDayFee = $canHaveSameDay ? (int) $this->configService->getFloatConfig($carrierPath, 'delivery/same_day_delivery_fee') + $addBasePrice : 0; $signatureFee = $canHaveSignature ? $this->configService->getFloatConfig($carrierPath, 'delivery/signature_fee') : 0; + $receiptCodeFee = $canHaveReceiptCode ? $this->configService->getFloatConfig($carrierPath, 'delivery/receipt_code_fee') : 0; $onlyRecipientFee = $canHaveOnlyRecipient ? $this->configService->getFloatConfig($carrierPath, 'delivery/only_recipient_fee') : 0; $isAgeCheckActive = $canHaveAgeCheck && $this->isAgeCheckActive($carrierPath); $allowPickup = $this->configService->getBoolConfig($carrierPath, 'pickup/active'); $allowStandardDelivery = $this->configService->getBoolConfig($carrierPath, 'delivery/active'); - $allowMorningDelivery = !$isAgeCheckActive && $canHaveMorning && $this->configService->getBoolConfig($carrierPath, 'morning/active'); - $allowEveningDelivery = !$isAgeCheckActive && $canHaveEvening && $this->configService->getBoolConfig($carrierPath, 'evening/active'); - $allowDeliveryOptions = !$this->package->deliveryOptionsDisabled + $allowMorningDelivery = ! $isAgeCheckActive && $canHaveMorning && $this->configService->getBoolConfig($carrierPath, 'morning/active'); + $allowEveningDelivery = ! $isAgeCheckActive && $canHaveEvening && $this->configService->getBoolConfig($carrierPath, 'evening/active'); + $allowDeliveryOptions = ! $this->package->deliveryOptionsDisabled && ($allowPickup || $allowStandardDelivery || $allowMorningDelivery || $allowEveningDelivery); if ($allowDeliveryOptions && $packageType === AbstractConsignment::PACKAGE_TYPE_MAILBOX_NAME) { @@ -224,6 +230,7 @@ private function getDeliveryData(?string $packageType = null): array 'allowDeliveryOptions' => $allowDeliveryOptions, 'allowStandardDelivery' => $allowStandardDelivery, 'allowSignature' => $canHaveSignature && $this->configService->getBoolConfig($carrierPath, 'delivery/signature_active'), + 'allowReceiptCode' => $canHaveReceiptCode && $this->configService->getBoolConfig($carrierPath, 'delivery/receipt_code_active'), 'allowOnlyRecipient' => $canHaveOnlyRecipient && $this->configService->getBoolConfig($carrierPath, 'delivery/only_recipient_active'), 'allowMorningDelivery' => $allowMorningDelivery, 'allowEveningDelivery' => $allowEveningDelivery, @@ -234,6 +241,7 @@ private function getDeliveryData(?string $packageType = null): array 'dropOffDays' => $this->getDropOffDays($carrierPath), 'priceSignature' => $signatureFee, + 'priceReceiptCode' => $receiptCodeFee, 'priceOnlyRecipient' => $onlyRecipientFee, 'priceStandardDelivery' => $addBasePrice, 'priceMondayDelivery' => $mondayFee, @@ -282,7 +290,7 @@ private function getDropOffDays(string $carrierPath): array $cutoffTimeSameDay = $this->configService->getTimeConfig($carrierPath, "drop_off_days/cutoff_time_same_day_$weekday"); $sameDayTimeEntry = $cutoffTimeSameDay ? ['cutoffTimeSameDay' => $cutoffTimeSameDay] : []; if ($this->configService->getBoolConfig($carrierPath, "drop_off_days/day_{$weekday}_active")) { - $dropOffDays[] = (object)array_merge( + $dropOffDays[] = (object) array_merge( [ 'weekday' => $weekday, 'cutoffTime' => $this->configService->getTimeConfig($carrierPath, "drop_off_days/cutoff_time_$weekday"), @@ -349,7 +357,7 @@ private function getDeliveryOptionsStrings(): array } /** - * @param string $carrier + * @param string $carrier * @param string|null $country * * @return string @@ -413,14 +421,14 @@ public function isAgeCheckActive(string $carrierPath): bool public function getDropOffDelay(string $carrierPath, string $key): int { $products = $this->quote->getAllItems(); - $productDelay = (int)$this->package->getProductDropOffDelay($products); + $productDelay = (int) $this->package->getProductDropOffDelay($products); $configDelay = $this->configService->getIntegerConfig($carrierPath, $key); return max($productDelay, $configDelay); } /** - * @return $this + * @return self */ public function hideDeliveryOptionsForProduct() { @@ -440,8 +448,8 @@ private function isPickupAllowed(string $carrier): bool $isMailboxPackage = AbstractConsignment::PACKAGE_TYPE_MAILBOX_NAME === $this->getPackageType(); $pickupEnabled = $this->configService->getBoolConfig($carrier, 'pickup/active'); $showPickupForMailbox = $this->configService->getBoolConfig($carrier, 'mailbox/pickup_mailbox'); - $showPickup = !$isMailboxPackage || $showPickupForMailbox; + $showPickup = ! $isMailboxPackage || $showPickupForMailbox; - return !$this->package->deliveryOptionsDisabled && $pickupEnabled && $showPickup; + return ! $this->package->deliveryOptionsDisabled && $pickupEnabled && $showPickup; } } diff --git a/Model/Sales/MagentoCollection.php b/Model/Sales/MagentoCollection.php index 81a5ae8e..a17ec7c3 100755 --- a/Model/Sales/MagentoCollection.php +++ b/Model/Sales/MagentoCollection.php @@ -52,27 +52,27 @@ */ abstract class MagentoCollection implements MagentoCollectionInterface { - public const PATH_MODEL_ORDER_COLLECTION = OrderCollection::class; - public const PATH_MODEL_SHIPMENT_COLLECTION = ShipmentCollection::class; - public const ERROR_ORDER_HAS_NO_SHIPMENT = 'No shipment can be made with this order. Shipments can not be created if the status is On Hold or if the product is digital.'; - public const ERROR_ORDER_HAS_NO_SOURCE = 'Creating shipments via bulk actions is not possible for orders without a source. Go to the details of the order and process the shipment manually.'; + public const PATH_MODEL_ORDER_COLLECTION = OrderCollection::class; + public const PATH_MODEL_SHIPMENT_COLLECTION = ShipmentCollection::class; + public const ERROR_ORDER_HAS_NO_SHIPMENT = 'No shipment can be made with this order. Shipments can not be created if the status is On Hold or if the product is digital.'; + public const ERROR_ORDER_HAS_NO_SOURCE = 'Creating shipments via bulk actions is not possible for orders without a source. Go to the details of the order and process the shipment manually.'; public const DEFAULT_ERROR_ORDER_HAS_NO_SOURCE = 'Source item not found by source code'; - private const PATH_ORDER_TRACK = '\Magento\Sales\Model\Order\Shipment\Track'; - private const PATH_MANAGER_INTERFACE = '\Magento\Framework\Message\ManagerInterface'; + private const PATH_ORDER_TRACK = '\Magento\Sales\Model\Order\Shipment\Track'; + private const PATH_MANAGER_INTERFACE = '\Magento\Framework\Message\ManagerInterface'; private const PATH_ORDER_TRACK_COLLECTION = '\Magento\Sales\Model\ResourceModel\Order\Shipment\Track\Collection'; - public MyParcelCollection $myParcelCollection; - public ?RequestInterface $request = null; - protected Manager $moduleManager; - protected SourceItem $sourceItem; - protected TrackSender $trackSender; + public MyParcelCollection $myParcelCollection; + public ?RequestInterface $request = null; + protected Manager $moduleManager; + protected SourceItem $sourceItem; + protected TrackSender $trackSender; protected ObjectManagerInterface $objectManager; - protected Track $modelTrack; - protected AreaList $areaList; - protected ManagerInterface $messageManager; - protected ConfigService $configService; + protected Track $modelTrack; + protected AreaList $areaList; + protected ManagerInterface $messageManager; + protected ConfigService $configService; /** * @var array @@ -85,6 +85,7 @@ abstract class MagentoCollection implements MagentoCollectionInterface 'carrier' => 'postnl', 'positions' => null, 'signature' => null, + 'receipt_code' => null, 'only_recipient' => null, 'return' => null, 'large_format' => null, @@ -102,8 +103,8 @@ abstract class MagentoCollection implements MagentoCollectionInterface /** * @param ObjectManagerInterface $objectManager - * @param null $request - * @param null $areaList + * @param null $request + * @param null $areaList */ public function __construct( ObjectManagerInterface $objectManager, @@ -134,7 +135,7 @@ public function __construct( /** * Set options from POST or GET variables * - * @return $this + * @return self */ public function setOptionsFromParameters() { @@ -207,7 +208,7 @@ public function getOption($option) * * @param $consignment BaseConsignment * - * @return $this + * @return self * @throws Exception */ public function addConsignment(BaseConsignment $consignment) @@ -230,7 +231,7 @@ public function getHtmlForGridColumns($orderId) * @todo; Adjust if there is a solution to the following problem: https://github.com/magento/magento2/pull/8413 */ // Temporarily fix to translate in cronjob - if (!empty($this->areaList)) { + if (! empty($this->areaList)) { $areaObject = $this->areaList->getArea(Area::AREA_ADMINHTML); $areaObject->load(Area::PART_TRANSLATE); } @@ -342,7 +343,7 @@ protected function createConsignmentAndGetTrackTraceHolder($magentoTrack): Track } /** - * @return $this + * @return self */ public function syncMagentoToMyparcel(): self { @@ -361,14 +362,14 @@ public function syncMagentoToMyparcel(): self } /** - * @return $this + * @return self * @throws ApiException * @throws MissingFieldException * @throws Exception */ public function createMyParcelConcepts(): self { - if (!count($this->myParcelCollection)) { + if (! count($this->myParcelCollection)) { $this->messageManager->addWarningMessage(__('myparcelnl_magento_error_no_shipments_to_process')); return $this; } @@ -388,7 +389,7 @@ public function createMyParcelConcepts(): self /** * Add MyParcel Track from Magento Track * - * @return $this + * @return self * @throws Exception */ public function setNewMyParcelTracks(): self @@ -398,7 +399,7 @@ public function setNewMyParcelTracks(): self $multiColloConsignments = []; /** * @var Order\Shipment $shipment - * @var Track $magentoTrack + * @var Track $magentoTrack */ foreach ($shipments as $shipment) { $magentoTracks = $this->getTrackByShipment($shipment)->getItems(); @@ -431,7 +432,7 @@ public function setNewMyParcelTracks(): self /** * @param array $multiColloConsignments * - * @return $this + * @return self */ protected function addGroupedConsignments(array $multiColloConsignments): self { @@ -452,7 +453,7 @@ protected function addGroupedConsignments(array $multiColloConsignments): self /** * @param AbstractConsignment $consignment - * @param int $quantity + * @param int $quantity * * @throws MissingFieldException */ @@ -506,7 +507,7 @@ function ( } /** - * @return $this + * @return self * @throws Exception */ public function updateMagentoTrack(): self @@ -522,13 +523,13 @@ public function updateMagentoTrack(): self $magentoTrack->getData('myparcel_consignment_id') ); - if (!$myParcelTrack) { + if (! $myParcelTrack) { if ($consignments->isEmpty()) { continue; } $myParcelTrack = $consignments->pop(); - if (!$myParcelTrack->getConsignmentId()) { + if (! $myParcelTrack->getConsignmentId()) { continue; } $magentoTrack->setData('myparcel_consignment_id', $myParcelTrack->getConsignmentId()); @@ -550,7 +551,7 @@ public function updateMagentoTrack(): self } /** - * @return $this + * @return self * @throws AccountNotActiveException * @throws ApiException * @throws MissingFieldException @@ -567,18 +568,18 @@ public function addReturnShipments(): self } /** - * @return $this + * @return self */ protected function updateOrderGrid(): self { $shipments = $this->getShipmentsCollection(); - if (!$shipments) { + if (! $shipments) { return $this; } foreach ($shipments as $shipment) { - if (!$shipment || !method_exists($shipment, 'getOrder')) { + if (! $shipment || ! method_exists($shipment, 'getOrder')) { continue; } @@ -629,7 +630,7 @@ protected function getMyparcelConsignmentIdsForShipments(): array foreach ($shipments as $shipment) { $trackCollection = $shipment->getAllTracks(); foreach ($trackCollection as $magentoTrack) { - $consignmentId = (int)$magentoTrack->getData('myparcel_consignment_id'); + $consignmentId = (int) $magentoTrack->getData('myparcel_consignment_id'); if ($consignmentId) { $consignmentIds[] = $consignmentId; } @@ -663,7 +664,7 @@ public function canUseMultiCollo(AbstractConsignment $consignment): bool */ private function setSourceItemWhenInventoryApiEnabled(): void { - if (!$this->moduleManager->isEnabled('Magento_InventoryApi')) { + if (! $this->moduleManager->isEnabled('Magento_InventoryApi')) { return; } $this->sourceItem = $this->objectManager->get(SourceItem::class); diff --git a/Model/Sales/TrackTraceHolder.php b/Model/Sales/TrackTraceHolder.php index c27e7dcd..52bd9a14 100755 --- a/Model/Sales/TrackTraceHolder.php +++ b/Model/Sales/TrackTraceHolder.php @@ -83,15 +83,15 @@ class TrackTraceHolder /** * @var ShipmentOptions */ - private $shipmentOptionsHelper; - private WeightService $weightService; + private $shipmentOptionsHelper; + private WeightService $weightService; private DeliveryCostsService $deliveryCostsService; /** * TrackTraceHolder constructor. * * @param ObjectManagerInterface $objectManager - * @param Order $order + * @param Order $order */ public function __construct( ObjectManagerInterface $objectManager, @@ -111,9 +111,9 @@ public function __construct( * Set all data to MyParcel object * * @param Order\Shipment\Track $magentoTrack - * @param array $options + * @param array $options * - * @return $this + * @return self * @throws Exception * @throws LocalizedException */ @@ -129,15 +129,15 @@ public function convertDataFromMagentoToApi(Track $magentoTrack, array $options) ?? DefaultOptions::getDefaultCarrier() ->getName(); - $totalWeight = $options['digital_stamp_weight'] !== null ? (int)$options['digital_stamp_weight'] - : (int)$this->defaultOptions->getDigitalStampDefaultWeight(); + $totalWeight = $options['digital_stamp_weight'] !== null ? (int) $options['digital_stamp_weight'] + : (int) $this->defaultOptions->getDigitalStampDefaultWeight(); try { // create new instance from known json - $deliveryOptionsAdapter = DeliveryOptionsAdapterFactory::create((array)$deliveryOptions); + $deliveryOptionsAdapter = DeliveryOptionsAdapterFactory::create((array) $deliveryOptions); } catch (BadMethodCallException $e) { // create new instance from unknown json data - $deliveryOptionsAdapter = new DeliveryOptionsFromOrderAdapter((array)$deliveryOptions + $options); + $deliveryOptionsAdapter = new DeliveryOptionsFromOrderAdapter((array) $deliveryOptions + $options); } $pickupLocationAdapter = $deliveryOptionsAdapter->getPickupLocation(); @@ -208,6 +208,7 @@ public function convertDataFromMagentoToApi(Track $magentoTrack, array $options) ->setDropOffPoint($dropOffPoint) ->setOnlyRecipient($this->shipmentOptionsHelper->hasOnlyRecipient()) ->setSignature($this->shipmentOptionsHelper->hasSignature()) + ->setReceiptCode($this->shipmentOptionsHelper->hasReceiptCode()) ->setReturn($this->shipmentOptionsHelper->hasReturn()) ->setSameDayDelivery($this->shipmentOptionsHelper->hasSameDayDelivery()) ->setLargeFormat($this->shipmentOptionsHelper->hasLargeFormat()) @@ -252,7 +253,7 @@ public function convertDataFromMagentoToApi(Track $magentoTrack, array $options) * * @param Shipment $shipment * - * @return $this + * @return self */ public function createTrackTraceFromShipment(Shipment $shipment) { @@ -269,7 +270,7 @@ public function createTrackTraceFromShipment(Shipment $shipment) } /** - * @param int $orderId + * @param int $orderId * @param string $status */ private function setOrderStatus(int $orderId, string $status): void @@ -285,15 +286,15 @@ private function setOrderStatus(int $orderId, string $status): void /** * Get country of origin from product settings or, if they are not found, from the MyParcel settings. * - * @param $product_id + * @param int $product_id * * @return string */ public function getCountryOfOrigin(int $product_id): string { - $product - = $this->objectManager->get('Magento\Catalog\Api\ProductRepositoryInterface') - ->getById($product_id); + $product = $this->objectManager->get('Magento\Catalog\Api\ProductRepositoryInterface') + ->getById($product_id); + $productCountryOfManufacture = $product->getCountryOfManufacture(); if ($productCountryOfManufacture) { @@ -308,7 +309,7 @@ public function getCountryOfOrigin(int $product_id): string * * @param null|string $apiKey * - * @return $this + * @return self * @throws LocalizedException */ public function validateApiKey(?string $apiKey): self @@ -326,7 +327,7 @@ public function validateApiKey(?string $apiKey): self /** * @param Order\Shipment\Track $magentoTrack - * @param int $totalWeight + * @param int $totalWeight * * @return TrackTraceHolder * @throws LocalizedException @@ -344,7 +345,7 @@ private function calculateTotalWeight(Track $magentoTrack, int $totalWeight = 0) return $this; } - $weightFromSettings = (int)$this->defaultOptions->getDigitalStampDefaultWeight(); + $weightFromSettings = (int) $this->defaultOptions->getDigitalStampDefaultWeight(); if ($weightFromSettings) { $this->consignment->setPhysicalProperties(["weight" => $weightFromSettings]); @@ -373,8 +374,8 @@ private function calculateTotalWeight(Track $magentoTrack, int $totalWeight = 0) } $this->consignment->setPhysicalProperties([ - 'weight' => $totalWeight, - ]); + 'weight' => $totalWeight, + ]); return $this; } @@ -382,14 +383,14 @@ private function calculateTotalWeight(Track $magentoTrack, int $totalWeight = 0) /** * @param Order\Shipment\Track $magentoTrack * - * @return $this + * @return self * @throws LocalizedException * @throws MissingFieldException * @throws Exception */ private function convertDataForCdCountry(Track $magentoTrack) { - if (!$this->consignment->isCdCountry()) { + if (! $this->consignment->isCdCountry()) { return $this; } @@ -403,7 +404,7 @@ private function convertDataForCdCountry(Track $magentoTrack) ->setWeight($this->weightService->convertToGrams($product->getWeight()) ?: 1) ->setItemValue($this->deliveryCostsService->getPriceInCents($product->getPrice())) ->setClassification( - (int)$this->getAttributeValue( + (int) $this->getAttributeValue( 'catalog_product_entity_int', $product['product_id'], 'classification' @@ -422,7 +423,7 @@ private function convertDataForCdCountry(Track $magentoTrack) ->setWeight($this->weightService->convertToGrams($item->getWeight() * $item->getQty())) ->setItemValue($item->getPrice() * 100) ->setClassification( - (int)$this->getAttributeValue( + (int) $this->getAttributeValue( 'catalog_product_entity_int', $item->getProductId(), 'classification' @@ -438,8 +439,8 @@ private function convertDataForCdCountry(Track $magentoTrack) /** * @param Order\Shipment\Track $magentoTrack - * @param object $address - * @param array $options + * @param object $address + * @param array $options * * @return bool * @throws LocalizedException @@ -502,10 +503,10 @@ private function getCarrierFromOptions(array $options): ?string } /** - * @param array $options - * @param string $packageType + * @param array $options + * @param string $packageType * @param Order\Shipment\Track $magentoTrack - * @param object $address + * @param object $address * * @return int * @throws LocalizedException @@ -522,7 +523,7 @@ private function getPackageType(array $options, Track $magentoTrack, $address): $packageType = $this->defaultOptions->getPackageType(); } - if (!is_numeric($packageType)) { + if (! is_numeric($packageType)) { $packageType = AbstractConsignment::PACKAGE_TYPES_NAMES_IDS_MAP[$packageType] ?? $this->defaultOptions->getPackageType(); } diff --git a/Model/Source/DefaultOptions.php b/Model/Source/DefaultOptions.php index 3c835b6f..a36c85c2 100755 --- a/Model/Source/DefaultOptions.php +++ b/Model/Source/DefaultOptions.php @@ -25,6 +25,7 @@ use MyParcelNL\Sdk\src\Model\Carrier\CarrierFactory; use MyParcelNL\Sdk\src\Model\Carrier\CarrierPostNL; use MyParcelNL\Sdk\src\Model\Consignment\AbstractConsignment; +use MyParcelNL\Sdk\src\Support\Str; class DefaultOptions { @@ -79,7 +80,7 @@ public function __construct(Order $order) /** * Get default of the option * - * @param string $option 'only_recipient'|'signature'|'return'|'large_format' + * @param string $option 'only_recipient'|'signature'|'receipt_code'|'return'|'large_format' * @param string $carrier * * @return bool @@ -108,11 +109,7 @@ public function hasOptionSet(string $option, string $carrier): bool */ public function getMaxCompanyName(?string $company): ?string { - if ($company !== null && (strlen($company) >= self::COMPANY_NAME_MAX_LENGTH)) { - $company = substr($company, 0, 47) . '...'; - } - - return $company; + return Str::limit($company, self::COMPANY_NAME_MAX_LENGTH); } /** diff --git a/Observer/NewShipment.php b/Observer/NewShipment.php index fd3f6460..1428a8b2 100755 --- a/Observer/NewShipment.php +++ b/Observer/NewShipment.php @@ -15,8 +15,11 @@ namespace MyParcelNL\Magento\Observer; use Magento\Framework\App\ObjectManager; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Controller\Result\RedirectFactory; use Magento\Framework\Event\Observer; use Magento\Framework\Event\ObserverInterface; +use Magento\Framework\Message\Manager; use Magento\Sales\Model\Order\Shipment; use MyParcelNL\Magento\Model\Sales\MagentoOrderCollection; use MyParcelNL\Magento\Model\Sales\TrackTraceHolder; @@ -46,11 +49,6 @@ class NewShipment implements ObserverInterface */ private $request; - /** - * @var \Magento\Sales\Model\Order\Shipment\Track - */ - private $modelTrack; - /** * @var MagentoOrderCollection */ @@ -69,9 +67,9 @@ class NewShipment implements ObserverInterface public function __construct(MagentoOrderCollection $orderCollection = null) { $this->objectManager = ObjectManager::getInstance(); - $this->request = $this->objectManager->get('Magento\Framework\App\RequestInterface'); - $this->redirectFactory = $this->objectManager->get('Magento\Framework\Controller\Result\RedirectFactory'); - $this->messageManager = $this->objectManager->get('Magento\Framework\Message\Manager'); + $this->request = $this->objectManager->get(RequestInterface::class); + $this->redirectFactory = $this->objectManager->get(RedirectFactory::class); + $this->messageManager = $this->objectManager->get(Manager::class); $this->orderCollection = $orderCollection ?? new MagentoOrderCollection($this->objectManager, $this->request); $this->configService = $this->objectManager->get(ConfigService::class); } @@ -112,7 +110,7 @@ public function execute(Observer $observer) private function setMagentoAndMyParcelTrack(Shipment $shipment): void { $options = $this->orderCollection->setOptionsFromParameters() - ->getOptions(); + ->getOptions(); if (isset($options['carrier']) && false === $options['carrier']) { unset($options['carrier']); @@ -210,8 +208,8 @@ private function updateTrackGrid($shipment, $entireOrder): void } $shipment->getOrder() - ->setData('track_status', $aHtml['track_status']) - ->setData('track_number', $aHtml['track_number']) - ->save(); + ->setData('track_status', $aHtml['track_status']) + ->setData('track_number', $aHtml['track_number']) + ->save(); } } diff --git a/composer.json b/composer.json index 21ca0c84..985d4f35 100755 --- a/composer.json +++ b/composer.json @@ -30,7 +30,7 @@ "type": "magento2-module", "require": { "php": "^7.1 || ^8.0", - "myparcelnl/sdk": "~v7.15.3", + "myparcelnl/sdk": "~v7.18", "magento/framework": ">=101.0.8 <102 || >=102.0.1" }, "require-dev": { diff --git a/etc/adminhtml/system.xml b/etc/adminhtml/system.xml index d0e5946d..b04ab6d7 100755 --- a/etc/adminhtml/system.xml +++ b/etc/adminhtml/system.xml @@ -121,44 +121,46 @@ - The times will be visible when nothing is filled in - + + + + - + The times will be visible when nothing is filled in - + The times will be visible when nothing is filled in - + The times will be visible when nothing is filled in - + - + - + - + - + - + - + @@ -204,6 +206,21 @@ 1 + + + Magento\Config\Model\Config\Source\Yesno + + 1 + + + + + This will be added to the regular shipping price + + 1 + 1 + + Magento\Config\Model\Config\Source\Yesno @@ -323,6 +340,17 @@ 1 + + + Magento\Config\Model\Config\Source\Yesno + + + + validate-number validate-zero-or-greater + + 1 + + Magento\Config\Model\Config\Source\Yesno diff --git a/i18n/en_US.csv b/i18n/en_US.csv index 08ddd101..cece314f 100755 --- a/i18n/en_US.csv +++ b/i18n/en_US.csv @@ -74,6 +74,7 @@ mailbox_title, Mailbox digital_stamp_title, Digital Stamp packet_title, Packet signature_title, Signature +receipt_code_title, Receiving code only_recipient_title, Only Recipient saturday_delivery, Saturday Delivery diff --git a/i18n/fr_FR.csv b/i18n/fr_FR.csv index 88a64165..cd0c37ce 100644 --- a/i18n/fr_FR.csv +++ b/i18n/fr_FR.csv @@ -76,6 +76,7 @@ Default shipping options,Options d'expédition standards "Fill in your preferences for a shipment. These settings will only apply for the mass actions in the order grid. When creating a single shipment, these settings can be changed manually. These settings will activate based on the order total amount.","Indiquez ici vos préférences standards quant aux options d'expédition. S'ils sont d'application, ces paramètres seront utilisés par défaut pour tous vos envois. Ces options peuvent bien sûr toujours être modifiées lors du traitement." Automate 'Signature on receipt',Automatisation de la 'Signature pour réception' Signature on receipt' operates above a certain order total amount,La 'Signature pour réception' est activée lorsque le montant total dépasse le montant indiqué ci-dessus +Automate 'Receipt code',Automatisation de la 'Code de réception' Automate 'Insurance € 500',Automatisation de l''Assurance jusqu'à € 500' "Insurance € 500' operates above a certain order total amount.","L''Assurance jusqu'à € 500' est activée lorsque le montant total dépasse le montant ci-dessus." From price,A partir du prix @@ -85,6 +86,8 @@ Track action,Action de suivi MyParcel options,Options MyParcel Package,Colis Signature on receipt,Signature pour réception +Receipt code,Code de réception +Receipt code fee,Frais de code de réception Home address only,Livraison à domicile uniquement Hide sender title,Titre de masquer l'expéditeur Insured up to:,Assuré jusqu'à : @@ -221,5 +224,6 @@ mailbox_title, Colis boîte aux lettres digital_stamp_title, Timbre digital packet_title, Colis signature_title, Signature à réception +receipt_code_title, Code de réception only_recipient_title, Adresse de résidence uniquement saturday_delivery, Livraison le samedi diff --git a/i18n/nl_NL.csv b/i18n/nl_NL.csv index 220368ce..0f98f1d9 100755 --- a/i18n/nl_NL.csv +++ b/i18n/nl_NL.csv @@ -90,6 +90,7 @@ Default shipping options,Standaard verzendinstellingen "Fill in your preferences for a shipment. These settings will only apply for the mass actions in the order grid. When creating a single shipment, these settings can be changed manually. These settings will activate based on the order total amount.","Vul hier uw standaard voorkeuren in voor uw verzendopties. Deze instellingen worden als default op al uw zendingen toegepast, indien van toepassing. Deze opties zijn later, per zending, uiteraard nog wel aan te passen tijdens het verwerken." Automate 'Signature on receipt',Automatiseer 'Handtekening voor ontvangst' Automate 'Home address only',Automatiseer 'Alleen huisadres' +Automate 'Receipt code',Automatiseer 'Ontvangstcode' Automate 'Return if no answer',Automatiseer 'Retour bij geen gehoor' Automate 'Large format',Automatiseer 'Groter dan 100 x 70 x 58 cm of zwaarder dan 23 kg' Large package,Groter dan 100 x 70 x 58 cm of zwaarder dan 23 kg @@ -125,6 +126,8 @@ Monday delivery,Maandag levering "Delivery on monday may require special conditions compared to other (week)days including but not limited to fee and cutoff time.","Levering op maandag kan speciale voorwaarden vereisen in vergelijking met andere (week)dagen, waaronder maar niet beperkt tot kosten en laatste bestelmoment." Number of days,Aantal dagen Delivery enabled,Bezorging ingeschakeld +Receipt code,Ontvangstcode +Receipt code fee,Ontvangstcode kosten Home address only,Alleen huisadres Home address only fee,Alleen huisadres kosten Digital stamp settings,Digitalepostzegel instellingen @@ -313,5 +316,6 @@ mailbox_title, Brievenbuspakje digital_stamp_title, Digitale postzegel packet_title, Pakket signature_title, Handtekening voor ontvangst +receipt_code_title, Ontvangstcode only_recipient_title, Alleen huisadres saturday_delivery, Zaterdag levering diff --git a/view/adminhtml/templates/new_shipment.phtml b/view/adminhtml/templates/new_shipment.phtml index 9698d673..c66c8041 100755 --- a/view/adminhtml/templates/new_shipment.phtml +++ b/view/adminhtml/templates/new_shipment.phtml @@ -148,6 +148,8 @@ foreach ($form->getCarrierSpecificAbstractConsignments() as $abstractConsignment foreach ($abstractConsignment->getAllowedShipmentOptions() as $shipmentOption) { if (AbstractConsignment::SHIPMENT_OPTION_INSURANCE === $shipmentOption || ! $block->consignmentHasShipmentOption($abstractConsignment, $shipmentOption) + || ($shipmentOption === AbstractConsignment::SHIPMENT_OPTION_RECEIPT_CODE + && AbstractConsignment::DELIVERY_TYPE_STANDARD !== $block->getDeliveryType()) ) { continue; } @@ -170,6 +172,11 @@ foreach ($form->getCarrierSpecificAbstractConsignments() as $abstractConsignment class="admin__field-label" for="mypa___"> getShipmentOptionsHumanMap()[$shipmentOption] ?? $shipmentOption ?> + getShipmentOptionsExplanationMap()[$shipmentOption] ?? '')) { + echo '
', htmlentities($explanation), '
'; + } ?>
From f6ee0413434f43d53edc873634120ded1b4fb033 Mon Sep 17 00:00:00 2001 From: Joeri van Veen Date: Tue, 12 Nov 2024 13:33:10 +0100 Subject: [PATCH 14/29] feat(carriers): add ups shipping options --- Adapter/ShipmentOptionsFromAdapter.php | 1 + Block/Sales/NewShipment.php | 6 ++ Block/Sales/NewShipmentForm.php | 1 + Helper/Data.php | 5 + Helper/ShipmentOptions.php | 9 ++ Model/Quote/Checkout.php | 8 ++ Model/Sales/MagentoCollection.php | 1 + Model/Sales/TrackTraceHolder.php | 1 + Model/Source/DefaultOptions.php | 2 +- etc/adminhtml/system.xml | 144 +++++++++++++++++++++++++ etc/di.xml | 7 ++ i18n/fr_FR.csv | 7 +- i18n/nl_NL.csv | 7 +- 13 files changed, 196 insertions(+), 3 deletions(-) diff --git a/Adapter/ShipmentOptionsFromAdapter.php b/Adapter/ShipmentOptionsFromAdapter.php index cca2c0b1..8957338a 100644 --- a/Adapter/ShipmentOptionsFromAdapter.php +++ b/Adapter/ShipmentOptionsFromAdapter.php @@ -19,6 +19,7 @@ public function __construct(array $inputData) { $options = $inputData ?? []; $this->signature = (bool) ($options[ShipmentOptions::SIGNATURE] ?? false); + $this->collect = (bool) ($options['collect'] ?? false); $this->receipt_code = (bool) ($options[ShipmentOptions::RECEIPT_CODE] ?? false); $this->only_recipient = (bool) ($options[ShipmentOptions::ONLY_RECIPIENT] ?? false); $this->large_format = (bool) ($options[ShipmentOptions::LARGE_FORMAT] ?? false); diff --git a/Block/Sales/NewShipment.php b/Block/Sales/NewShipment.php index d6ab7146..71af188b 100755 --- a/Block/Sales/NewShipment.php +++ b/Block/Sales/NewShipment.php @@ -28,6 +28,7 @@ use MyParcelNL\Magento\Service\Config\ConfigService; use MyParcelNL\Magento\Service\Weight\WeightService; use MyParcelNL\Sdk\src\Model\Carrier\CarrierPostNL; +use MyParcelNL\Sdk\src\Model\Carrier\CarrierUPS; use MyParcelNL\Sdk\src\Model\Consignment\AbstractConsignment; class NewShipment extends AbstractItems @@ -169,6 +170,11 @@ public function consignmentHasShipmentOption(AbstractConsignment $consignment, s AbstractConsignment::SHIPMENT_OPTION_SIGNATURE], true); } + // For UPS shipment options are available for all countries in the EU + if (CarrierUPS::NAME === $consignment->getCarrierName()) { + return true; + } + // No shipment options available in any other cases return false; } diff --git a/Block/Sales/NewShipmentForm.php b/Block/Sales/NewShipmentForm.php index 3b610c7e..0c488ef2 100644 --- a/Block/Sales/NewShipmentForm.php +++ b/Block/Sales/NewShipmentForm.php @@ -47,6 +47,7 @@ public function __construct() { $this->shipmentOptionsHumanMap = [ AbstractConsignment::SHIPMENT_OPTION_SIGNATURE => __('Signature on receipt'), + AbstractConsignment::SHIPMENT_OPTION_COLLECT => __('Collect package'), AbstractConsignment::SHIPMENT_OPTION_ONLY_RECIPIENT => __('Home address only'), AbstractConsignment::SHIPMENT_OPTION_AGE_CHECK => __('Age check 18+'), AbstractConsignment::SHIPMENT_OPTION_HIDE_SENDER => __('Hide sender'), diff --git a/Helper/Data.php b/Helper/Data.php index bd102b40..6750c31f 100755 --- a/Helper/Data.php +++ b/Helper/Data.php @@ -242,6 +242,11 @@ public function consignmentHasShipmentOption(AbstractConsignment $consignment, s AbstractConsignment::SHIPMENT_OPTION_SIGNATURE], true); } + // For UPS shipment options are available for all countries in the EU + if (CarrierUPS::NAME === $consignment->getCarrierName()) { + return true; + } + // No shipment options available in any other cases return false; } diff --git a/Helper/ShipmentOptions.php b/Helper/ShipmentOptions.php index 9a5561ca..6f48b1e4 100644 --- a/Helper/ShipmentOptions.php +++ b/Helper/ShipmentOptions.php @@ -18,6 +18,7 @@ class ShipmentOptions public const ONLY_RECIPIENT = 'only_recipient'; private const SAME_DAY_DELIVERY = 'same_day_delivery'; public const SIGNATURE = 'signature'; + public const COLLECT = AbstractConsignment::SHIPMENT_OPTION_COLLECT; public const RECEIPT_CODE = AbstractConsignment::SHIPMENT_OPTION_RECEIPT_CODE; public const RETURN = 'return'; public const AGE_CHECK = 'age_check'; @@ -113,6 +114,13 @@ public function hasSignature(): bool return $signatureFromOptions ?? $this->optionIsEnabled(self::SIGNATURE); } + public function hasCollect(): bool + { + $collectFromOptions = self::getValueOfOptionWhenSet(self::COLLECT, $this->options); + + return $collectFromOptions ?? $this->optionIsEnabled(self::COLLECT); + } + public function hasReceiptCode(): bool { $deliveryOptions = $this->order->getData(Checkout::FIELD_DELIVERY_OPTIONS) ?? []; @@ -402,6 +410,7 @@ public function getShipmentOptions(): array self::RETURN => $this->hasReturn(), self::ONLY_RECIPIENT => $this->hasOnlyRecipient(), self::SIGNATURE => $this->hasSignature(), + self::COLLECT => $this->hasCollect(), self::RECEIPT_CODE => $this->hasReceiptCode(), self::AGE_CHECK => $this->hasAgeCheck(), self::LARGE_FORMAT => $this->hasLargeFormat(), diff --git a/Model/Quote/Checkout.php b/Model/Quote/Checkout.php index 76de74c2..40e5354f 100644 --- a/Model/Quote/Checkout.php +++ b/Model/Quote/Checkout.php @@ -186,7 +186,9 @@ private function getDeliveryData(?string $packageType = null): array $canHaveMonday = $consignment->canHaveExtraOption(AbstractConsignment::EXTRA_OPTION_DELIVERY_MONDAY); $canHaveMorning = $consignment->canHaveDeliveryType(AbstractConsignment::DELIVERY_TYPE_MORNING_NAME); $canHaveEvening = $consignment->canHaveDeliveryType(AbstractConsignment::DELIVERY_TYPE_EVENING_NAME); + $canHaveExpress = $consignment->canHaveDeliveryType(AbstractConsignment::DELIVERY_TYPE_EXPRESS_NAME); $canHaveSignature = $consignment->canHaveShipmentOption(AbstractConsignment::SHIPMENT_OPTION_SIGNATURE); + $canHaveCollect = $consignment->canHaveShipmentOption(AbstractConsignment::SHIPMENT_OPTION_COLLECT); $canHaveReceiptCode = $consignment->canHaveShipmentOption(AbstractConsignment::SHIPMENT_OPTION_RECEIPT_CODE); $canHaveOnlyRecipient = $consignment->canHaveShipmentOption(AbstractConsignment::SHIPMENT_OPTION_ONLY_RECIPIENT); $canHaveAgeCheck = $consignment->canHaveShipmentOption(AbstractConsignment::SHIPMENT_OPTION_AGE_CHECK); @@ -209,6 +211,7 @@ private function getDeliveryData(?string $packageType = null): array $eveningFee = $canHaveEvening ? $this->configService->getFloatConfig($carrierPath, 'evening/fee') + $addBasePrice : 0; $sameDayFee = $canHaveSameDay ? (int) $this->configService->getFloatConfig($carrierPath, 'delivery/same_day_delivery_fee') + $addBasePrice : 0; $signatureFee = $canHaveSignature ? $this->configService->getFloatConfig($carrierPath, 'delivery/signature_fee') : 0; + $collectFee = $canHaveCollect ? $this->helper->getMethodPrice($carrierPath, 'delivery/collect_fee', false) : 0; $receiptCodeFee = $canHaveReceiptCode ? $this->configService->getFloatConfig($carrierPath, 'delivery/receipt_code_fee') : 0; $onlyRecipientFee = $canHaveOnlyRecipient ? $this->configService->getFloatConfig($carrierPath, 'delivery/only_recipient_fee') : 0; $isAgeCheckActive = $canHaveAgeCheck && $this->isAgeCheckActive($carrierPath); @@ -217,6 +220,7 @@ private function getDeliveryData(?string $packageType = null): array $allowStandardDelivery = $this->configService->getBoolConfig($carrierPath, 'delivery/active'); $allowMorningDelivery = ! $isAgeCheckActive && $canHaveMorning && $this->configService->getBoolConfig($carrierPath, 'morning/active'); $allowEveningDelivery = ! $isAgeCheckActive && $canHaveEvening && $this->configService->getBoolConfig($carrierPath, 'evening/active'); + $allowExpressDelivery = $canHaveExpress && $this->configService->getBoolConfig($carrierPath, 'express/active'); $allowDeliveryOptions = ! $this->package->deliveryOptionsDisabled && ($allowPickup || $allowStandardDelivery || $allowMorningDelivery || $allowEveningDelivery); @@ -230,6 +234,7 @@ private function getDeliveryData(?string $packageType = null): array 'allowDeliveryOptions' => $allowDeliveryOptions, 'allowStandardDelivery' => $allowStandardDelivery, 'allowSignature' => $canHaveSignature && $this->configService->getBoolConfig($carrierPath, 'delivery/signature_active'), + 'allowCollect' => $canHaveCollect && $this->configService->getBoolConfig($carrierPath, 'delivery/collect_active'), 'allowReceiptCode' => $canHaveReceiptCode && $this->configService->getBoolConfig($carrierPath, 'delivery/receipt_code_active'), 'allowOnlyRecipient' => $canHaveOnlyRecipient && $this->configService->getBoolConfig($carrierPath, 'delivery/only_recipient_active'), 'allowMorningDelivery' => $allowMorningDelivery, @@ -237,10 +242,12 @@ private function getDeliveryData(?string $packageType = null): array 'allowPickupLocations' => $canHavePickup && $this->isPickupAllowed($carrierPath), 'allowMondayDelivery' => $canHaveMonday && $this->configService->getBoolConfig($carrierPath, 'delivery/monday_active'), 'allowSameDayDelivery' => $canHaveSameDay && $this->configService->getBoolConfig($carrierPath, 'delivery/same_day_delivery_active'), + 'allowExpressDelivery' => $allowExpressDelivery, 'dropOffDays' => $this->getDropOffDays($carrierPath), 'priceSignature' => $signatureFee, + 'priceCollect' => $collectFee, 'priceReceiptCode' => $receiptCodeFee, 'priceOnlyRecipient' => $onlyRecipientFee, 'priceStandardDelivery' => $addBasePrice, @@ -248,6 +255,7 @@ private function getDeliveryData(?string $packageType = null): array 'priceMorningDelivery' => $morningFee, 'priceEveningDelivery' => $eveningFee, 'priceSameDayDelivery' => $sameDayFee, + 'priceExpressdelivery' => $allowExpressDelivery ? $this->configService->getFloatConfig($carrierPath, 'express/fee') : 0, 'priceSameDayDeliveryAndOnlyRecipient' => $sameDayFee + $onlyRecipientFee, 'priceMorningSignature' => ($morningFee + $signatureFee), diff --git a/Model/Sales/MagentoCollection.php b/Model/Sales/MagentoCollection.php index a17ec7c3..430c1252 100755 --- a/Model/Sales/MagentoCollection.php +++ b/Model/Sales/MagentoCollection.php @@ -85,6 +85,7 @@ abstract class MagentoCollection implements MagentoCollectionInterface 'carrier' => 'postnl', 'positions' => null, 'signature' => null, + 'collect' => null, 'receipt_code' => null, 'only_recipient' => null, 'return' => null, diff --git a/Model/Sales/TrackTraceHolder.php b/Model/Sales/TrackTraceHolder.php index 52bd9a14..6586d9ad 100755 --- a/Model/Sales/TrackTraceHolder.php +++ b/Model/Sales/TrackTraceHolder.php @@ -208,6 +208,7 @@ public function convertDataFromMagentoToApi(Track $magentoTrack, array $options) ->setDropOffPoint($dropOffPoint) ->setOnlyRecipient($this->shipmentOptionsHelper->hasOnlyRecipient()) ->setSignature($this->shipmentOptionsHelper->hasSignature()) + ->setCollect($this->shipmentOptionsHelper->hasCollect()) ->setReceiptCode($this->shipmentOptionsHelper->hasReceiptCode()) ->setReturn($this->shipmentOptionsHelper->hasReturn()) ->setSameDayDelivery($this->shipmentOptionsHelper->hasSameDayDelivery()) diff --git a/Model/Source/DefaultOptions.php b/Model/Source/DefaultOptions.php index a36c85c2..7ccafb8e 100755 --- a/Model/Source/DefaultOptions.php +++ b/Model/Source/DefaultOptions.php @@ -80,7 +80,7 @@ public function __construct(Order $order) /** * Get default of the option * - * @param string $option 'only_recipient'|'signature'|'receipt_code'|'return'|'large_format' + * @param string $option 'only_recipient'|'signature'|'collect'|'receipt_code'|'return'|'large_format' * @param string $carrier * * @return bool diff --git a/etc/adminhtml/system.xml b/etc/adminhtml/system.xml index b04ab6d7..d32d646c 100755 --- a/etc/adminhtml/system.xml +++ b/etc/adminhtml/system.xml @@ -1206,6 +1206,58 @@ Magento\Config\Model\Config\Source\Yesno
+ + + Magento\Config\Model\Config\Source\Yesno + + 1 + + + + + This will be added to the regular shipping price + + 1 + 1 + + + + + Magento\Config\Model\Config\Source\Yesno + + 1 + + + + + This will be added to the regular shipping price + + 1 + 1 + + + + + Magento\Config\Model\Config\Source\Yesno + + 1 + + + + + This will be added to the regular shipping price + + 1 + 1 + + @@ -1295,6 +1347,98 @@ For orders before this time, the drop-off is considered done on this day.
+ + + Fill in your preferences for a shipment. These settings will only apply for the mass actions in + the order grid. When creating a single shipment, these settings can be changed manually. These + settings will activate based on the order total amount. + + + + Magento\Config\Model\Config\Source\Yesno + + + + validate-number validate-zero-or-greater + 'Signature on receipt' operates above a certain order total amount + + 1 + + + + + Magento\Config\Model\Config\Source\Yesno + + + + validate-number validate-zero-or-greater + + 1 + + + + + Magento\Config\Model\Config\Source\Yesno + + + + validate-number validate-zero-or-greater + 'Home address only' operates above a certain order total amount + + 1 + + + + + Magento\Config\Model\Config\Source\Yesno + + + + validate-number validate-zero-or-greater + The minimum amount from when insurance is active. + + + + MyParcelNL\Magento\Model\Source\CarrierInsurancePossibilities\UPS\Local + + + + validate-number validate-number-range number-range-0-100 + Use percentage of total order amount for insurance. After the calculation, the next + available price scale is selected. + + + + + + + + Magento\Config\Model\Config\Source\Yesno + UPS guarantees delivery within one day with this option active. + + + + This will be added to the regular shipping price + + 1 + + +
diff --git a/etc/di.xml b/etc/di.xml index 279a4052..f28b272b 100755 --- a/etc/di.xml +++ b/etc/di.xml @@ -70,6 +70,13 @@ + + + ups + local + + + diff --git a/i18n/fr_FR.csv b/i18n/fr_FR.csv index cd0c37ce..08312e80 100644 --- a/i18n/fr_FR.csv +++ b/i18n/fr_FR.csv @@ -75,8 +75,9 @@ Select a standard orientation for printing labels.,Sélectionnez une orientation Default shipping options,Options d'expédition standards "Fill in your preferences for a shipment. These settings will only apply for the mass actions in the order grid. When creating a single shipment, these settings can be changed manually. These settings will activate based on the order total amount.","Indiquez ici vos préférences standards quant aux options d'expédition. S'ils sont d'application, ces paramètres seront utilisés par défaut pour tous vos envois. Ces options peuvent bien sûr toujours être modifiées lors du traitement." Automate 'Signature on receipt',Automatisation de la 'Signature pour réception' -Signature on receipt' operates above a certain order total amount,La 'Signature pour réception' est activée lorsque le montant total dépasse le montant indiqué ci-dessus +Automate 'Collect package',Automatisation de 'Livré en 1 jour' Automate 'Receipt code',Automatisation de la 'Code de réception' +Signature on receipt' operates above a certain order total amount,La 'Signature pour réception' est activée lorsque le montant total dépasse le montant indiqué ci-dessus Automate 'Insurance € 500',Automatisation de l''Assurance jusqu'à € 500' "Insurance € 500' operates above a certain order total amount.","L''Assurance jusqu'à € 500' est activée lorsque le montant total dépasse le montant ci-dessus." From price,A partir du prix @@ -86,6 +87,7 @@ Track action,Action de suivi MyParcel options,Options MyParcel Package,Colis Signature on receipt,Signature pour réception +Collect package,Faire récupérer le colis Receipt code,Code de réception Receipt code fee,Frais de code de réception Home address only,Livraison à domicile uniquement @@ -139,6 +141,9 @@ Cut-off time,Heure limite de commande "If a request is made for the delivery options between Friday after, and Monday before, cut-off time then Tuesday will be shown as the next possible delivery date.","Lorsqu'une commande est passée après la dernière heure de commande le vendredi et avant celle-ci le lundi, c'est donc le mardi qui sera affiché comme premier jour de livraison." Drop-off days,Jours de dépôt Monday delivery,Livraison le lundi +Express delivery,Livré en un jour +Express delivery fee,Livré en un jour - prix +Express delivery active,Livré en un jour actif Same day delivery,Livraison le jour même Same day title,Titre le jour même "Delivery on monday may require special conditions compared to other (week)days including but not limited to fee and cutoff time.","La livraison le lundi peut nécessiter des conditions spéciales par rapport aux autres jours de la semaine, y compris mais sans s'y limiter, des frais et heure limite de commande." diff --git a/i18n/nl_NL.csv b/i18n/nl_NL.csv index 0f98f1d9..054d36fd 100755 --- a/i18n/nl_NL.csv +++ b/i18n/nl_NL.csv @@ -89,8 +89,9 @@ Show map first,Toon kaart eerst Default shipping options,Standaard verzendinstellingen "Fill in your preferences for a shipment. These settings will only apply for the mass actions in the order grid. When creating a single shipment, these settings can be changed manually. These settings will activate based on the order total amount.","Vul hier uw standaard voorkeuren in voor uw verzendopties. Deze instellingen worden als default op al uw zendingen toegepast, indien van toepassing. Deze opties zijn later, per zending, uiteraard nog wel aan te passen tijdens het verwerken." Automate 'Signature on receipt',Automatiseer 'Handtekening voor ontvangst' -Automate 'Home address only',Automatiseer 'Alleen huisadres' +Automate 'Collect package',Automatiseer 'Pakket laten ophalen' Automate 'Receipt code',Automatiseer 'Ontvangstcode' +Automate 'Home address only',Automatiseer 'Alleen huisadres' Automate 'Return if no answer',Automatiseer 'Retour bij geen gehoor' Automate 'Large format',Automatiseer 'Groter dan 100 x 70 x 58 cm of zwaarder dan 23 kg' Large package,Groter dan 100 x 70 x 58 cm of zwaarder dan 23 kg @@ -115,6 +116,9 @@ Enter a basic price for a mailbox. The regular price will not affect this price. Morning delivery,Ochtendlevering Evening delivery,Avondlevering Evening delivery fee,Avondlevering kosten +Express delivery,Binnen 1 dag bezorgd +Express delivery fee,Binnen 1 dag bezorgd kosten +Express delivery active,Binnen 1 dag bezorgd ingeschakeld Same day delivery,Zelfde dag bezorgd Same day title,Zelfde dag titel Morning delivery active,Ochtendlevering ingeschakeld @@ -128,6 +132,7 @@ Number of days,Aantal dagen Delivery enabled,Bezorging ingeschakeld Receipt code,Ontvangstcode Receipt code fee,Ontvangstcode kosten +Collect package,Pakket laten ophalen Home address only,Alleen huisadres Home address only fee,Alleen huisadres kosten Digital stamp settings,Digitalepostzegel instellingen From c4c942fa0603714e386d628535edd9e555c45dd8 Mon Sep 17 00:00:00 2001 From: Joeri van Veen Date: Mon, 25 Nov 2024 13:53:23 +0100 Subject: [PATCH 15/29] fix: improve service name and fix receipt code option --- Adapter/ShipmentOptionsFromAdapter.php | 2 +- Block/Sales/NewShipment.php | 22 ++++-- Block/Sales/NewShipmentForm.php | 1 + Block/Sales/OrdersAction.php | 6 +- Block/Sales/ShipmentsAction.php | 6 +- Block/Sales/View.php | 4 +- .../Form/AbstractDefaultDropOffPoint.php | 2 +- .../Order/CreateAndPrintMyParcelTrack.php | 8 +- .../Order/SendMyParcelReturnMail.php | 6 +- .../Settings/CarrierConfigurationImport.php | 13 ++-- .../Shipment/CreateAndPrintMyParcelTrack.php | 8 +- Cron/UpdateStatus.php | 8 +- Helper/CustomsDeclarationFromOrder.php | 10 +-- Helper/ShipmentOptions.php | 75 +++++++++---------- Model/Carrier/Carrier.php | 34 ++++----- .../DeliveryOptionsToShippingMethods.php | 6 +- Model/Quote/Checkout.php | 38 +++++----- ...SaveOrderBeforeSalesModelQuoteObserver.php | 22 +++--- Model/Sales/MagentoCollection.php | 14 ++-- Model/Sales/MagentoOrderCollection.php | 4 +- Model/Sales/Package.php | 4 +- Model/Sales/Repository/DeliveryRepository.php | 4 +- Model/Sales/TrackTraceHolder.php | 43 +++++------ Model/Source/AgeCheckNo.php | 10 +-- Model/Source/AgeCheckYes.php | 6 +- Model/Source/DefaultOptions.php | 22 +++--- Model/Source/DigitalStampWeightOptions.php | 6 +- Model/Source/ExportMode.php | 10 +-- Model/Source/LargeFormatOptions.php | 8 +- Observer/CreateConceptAfterInvoice.php | 8 +- Observer/NewShipment.php | 6 +- Observer/SalesOrderStatusHistoryObserver.php | 6 +- .../{Config/ConfigService.php => Config.php} | 4 +- Service/Costs/TaxService.php | 10 --- .../{Date/DatingService.php => Dating.php} | 4 +- ...veryCostsService.php => DeliveryCosts.php} | 10 +-- Service/Tax.php | 10 +++ .../{Weight/WeightService.php => Weight.php} | 16 ++-- Setup/UpgradeData.php | 4 +- Ui/Component/Listing/Column/TrackActions.php | 10 +-- view/adminhtml/templates/new_shipment.phtml | 2 - 41 files changed, 251 insertions(+), 241 deletions(-) rename Service/{Config/ConfigService.php => Config.php} (98%) delete mode 100644 Service/Costs/TaxService.php rename Service/{Date/DatingService.php => Dating.php} (92%) rename Service/{Costs/DeliveryCostsService.php => DeliveryCosts.php} (79%) create mode 100644 Service/Tax.php rename Service/{Weight/WeightService.php => Weight.php} (78%) diff --git a/Adapter/ShipmentOptionsFromAdapter.php b/Adapter/ShipmentOptionsFromAdapter.php index 8957338a..14993ea9 100644 --- a/Adapter/ShipmentOptionsFromAdapter.php +++ b/Adapter/ShipmentOptionsFromAdapter.php @@ -19,7 +19,7 @@ public function __construct(array $inputData) { $options = $inputData ?? []; $this->signature = (bool) ($options[ShipmentOptions::SIGNATURE] ?? false); - $this->collect = (bool) ($options['collect'] ?? false); + $this->collect = (bool) ($options[ShipmentOptions::COLLECT] ?? false); $this->receipt_code = (bool) ($options[ShipmentOptions::RECEIPT_CODE] ?? false); $this->only_recipient = (bool) ($options[ShipmentOptions::ONLY_RECIPIENT] ?? false); $this->large_format = (bool) ($options[ShipmentOptions::LARGE_FORMAT] ?? false); diff --git a/Block/Sales/NewShipment.php b/Block/Sales/NewShipment.php index 71af188b..6b570cad 100755 --- a/Block/Sales/NewShipment.php +++ b/Block/Sales/NewShipment.php @@ -25,8 +25,8 @@ use MyParcelNL\Magento\Model\Sales\MagentoOrderCollection; use MyParcelNL\Magento\Model\Source\DefaultOptions; use MyParcelNL\Magento\Model\Sales\TrackTraceHolder; -use MyParcelNL\Magento\Service\Config\ConfigService; -use MyParcelNL\Magento\Service\Weight\WeightService; +use MyParcelNL\Magento\Service\Config; +use MyParcelNL\Magento\Service\Weight; use MyParcelNL\Sdk\src\Model\Carrier\CarrierPostNL; use MyParcelNL\Sdk\src\Model\Carrier\CarrierUPS; use MyParcelNL\Sdk\src\Model\Consignment\AbstractConsignment; @@ -68,8 +68,8 @@ public function __construct( ) { $this->order = $registry->registry('current_shipment')->getOrder(); - $this->weightService = $objectManager->get(WeightService::class); - $this->configService = $objectManager->get(ConfigService::class); + $this->weightService = $objectManager->get(Weight::class); + $this->configService = $objectManager->get(Config::class); $this->form = new NewShipmentForm(); $this->defaultOptions = new DefaultOptions($this->order); @@ -159,15 +159,23 @@ public function consignmentHasShipmentOption(AbstractConsignment $consignment, s /** * Business logic determining what shipment options to show, if any. */ + if (AbstractConsignment::SHIPMENT_OPTION_RECEIPT_CODE === $shipmentOption + && AbstractConsignment::DELIVERY_TYPE_STANDARD !== $this->getDeliveryType() + ) { + return false; // receipt code is only available for standard delivery + } + if (AbstractConsignment::CC_NL === $consignment->getCountry()) { return $consignment->canHaveShipmentOption($shipmentOption); } - // For PostNL in Belgium - only recipient-only/signature is available + // For PostNL in Belgium - recipient-only, signature and receipt-code are available if (AbstractConsignment::CC_BE === $consignment->getCountry() && CarrierPostNL::NAME === $consignment->getCarrierName()) { return in_array($shipmentOption, [ AbstractConsignment::SHIPMENT_OPTION_ONLY_RECIPIENT, - AbstractConsignment::SHIPMENT_OPTION_SIGNATURE], true); + AbstractConsignment::SHIPMENT_OPTION_SIGNATURE, + AbstractConsignment::SHIPMENT_OPTION_RECEIPT_CODE, + ], true); } // For UPS shipment options are available for all countries in the EU @@ -192,6 +200,6 @@ public function getNewShipmentForm(): NewShipmentForm */ public function isOrderManagementEnabled(): bool { - return ConfigService::EXPORT_MODE_PPS === $this->configService->getExportMode(); + return Config::EXPORT_MODE_PPS === $this->configService->getExportMode(); } } diff --git a/Block/Sales/NewShipmentForm.php b/Block/Sales/NewShipmentForm.php index 0c488ef2..deeda793 100644 --- a/Block/Sales/NewShipmentForm.php +++ b/Block/Sales/NewShipmentForm.php @@ -47,6 +47,7 @@ public function __construct() { $this->shipmentOptionsHumanMap = [ AbstractConsignment::SHIPMENT_OPTION_SIGNATURE => __('Signature on receipt'), + AbstractConsignment::SHIPMENT_OPTION_RECEIPT_CODE => __('Receiving code'), AbstractConsignment::SHIPMENT_OPTION_COLLECT => __('Collect package'), AbstractConsignment::SHIPMENT_OPTION_ONLY_RECIPIENT => __('Home address only'), AbstractConsignment::SHIPMENT_OPTION_AGE_CHECK => __('Age check 18+'), diff --git a/Block/Sales/OrdersAction.php b/Block/Sales/OrdersAction.php index 30ad0938..9eec28fd 100755 --- a/Block/Sales/OrdersAction.php +++ b/Block/Sales/OrdersAction.php @@ -17,11 +17,11 @@ use Magento\Backend\Block\Template; use Magento\Backend\Block\Template\Context; use Magento\Framework\App\ObjectManager; -use MyParcelNL\Magento\Service\Config\ConfigService; +use MyParcelNL\Magento\Service\Config; class OrdersAction extends Template { - private ConfigService $configService; + private Config $configService; /** * @param Context $context @@ -33,7 +33,7 @@ public function __construct( ) { $objectManager = ObjectManager::getInstance(); - $this->configService = $objectManager->get(ConfigService::class); + $this->configService = $objectManager->get(Config::class); parent::__construct($context, $data); } diff --git a/Block/Sales/ShipmentsAction.php b/Block/Sales/ShipmentsAction.php index 35568888..a26e1d65 100755 --- a/Block/Sales/ShipmentsAction.php +++ b/Block/Sales/ShipmentsAction.php @@ -17,11 +17,11 @@ use Magento\Backend\Block\Template; use Magento\Backend\Block\Template\Context; use Magento\Framework\App\ObjectManager; -use MyParcelNL\Magento\Service\Config\ConfigService; +use MyParcelNL\Magento\Service\Config; class ShipmentsAction extends Template { - private ConfigService $configService; + private Config $configService; /** * @param Context $context @@ -32,7 +32,7 @@ public function __construct( array $data = [] ) { $objectManager = ObjectManager::getInstance(); - $this->configService = $objectManager->get(ConfigService::class); + $this->configService = $objectManager->get(Config::class); parent::__construct($context, $data); } diff --git a/Block/Sales/View.php b/Block/Sales/View.php index ce8e82b9..524f1159 100755 --- a/Block/Sales/View.php +++ b/Block/Sales/View.php @@ -23,7 +23,7 @@ use Magento\Framework\Exception\LocalizedException; use Magento\Sales\Block\Adminhtml\Order\AbstractOrder; use MyParcelNL\Magento\Facade\Logger; -use MyParcelNL\Magento\Service\Config\ConfigService; +use MyParcelNL\Magento\Service\Config; use MyParcelNL\Sdk\src\Adapter\DeliveryOptions\AbstractDeliveryOptionsAdapter; use MyParcelNL\Sdk\src\Factory\DeliveryOptionsAdapterFactory; use Throwable; @@ -42,7 +42,7 @@ public function getCheckoutOptionsHtml(): string $order = $this->getOrder(); /** @var object $data Data from checkout */ - $data = json_decode($order->getData(ConfigService::FIELD_DELIVERY_OPTIONS) ?? null, true); + $data = json_decode($order->getData(Config::FIELD_DELIVERY_OPTIONS) ?? null, true); if (!is_array($data)) { return ''; diff --git a/Block/System/Config/Form/AbstractDefaultDropOffPoint.php b/Block/System/Config/Form/AbstractDefaultDropOffPoint.php index 2f11154f..3cd1758e 100644 --- a/Block/System/Config/Form/AbstractDefaultDropOffPoint.php +++ b/Block/System/Config/Form/AbstractDefaultDropOffPoint.php @@ -10,7 +10,7 @@ use Magento\Framework\App\ObjectManager; use Magento\Framework\Data\Form\Element\AbstractElement; use MyParcelNL\Magento\Model\Settings\AccountSettings; -use MyParcelNL\Magento\Service\Config\ConfigService; +use MyParcelNL\Magento\Service\Config; use MyParcelNL\Sdk\src\Model\Carrier\CarrierFactory; abstract class AbstractDefaultDropOffPoint extends Field diff --git a/Controller/Adminhtml/Order/CreateAndPrintMyParcelTrack.php b/Controller/Adminhtml/Order/CreateAndPrintMyParcelTrack.php index e5c78b86..17cf3875 100755 --- a/Controller/Adminhtml/Order/CreateAndPrintMyParcelTrack.php +++ b/Controller/Adminhtml/Order/CreateAndPrintMyParcelTrack.php @@ -11,7 +11,7 @@ use MyParcelNL\Magento\Model\Sales\MagentoCollection; use MyParcelNL\Magento\Model\Sales\MagentoOrderCollection; use MyParcelNL\Magento\Model\Sales\TrackTraceHolder; -use MyParcelNL\Magento\Service\Config\ConfigService; +use MyParcelNL\Magento\Service\Config; use MyParcelNL\Magento\Ui\Component\Listing\Column\TrackAndTrace; use MyParcelNL\Sdk\src\Exception\ApiException; use MyParcelNL\Sdk\src\Exception\MissingFieldException; @@ -39,7 +39,7 @@ class CreateAndPrintMyParcelTrack extends \Magento\Framework\App\Action\Action private MagentoOrderCollection $orderCollection; - private ConfigService $configService; + private Config $configService; /** * CreateAndPrintMyParcelTrack constructor. @@ -51,7 +51,7 @@ public function __construct(Context $context) // TODO joeri don’t use deprecated action parent::__construct($context); - $this->configService = $this->_objectManager->get(ConfigService::class); + $this->configService = $this->_objectManager->get(Config::class); $this->resultRedirectFactory = $context->getResultRedirectFactory(); $this->orderCollection = new MagentoOrderCollection( $this->_objectManager, @@ -111,7 +111,7 @@ private function massAction() $orderIds = $this->filterCorrectAddress($orderIds); $this->addOrdersToCollection($orderIds); - if (ConfigService::EXPORT_MODE_PPS === $this->configService->getExportMode()) { + if (Config::EXPORT_MODE_PPS === $this->configService->getExportMode()) { $this->orderCollection->setFulfilment(); return $this; diff --git a/Controller/Adminhtml/Order/SendMyParcelReturnMail.php b/Controller/Adminhtml/Order/SendMyParcelReturnMail.php index 98b11176..1450c90f 100755 --- a/Controller/Adminhtml/Order/SendMyParcelReturnMail.php +++ b/Controller/Adminhtml/Order/SendMyParcelReturnMail.php @@ -6,7 +6,7 @@ use Magento\Backend\App\Action\Context; use Magento\Framework\Exception\LocalizedException; use MyParcelNL\Magento\Model\Sales\MagentoOrderCollection; -use MyParcelNL\Magento\Service\Config\ConfigService; +use MyParcelNL\Magento\Service\Config; /** * Action to send mails with a return label @@ -25,7 +25,7 @@ class SendMyParcelReturnMail extends \Magento\Framework\App\Action\Action const PATH_URI_ORDER_INDEX = 'sales/order/index'; private MagentoOrderCollection $orderCollection; - private ConfigService $configService; + private Config $configService; /** * CreateAndPrintMyParcelTrack constructor. @@ -36,7 +36,7 @@ public function __construct(Context $context) { parent::__construct($context); - $this->configService = $context->getObjectManager()->get(ConfigService::class); + $this->configService = $context->getObjectManager()->get(Config::class); $this->resultRedirectFactory = $context->getResultRedirectFactory(); $this->orderCollection = new MagentoOrderCollection( $context->getObjectManager(), diff --git a/Controller/Adminhtml/Settings/CarrierConfigurationImport.php b/Controller/Adminhtml/Settings/CarrierConfigurationImport.php index 61379be3..a72ffe2e 100644 --- a/Controller/Adminhtml/Settings/CarrierConfigurationImport.php +++ b/Controller/Adminhtml/Settings/CarrierConfigurationImport.php @@ -4,7 +4,7 @@ namespace MyParcelNL\Magento\Controller\Adminhtml\Settings; -use Magento\Config\Model\ResourceModel\Config; +use Magento\Config\Model\ResourceModel\Config as resourceConfig; use Magento\Backend\App\Action; use Magento\Backend\App\Action\Context; use Magento\Framework\App\Cache\Frontend\Pool; @@ -13,7 +13,7 @@ use Magento\Framework\App\ObjectManager; use Magento\Framework\Controller\Result\JsonFactory; use Magento\Framework\Model\ResourceModel\Db\Context as DbContext; -use MyParcelNL\Magento\Service\Config\ConfigService; +use MyParcelNL\Magento\Service\Config; use MyParcelNL\Sdk\src\Model\Account\CarrierConfiguration; use MyParcelNL\Sdk\src\Model\Account\CarrierOptions; use MyParcelNL\Sdk\src\Support\Collection; @@ -55,8 +55,7 @@ public function __construct( ) { parent::__construct($context); $this->resultFactory = $resultFactory; - $this->config = $config; - $this->apiKey = $this->config->getValue(ConfigService::XML_PATH_GENERAL . 'api/key'); + $this->apiKey = $config->getValue(Config::XML_PATH_GENERAL . 'api/key'); $this->context = $dbContext; $this->typeListInterface = $typeListInterface; $this->pool = $pool; @@ -69,8 +68,8 @@ public function __construct( */ public function execute() { - $config = new Config($this->context); - $path = ConfigService::XML_PATH_GENERAL . 'account_settings'; + $config = new ResourceConfig($this->context); + $path = Config::XML_PATH_GENERAL . 'account_settings'; $configuration = $this->fetchConfigurations(); $config->saveConfig($path, json_encode($this->createArray($configuration))); @@ -120,7 +119,7 @@ public static function getAccountSettings(): ?Collection { $objectManager = ObjectManager::getInstance(); $accountSettings = $objectManager->get(ScopeConfigInterface::class) - ->getValue(ConfigService::XML_PATH_GENERAL . 'account_settings'); + ->getValue(Config::XML_PATH_GENERAL . 'account_settings'); if (! $accountSettings) { return null; diff --git a/Controller/Adminhtml/Shipment/CreateAndPrintMyParcelTrack.php b/Controller/Adminhtml/Shipment/CreateAndPrintMyParcelTrack.php index a2938488..98e2f0e0 100755 --- a/Controller/Adminhtml/Shipment/CreateAndPrintMyParcelTrack.php +++ b/Controller/Adminhtml/Shipment/CreateAndPrintMyParcelTrack.php @@ -8,7 +8,7 @@ use Magento\Framework\Exception\LocalizedException; use MyParcelNL\Magento\Model\Sales\MagentoCollection; use MyParcelNL\Magento\Model\Sales\MagentoShipmentCollection; -use MyParcelNL\Magento\Service\Config\ConfigService; +use MyParcelNL\Magento\Service\Config; /** * Action to create and print MyParcel Track @@ -29,8 +29,8 @@ class CreateAndPrintMyParcelTrack extends \Magento\Framework\App\Action\Action /** * @var MagentoShipmentCollection */ - private $shipmentCollection; - private ConfigService $configService; + private $shipmentCollection; + private Config $configService; /** * CreateAndPrintMyParcelTrack constructor. @@ -41,7 +41,7 @@ public function __construct(Context $context) { parent::__construct($context); - $this->configService = $context->getObjectManager()->get(ConfigService::class); + $this->configService = $context->getObjectManager()->get(Config::class); $this->resultRedirectFactory = $context->getResultRedirectFactory(); $this->shipmentCollection = new MagentoShipmentCollection( $context->getObjectManager(), diff --git a/Cron/UpdateStatus.php b/Cron/UpdateStatus.php index a6b9758f..2c32406d 100755 --- a/Cron/UpdateStatus.php +++ b/Cron/UpdateStatus.php @@ -35,7 +35,7 @@ use MyParcelNL\Magento\Model\Carrier\Carrier; use MyParcelNL\Magento\Model\Sales\MagentoCollection; use MyParcelNL\Magento\Model\Sales\MagentoOrderCollection; -use MyParcelNL\Magento\Service\Config\ConfigService; +use MyParcelNL\Magento\Service\Config; use MyParcelNL\Magento\Ui\Component\Listing\Column\TrackAndTrace; use MyParcelNL\Sdk\src\Collection\Fulfilment\OrderCollection; use MyParcelNL\Sdk\src\Exception\AccountNotActiveException; @@ -54,7 +54,7 @@ class UpdateStatus private ObjectManager $objectManager; private \Magento\Sales\Model\ResourceModel\Order $orderResource; private MagentoOrderCollection $orderCollection; - private ConfigService $configService; + private Config $configService; /** * UpdateStatus constructor. @@ -70,7 +70,7 @@ public function __construct( ) { $this->objectManager = $objectManager = ObjectManager::getInstance(); - $this->configService = $objectManager->get(ConfigService::class); + $this->configService = $objectManager->get(Config::class); $this->orderCollection = new MagentoOrderCollection($this->objectManager, null, $areaList); $this->orderResource = $orderResource; } @@ -84,7 +84,7 @@ public function __construct( */ public function execute(): self { - if (ConfigService::EXPORT_MODE_PPS === $this->configService->getExportMode()) { + if (Config::EXPORT_MODE_PPS === $this->configService->getExportMode()) { return $this->updateStatusPPS(); } return $this->updateStatusShipments(); diff --git a/Helper/CustomsDeclarationFromOrder.php b/Helper/CustomsDeclarationFromOrder.php index 45798ec9..e3052fe2 100644 --- a/Helper/CustomsDeclarationFromOrder.php +++ b/Helper/CustomsDeclarationFromOrder.php @@ -7,8 +7,8 @@ use Magento\Catalog\Model\Product; use Magento\Framework\App\ObjectManager; use Magento\Sales\Model\Order; -use MyParcelNL\Magento\Service\Costs\DeliveryCostsService; -use MyParcelNL\Magento\Service\Weight\WeightService; +use MyParcelNL\Magento\Service\DeliveryCosts; +use MyParcelNL\Magento\Service\Weight; use MyParcelNL\Sdk\src\Exception\MissingFieldException; use MyParcelNL\Sdk\src\Model\Consignment\AbstractConsignment; use MyParcelNL\Sdk\src\Model\CustomsDeclaration; @@ -35,7 +35,7 @@ class CustomsDeclarationFromOrder private $order; /** - * @var WeightService + * @var Weight */ private $weightService; @@ -47,7 +47,7 @@ public function __construct(Order $order) $objectManager = ObjectManager::getInstance(); $this->order = $order; $this->objectManager = $objectManager; - $this->weightService = $objectManager->get(WeightService::class); + $this->weightService = $objectManager->get(Weight::class); } /** @@ -76,7 +76,7 @@ public function createCustomsDeclaration(): CustomsDeclaration ->setAmount($amount) ->setWeight($this->weightService->convertToGrams($product->getWeight())) ->setItemValueArray([ - 'amount' => DeliveryCostsService::getPriceInCents($product->getPrice()), + 'amount' => DeliveryCosts::getPriceInCents($product->getPrice()), 'currency' => $this->order->getOrderCurrency()->getCode() ?? self::CURRENCY_EURO, ]) ->setCountry($this->getCountryOfOrigin($product)) diff --git a/Helper/ShipmentOptions.php b/Helper/ShipmentOptions.php index 6f48b1e4..2fb151ad 100644 --- a/Helper/ShipmentOptions.php +++ b/Helper/ShipmentOptions.php @@ -6,30 +6,30 @@ use Magento\Framework\ObjectManagerInterface; use Magento\Sales\Model\Order; use MyParcelNL\Magento\Model\Source\DefaultOptions; -use MyParcelNL\Magento\Service\Config\ConfigService; -use MyParcelNL\Magento\Service\Date\DatingService; +use MyParcelNL\Magento\Service\Config; +use MyParcelNL\Magento\Service\Dating; use MyParcelNL\Sdk\src\Model\Carrier\CarrierPostNL; use MyParcelNL\Sdk\src\Model\Consignment\AbstractConsignment; use Magento\Framework\App\ResourceConnection; class ShipmentOptions { - public const INSURANCE = 'insurance'; - public const ONLY_RECIPIENT = 'only_recipient'; - private const SAME_DAY_DELIVERY = 'same_day_delivery'; - public const SIGNATURE = 'signature'; - public const COLLECT = AbstractConsignment::SHIPMENT_OPTION_COLLECT; - public const RECEIPT_CODE = AbstractConsignment::SHIPMENT_OPTION_RECEIPT_CODE; - public const RETURN = 'return'; - public const AGE_CHECK = 'age_check'; - public const LARGE_FORMAT = 'large_format'; - private const HIDE_SENDER = 'hide_sender'; + public const INSURANCE = AbstractConsignment::SHIPMENT_OPTION_INSURANCE; + public const ONLY_RECIPIENT = AbstractConsignment::SHIPMENT_OPTION_ONLY_RECIPIENT; + private const SAME_DAY_DELIVERY = AbstractConsignment::SHIPMENT_OPTION_SAME_DAY_DELIVERY; + public const SIGNATURE = AbstractConsignment::SHIPMENT_OPTION_SIGNATURE; + public const COLLECT = AbstractConsignment::SHIPMENT_OPTION_COLLECT; + public const RECEIPT_CODE = AbstractConsignment::SHIPMENT_OPTION_RECEIPT_CODE; + public const RETURN = AbstractConsignment::SHIPMENT_OPTION_RETURN; + public const AGE_CHECK = AbstractConsignment::SHIPMENT_OPTION_AGE_CHECK; + public const LARGE_FORMAT = AbstractConsignment::SHIPMENT_OPTION_LARGE_FORMAT; + private const HIDE_SENDER = AbstractConsignment::SHIPMENT_OPTION_HIDE_SENDER; private const LABEL_DESCRIPTION = 'label_description'; - private const ORDER_NUMBER = '%order_nr%'; - private const DELIVERY_DATE = '%delivery_date%'; - private const PRODUCT_ID = '%product_id%'; - private const PRODUCT_NAME = '%product_name%'; - private const PRODUCT_QTY = '%product_qty%'; + private const ORDER_NUMBER = '%order_nr%'; + private const DELIVERY_DATE = '%delivery_date%'; + private const PRODUCT_ID = '%product_id%'; + private const PRODUCT_NAME = '%product_name%'; + private const PRODUCT_QTY = '%product_qty%'; /** * @var string @@ -65,14 +65,14 @@ class ShipmentOptions * @var string|null */ private ?string $cc; - private DatingService $datingService; + private Dating $datingService; /** - * @param DefaultOptions $defaultOptions - * @param Order $order + * @param DefaultOptions $defaultOptions + * @param Order $order * @param ObjectManagerInterface $objectManager - * @param string $carrier - * @param array $options + * @param string $carrier + * @param array $options */ public function __construct( DefaultOptions $defaultOptions, @@ -83,8 +83,8 @@ public function __construct( ) { $this->defaultOptions = $defaultOptions; - $this->configService = $objectManager->get(ConfigService::class); - $this->datingService = $objectManager->get(DatingService::class); + $this->configService = $objectManager->get(Config::class); + $this->datingService = $objectManager->get(Dating::class); $this->order = $order; $this->objectManager = $objectManager; $this->carrier = $carrier; @@ -205,7 +205,7 @@ public static function getAgeCheckFromProduct($products): ?bool self::AGE_CHECK ); - if (!isset($productAgeCheck) || '' === $productAgeCheck) { + if (! isset($productAgeCheck) || '' === $productAgeCheck) { $hasAgeCheck = null; } elseif ('1' === $productAgeCheck) { return true; @@ -243,8 +243,8 @@ public static function getAttributeValue(string $tableName, string $entityId, st /** * @param $connection - * @param string $tableName - * @param string $databaseColumn + * @param string $tableName + * @param string $databaseColumn * * @return mixed */ @@ -284,17 +284,17 @@ public static function getValueFromAttribute( /** * @param string $key - * @param array $options + * @param array $options * * @return bool|null boolean value of the option named $key, or null when not set in $options */ public static function getValueOfOptionWhenSet(string $key, array $options): ?bool { - if (!isset($options[$key])) { + if (! isset($options[$key])) { return null; } - return (bool)$options[$key]; + return (bool) $options[$key]; } /** @@ -302,7 +302,7 @@ public static function getValueOfOptionWhenSet(string $key, array $options): ?bo */ public function hasLargeFormat(): bool { - if (!in_array($this->cc, AbstractConsignment::EURO_COUNTRIES)) { + if (! in_array($this->cc, AbstractConsignment::EURO_COUNTRIES)) { return false; } @@ -322,11 +322,11 @@ public function getLabelDescription(): string $this->order->getStoreId() ); - if (!$labelDescription) { + if (! $labelDescription) { return ''; } - $deliveryOptions = $this->order->getData(ConfigService::FIELD_DELIVERY_OPTIONS); + $deliveryOptions = $this->order->getData(Config::FIELD_DELIVERY_OPTIONS); $checkoutDate = json_decode($deliveryOptions, true)['date'] ?? null; $productInfo = $this->getItemsCollectionByShipmentId($this->order->getId()); $labelDescription = str_replace( @@ -347,11 +347,11 @@ public function getLabelDescription(): string $labelDescription ); - return (string)$labelDescription; + return (string) $labelDescription; } /** - * @param array $productInfo + * @param array $productInfo * @param string $field * * @return string|null @@ -393,11 +393,11 @@ public function getItemsCollectionByShipmentId($shipmentId): array */ private function optionIsEnabled($optionKey): bool { - if (!isset($this->options[$optionKey])) { + if (! isset($this->options[$optionKey])) { return $this->defaultOptions->hasOptionSet($optionKey, $this->carrier); } - return (bool)$this->options[$optionKey]; + return (bool) $this->options[$optionKey]; } /** @@ -420,4 +420,3 @@ public function getShipmentOptions(): array ]; } } - diff --git a/Model/Carrier/Carrier.php b/Model/Carrier/Carrier.php index a170f1cf..2a98b2e4 100644 --- a/Model/Carrier/Carrier.php +++ b/Model/Carrier/Carrier.php @@ -33,8 +33,8 @@ use Magento\Shipping\Model\Carrier\CarrierInterface; use Magento\Shipping\Model\Rate\ResultFactory; use MyParcelNL\Magento\Model\Sales\Repository\PackageRepository; -use MyParcelNL\Magento\Service\Config\ConfigService; -use MyParcelNL\Magento\Service\Costs\DeliveryCostsService; +use MyParcelNL\Magento\Service\Config; +use MyParcelNL\Magento\Service\DeliveryCosts; use MyParcelNL\Sdk\src\Adapter\DeliveryOptions\DeliveryOptionsV3Adapter; use MyParcelNL\Sdk\src\Adapter\DeliveryOptions\ShipmentOptionsV3Adapter; use MyParcelNL\Sdk\src\Factory\DeliveryOptionsAdapterFactory; @@ -61,16 +61,16 @@ class Carrier extends AbstractCarrier implements CarrierInterface * Carrier constructor. * * @param ScopeConfigInterface $scopeConfig - * @param ErrorFactory $rateErrorFactory - * @param LoggerInterface $logger - * @param ConfigService $configService - * @param DeliveryCostsService $deliveryCostsService - * @param ResultFactory $rateFactory - * @param MethodFactory $rateMethodFactory - * @param Session $session - * @param PackageRepository $package - * @param Freeshipping $freeShipping - * @param array $data + * @param ErrorFactory $rateErrorFactory + * @param LoggerInterface $logger + * @param Config $configService + * @param DeliveryCosts $deliveryCostsService + * @param ResultFactory $rateFactory + * @param MethodFactory $rateMethodFactory + * @param Session $session + * @param PackageRepository $package + * @param Freeshipping $freeShipping + * @param array $data * * @throws Exception */ @@ -78,8 +78,8 @@ public function __construct( ScopeConfigInterface $scopeConfig, ErrorFactory $rateErrorFactory, LoggerInterface $logger, - ConfigService $configService, - DeliveryCostsService $deliveryCostsService, + Config $configService, + DeliveryCosts $deliveryCostsService, ResultFactory $rateFactory, MethodFactory $rateMethodFactory, Session $session, @@ -101,7 +101,7 @@ public function __construct( $this->quote = $session->getQuote(); try { - $this->deliveryOptions = DeliveryOptionsAdapterFactory::create(json_decode($this->quote->getData(ConfigService::FIELD_DELIVERY_OPTIONS), true)); + $this->deliveryOptions = DeliveryOptionsAdapterFactory::create(json_decode($this->quote->getData(Config::FIELD_DELIVERY_OPTIONS), true)); } catch (Throwable $e) { $this->deliveryOptions = DeliveryOptionsAdapterFactory::create(DeliveryOptionsV3Adapter::DEFAULTS); } @@ -140,7 +140,7 @@ public function collectRates(RateRequest $request) private function getMethodAmount(): float { - $configPath = ConfigService::CARRIERS_XML_PATH_MAP[$this->deliveryOptions->getCarrier()] ?? ''; + $configPath = Config::CARRIERS_XML_PATH_MAP[$this->deliveryOptions->getCarrier()] ?? ''; $shipmentOptions = $this->deliveryOptions->getShipmentOptions() ?? new ShipmentOptionsV3Adapter([]); $shipmentFees = [ "{$this->deliveryOptions->getDeliveryType()}/fee" => true, @@ -226,7 +226,7 @@ private function getShippingMethod($alias, string $settingPath) */ private function createTitle($settingPath) { - $title = $this->configService->getConfigValue(ConfigService::XML_PATH_POSTNL_SETTINGS . $settingPath . 'title'); + $title = $this->configService->getConfigValue(Config::XML_PATH_POSTNL_SETTINGS . $settingPath . 'title'); if ($title === null) { $title = __($settingPath . 'title'); diff --git a/Model/Checkout/DeliveryOptionsToShippingMethods.php b/Model/Checkout/DeliveryOptionsToShippingMethods.php index fd50937f..2014f006 100755 --- a/Model/Checkout/DeliveryOptionsToShippingMethods.php +++ b/Model/Checkout/DeliveryOptionsToShippingMethods.php @@ -5,7 +5,7 @@ namespace MyParcelNL\Magento\Model\Checkout; use Exception; -use MyParcelNL\Magento\Service\Config\ConfigService; +use MyParcelNL\Magento\Service\Config; use MyParcelNL\Sdk\src\Factory\DeliveryOptionsAdapterFactory; class DeliveryOptionsToShippingMethods @@ -57,8 +57,8 @@ private function getCarrierXmlPath(): string { $carrier = $this->deliveryOptions->getCarrier(); - if (array_key_exists($carrier, ConfigService::CARRIERS_XML_PATH_MAP)) { - return ConfigService::CARRIERS_XML_PATH_MAP[$carrier]; + if (array_key_exists($carrier, Config::CARRIERS_XML_PATH_MAP)) { + return Config::CARRIERS_XML_PATH_MAP[$carrier]; } throw new Exception("No XML path found for carrier '{$carrier}'."); diff --git a/Model/Quote/Checkout.php b/Model/Quote/Checkout.php index 40e5354f..cb309fe8 100644 --- a/Model/Quote/Checkout.php +++ b/Model/Quote/Checkout.php @@ -11,16 +11,16 @@ use MyParcelNL\Magento\Facade\Logger; use MyParcelNL\Magento\Model\Sales\Repository\PackageRepository; use MyParcelNL\Magento\Model\Source\PriceDeliveryOptionsView; -use MyParcelNL\Magento\Service\Config\ConfigService; -use MyParcelNL\Magento\Service\Costs\DeliveryCostsService; +use MyParcelNL\Magento\Service\Config; +use MyParcelNL\Magento\Service\DeliveryCosts; use MyParcelNL\Sdk\src\Factory\ConsignmentFactory; use MyParcelNL\Sdk\src\Model\Consignment\AbstractConsignment; use Throwable; class Checkout { - private ConfigService $configService; - private DeliveryCostsService $deliveryCostsService; + private Config $configService; + private DeliveryCosts $deliveryCostsService; /** * @var \MyParcelNL\Magento\Model\Sales\Repository\PackageRepository @@ -48,15 +48,15 @@ class Checkout * * @param Session $session * @param Cart $cart - * @param ConfigService $configService + * @param Config $configService * @param PackageRepository $package * @param StoreManagerInterface $currency */ public function __construct( Session $session, Cart $cart, - ConfigService $configService, - DeliveryCostsService $deliveryCostsService, + Config $configService, + DeliveryCosts $deliveryCostsService, PackageRepository $package, StoreManagerInterface $currency ) @@ -117,14 +117,14 @@ private function getGeneralData() { return [ 'allowRetry' => true, - 'platform' => ConfigService::PLATFORM, + 'platform' => Config::PLATFORM, 'carriers' => $this->getActiveCarriers(), 'currency' => $this->currency->getStore()->getCurrentCurrency()->getCode(), - 'allowShowDeliveryDate' => $this->configService->getBoolConfig(ConfigService::XML_PATH_GENERAL, 'date_settings/allow_show_delivery_date'), - 'deliveryDaysWindow' => $this->configService->getIntegerConfig(ConfigService::XML_PATH_GENERAL, 'date_settings/deliverydays_window'), - 'dropOffDelay' => $this->getDropOffDelay(ConfigService::XML_PATH_GENERAL, 'date_settings/dropoff_delay'), - 'pickupLocationsDefaultView' => $this->configService->getConfigValue(ConfigService::XML_PATH_GENERAL . 'shipping_methods/pickup_locations_view'), - 'showPriceSurcharge' => $this->configService->getConfigValue(ConfigService::XML_PATH_GENERAL . 'shipping_methods/delivery_options_prices') === PriceDeliveryOptionsView::SURCHARGE, + 'allowShowDeliveryDate' => $this->configService->getBoolConfig(Config::XML_PATH_GENERAL, 'date_settings/allow_show_delivery_date'), + 'deliveryDaysWindow' => $this->configService->getIntegerConfig(Config::XML_PATH_GENERAL, 'date_settings/deliverydays_window'), + 'dropOffDelay' => $this->getDropOffDelay(Config::XML_PATH_GENERAL, 'date_settings/dropoff_delay'), + 'pickupLocationsDefaultView' => $this->configService->getConfigValue(Config::XML_PATH_GENERAL . 'shipping_methods/pickup_locations_view'), + 'showPriceSurcharge' => $this->configService->getConfigValue(Config::XML_PATH_GENERAL . 'shipping_methods/delivery_options_prices') === PriceDeliveryOptionsView::SURCHARGE, 'basePrice' => $this->deliveryCostsService->getBasePrice($this->quote), ]; } @@ -166,8 +166,8 @@ private function getDeliveryData(?string $packageType = null): array { $myParcelConfig = []; $activeCarriers = $this->getActiveCarriers(); - $carrierPaths = ConfigService::CARRIERS_XML_PATH_MAP; - $showTotalPrice = $this->configService->getConfigValue(ConfigService::XML_PATH_GENERAL . 'shipping_methods/delivery_options_prices') === PriceDeliveryOptionsView::TOTAL; + $carrierPaths = Config::CARRIERS_XML_PATH_MAP; + $showTotalPrice = $this->configService->getConfigValue(Config::XML_PATH_GENERAL . 'shipping_methods/delivery_options_prices') === PriceDeliveryOptionsView::TOTAL; foreach ($activeCarriers as $carrier) { $carrierPath = $carrierPaths[$carrier]; @@ -187,12 +187,12 @@ private function getDeliveryData(?string $packageType = null): array $canHaveMorning = $consignment->canHaveDeliveryType(AbstractConsignment::DELIVERY_TYPE_MORNING_NAME); $canHaveEvening = $consignment->canHaveDeliveryType(AbstractConsignment::DELIVERY_TYPE_EVENING_NAME); $canHaveExpress = $consignment->canHaveDeliveryType(AbstractConsignment::DELIVERY_TYPE_EXPRESS_NAME); + $canHavePickup = $consignment->canHaveDeliveryType(AbstractConsignment::DELIVERY_TYPE_PICKUP_NAME); $canHaveSignature = $consignment->canHaveShipmentOption(AbstractConsignment::SHIPMENT_OPTION_SIGNATURE); $canHaveCollect = $consignment->canHaveShipmentOption(AbstractConsignment::SHIPMENT_OPTION_COLLECT); $canHaveReceiptCode = $consignment->canHaveShipmentOption(AbstractConsignment::SHIPMENT_OPTION_RECEIPT_CODE); $canHaveOnlyRecipient = $consignment->canHaveShipmentOption(AbstractConsignment::SHIPMENT_OPTION_ONLY_RECIPIENT); $canHaveAgeCheck = $consignment->canHaveShipmentOption(AbstractConsignment::SHIPMENT_OPTION_AGE_CHECK); - $canHavePickup = $consignment->canHaveDeliveryType(AbstractConsignment::DELIVERY_TYPE_PICKUP_NAME); $mailboxFee = 0; if ($canHaveMailbox) { @@ -211,7 +211,7 @@ private function getDeliveryData(?string $packageType = null): array $eveningFee = $canHaveEvening ? $this->configService->getFloatConfig($carrierPath, 'evening/fee') + $addBasePrice : 0; $sameDayFee = $canHaveSameDay ? (int) $this->configService->getFloatConfig($carrierPath, 'delivery/same_day_delivery_fee') + $addBasePrice : 0; $signatureFee = $canHaveSignature ? $this->configService->getFloatConfig($carrierPath, 'delivery/signature_fee') : 0; - $collectFee = $canHaveCollect ? $this->helper->getMethodPrice($carrierPath, 'delivery/collect_fee', false) : 0; + $collectFee = $canHaveCollect ? $this->configService->getFloatConfig($carrierPath, 'delivery/collect_fee', false) : 0; $receiptCodeFee = $canHaveReceiptCode ? $this->configService->getFloatConfig($carrierPath, 'delivery/receipt_code_fee') : 0; $onlyRecipientFee = $canHaveOnlyRecipient ? $this->configService->getFloatConfig($carrierPath, 'delivery/only_recipient_fee') : 0; $isAgeCheckActive = $canHaveAgeCheck && $this->isAgeCheckActive($carrierPath); @@ -280,7 +280,7 @@ private function getDeliveryData(?string $packageType = null): array public function getActiveCarriers(): array { $carriers = []; - foreach (ConfigService::CARRIERS_XML_PATH_MAP as $carrier => $path) { + foreach (Config::CARRIERS_XML_PATH_MAP as $carrier => $path) { if ($this->configService->getBoolConfig($path, 'delivery/active') || $this->configService->getBoolConfig($path, 'pickup/active') ) { @@ -380,7 +380,7 @@ public function checkPackageType(string $carrier, ?string $country = null): stri return AbstractConsignment::DEFAULT_PACKAGE_TYPE_NAME; } - $carrierPath = ConfigService::CARRIERS_XML_PATH_MAP[$carrier]; + $carrierPath = Config::CARRIERS_XML_PATH_MAP[$carrier]; $products = $this->quote->getAllItems(); $country = $country ?? $this->country ?? $this->quote->getShippingAddress()->getCountryId(); $canHaveDigitalStamp = $consignment->canHavePackageType(AbstractConsignment::PACKAGE_TYPE_DIGITAL_STAMP_NAME); diff --git a/Model/Quote/SaveOrderBeforeSalesModelQuoteObserver.php b/Model/Quote/SaveOrderBeforeSalesModelQuoteObserver.php index ba537c08..5ce43e77 100644 --- a/Model/Quote/SaveOrderBeforeSalesModelQuoteObserver.php +++ b/Model/Quote/SaveOrderBeforeSalesModelQuoteObserver.php @@ -26,7 +26,7 @@ use Magento\Sales\Model\Order; use MyParcelNL\Magento\Model\Carrier\Carrier; use MyParcelNL\Magento\Model\Sales\Repository\DeliveryRepository; -use MyParcelNL\Magento\Service\Config\ConfigService; +use MyParcelNL\Magento\Service\Config; use MyParcelNL\Sdk\src\Helper\ValidatePostalCode; use MyParcelNL\Sdk\src\Helper\ValidateStreet; use MyParcelNL\Sdk\src\Model\Consignment\AbstractConsignment; @@ -48,11 +48,11 @@ class SaveOrderBeforeSalesModelQuoteObserver implements ObserverInterface * SaveOrderBeforeSalesModelQuoteObserver constructor. * * @param DeliveryRepository $delivery - * @param ConfigService $configService + * @param Config $configService */ public function __construct( DeliveryRepository $delivery, - ConfigService $configService + Config $configService ) { $this->delivery = $delivery; @@ -82,24 +82,24 @@ public function execute(Observer $observer) $destinationCountry = $order->getShippingAddress()->getCountryId(); if (!ValidateStreet::validate($fullStreet, AbstractConsignment::CC_NL, $destinationCountry)) { - $order->setData(ConfigService::FIELD_TRACK_STATUS, __('⚠️  Please check street')); + $order->setData(Config::FIELD_TRACK_STATUS, __('⚠️  Please check street')); } if (!ValidatePostalCode::validate($postcode, $destinationCountry)) { - $order->setData(ConfigService::FIELD_TRACK_STATUS, __('⚠️  Please check postal code')); + $order->setData(Config::FIELD_TRACK_STATUS, __('⚠️  Please check postal code')); } - if ($quote->hasData(ConfigService::FIELD_DELIVERY_OPTIONS) && $this->hasMyParcelDeliveryOptions($quote)) { - $jsonDeliveryOptions = $quote->getData(ConfigService::FIELD_DELIVERY_OPTIONS) ?? ''; + if ($quote->hasData(Config::FIELD_DELIVERY_OPTIONS) && $this->hasMyParcelDeliveryOptions($quote)) { + $jsonDeliveryOptions = $quote->getData(Config::FIELD_DELIVERY_OPTIONS) ?? ''; $deliveryOptions = json_decode($jsonDeliveryOptions, true) ?? []; - $order->setData(ConfigService::FIELD_DELIVERY_OPTIONS, $jsonDeliveryOptions); + $order->setData(Config::FIELD_DELIVERY_OPTIONS, $jsonDeliveryOptions); $dropOffDay = $this->delivery->getDropOffDayFromDeliveryOptions($deliveryOptions); - $order->setData(ConfigService::FIELD_DROP_OFF_DAY, $dropOffDay); + $order->setData(Config::FIELD_DROP_OFF_DAY, $dropOffDay); $selectedCarrier = $this->delivery->getCarrierFromDeliveryOptions($deliveryOptions); - $order->setData(ConfigService::FIELD_MYPARCEL_CARRIER, $selectedCarrier); + $order->setData(Config::FIELD_MYPARCEL_CARRIER, $selectedCarrier); } return $this; @@ -118,6 +118,6 @@ private function hasMyParcelDeliveryOptions(Quote $quote): bool return true; } - return array_key_exists(ConfigService::FIELD_DELIVERY_OPTIONS, $quote->getData()); + return array_key_exists(Config::FIELD_DELIVERY_OPTIONS, $quote->getData()); } } diff --git a/Model/Sales/MagentoCollection.php b/Model/Sales/MagentoCollection.php index 430c1252..3a7cab10 100755 --- a/Model/Sales/MagentoCollection.php +++ b/Model/Sales/MagentoCollection.php @@ -34,8 +34,8 @@ use MyParcelNL\Magento\Model\Source\ReturnInTheBox; use MyParcelNL\Magento\Model\Source\SourceItem; use MyParcelNL\Magento\Observer\NewShipment; -use MyParcelNL\Magento\Service\Config\ConfigService; -use MyParcelNL\Magento\Service\Weight\WeightService; +use MyParcelNL\Magento\Service\Config; +use MyParcelNL\Magento\Service\Weight; use MyParcelNL\Magento\Ui\Component\Listing\Column\TrackAndTrace; use MyParcelNL\Sdk\src\Exception\AccountNotActiveException; use MyParcelNL\Sdk\src\Exception\ApiException; @@ -71,8 +71,8 @@ abstract class MagentoCollection implements MagentoCollectionInterface protected ObjectManagerInterface $objectManager; protected Track $modelTrack; protected AreaList $areaList; - protected ManagerInterface $messageManager; - protected ConfigService $configService; + protected ManagerInterface $messageManager; + protected Config $configService; /** * @var array @@ -122,8 +122,8 @@ public function __construct( $this->moduleManager = $objectManager->get(Manager::class); $this->request = $request; $this->trackSender = $this->objectManager->get(TrackSender::class); - $this->configService = $objectManager->get(ConfigService::class); - $this->weightService = $objectManager->get(WeightService::class); + $this->configService = $objectManager->get(Config::class); + $this->weightService = $objectManager->get(Weight::class); $this->modelTrack = $objectManager->create(self::PATH_ORDER_TRACK); $this->messageManager = $objectManager->create(self::PATH_MANAGER_INTERFACE); $this->myParcelCollection = (new MyParcelCollection())->setUserAgents( @@ -299,7 +299,7 @@ protected function setNewMagentoTrack($shipment) ->setOrderId($shipment->getOrderId()) ->setShipment($shipment) ->setCarrierCode(Carrier::CODE) - ->setTitle(ConfigService::MYPARCEL_TRACK_TITLE) + ->setTitle(Config::MYPARCEL_TRACK_TITLE) ->setQty($shipment->getTotalQty()) ->setTrackNumber(TrackAndTrace::VALUE_EMPTY) ->save(); diff --git a/Model/Sales/MagentoOrderCollection.php b/Model/Sales/MagentoOrderCollection.php index 04a6a377..496a2f41 100755 --- a/Model/Sales/MagentoOrderCollection.php +++ b/Model/Sales/MagentoOrderCollection.php @@ -22,7 +22,7 @@ use MyParcelNL\Magento\Helper\CustomsDeclarationFromOrder; use MyParcelNL\Magento\Helper\ShipmentOptions; use MyParcelNL\Magento\Model\Source\DefaultOptions; -use MyParcelNL\Magento\Service\Config\ConfigService; +use MyParcelNL\Magento\Service\Config; use MyParcelNL\Magento\Service\Normalizer\ConsignmentNormalizer; use MyParcelNL\Sdk\src\Collection\Fulfilment\OrderCollection; use MyParcelNL\Sdk\src\Collection\Fulfilment\OrderNotesCollection; @@ -179,7 +179,7 @@ public function setFulfilment(): self foreach ($this->getOrders() as $magentoOrder) { $defaultOptions = new DefaultOptions($magentoOrder); - $myparcelDeliveryOptions = $magentoOrder[ConfigService::FIELD_DELIVERY_OPTIONS] ?? ''; + $myparcelDeliveryOptions = $magentoOrder[Config::FIELD_DELIVERY_OPTIONS] ?? ''; $deliveryOptions = json_decode($myparcelDeliveryOptions, true); $selectedCarrier = $deliveryOptions['carrier'] ?? $this->options['carrier'] ?? CarrierPostNL::NAME; $shipmentOptionsHelper = new ShipmentOptions( diff --git a/Model/Sales/Package.php b/Model/Sales/Package.php index fe05b377..3c2d95b2 100755 --- a/Model/Sales/Package.php +++ b/Model/Sales/Package.php @@ -18,9 +18,9 @@ namespace MyParcelNL\Magento\Model\Sales; -use MyParcelNL\Magento\Service\Config\ConfigService; +use MyParcelNL\Magento\Service\Config; -class Package extends ConfigService implements PackageInterface //used to extend MyParcelNL\Magento\Helper\Data; +class Package extends Config implements PackageInterface //used to extend MyParcelNL\Magento\Helper\Data; { /** * @var int diff --git a/Model/Sales/Repository/DeliveryRepository.php b/Model/Sales/Repository/DeliveryRepository.php index dc8fd205..ffbfdfc4 100755 --- a/Model/Sales/Repository/DeliveryRepository.php +++ b/Model/Sales/Repository/DeliveryRepository.php @@ -19,9 +19,9 @@ namespace MyParcelNL\Magento\Model\Sales\Repository; use MyParcelNL\Magento\Model\Sales\DeliveryInterface; -use MyParcelNL\Magento\Service\Config\ConfigService; +use MyParcelNL\Magento\Service\Config; -class DeliveryRepository extends ConfigService implements DeliveryInterface // used to extend MyParcelNL\Magento\Helper\Data; +class DeliveryRepository extends Config implements DeliveryInterface // used to extend MyParcelNL\Magento\Helper\Data; { /** * @var int diff --git a/Model/Sales/TrackTraceHolder.php b/Model/Sales/TrackTraceHolder.php index 6586d9ad..acf80d43 100755 --- a/Model/Sales/TrackTraceHolder.php +++ b/Model/Sales/TrackTraceHolder.php @@ -28,10 +28,10 @@ use MyParcelNL\Magento\Model\Carrier\Carrier; use MyParcelNL\Magento\Model\Settings\AccountSettings; use MyParcelNL\Magento\Model\Source\DefaultOptions; -use MyParcelNL\Magento\Service\Config\ConfigService; -use MyParcelNL\Magento\Service\Costs\DeliveryCostsService; -use MyParcelNL\Magento\Service\Date\DatingService; -use MyParcelNL\Magento\Service\Weight\WeightService; +use MyParcelNL\Magento\Service\Config; +use MyParcelNL\Magento\Service\DeliveryCosts; +use MyParcelNL\Magento\Service\Dating; +use MyParcelNL\Magento\Service\Weight; use MyParcelNL\Magento\Ui\Component\Listing\Column\TrackAndTrace; use MyParcelNL\Sdk\src\Exception\MissingFieldException; use MyParcelNL\Sdk\src\Factory\ConsignmentFactory; @@ -73,7 +73,7 @@ class TrackTraceHolder */ private $carrier; - private ConfigService $configService; + private Config $configService; /** * @var ObjectManagerInterface @@ -83,9 +83,10 @@ class TrackTraceHolder /** * @var ShipmentOptions */ - private $shipmentOptionsHelper; - private WeightService $weightService; - private DeliveryCostsService $deliveryCostsService; + private $shipmentOptionsHelper; + private Weight $weight; + private DeliveryCosts $deliveryCosts; + private Dating $dating; /** * TrackTraceHolder constructor. @@ -98,13 +99,13 @@ public function __construct( Order $order ) { - $this->objectManager = $objectManager; - $this->configService = $objectManager->get(ConfigService::class); - $this->weightService = $objectManager->get(WeightService::class); - $this->datingService = $objectManager->get(DatingService::class); - $this->deliveryCostsService = $objectManager->get(DeliveryCostsService::class); - $this->messageManager = $this->objectManager->create('Magento\Framework\Message\ManagerInterface'); - $this->defaultOptions = new DefaultOptions($order); + $this->objectManager = $objectManager; + $this->configService = $objectManager->get(Config::class); + $this->weight = $objectManager->get(Weight::class); + $this->dating = $objectManager->get(Dating::class); + $this->deliveryCosts = $objectManager->get(DeliveryCosts::class); + $this->messageManager = $this->objectManager->create('Magento\Framework\Message\ManagerInterface'); + $this->defaultOptions = new DefaultOptions($order); } /** @@ -188,7 +189,7 @@ public function convertDataFromMagentoToApi(Track $magentoTrack, array $options) $deliveryDate = ( AbstractConsignment::PACKAGE_TYPE_PACKAGE_SMALL === $packageType && 'NL' !== $address->getCountryId() - ) ? null : $this->datingService->convertDeliveryDate($deliveryOptionsAdapter->getDate()); + ) ? null : $this->dating->convertDeliveryDate($deliveryOptionsAdapter->getDate()); $dropOffPoint = AccountSettings::getInstance()->getDropOffPoint( CarrierFactory::createFromName($deliveryOptionsAdapter->getCarrier()) ); @@ -263,7 +264,7 @@ public function createTrackTraceFromShipment(Shipment $shipment) ->setOrderId($shipment->getOrderId()) ->setShipment($shipment) ->setCarrierCode(Carrier::CODE) - ->setTitle(ConfigService::MYPARCEL_TRACK_TITLE) + ->setTitle(Config::MYPARCEL_TRACK_TITLE) ->setQty($shipment->getTotalQty()) ->setTrackNumber(TrackAndTrace::VALUE_EMPTY); @@ -361,7 +362,7 @@ private function calculateTotalWeight(Track $magentoTrack, int $totalWeight = 0) $totalWeight += $shipmentItem['weight'] * $shipmentItem['qty']; } - $totalWeight = $this->weightService->convertToGrams($totalWeight); + $totalWeight = $this->weight->convertToGrams($totalWeight); if (0 === $totalWeight) { throw new RuntimeException( @@ -402,8 +403,8 @@ private function convertDataForCdCountry(Track $magentoTrack) $myParcelProduct = (new MyParcelCustomsItem()) ->setDescription($product->getName()) ->setAmount($product->getQty()) - ->setWeight($this->weightService->convertToGrams($product->getWeight()) ?: 1) - ->setItemValue($this->deliveryCostsService->getPriceInCents($product->getPrice())) + ->setWeight($this->weight->convertToGrams($product->getWeight()) ?: 1) + ->setItemValue($this->deliveryCosts->getPriceInCents($product->getPrice())) ->setClassification( (int) $this->getAttributeValue( 'catalog_product_entity_int', @@ -421,7 +422,7 @@ private function convertDataForCdCountry(Track $magentoTrack) $myParcelProduct = (new MyParcelCustomsItem()) ->setDescription($item->getName()) ->setAmount($item->getQty()) - ->setWeight($this->weightService->convertToGrams($item->getWeight() * $item->getQty())) + ->setWeight($this->weight->convertToGrams($item->getWeight() * $item->getQty())) ->setItemValue($item->getPrice() * 100) ->setClassification( (int) $this->getAttributeValue( diff --git a/Model/Source/AgeCheckNo.php b/Model/Source/AgeCheckNo.php index c48e9759..d60a3342 100755 --- a/Model/Source/AgeCheckNo.php +++ b/Model/Source/AgeCheckNo.php @@ -16,7 +16,7 @@ namespace MyParcelNL\Magento\Model\Source; use Magento\Framework\Data\OptionSourceInterface; -use MyParcelNL\Magento\Service\Config\ConfigService; +use MyParcelNL\Magento\Service\Config; use MyParcelNL\Sdk\src\Model\Carrier\CarrierPostNL; /** @@ -25,12 +25,12 @@ */ class AgeCheckNo implements OptionSourceInterface { - static private ConfigService $configService; + static private Config $configService; /** - * @param ConfigService $configService + * @param Config $configService */ - public function __construct(ConfigService $configService) + public function __construct(Config $configService) { self::$configService = $configService; } @@ -42,7 +42,7 @@ public function __construct(ConfigService $configService) */ public function getDefault($option) { - throw new \Exception('this is not really a default'); + //throw new \Exception('this is not really a default'); $settings = self::$configService->getCarrierConfig(CarrierPostNL::NAME, 'default_options'); return (bool) $settings[$option . '_active']; diff --git a/Model/Source/AgeCheckYes.php b/Model/Source/AgeCheckYes.php index 519f113f..b95d8a79 100755 --- a/Model/Source/AgeCheckYes.php +++ b/Model/Source/AgeCheckYes.php @@ -17,7 +17,7 @@ use Magento\Framework\Data\OptionSourceInterface; use Magento\Sales\Model\Order; -use MyParcelNL\Magento\Service\Config\ConfigService; +use MyParcelNL\Magento\Service\Config; use MyParcelNL\Sdk\src\Model\Carrier\CarrierPostNL; /** @@ -26,7 +26,7 @@ */ class AgeCheckYes implements OptionSourceInterface { - static private ConfigService $configService; + static private Config $configService; /** * Insurance constructor. @@ -34,7 +34,7 @@ class AgeCheckYes implements OptionSourceInterface * @param $order Order * @param $helper Data */ - public function __construct(ConfigService $configService) + public function __construct(Config $configService) { self::$configService = $configService; } diff --git a/Model/Source/DefaultOptions.php b/Model/Source/DefaultOptions.php index 7ccafb8e..4366035f 100755 --- a/Model/Source/DefaultOptions.php +++ b/Model/Source/DefaultOptions.php @@ -17,8 +17,8 @@ use Magento\Framework\App\ObjectManager; use Magento\Sales\Model\Order; use MyParcelNL\Magento\Model\Sales\Repository\PackageRepository; -use MyParcelNL\Magento\Service\Config\ConfigService; -use MyParcelNL\Magento\Service\Weight\WeightService; +use MyParcelNL\Magento\Service\Config; +use MyParcelNL\Magento\Service\Weight; use MyParcelNL\Sdk\src\Factory\ConsignmentFactory; use MyParcelNL\Sdk\src\Factory\DeliveryOptionsAdapterFactory; use MyParcelNL\Sdk\src\Model\Carrier\AbstractCarrier; @@ -54,10 +54,10 @@ class DefaultOptions private const INSURANCE_PERCENTAGE = 'insurance_percentage'; public const DEFAULT_OPTION_VALUE = 'default'; - private ConfigService $configService; - private Order $order; - private array $chosenOptions; - private WeightService $weightService; + private Config $configService; + private Order $order; + private array $chosenOptions; + private Weight $weightService; /** * @param Order $order @@ -65,12 +65,12 @@ class DefaultOptions public function __construct(Order $order) { $objectManager = ObjectManager::getInstance(); - $this->configService = $objectManager->get(ConfigService::class); - $this->weightService = $objectManager->get(WeightService::class); + $this->configService = $objectManager->get(Config::class); + $this->weightService = $objectManager->get(Weight::class); $this->order = $order; try { $this->chosenOptions = DeliveryOptionsAdapterFactory::create( - (array) json_decode($order->getData(ConfigService::FIELD_DELIVERY_OPTIONS), true) + (array) json_decode($order->getData(Config::FIELD_DELIVERY_OPTIONS), true) )->toArray(); } catch (Exception $e) { $this->chosenOptions = []; @@ -109,6 +109,10 @@ public function hasOptionSet(string $option, string $carrier): bool */ public function getMaxCompanyName(?string $company): ?string { + if (null === $company) { + return null; + } + return Str::limit($company, self::COMPANY_NAME_MAX_LENGTH); } diff --git a/Model/Source/DigitalStampWeightOptions.php b/Model/Source/DigitalStampWeightOptions.php index 6fecca4a..830dc68f 100755 --- a/Model/Source/DigitalStampWeightOptions.php +++ b/Model/Source/DigitalStampWeightOptions.php @@ -16,7 +16,7 @@ namespace MyParcelNL\Magento\Model\Source; use Magento\Framework\Data\OptionSourceInterface; -use MyParcelNL\Magento\Service\Config\ConfigService; +use MyParcelNL\Magento\Service\Config; use MyParcelNL\Sdk\src\Model\Carrier\CarrierPostNL; /** @@ -28,9 +28,9 @@ class DigitalStampWeightOptions implements OptionSourceInterface static private $configService; /** - * @param $configService ConfigService + * @param $configService Config */ - public function __construct(ConfigService $configService) + public function __construct(Config $configService) { self::$configService = $configService; } diff --git a/Model/Source/ExportMode.php b/Model/Source/ExportMode.php index 9496a415..c4c69923 100755 --- a/Model/Source/ExportMode.php +++ b/Model/Source/ExportMode.php @@ -6,7 +6,7 @@ use Magento\Framework\Data\OptionSourceInterface; use MyParcelNL\Magento\Model\Sales\TrackTraceHolder; -use MyParcelNL\Magento\Service\Config\ConfigService; +use MyParcelNL\Magento\Service\Config; class ExportMode implements OptionSourceInterface { @@ -17,11 +17,11 @@ public function toOptionArray(): array { return [ [ - 'value' => ConfigService::EXPORT_MODE_SHIPMENTS, + 'value' => Config::EXPORT_MODE_SHIPMENTS, 'label' => __('Export shipping details only') ], [ - 'value' => ConfigService::EXPORT_MODE_PPS, + 'value' => Config::EXPORT_MODE_PPS, 'label' => __('Export entire order') ] ]; @@ -33,8 +33,8 @@ public function toOptionArray(): array public function toArray(): array { return [ - 'shipments' => __(ConfigService::EXPORT_MODE_SHIPMENTS), - 'pps' => __(ConfigService::EXPORT_MODE_PPS) + 'shipments' => __(Config::EXPORT_MODE_SHIPMENTS), + 'pps' => __(Config::EXPORT_MODE_PPS) ]; } } diff --git a/Model/Source/LargeFormatOptions.php b/Model/Source/LargeFormatOptions.php index 544a121e..f8e889dd 100755 --- a/Model/Source/LargeFormatOptions.php +++ b/Model/Source/LargeFormatOptions.php @@ -5,16 +5,16 @@ namespace MyParcelNL\Magento\Model\Source; use Magento\Framework\Data\OptionSourceInterface; -use MyParcelNL\Magento\Service\Config\ConfigService; +use MyParcelNL\Magento\Service\Config; class LargeFormatOptions implements OptionSourceInterface { - static private ConfigService $configService; + static private Config $configService; /** - * @param $configService ConfigService + * @param $configService Config */ - public function __construct(ConfigService $configService) + public function __construct(Config $configService) { self::$configService = $configService; } diff --git a/Observer/CreateConceptAfterInvoice.php b/Observer/CreateConceptAfterInvoice.php index ce37c60b..b5373d6f 100644 --- a/Observer/CreateConceptAfterInvoice.php +++ b/Observer/CreateConceptAfterInvoice.php @@ -26,7 +26,7 @@ use MyParcelNL\Magento\Model\Sales\MagentoCollection; use MyParcelNL\Magento\Model\Sales\MagentoOrderCollection; use MyParcelNL\Magento\Model\Sales\MagentoShipmentCollection; -use MyParcelNL\Magento\Service\Config\ConfigService; +use MyParcelNL\Magento\Service\Config; use MyParcelNL\Sdk\src\Exception\ApiException; use MyParcelNL\Sdk\src\Exception\MissingFieldException; @@ -54,7 +54,7 @@ class CreateConceptAfterInvoice implements ObserverInterface */ private $orderCollection; - private ConfigService $configService; + private Config $configService; /** * @var MagentoShipmentCollection @@ -76,7 +76,7 @@ public function __construct(MagentoOrderCollection $orderCollection = null) $objectManager = ObjectManager::getInstance(); //$this->request = $objectManager->get('Magento\Framework\App\RequestInterface'); $this->orderCollection = $orderCollection ?? new MagentoOrderCollection($this->objectManager, $this->request); - $this->configService = $objectManager->get(ConfigService::class); + $this->configService = $objectManager->get(Config::class); //$this->modelTrack = $objectManager->create('Magento\Sales\Model\Order\Shipment\Track'); //$this->orderFactory = $objectManager->get('\Magento\Sales\Model\Order'); } @@ -128,7 +128,7 @@ private function exportAccordingToMode($orderIds) ->setOptionsFromParameters() ->setNewMagentoShipment(); - if (ConfigService::EXPORT_MODE_PPS === $this->configService->getExportMode()) { + if (Config::EXPORT_MODE_PPS === $this->configService->getExportMode()) { $this->orderCollection->setFulfilment(); return $this; diff --git a/Observer/NewShipment.php b/Observer/NewShipment.php index 1428a8b2..8d9aa73d 100755 --- a/Observer/NewShipment.php +++ b/Observer/NewShipment.php @@ -23,7 +23,7 @@ use Magento\Sales\Model\Order\Shipment; use MyParcelNL\Magento\Model\Sales\MagentoOrderCollection; use MyParcelNL\Magento\Model\Sales\TrackTraceHolder; -use MyParcelNL\Magento\Service\Config\ConfigService; +use MyParcelNL\Magento\Service\Config; class NewShipment implements ObserverInterface { @@ -71,7 +71,7 @@ public function __construct(MagentoOrderCollection $orderCollection = null) $this->redirectFactory = $this->objectManager->get(RedirectFactory::class); $this->messageManager = $this->objectManager->get(Manager::class); $this->orderCollection = $orderCollection ?? new MagentoOrderCollection($this->objectManager, $this->request); - $this->configService = $this->objectManager->get(ConfigService::class); + $this->configService = $this->objectManager->get(Config::class); } /** @@ -149,7 +149,7 @@ private function setMagentoAndMyParcelTrack(Shipment $shipment): void ); } - if (ConfigService::EXPORT_MODE_PPS === $this->configService->getExportMode()) { + if (Config::EXPORT_MODE_PPS === $this->configService->getExportMode()) { $this->exportEntireOrder($shipment); $this->updateTrackGrid($shipment, true); diff --git a/Observer/SalesOrderStatusHistoryObserver.php b/Observer/SalesOrderStatusHistoryObserver.php index 82746f78..e8cf923d 100644 --- a/Observer/SalesOrderStatusHistoryObserver.php +++ b/Observer/SalesOrderStatusHistoryObserver.php @@ -9,18 +9,18 @@ use Magento\Framework\Event\ObserverInterface; use Magento\Sales\Model\Order; use Magento\Sales\Model\Order\Status\History; -use MyParcelNL\Magento\Service\Config\ConfigService; +use MyParcelNL\Magento\Service\Config; use MyParcelNL\Sdk\src\Collection\Fulfilment\OrderNotesCollection; use MyParcelNL\Sdk\src\Model\Fulfilment\OrderNote; class SalesOrderStatusHistoryObserver implements ObserverInterface { - private ConfigService $configService; + private Config $configService; private ObjectManager $objectManager; public function __construct() { $this->objectManager = ObjectManager::getInstance(); - $this->configService = $this->objectManager->get(ConfigService::class); + $this->configService = $this->objectManager->get(Config::class); } /** diff --git a/Service/Config/ConfigService.php b/Service/Config.php similarity index 98% rename from Service/Config/ConfigService.php rename to Service/Config.php index 1cdeb7ca..fe574ec4 100644 --- a/Service/Config/ConfigService.php +++ b/Service/Config.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace MyParcelNL\Magento\Service\Config; +namespace MyParcelNL\Magento\Service; use Magento\Framework\App\Helper\AbstractHelper; use Magento\Framework\App\Helper\Context; @@ -16,7 +16,7 @@ use MyParcelNL\Sdk\src\Model\Carrier\CarrierUPS; use MyParcelNL\Sdk\src\Services\Web\CheckApiKeyWebService; -class ConfigService extends AbstractHelper +class Config extends AbstractHelper { public const MODULE_NAME = 'MyParcelNL_Magento'; public const PLATFORM = 'myparcel'; diff --git a/Service/Costs/TaxService.php b/Service/Costs/TaxService.php deleted file mode 100644 index ec96156b..00000000 --- a/Service/Costs/TaxService.php +++ /dev/null @@ -1,10 +0,0 @@ -weightService = $weightService; } diff --git a/Service/Tax.php b/Service/Tax.php new file mode 100644 index 00000000..ab3fa9be --- /dev/null +++ b/Service/Tax.php @@ -0,0 +1,10 @@ +configService = $configService; + $this->config = $config; } /** @@ -28,7 +28,7 @@ public function __construct(ConfigService $configService) */ public function convertToGrams(?float $weight): int { - $weightType = $this->configService->getGeneralConfig('print/weight_indication'); + $weightType = $this->config->getGeneralConfig('print/weight_indication'); if ('kilo' === $weightType) { return (int)($weight * 1000) ?: self::DEFAULT_WEIGHT; @@ -49,7 +49,7 @@ public function getEmptyPackageWeightInGrams(string $packageType): int return 0; } - return $this->configService->getGeneralConfig("$packageType/empty_package_weight") ?: 0; + return $this->config->getGeneralConfig("$packageType/empty_package_weight") ?: 0; } /** diff --git a/Setup/UpgradeData.php b/Setup/UpgradeData.php index 22975925..5868a72c 100644 --- a/Setup/UpgradeData.php +++ b/Setup/UpgradeData.php @@ -26,7 +26,7 @@ use Magento\Framework\Setup\ModuleContextInterface; use Magento\Framework\Setup\ModuleDataSetupInterface; use Magento\Framework\Setup\UpgradeDataInterface; -use MyParcelNL\Magento\Service\Config\ConfigService; +use MyParcelNL\Magento\Service\Config; use MyParcelNL\Magento\Setup\Migrations\ReplaceDpzRange; use MyParcelNL\Magento\Setup\Migrations\ReplaceFitInMailbox; use MyParcelNL\Magento\Setup\Migrations\ReplaceDisableCheckout; @@ -777,7 +777,7 @@ public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface continue; } - foreach (ConfigService::CARRIERS_XML_PATH_MAP as $carrierName => $carrierPath) { + foreach (Config::CARRIERS_XML_PATH_MAP as $carrierName => $carrierPath) { echo "\nMigrating $carrierName for scope $scope ($scopeId)"; /** * update the carrier specific date settings to a single setting for later diff --git a/Ui/Component/Listing/Column/TrackActions.php b/Ui/Component/Listing/Column/TrackActions.php index 874125c2..087cf874 100755 --- a/Ui/Component/Listing/Column/TrackActions.php +++ b/Ui/Component/Listing/Column/TrackActions.php @@ -8,13 +8,13 @@ use Magento\Framework\View\Element\UiComponent\ContextInterface; use Magento\Framework\View\Element\UiComponentFactory; use Magento\Ui\Component\Listing\Columns\Column; -use MyParcelNL\Magento\Service\Config\ConfigService; +use MyParcelNL\Magento\Service\Config; class TrackActions extends Column { public const NAME = 'track_actions'; - private ConfigService $configService; + private Config $configService; private UrlInterface $urlBuilder; /** @@ -34,7 +34,7 @@ public function __construct( { $this->urlBuilder = $urlBuilder; $objectManager = ObjectManager::getInstance(); - $this->configService = $objectManager->get(ConfigService::class); + $this->configService = $objectManager->get(Config::class); parent::__construct($context, $uiComponentFactory, $components, $data); } @@ -52,7 +52,7 @@ public function prepareDataSource(array $dataSource) return $dataSource; } - $orderManagementActivated = ConfigService::EXPORT_MODE_PPS === $this->configService->getExportMode(); + $orderManagementActivated = Config::EXPORT_MODE_PPS === $this->configService->getExportMode(); foreach ($dataSource['data']['items'] as &$item) { if (!array_key_exists(ShippingStatus::NAME, $item)) { @@ -65,7 +65,7 @@ public function prepareDataSource(array $dataSource) } if (!isset($item[ShippingStatus::NAME])) { - if (ConfigService::EXPORT_MODE_PPS === $this->configService->getExportMode()) { + if (Config::EXPORT_MODE_PPS === $this->configService->getExportMode()) { $item[$this->getData('name')]['action-create_concept'] = [ 'href' => $this->urlBuilder->getUrl( 'myparcel/order/CreateAndPrintMyParcelTrack', diff --git a/view/adminhtml/templates/new_shipment.phtml b/view/adminhtml/templates/new_shipment.phtml index c66c8041..3014ddba 100755 --- a/view/adminhtml/templates/new_shipment.phtml +++ b/view/adminhtml/templates/new_shipment.phtml @@ -148,8 +148,6 @@ foreach ($form->getCarrierSpecificAbstractConsignments() as $abstractConsignment foreach ($abstractConsignment->getAllowedShipmentOptions() as $shipmentOption) { if (AbstractConsignment::SHIPMENT_OPTION_INSURANCE === $shipmentOption || ! $block->consignmentHasShipmentOption($abstractConsignment, $shipmentOption) - || ($shipmentOption === AbstractConsignment::SHIPMENT_OPTION_RECEIPT_CODE - && AbstractConsignment::DELIVERY_TYPE_STANDARD !== $block->getDeliveryType()) ) { continue; } From 248f7d440d84853922c93e311e3b696bb12d961e Mon Sep 17 00:00:00 2001 From: Joeri van Veen Date: Thu, 19 Dec 2024 10:45:07 +0100 Subject: [PATCH 16/29] fix: prevent random error messages from halting shipment creation --- Controller/Adminhtml/Order/CreateAndPrintMyParcelTrack.php | 4 ---- 1 file changed, 4 deletions(-) diff --git a/Controller/Adminhtml/Order/CreateAndPrintMyParcelTrack.php b/Controller/Adminhtml/Order/CreateAndPrintMyParcelTrack.php index 17cf3875..819b47ce 100755 --- a/Controller/Adminhtml/Order/CreateAndPrintMyParcelTrack.php +++ b/Controller/Adminhtml/Order/CreateAndPrintMyParcelTrack.php @@ -124,10 +124,6 @@ private function massAction() if (! $this->orderCollection->hasShipment()) { $this->messageManager->addErrorMessage(__(MagentoCollection::ERROR_ORDER_HAS_NO_SHIPMENT)); - } - - if ($this->messageManager->getMessages()->getErrors()) { - $this->messageManager->getMessages(); return $this; } From 6be9c4515d1a4984e2307f8224fb56fdcf7e4a9c Mon Sep 17 00:00:00 2001 From: Joeri van Veen Date: Mon, 23 Dec 2024 09:15:18 +0100 Subject: [PATCH 17/29] feat: show error message when received from api --- Controller/Adminhtml/Order/CreateAndPrintMyParcelTrack.php | 1 + 1 file changed, 1 insertion(+) diff --git a/Controller/Adminhtml/Order/CreateAndPrintMyParcelTrack.php b/Controller/Adminhtml/Order/CreateAndPrintMyParcelTrack.php index 819b47ce..164970f0 100755 --- a/Controller/Adminhtml/Order/CreateAndPrintMyParcelTrack.php +++ b/Controller/Adminhtml/Order/CreateAndPrintMyParcelTrack.php @@ -72,6 +72,7 @@ public function execute() $this->massAction(); } catch (ApiException | MissingFieldException $e) { $this->_objectManager->get('Psr\Log\LoggerInterface')->critical($e); + $this->messageManager->addErrorMessage($e->getMessage()); } return $this->resultRedirectFactory->create()->setPath(self::PATH_URI_ORDER_INDEX); From 6f2db4afd923aa1b39c813eefd28de281d88e818 Mon Sep 17 00:00:00 2001 From: Joeri van Veen Date: Mon, 23 Dec 2024 10:57:01 +0100 Subject: [PATCH 18/29] fix: fix order of options for postnl, remove non existent option from ups --- etc/adminhtml/system.xml | 28 +++++----------------------- 1 file changed, 5 insertions(+), 23 deletions(-) diff --git a/etc/adminhtml/system.xml b/etc/adminhtml/system.xml index d32d646c..aeb1e2b8 100755 --- a/etc/adminhtml/system.xml +++ b/etc/adminhtml/system.xml @@ -198,7 +198,7 @@ 1 - + This will be added to the regular shipping price @@ -1206,16 +1206,16 @@ Magento\Config\Model\Config\Source\Yesno - + Magento\Config\Model\Config\Source\Yesno 1 - + This will be added to the regular shipping price @@ -1223,24 +1223,6 @@ 1 - - - Magento\Config\Model\Config\Source\Yesno - - 1 - - - - - This will be added to the regular shipping price - - 1 - 1 - - From 37dd95f492c4ad7c5eba3c408def15e7cf9a20a9 Mon Sep 17 00:00:00 2001 From: Joeri van Veen Date: Mon, 23 Dec 2024 11:01:38 +0100 Subject: [PATCH 19/29] feat: remove weight from large format option --- Model/Sales/Repository/PackageRepository.php | 1 - Model/Source/DefaultOptions.php | 17 ++--------------- Model/Source/LargeFormatOptions.php | 2 -- i18n/en_US.csv | 4 ++-- i18n/fr_FR.csv | 4 ++-- i18n/nl_NL.csv | 4 ++-- 6 files changed, 8 insertions(+), 24 deletions(-) diff --git a/Model/Sales/Repository/PackageRepository.php b/Model/Sales/Repository/PackageRepository.php index ee2e0a53..f9f7b65f 100755 --- a/Model/Sales/Repository/PackageRepository.php +++ b/Model/Sales/Repository/PackageRepository.php @@ -30,7 +30,6 @@ class PackageRepository extends Package public const DEFAULT_MAXIMUM_MAILBOX_WEIGHT = 2000; public const MAXIMUM_DIGITAL_STAMP_WEIGHT = 2000; public const MAXIMUM_PACKAGE_SMALL_WEIGHT = 2000; - public const DEFAULT_LARGE_FORMAT_WEIGHT = 23000; public const CARRIER_TYPE_CUSTOM = 'custom'; /** diff --git a/Model/Source/DefaultOptions.php b/Model/Source/DefaultOptions.php index 4366035f..f699ae80 100755 --- a/Model/Source/DefaultOptions.php +++ b/Model/Source/DefaultOptions.php @@ -127,26 +127,13 @@ public function getMaxCompanyName(?string $company): ?string public function hasDefaultLargeFormat(string $carrier, string $option): bool { $price = $this->order->getGrandTotal(); - $weight = $this->weightService->convertToGrams($this->order->getWeight()); $settings = $this->configService->getCarrierConfig($carrier, 'default_options'); $activeKey = "{$option}_active"; - if (isset($settings[$activeKey]) && - 'weight' === $settings[$activeKey] && - $weight >= PackageRepository::DEFAULT_LARGE_FORMAT_WEIGHT - ) { - return true; - } - - if (isset($settings[$activeKey]) && + return isset($settings[$activeKey]) && 'price' === $settings[$activeKey] && - $price >= $settings["{$option}_from_price"] - ) { - return true; - } - - return false; + $price >= $settings["{$option}_from_price"]; } /** diff --git a/Model/Source/LargeFormatOptions.php b/Model/Source/LargeFormatOptions.php index f8e889dd..deec92e7 100755 --- a/Model/Source/LargeFormatOptions.php +++ b/Model/Source/LargeFormatOptions.php @@ -28,7 +28,6 @@ public function toOptionArray() { return [ ['value' => 'price', 'label' => __('Price')], - ['value' => 'weight', 'label' => __('Weight')], ['value' => '0', 'label' => __('No')] ]; } @@ -42,7 +41,6 @@ public function toArray() { return [ 'price' => __('Price'), - 'weight' => __('Weight'), '0' => __('No') ]; } diff --git a/i18n/en_US.csv b/i18n/en_US.csv index cece314f..48b5a516 100755 --- a/i18n/en_US.csv +++ b/i18n/en_US.csv @@ -58,8 +58,8 @@ location_page, location manager package_small, Small package show_total_price, Show total price show_surcharge_price, Show surcharge -Automate 'Large format',Automate 'Larger than 100 x 70 x 58 cm or heavier than 23 kg' -Large package,Larger than 100 x 70 x 58 cm or heavier than 23 kg +Automate 'Large format',Automate 'Larger than 100 x 70 x 58 cm' +Large package,Larger than 100 x 70 x 58 cm delivery_title, Delivery Options standard_title, Standard Delivery diff --git a/i18n/fr_FR.csv b/i18n/fr_FR.csv index 08312e80..beb5ee50 100644 --- a/i18n/fr_FR.csv +++ b/i18n/fr_FR.csv @@ -209,8 +209,8 @@ Thursday,Jeudi Friday,Vendredi Saturday,Samedi Sunday,Dimanche -Automate 'Large format',Automatiser "Plus grand que 100 x 70 x 58 cm ou plus lourd que 23 kg" -Large package,Plus grand que 100 x 70 x 58 cm ou plus lourd que 23 kg +Automate 'Large format',Automatiser "Plus grand que 100 x 70 x 58 cm" +Large package,Plus grand que 100 x 70 x 58 cm {field} is required.,{field} est requis. Address not found.,Adresse introuvable. diff --git a/i18n/nl_NL.csv b/i18n/nl_NL.csv index 054d36fd..4e2e3ed1 100755 --- a/i18n/nl_NL.csv +++ b/i18n/nl_NL.csv @@ -93,8 +93,8 @@ Automate 'Collect package',Automatiseer 'Pakket laten ophalen' Automate 'Receipt code',Automatiseer 'Ontvangstcode' Automate 'Home address only',Automatiseer 'Alleen huisadres' Automate 'Return if no answer',Automatiseer 'Retour bij geen gehoor' -Automate 'Large format',Automatiseer 'Groter dan 100 x 70 x 58 cm of zwaarder dan 23 kg' -Large package,Groter dan 100 x 70 x 58 cm of zwaarder dan 23 kg +Automate 'Large format',Automatiseer 'Groter dan 100 x 70 x 58 cm' +Large package,Groter dan 100 x 70 x 58 cm Automate 'Age check 18+',Automatiseer 'Leeftijdscontrole 18+' Automate 'Insurance € 100',Automatiseer 'Verzekerd tot €100' Automate 'Insurance € 250',Automatiseer 'Verzekerd tot €250' From 4a462ec0d683b47360c9bea7aa7d4723b3d797c7 Mon Sep 17 00:00:00 2001 From: Joeri van Veen Date: Mon, 23 Dec 2024 12:36:24 +0100 Subject: [PATCH 20/29] fix: get quote from request to prevent infinite loop --- Model/Carrier/Carrier.php | 122 +++++++++++++++++++++++++------------- 1 file changed, 81 insertions(+), 41 deletions(-) diff --git a/Model/Carrier/Carrier.php b/Model/Carrier/Carrier.php index 2a98b2e4..afaa6083 100644 --- a/Model/Carrier/Carrier.php +++ b/Model/Carrier/Carrier.php @@ -19,6 +19,7 @@ namespace MyParcelNL\Magento\Model\Carrier; use Exception; +use http\Exception\InvalidArgumentException; use Magento\Checkout\Model\Session; use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\DataObject; @@ -35,6 +36,7 @@ use MyParcelNL\Magento\Model\Sales\Repository\PackageRepository; use MyParcelNL\Magento\Service\Config; use MyParcelNL\Magento\Service\DeliveryCosts; +use MyParcelNL\Sdk\src\Adapter\DeliveryOptions\AbstractDeliveryOptionsAdapter; use MyParcelNL\Sdk\src\Adapter\DeliveryOptions\DeliveryOptionsV3Adapter; use MyParcelNL\Sdk\src\Adapter\DeliveryOptions\ShipmentOptionsV3Adapter; use MyParcelNL\Sdk\src\Factory\DeliveryOptionsAdapterFactory; @@ -55,22 +57,22 @@ class Carrier extends AbstractCarrier implements CarrierInterface * @var PackageRepository */ private $package; - private Quote $quote; + + private AbstractDeliveryOptionsAdapter $deliveryOptions; /** * Carrier constructor. * * @param ScopeConfigInterface $scopeConfig - * @param ErrorFactory $rateErrorFactory - * @param LoggerInterface $logger - * @param Config $configService - * @param DeliveryCosts $deliveryCostsService - * @param ResultFactory $rateFactory - * @param MethodFactory $rateMethodFactory - * @param Session $session - * @param PackageRepository $package - * @param Freeshipping $freeShipping - * @param array $data + * @param ErrorFactory $rateErrorFactory + * @param LoggerInterface $logger + * @param Config $configService + * @param DeliveryCosts $deliveryCostsService + * @param ResultFactory $rateFactory + * @param MethodFactory $rateMethodFactory + * @param PackageRepository $package + * @param Freeshipping $freeShipping + * @param array $data * * @throws Exception */ @@ -82,7 +84,6 @@ public function __construct( DeliveryCosts $deliveryCostsService, ResultFactory $rateFactory, MethodFactory $rateMethodFactory, - Session $session, PackageRepository $package, Freeshipping $freeShipping, array $data = [] @@ -95,22 +96,14 @@ public function __construct( $data, ); - $this->_name = $configService->getConfigValue('carriers/myparcel_delivery/name') ?: self::CODE; + $this->_name = $configService->getConfigValue('carriers/myparcel_delivery/name') ?: self::CODE; $this->_title = $configService->getConfigValue('carriers/myparcel_delivery/title') ?: self::CODE; - $this->quote = $session->getQuote(); - - try { - $this->deliveryOptions = DeliveryOptionsAdapterFactory::create(json_decode($this->quote->getData(Config::FIELD_DELIVERY_OPTIONS), true)); - } catch (Throwable $e) { - $this->deliveryOptions = DeliveryOptionsAdapterFactory::create(DeliveryOptionsV3Adapter::DEFAULTS); - } - - $this->package = $package; - $this->rateResultFactory = $rateFactory; - $this->rateMethodFactory = $rateMethodFactory; - $this->_freeShipping = $freeShipping; - $this->configService = $configService; + $this->package = $package; + $this->rateResultFactory = $rateFactory; + $this->rateMethodFactory = $rateMethodFactory; + $this->_freeShipping = $freeShipping; + $this->configService = $configService; $this->deliveryCostsService = $deliveryCostsService; } @@ -124,31 +117,78 @@ public function collectRates(RateRequest $request) return false; } + $quote = $this->getQuoteFromRequest($request); + if (null === $quote) { + throw new InvalidArgumentException('No quote found in request'); + } + $result = $this->rateResultFactory->create(); $method = $this->rateMethodFactory->create(); $method->setCarrier($this->_code); $method->setCarrierTitle($this->_title); $method->setMethod($this->_name); - $method->setMethodTitle($this->getMethodTitle()); - $method->setPrice((string)$this->getMethodAmount()); + $method->setMethodTitle($this->getMethodTitle($quote)); + $method->setPrice((string)$this->getMethodAmount($quote)); $result->append($method); return $result; } - private function getMethodAmount(): float + private function getDeliveryOptionsFromQuote(Quote $quote): AbstractDeliveryOptionsAdapter + { + if (isset($this->deliveryOptions)) { + return $this->deliveryOptions; + } + + try { + $this->deliveryOptions = DeliveryOptionsAdapterFactory::create(json_decode($quote->getData(Config::FIELD_DELIVERY_OPTIONS), true, 512, JSON_THROW_ON_ERROR)); + } catch (Throwable $e) { + $this->deliveryOptions = DeliveryOptionsAdapterFactory::create(DeliveryOptionsV3Adapter::DEFAULTS); + } + + return $this->deliveryOptions; + } + + private function getQuoteFromRequest(RateRequest $request): ?Quote + { + /** + * Do not use checkoutSession->getQuote()!!! it will cause infinite loop for + * quotes with trigger_recollect = 1, see Quote::_afterLoad() + * https://magento.stackexchange.com/questions/340048/how-to-properly-get-current-quote-in-carrier-collect-rates-function + */ + $items = $request->getAllItems(); + if (empty($items)) { + return null; + } + + /** @var \Magento\Quote\Model\Quote\Item $firstItem */ + $firstItem = reset($items); + if (!$firstItem) { + return null; + } + + $quote = $firstItem->getQuote(); + if (!($quote instanceof Quote)) { + return null; + } + + return $quote; + } + + private function getMethodAmount(Quote $quote): float { - $configPath = Config::CARRIERS_XML_PATH_MAP[$this->deliveryOptions->getCarrier()] ?? ''; - $shipmentOptions = $this->deliveryOptions->getShipmentOptions() ?? new ShipmentOptionsV3Adapter([]); - $shipmentFees = [ - "{$this->deliveryOptions->getDeliveryType()}/fee" => true, + $deliveryOptions = $this->getDeliveryOptionsFromQuote($quote); + $configPath = Config::CARRIERS_XML_PATH_MAP[$deliveryOptions->getCarrier()] ?? ''; + $shipmentOptions = $deliveryOptions->getShipmentOptions() ?? new ShipmentOptionsV3Adapter([]); + $shipmentFees = [ + "{$deliveryOptions->getDeliveryType()}/fee" => true, //"{$this->deliveryOptions->getPackageType()}/fee" => true, - 'delivery/signature_fee' => $shipmentOptions->hasSignature(), - 'delivery/only_recipient_fee' => $shipmentOptions->hasOnlyRecipient(), + 'delivery/signature_fee' => $shipmentOptions->hasSignature(), + 'delivery/only_recipient_fee' => $shipmentOptions->hasOnlyRecipient(), ]; - $amount = $this->deliveryCostsService->getBasePrice($this->quote); + $amount = $this->deliveryCostsService->getBasePrice($quote); foreach ($shipmentFees as $key => $value) { if (!$value) { continue; @@ -164,9 +204,9 @@ private function getMethodAmount(): float return $amount; } - private function getMethodTitle(): string + private function getMethodTitle(Quote $quote): string { - $d = $this->deliveryOptions; + $d = $this->getDeliveryOptionsFromQuote($quote); $s = $d->getShipmentOptions() ?? new ShipmentOptionsV3Adapter([]); ob_start(); @@ -226,10 +266,10 @@ private function getShippingMethod($alias, string $settingPath) */ private function createTitle($settingPath) { - $title = $this->configService->getConfigValue(Config::XML_PATH_POSTNL_SETTINGS . $settingPath . 'title'); + $title = $this->configService->getConfigValue(Config::XML_PATH_POSTNL_SETTINGS . "{$settingPath}title"); if ($title === null) { - $title = __($settingPath . 'title'); + $title = __("{$settingPath}title"); } return $title; @@ -249,7 +289,7 @@ private function createPrice($alias, $settingPath) return 0; } - return 10 + $this->configService->getMethodPrice($settingPath . 'fee', $alias); + return 10 + $this->configService->getFloatConfig("{$settingPath}fee", $alias); } public function isTrackingAvailable(): bool From db2a09a63e0e12ffac4312dfcfd197de153dfad6 Mon Sep 17 00:00:00 2001 From: Joeri van Veen Date: Mon, 23 Dec 2024 13:58:35 +0100 Subject: [PATCH 21/29] wip --- Block/Sales/NewShipment.php | 4 +- Helper/Data.php | 1 + Helper/ShipmentOptions.php | 2 +- Model/Carrier/Carrier.php | 92 ++++++++++++------------ Model/Checkout/LayoutProcessorPlugin.php | 5 +- Model/Sales/TrackTraceHolder.php | 2 +- Service/Config.php | 15 +++- Service/DeliveryCosts.php | 16 +++-- 8 files changed, 75 insertions(+), 62 deletions(-) diff --git a/Block/Sales/NewShipment.php b/Block/Sales/NewShipment.php index 6b570cad..e41d87dd 100755 --- a/Block/Sales/NewShipment.php +++ b/Block/Sales/NewShipment.php @@ -21,10 +21,8 @@ use Magento\Framework\ObjectManagerInterface; use Magento\Framework\Registry; use Magento\Sales\Block\Adminhtml\Items\AbstractItems; -use MyParcelNL\Magento\Helper\Checkout; use MyParcelNL\Magento\Model\Sales\MagentoOrderCollection; use MyParcelNL\Magento\Model\Source\DefaultOptions; -use MyParcelNL\Magento\Model\Sales\TrackTraceHolder; use MyParcelNL\Magento\Service\Config; use MyParcelNL\Magento\Service\Weight; use MyParcelNL\Sdk\src\Model\Carrier\CarrierPostNL; @@ -145,7 +143,7 @@ public function getCountry() public function getDeliveryType(): int { try { - $deliveryTypeName = json_decode($this->order->getData(Checkout::FIELD_DELIVERY_OPTIONS), true)['deliveryType']; + $deliveryTypeName = json_decode($this->order->getData(Config::FIELD_DELIVERY_OPTIONS), true)['deliveryType']; $deliveryType = AbstractConsignment::DELIVERY_TYPES_NAMES_IDS_MAP[$deliveryTypeName]; } catch (Exception $e) { $deliveryType = AbstractConsignment::DEFAULT_DELIVERY_TYPE; diff --git a/Helper/Data.php b/Helper/Data.php index 6750c31f..56f2ee45 100755 --- a/Helper/Data.php +++ b/Helper/Data.php @@ -61,6 +61,7 @@ public function __construct( ModuleListInterface $moduleList, CheckApiKeyService $checkApiKeyService ) { + throw new Exception('Do not use Helper/Data.php'); parent::__construct($context); $this->moduleList = $moduleList; $this->checkApiKeyService = $checkApiKeyService; diff --git a/Helper/ShipmentOptions.php b/Helper/ShipmentOptions.php index 2fb151ad..bc8d51ab 100644 --- a/Helper/ShipmentOptions.php +++ b/Helper/ShipmentOptions.php @@ -123,7 +123,7 @@ public function hasCollect(): bool public function hasReceiptCode(): bool { - $deliveryOptions = $this->order->getData(Checkout::FIELD_DELIVERY_OPTIONS) ?? []; + $deliveryOptions = $this->order->getData(Config::FIELD_DELIVERY_OPTIONS) ?? []; $deliveryType = $deliveryOptions['deliveryType'] ?? AbstractConsignment::DEFAULT_DELIVERY_TYPE; if (AbstractConsignment::CC_NL !== $this->cc diff --git a/Model/Carrier/Carrier.php b/Model/Carrier/Carrier.php index afaa6083..ff0c22c9 100644 --- a/Model/Carrier/Carrier.php +++ b/Model/Carrier/Carrier.php @@ -96,8 +96,8 @@ public function __construct( $data, ); - $this->_name = $configService->getConfigValue('carriers/myparcel_delivery/name') ?: self::CODE; - $this->_title = $configService->getConfigValue('carriers/myparcel_delivery/title') ?: self::CODE; + $this->_name = $configService->getMagentoCarrierConfig('name') ?: self::CODE; + $this->_title = $configService->getMagentoCarrierConfig('title') ?: self::CODE; $this->package = $package; $this->rateResultFactory = $rateFactory; @@ -136,47 +136,6 @@ public function collectRates(RateRequest $request) return $result; } - private function getDeliveryOptionsFromQuote(Quote $quote): AbstractDeliveryOptionsAdapter - { - if (isset($this->deliveryOptions)) { - return $this->deliveryOptions; - } - - try { - $this->deliveryOptions = DeliveryOptionsAdapterFactory::create(json_decode($quote->getData(Config::FIELD_DELIVERY_OPTIONS), true, 512, JSON_THROW_ON_ERROR)); - } catch (Throwable $e) { - $this->deliveryOptions = DeliveryOptionsAdapterFactory::create(DeliveryOptionsV3Adapter::DEFAULTS); - } - - return $this->deliveryOptions; - } - - private function getQuoteFromRequest(RateRequest $request): ?Quote - { - /** - * Do not use checkoutSession->getQuote()!!! it will cause infinite loop for - * quotes with trigger_recollect = 1, see Quote::_afterLoad() - * https://magento.stackexchange.com/questions/340048/how-to-properly-get-current-quote-in-carrier-collect-rates-function - */ - $items = $request->getAllItems(); - if (empty($items)) { - return null; - } - - /** @var \Magento\Quote\Model\Quote\Item $firstItem */ - $firstItem = reset($items); - if (!$firstItem) { - return null; - } - - $quote = $firstItem->getQuote(); - if (!($quote instanceof Quote)) { - return null; - } - - return $quote; - } - private function getMethodAmount(Quote $quote): float { $deliveryOptions = $this->getDeliveryOptionsFromQuote($quote); @@ -236,6 +195,12 @@ public function getAllowedMethods(): array return [$this->_name]; } + public function isTrackingAvailable(): bool + { + // TODO: Implement isTrackingAvailable() method. + return true; + } + /** * @param $alias * @param string $settingPath @@ -292,9 +257,44 @@ private function createPrice($alias, $settingPath) return 10 + $this->configService->getFloatConfig("{$settingPath}fee", $alias); } - public function isTrackingAvailable(): bool + private function getQuoteFromRequest(RateRequest $request): ?Quote { - // TODO: Implement isTrackingAvailable() method. - return true; + /** + * Do not use checkoutSession->getQuote()!!! it will cause infinite loop for + * quotes with trigger_recollect = 1, see Quote::_afterLoad() + * https://magento.stackexchange.com/questions/340048/how-to-properly-get-current-quote-in-carrier-collect-rates-function + */ + $items = $request->getAllItems(); + if (empty($items)) { + return null; + } + + /** @var \Magento\Quote\Model\Quote\Item $firstItem */ + $firstItem = reset($items); + if (!$firstItem) { + return null; + } + + $quote = $firstItem->getQuote(); + if (!($quote instanceof Quote)) { + return null; + } + + return $quote; + } + + private function getDeliveryOptionsFromQuote(Quote $quote): AbstractDeliveryOptionsAdapter + { + if (isset($this->deliveryOptions)) { + return $this->deliveryOptions; + } + + try { + $this->deliveryOptions = DeliveryOptionsAdapterFactory::create(json_decode($quote->getData(Config::FIELD_DELIVERY_OPTIONS), true, 512, JSON_THROW_ON_ERROR)); + } catch (Throwable $e) { + $this->deliveryOptions = DeliveryOptionsAdapterFactory::create(DeliveryOptionsV3Adapter::DEFAULTS); + } + + return $this->deliveryOptions; } } diff --git a/Model/Checkout/LayoutProcessorPlugin.php b/Model/Checkout/LayoutProcessorPlugin.php index 34f28c04..f5079060 100755 --- a/Model/Checkout/LayoutProcessorPlugin.php +++ b/Model/Checkout/LayoutProcessorPlugin.php @@ -21,6 +21,7 @@ use Magento\Checkout\Block\Checkout\LayoutProcessor; use MyParcelNL\Magento\Helper\Checkout as CheckoutHelper; use MyParcelNL\Magento\Model\Quote\Checkout; +use MyParcelNL\Magento\Service\Config; class LayoutProcessorPlugin { @@ -49,7 +50,7 @@ public function afterProcess(LayoutProcessor $subject, array $jsLayout) { $jsLayout['components']['checkout']['children']['steps']['children']['shipping-step'] ['children']['shippingAddress']['children']['before-shipping-method-form']['children'], [ - CheckoutHelper::FIELD_DELIVERY_OPTIONS => [ + Config::FIELD_DELIVERY_OPTIONS => [ 'component' => 'Magento_Ui/js/form/element/abstract', 'config' => [ 'customScope' => 'shippingAddress', @@ -58,7 +59,7 @@ public function afterProcess(LayoutProcessor $subject, array $jsLayout) { 'options' => [], 'id' => 'myparcel-delivery-options', ], - 'dataScope' => 'shippingAddress.' . CheckoutHelper::FIELD_DELIVERY_OPTIONS, + 'dataScope' => 'shippingAddress.' . Config::FIELD_DELIVERY_OPTIONS, 'label' => 'Delivery Options', 'provider' => 'checkoutProvider', 'visible' => false, diff --git a/Model/Sales/TrackTraceHolder.php b/Model/Sales/TrackTraceHolder.php index acf80d43..0c65813d 100755 --- a/Model/Sales/TrackTraceHolder.php +++ b/Model/Sales/TrackTraceHolder.php @@ -404,7 +404,7 @@ private function convertDataForCdCountry(Track $magentoTrack) ->setDescription($product->getName()) ->setAmount($product->getQty()) ->setWeight($this->weight->convertToGrams($product->getWeight()) ?: 1) - ->setItemValue($this->deliveryCosts->getPriceInCents($product->getPrice())) + ->setItemValue(DeliveryCosts::getPriceInCents($product->getPrice())) ->setClassification( (int) $this->getAttributeValue( 'catalog_product_entity_int', diff --git a/Service/Config.php b/Service/Config.php index fe574ec4..e4b37533 100644 --- a/Service/Config.php +++ b/Service/Config.php @@ -20,6 +20,7 @@ class Config extends AbstractHelper { public const MODULE_NAME = 'MyParcelNL_Magento'; public const PLATFORM = 'myparcel'; + public const XML_PATH_MAGENTO_CARRIER = 'carriers/myparcel_delivery/'; public const XML_PATH_GENERAL = 'myparcelnl_magento_general/'; public const XML_PATH_POSTNL_SETTINGS = 'myparcelnl_magento_postnl_settings/'; public const XML_PATH_DHLFORYOU_SETTINGS = 'myparcelnl_magento_dhlforyou_settings/'; @@ -32,7 +33,6 @@ class Config extends AbstractHelper public const FIELD_MYPARCEL_CARRIER = 'myparcel_carrier'; public const FIELD_DELIVERY_OPTIONS = 'myparcel_delivery_options'; public const FIELD_TRACK_STATUS = 'track_status'; - public const DEFAULT_COUNTRY_CODE = 'NL'; public const MYPARCEL_TRACK_TITLE = 'MyParcel'; public const EXPORT_MODE_PPS = 'pps'; public const EXPORT_MODE_SHIPMENTS = 'shipments'; @@ -133,7 +133,13 @@ public function getIntegerConfig($path, $key): int */ public function getCarrierConfig(string $carrier, string $code = '', $storeId = null) { - return $this->getConfigValue(self::CARRIERS_XML_PATH_MAP[$carrier] . $code, $storeId); + $path = self::CARRIERS_XML_PATH_MAP[$carrier] ?? null; + + if (null === $path) { + return null; + } + + return $this->getConfigValue("$path$code", $storeId); } @@ -150,6 +156,11 @@ public function getGeneralConfig(string $code = '', int $storeId = null) return $this->getConfigValue(self::XML_PATH_GENERAL . $code, $storeId); } + public function getMagentoCarrierConfig(string $code = '', int $storeId = null) + { + return $this->getConfigValue(self::XML_PATH_MAGENTO_CARRIER . $code, $storeId); + } + /** * @return string|null */ diff --git a/Service/DeliveryCosts.php b/Service/DeliveryCosts.php index 7bb4893f..1725e5cc 100644 --- a/Service/DeliveryCosts.php +++ b/Service/DeliveryCosts.php @@ -9,11 +9,13 @@ class DeliveryCosts { - private Weight $weightService; + private Weight $weight; + private Config $config; - public function __construct(Weight $weightService) + public function __construct(Weight $weight , Config $config) { - $this->weightService = $weightService; + $this->weight = $weight; + $this->config = $config; } public function getBasePrice(Quote $quote): float @@ -21,11 +23,11 @@ public function getBasePrice(Quote $quote): float $carrier = $quote->getShippingAddress()->getShippingMethod(); // todo get actual (chosen) carrier $countryCode = $quote->getShippingAddress()->getCountryId(); $packageType = 'package'; // todo get actual (chosen) package type - $weight = $this->weightService->getEmptyPackageWeightInGrams($packageType) - + $this->weightService->getQuoteWeightInGrams($quote); + $weight = $this->weight->getEmptyPackageWeightInGrams($packageType) + + $this->weight->getQuoteWeightInGrams($quote); // todo implement the actual logic based on configured multi dimensional object - return 5; + return (float) $this->config->getMagentoCarrierConfig('shipping_cost'); } /** @@ -33,7 +35,7 @@ public function getBasePrice(Quote $quote): float * * @return int */ - public function getPriceInCents(float $price): int + public static function getPriceInCents(float $price): int { return (int)($price * 100); } From e6c9ebc8a147dcaad45f47d1ed71be98c9394d36 Mon Sep 17 00:00:00 2001 From: Joeri van Veen Date: Mon, 23 Dec 2024 14:57:28 +0100 Subject: [PATCH 22/29] refactor: put quote helper methods in a trait for more logical re-use --- Helper/ShipmentOptions.php | 4 +- Model/Carrier/Carrier.php | 78 +++++++------------------------- Model/Sales/TrackTraceHolder.php | 6 +-- Service/Dating.php | 3 +- Service/DeliveryCosts.php | 1 - Service/NeedsQuoteProps.php | 62 +++++++++++++++++++++++++ 6 files changed, 82 insertions(+), 72 deletions(-) create mode 100644 Service/NeedsQuoteProps.php diff --git a/Helper/ShipmentOptions.php b/Helper/ShipmentOptions.php index bc8d51ab..2d0a8bd9 100644 --- a/Helper/ShipmentOptions.php +++ b/Helper/ShipmentOptions.php @@ -65,7 +65,6 @@ class ShipmentOptions * @var string|null */ private ?string $cc; - private Dating $datingService; /** * @param DefaultOptions $defaultOptions @@ -84,7 +83,6 @@ public function __construct( { $this->defaultOptions = $defaultOptions; $this->configService = $objectManager->get(Config::class); - $this->datingService = $objectManager->get(Dating::class); $this->order = $order; $this->objectManager = $objectManager; $this->carrier = $carrier; @@ -339,7 +337,7 @@ public function getLabelDescription(): string ], [ $this->order->getIncrementId(), - $this->datingService->convertDeliveryDate($checkoutDate, 'd-m-Y') ?: '', + Dating::convertDeliveryDate($checkoutDate, 'd-m-Y') ?: '', $this->getProductInfo($productInfo, 'product_id'), $this->getProductInfo($productInfo, 'name'), $productInfo ? round($this->getProductInfo($productInfo, 'qty')) : null, diff --git a/Model/Carrier/Carrier.php b/Model/Carrier/Carrier.php index ff0c22c9..ef1e7035 100644 --- a/Model/Carrier/Carrier.php +++ b/Model/Carrier/Carrier.php @@ -20,7 +20,6 @@ use Exception; use http\Exception\InvalidArgumentException; -use Magento\Checkout\Model\Session; use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\DataObject; use Magento\Framework\Phrase; @@ -36,15 +35,14 @@ use MyParcelNL\Magento\Model\Sales\Repository\PackageRepository; use MyParcelNL\Magento\Service\Config; use MyParcelNL\Magento\Service\DeliveryCosts; -use MyParcelNL\Sdk\src\Adapter\DeliveryOptions\AbstractDeliveryOptionsAdapter; -use MyParcelNL\Sdk\src\Adapter\DeliveryOptions\DeliveryOptionsV3Adapter; +use MyParcelNL\Magento\Service\NeedsQuoteProps; use MyParcelNL\Sdk\src\Adapter\DeliveryOptions\ShipmentOptionsV3Adapter; -use MyParcelNL\Sdk\src\Factory\DeliveryOptionsAdapterFactory; use Psr\Log\LoggerInterface; -use Throwable; class Carrier extends AbstractCarrier implements CarrierInterface { + use NeedsQuoteProps; + public const CODE = 'myparcel'; // same as in /etc/config.xml protected $_code = self::CODE; // $_code is a mandatory property for a Magento carrier @@ -58,16 +56,14 @@ class Carrier extends AbstractCarrier implements CarrierInterface */ private $package; - private AbstractDeliveryOptionsAdapter $deliveryOptions; - /** * Carrier constructor. * * @param ScopeConfigInterface $scopeConfig * @param ErrorFactory $rateErrorFactory * @param LoggerInterface $logger - * @param Config $configService - * @param DeliveryCosts $deliveryCostsService + * @param Config $config + * @param DeliveryCosts $deliveryCosts * @param ResultFactory $rateFactory * @param MethodFactory $rateMethodFactory * @param PackageRepository $package @@ -80,8 +76,8 @@ public function __construct( ScopeConfigInterface $scopeConfig, ErrorFactory $rateErrorFactory, LoggerInterface $logger, - Config $configService, - DeliveryCosts $deliveryCostsService, + Config $config, + DeliveryCosts $deliveryCosts, ResultFactory $rateFactory, MethodFactory $rateMethodFactory, PackageRepository $package, @@ -96,15 +92,15 @@ public function __construct( $data, ); - $this->_name = $configService->getMagentoCarrierConfig('name') ?: self::CODE; - $this->_title = $configService->getMagentoCarrierConfig('title') ?: self::CODE; + $this->_name = $config->getMagentoCarrierConfig('name') ?: self::CODE; + $this->_title = $config->getMagentoCarrierConfig('title') ?: self::CODE; + $this->config = $config; $this->package = $package; $this->rateResultFactory = $rateFactory; $this->rateMethodFactory = $rateMethodFactory; $this->_freeShipping = $freeShipping; - $this->configService = $configService; - $this->deliveryCostsService = $deliveryCostsService; + $this->deliveryCosts = $deliveryCosts; } protected function _doShipmentRequest(DataObject $request) @@ -117,7 +113,8 @@ public function collectRates(RateRequest $request) return false; } - $quote = $this->getQuoteFromRequest($request); + $quote = $this->getQuoteFromRateRequest($request); + if (null === $quote) { throw new InvalidArgumentException('No quote found in request'); } @@ -147,12 +144,12 @@ private function getMethodAmount(Quote $quote): float 'delivery/signature_fee' => $shipmentOptions->hasSignature(), 'delivery/only_recipient_fee' => $shipmentOptions->hasOnlyRecipient(), ]; - $amount = $this->deliveryCostsService->getBasePrice($quote); + $amount = $this->deliveryCosts->getBasePrice($quote); foreach ($shipmentFees as $key => $value) { if (!$value) { continue; } - $amount += (float)$this->configService->getConfigValue("$configPath$key"); + $amount += (float)$this->config->getConfigValue("$configPath$key"); } return $amount; @@ -231,7 +228,7 @@ private function getShippingMethod($alias, string $settingPath) */ private function createTitle($settingPath) { - $title = $this->configService->getConfigValue(Config::XML_PATH_POSTNL_SETTINGS . "{$settingPath}title"); + $title = $this->config->getConfigValue(Config::XML_PATH_POSTNL_SETTINGS . "{$settingPath}title"); if ($title === null) { $title = __("{$settingPath}title"); @@ -254,47 +251,6 @@ private function createPrice($alias, $settingPath) return 0; } - return 10 + $this->configService->getFloatConfig("{$settingPath}fee", $alias); - } - - private function getQuoteFromRequest(RateRequest $request): ?Quote - { - /** - * Do not use checkoutSession->getQuote()!!! it will cause infinite loop for - * quotes with trigger_recollect = 1, see Quote::_afterLoad() - * https://magento.stackexchange.com/questions/340048/how-to-properly-get-current-quote-in-carrier-collect-rates-function - */ - $items = $request->getAllItems(); - if (empty($items)) { - return null; - } - - /** @var \Magento\Quote\Model\Quote\Item $firstItem */ - $firstItem = reset($items); - if (!$firstItem) { - return null; - } - - $quote = $firstItem->getQuote(); - if (!($quote instanceof Quote)) { - return null; - } - - return $quote; - } - - private function getDeliveryOptionsFromQuote(Quote $quote): AbstractDeliveryOptionsAdapter - { - if (isset($this->deliveryOptions)) { - return $this->deliveryOptions; - } - - try { - $this->deliveryOptions = DeliveryOptionsAdapterFactory::create(json_decode($quote->getData(Config::FIELD_DELIVERY_OPTIONS), true, 512, JSON_THROW_ON_ERROR)); - } catch (Throwable $e) { - $this->deliveryOptions = DeliveryOptionsAdapterFactory::create(DeliveryOptionsV3Adapter::DEFAULTS); - } - - return $this->deliveryOptions; + return 10 + $this->config->getFloatConfig("{$settingPath}fee", $alias); } } diff --git a/Model/Sales/TrackTraceHolder.php b/Model/Sales/TrackTraceHolder.php index 0c65813d..c2315f4b 100755 --- a/Model/Sales/TrackTraceHolder.php +++ b/Model/Sales/TrackTraceHolder.php @@ -85,8 +85,6 @@ class TrackTraceHolder */ private $shipmentOptionsHelper; private Weight $weight; - private DeliveryCosts $deliveryCosts; - private Dating $dating; /** * TrackTraceHolder constructor. @@ -102,8 +100,6 @@ public function __construct( $this->objectManager = $objectManager; $this->configService = $objectManager->get(Config::class); $this->weight = $objectManager->get(Weight::class); - $this->dating = $objectManager->get(Dating::class); - $this->deliveryCosts = $objectManager->get(DeliveryCosts::class); $this->messageManager = $this->objectManager->create('Magento\Framework\Message\ManagerInterface'); $this->defaultOptions = new DefaultOptions($order); } @@ -189,7 +185,7 @@ public function convertDataFromMagentoToApi(Track $magentoTrack, array $options) $deliveryDate = ( AbstractConsignment::PACKAGE_TYPE_PACKAGE_SMALL === $packageType && 'NL' !== $address->getCountryId() - ) ? null : $this->dating->convertDeliveryDate($deliveryOptionsAdapter->getDate()); + ) ? null : Dating::convertDeliveryDate($deliveryOptionsAdapter->getDate()); $dropOffPoint = AccountSettings::getInstance()->getDropOffPoint( CarrierFactory::createFromName($deliveryOptionsAdapter->getCarrier()) ); diff --git a/Service/Dating.php b/Service/Dating.php index e5f5cbc1..e59570ca 100644 --- a/Service/Dating.php +++ b/Service/Dating.php @@ -16,7 +16,7 @@ class Dating * @param string $format * @return string|null */ - public function convertDeliveryDate(?string $date, string $format = 'Y-m-d H:i:s'): ?string + public static function convertDeliveryDate(?string $date, string $format = 'Y-m-d H:i:s'): ?string { if (null === $date) { return null; @@ -36,5 +36,4 @@ public function convertDeliveryDate(?string $date, string $format = 'Y-m-d H:i:s return date($format, $deliveryDate); } - } diff --git a/Service/DeliveryCosts.php b/Service/DeliveryCosts.php index 1725e5cc..933d3877 100644 --- a/Service/DeliveryCosts.php +++ b/Service/DeliveryCosts.php @@ -5,7 +5,6 @@ namespace MyParcelNL\Magento\Service; use Magento\Quote\Model\Quote; -use MyParcelNL\Magento\Service\Weight; class DeliveryCosts { diff --git a/Service/NeedsQuoteProps.php b/Service/NeedsQuoteProps.php new file mode 100644 index 00000000..fdc9cffa --- /dev/null +++ b/Service/NeedsQuoteProps.php @@ -0,0 +1,62 @@ +getQuote()!!! it will cause infinite loop for + * quotes with trigger_recollect = 1, see Quote::_afterLoad() + * https://magento.stackexchange.com/questions/340048/how-to-properly-get-current-quote-in-carrier-collect-rates-function + */ + $items = $request->getAllItems(); + if (empty($items)) { + return null; + } + + /** @var \Magento\Quote\Model\Quote\Item $firstItem */ + $firstItem = reset($items); + if (!$firstItem) { + return null; + } + + $quote = $firstItem->getQuote(); + if (!($quote instanceof Quote)) { + return null; + } + + return $quote; + } + + protected function getDeliveryOptionsFromQuote(Quote $quote): AbstractDeliveryOptionsAdapter + { + if (isset($this->deliveryOptions)) { + return $this->deliveryOptions; + } + + try { + $this->deliveryOptions = DeliveryOptionsAdapterFactory::create(json_decode($quote->getData(Config::FIELD_DELIVERY_OPTIONS), true, 512, JSON_THROW_ON_ERROR)); + } catch (\Throwable $e) { + Logger::log('warning', 'Failed to retrieve delivery options from quote ' . $quote->getId()); + $this->deliveryOptions = new DeliveryOptionsV3Adapter(); + } + + return $this->deliveryOptions; + } +} From e62b3e177df76d12b45c9dcb0bb4e0fa54162f64 Mon Sep 17 00:00:00 2001 From: Joeri van Veen Date: Mon, 23 Dec 2024 15:15:22 +0100 Subject: [PATCH 23/29] fix: remove some useless logging --- Model/Carrier/Carrier.php | 11 +---------- Model/Sales/Repository/PackageRepository.php | 6 ------ Service/NeedsQuoteProps.php | 14 ++++++++++---- 3 files changed, 11 insertions(+), 20 deletions(-) diff --git a/Model/Carrier/Carrier.php b/Model/Carrier/Carrier.php index ef1e7035..79baaea4 100644 --- a/Model/Carrier/Carrier.php +++ b/Model/Carrier/Carrier.php @@ -48,13 +48,7 @@ class Carrier extends AbstractCarrier implements CarrierInterface protected $_code = self::CODE; // $_code is a mandatory property for a Magento carrier protected $_name; protected $_title; - protected $_freeShipping; - - - /** - * @var PackageRepository - */ - private $package; + protected Freeshipping $_freeShipping; /** * Carrier constructor. @@ -66,7 +60,6 @@ class Carrier extends AbstractCarrier implements CarrierInterface * @param DeliveryCosts $deliveryCosts * @param ResultFactory $rateFactory * @param MethodFactory $rateMethodFactory - * @param PackageRepository $package * @param Freeshipping $freeShipping * @param array $data * @@ -80,7 +73,6 @@ public function __construct( DeliveryCosts $deliveryCosts, ResultFactory $rateFactory, MethodFactory $rateMethodFactory, - PackageRepository $package, Freeshipping $freeShipping, array $data = [] ) @@ -96,7 +88,6 @@ public function __construct( $this->_title = $config->getMagentoCarrierConfig('title') ?: self::CODE; $this->config = $config; - $this->package = $package; $this->rateResultFactory = $rateFactory; $this->rateMethodFactory = $rateMethodFactory; $this->_freeShipping = $freeShipping; diff --git a/Model/Sales/Repository/PackageRepository.php b/Model/Sales/Repository/PackageRepository.php index f9f7b65f..200de250 100755 --- a/Model/Sales/Repository/PackageRepository.php +++ b/Model/Sales/Repository/PackageRepository.php @@ -170,8 +170,6 @@ public function setMailboxSettings(string $carrierPath = self::XML_PATH_POSTNL_S $settings = $this->getConfigValue("{$carrierPath}mailbox"); if (null === $settings || ! array_key_exists('active', $settings)) { - $this->_logger->critical("Can't set settings with path: {$carrierPath}mailbox"); - return $this; } @@ -266,8 +264,6 @@ public function setDigitalStampSettings(string $carrierPath = self::XML_PATH_POS $settings = $this->getConfigValue("{$carrierPath}digital_stamp"); if (null === $settings || ! array_key_exists('active', $settings)) { - $this->_logger->critical("Can't set settings with path: {$carrierPath}digital_stamp"); - return $this; } @@ -292,8 +288,6 @@ public function setPackageSmallSettings(string $carrierPath = self::XML_PATH_POS $settings = $this->getConfigValue("{$carrierPath}package_small"); if (null === $settings || ! array_key_exists('active', $settings)) { - $this->_logger->critical("Can't set settings with path: {$carrierPath}package_small"); - return $this; } diff --git a/Service/NeedsQuoteProps.php b/Service/NeedsQuoteProps.php index fdc9cffa..75866dc4 100644 --- a/Service/NeedsQuoteProps.php +++ b/Service/NeedsQuoteProps.php @@ -50,10 +50,16 @@ protected function getDeliveryOptionsFromQuote(Quote $quote): AbstractDeliveryOp return $this->deliveryOptions; } - try { - $this->deliveryOptions = DeliveryOptionsAdapterFactory::create(json_decode($quote->getData(Config::FIELD_DELIVERY_OPTIONS), true, 512, JSON_THROW_ON_ERROR)); - } catch (\Throwable $e) { - Logger::log('warning', 'Failed to retrieve delivery options from quote ' . $quote->getId()); + $do = $quote->getData(Config::FIELD_DELIVERY_OPTIONS); + + if (is_string($do)) { + try { + $this->deliveryOptions = DeliveryOptionsAdapterFactory::create(json_decode($do, true, 512, JSON_THROW_ON_ERROR)); + } catch (\Throwable $e) { + Logger::log('warning', 'Failed to retrieve delivery options from quote ' . $quote->getId(), (array)$do); + $this->deliveryOptions = new DeliveryOptionsV3Adapter(); + } + } else { $this->deliveryOptions = new DeliveryOptionsV3Adapter(); } From a1a162e6ad831497493e1fe2b1d4a3d0d0f8c6db Mon Sep 17 00:00:00 2001 From: Joeri van Veen Date: Tue, 24 Dec 2024 14:41:14 +0100 Subject: [PATCH 24/29] wip --- Model/Carrier/Carrier.php | 23 ++- Model/Checkout/ShippingMethods.php | 6 +- Model/Quote/Checkout.php | 190 +++++++++--------- Model/Sales/Repository/PackageRepository.php | 4 +- Service/NeedsQuoteProps.php | 70 +++++++ i18n/nl_NL.csv | 2 +- view/frontend/web/js/model/checkout.js | 6 +- view/frontend/web/js/view/delivery-options.js | 3 +- view/frontend/web/js/view/shipping.js | 1 - 9 files changed, 192 insertions(+), 113 deletions(-) diff --git a/Model/Carrier/Carrier.php b/Model/Carrier/Carrier.php index 79baaea4..5e49c7b9 100644 --- a/Model/Carrier/Carrier.php +++ b/Model/Carrier/Carrier.php @@ -132,10 +132,18 @@ private function getMethodAmount(Quote $quote): float $shipmentFees = [ "{$deliveryOptions->getDeliveryType()}/fee" => true, //"{$this->deliveryOptions->getPackageType()}/fee" => true, - 'delivery/signature_fee' => $shipmentOptions->hasSignature(), 'delivery/only_recipient_fee' => $shipmentOptions->hasOnlyRecipient(), + 'delivery/signature_fee' => $shipmentOptions->hasSignature(), + 'delivery/receipt_code_fee' => $shipmentOptions->hasReceiptCode(), ]; - $amount = $this->deliveryCosts->getBasePrice($quote); + + if ($this->isFreeShippingAvailable($quote)) { + $amount = 0.0; + } else { + $amount = $this->deliveryCosts->getBasePrice($quote); + } + file_put_contents('/Applications/MAMP/htdocs/magento246/var/log/joeri.log', 'DOEDOE: ' . var_export($amount, true) . "\n", FILE_APPEND); + foreach ($shipmentFees as $key => $value) { if (!$value) { continue; @@ -144,11 +152,6 @@ private function getMethodAmount(Quote $quote): float } return $amount; - //$this->configService->getMethodPrice(ConfigService::XML_PATH_POSTNL_SETTINGS . 'fee', $alias); - $freeShippingIsAvailable = false; // todo find out if this order has free shipping // $this->_freeShipping->getConfigData('active') - // todo: get actual price based on chosen and possible options for this quote / cart - $amount = $freeShippingIsAvailable ? 0.00 : 10.00; - return $amount; } private function getMethodTitle(Quote $quote): string @@ -157,15 +160,15 @@ private function getMethodTitle(Quote $quote): string $s = $d->getShipmentOptions() ?? new ShipmentOptionsV3Adapter([]); ob_start(); - echo __("{$d->getDeliveryType()}_title"), ' '; + echo __("{$d->getDeliveryType()}_title"), ', '; foreach ($s->toArray() as $key => $value) { if ($value) { - echo __("{$key}_title"), ' '; + echo __("{$key}_title"), ', '; } } - return ob_get_clean(); + return substr(trim(ob_get_clean()), 0, -1); } public function proccessAdditionalValidation(DataObject $request) diff --git a/Model/Checkout/ShippingMethods.php b/Model/Checkout/ShippingMethods.php index f07ecdf5..13446ea5 100755 --- a/Model/Checkout/ShippingMethods.php +++ b/Model/Checkout/ShippingMethods.php @@ -15,7 +15,7 @@ class ShippingMethods implements ShippingMethodsInterface /** * @var \Magento\Checkout\Model\Session */ - private $session; + private Session $session; /** * ShippingMethods constructor. @@ -40,11 +40,11 @@ public function getFromDeliveryOptions($deliveryOptions): array } try { - $shipping = new DeliveryOptionsToShippingMethods($deliveryOptions[0]); + //$shipping = new DeliveryOptionsToShippingMethods($deliveryOptions[0]); $response = [ 'root' => [ - 'element_id' => $shipping->getShippingMethod(), + 'element_id' => 'myparcel-miep',//TODO get the user inputted title here //$shipping->getShippingMethod(), ], ]; } catch (Exception $e) { diff --git a/Model/Quote/Checkout.php b/Model/Quote/Checkout.php index cb309fe8..779e7484 100644 --- a/Model/Quote/Checkout.php +++ b/Model/Quote/Checkout.php @@ -2,25 +2,27 @@ namespace MyParcelNL\Magento\Model\Quote; -use Magento\Checkout\Model\Cart; -use Magento\Checkout\Model\Session; use Magento\Eav\Model\Entity\Collection\AbstractCollection; use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Quote\Model\Quote; use Magento\Store\Model\StoreManagerInterface; use MyParcelNL\Magento\Facade\Logger; use MyParcelNL\Magento\Model\Sales\Repository\PackageRepository; use MyParcelNL\Magento\Model\Source\PriceDeliveryOptionsView; use MyParcelNL\Magento\Service\Config; use MyParcelNL\Magento\Service\DeliveryCosts; +use MyParcelNL\Magento\Service\NeedsQuoteProps; use MyParcelNL\Sdk\src\Factory\ConsignmentFactory; use MyParcelNL\Sdk\src\Model\Consignment\AbstractConsignment; use Throwable; class Checkout { - private Config $configService; - private DeliveryCosts $deliveryCostsService; + use NeedsQuoteProps; + + private Config $config; + private DeliveryCosts $deliveryCosts; /** * @var \MyParcelNL\Magento\Model\Sales\Repository\PackageRepository @@ -35,38 +37,33 @@ class Checkout /** * @var StoreManagerInterface */ - private $currency; + private StoreManagerInterface $currency; /** - * @var mixed + * @var string */ - private $country; - private Session $session; + private string $country; /** * Checkout constructor. * - * @param Session $session - * @param Cart $cart - * @param Config $configService - * @param PackageRepository $package + * @param Config $config + * @param DeliveryCosts $deliveryCosts + * @param PackageRepository $package * @param StoreManagerInterface $currency */ public function __construct( - Session $session, - Cart $cart, - Config $configService, - DeliveryCosts $deliveryCostsService, - PackageRepository $package, + Config $config, + DeliveryCosts $deliveryCosts, + PackageRepository $package, // TODO DEPRECATED StoreManagerInterface $currency ) { - $this->session = $session; - $this->configService = $configService; - $this->deliveryCostsService = $deliveryCostsService; - $this->quote = $cart->getQuote(); - $this->package = $package; - $this->currency = $currency; + $this->config = $config; + $this->deliveryCosts = $deliveryCosts; + $this->package = $package; + $this->currency = $currency; + $this->quote = $this->getQuoteFromCurrentSession(); } /** @@ -75,24 +72,33 @@ public function __construct( * @param array $forAddress associative array holding the latest address from the client * * @return array - * @throws NoSuchEntityException + * @throws NoSuchEntityException|LocalizedException */ public function getDeliveryOptions(array $forAddress = []): array { $this->hideDeliveryOptionsForProduct(); + /** + * Use 0.0 for baseprice when free shipping is available. + * Note that when free shipping is sorted before the MyParcel method, price will be 0 anyway. + * Sort it after the MyParcel method to be able to correctly apply surcharges from the checkout. + */ + if ($this->isFreeShippingAvailable($this->quote)) { + $basePrice = 0.0; + }else { + $basePrice = $this->deliveryCosts->getBasePrice($this->quote); + } + $packageType = $this->getPackageType(); if (isset($forAddress['countryId'])) { $this->country = $forAddress['countryId']; } - $packageType = $this->getPackageType(); - $data = [ /* the 'method' string here is actually the carrier_code of the method */ - 'methods' => explode(',', $this->configService->getGeneralConfig('shipping_methods/methods') ?? ''), + 'methods' => explode(',', $this->config->getGeneralConfig('shipping_methods/methods') ?? ''), 'config' => array_merge( $this->getGeneralData(), - $this->getDeliveryData($packageType), + $this->getDeliveryData($packageType, $basePrice), ['packageType' => $packageType] ), 'strings' => $this->getDeliveryOptionsStrings(), @@ -101,7 +107,7 @@ public function getDeliveryOptions(array $forAddress = []): array return [ 'root' => [ - 'version' => $this->configService->getVersion(), + 'version' => $this->config->getVersion(), 'data' => $data, ], ]; @@ -120,12 +126,12 @@ private function getGeneralData() 'platform' => Config::PLATFORM, 'carriers' => $this->getActiveCarriers(), 'currency' => $this->currency->getStore()->getCurrentCurrency()->getCode(), - 'allowShowDeliveryDate' => $this->configService->getBoolConfig(Config::XML_PATH_GENERAL, 'date_settings/allow_show_delivery_date'), - 'deliveryDaysWindow' => $this->configService->getIntegerConfig(Config::XML_PATH_GENERAL, 'date_settings/deliverydays_window'), + 'allowShowDeliveryDate' => $this->config->getBoolConfig(Config::XML_PATH_GENERAL, 'date_settings/allow_show_delivery_date'), + 'deliveryDaysWindow' => $this->config->getIntegerConfig(Config::XML_PATH_GENERAL, 'date_settings/deliverydays_window'), 'dropOffDelay' => $this->getDropOffDelay(Config::XML_PATH_GENERAL, 'date_settings/dropoff_delay'), - 'pickupLocationsDefaultView' => $this->configService->getConfigValue(Config::XML_PATH_GENERAL . 'shipping_methods/pickup_locations_view'), - 'showPriceSurcharge' => $this->configService->getConfigValue(Config::XML_PATH_GENERAL . 'shipping_methods/delivery_options_prices') === PriceDeliveryOptionsView::SURCHARGE, - 'basePrice' => $this->deliveryCostsService->getBasePrice($this->quote), + 'pickupLocationsDefaultView' => $this->config->getConfigValue(Config::XML_PATH_GENERAL . 'shipping_methods/pickup_locations_view'), + 'showPriceSurcharge' => $this->config->getConfigValue(Config::XML_PATH_GENERAL . 'shipping_methods/delivery_options_prices') === PriceDeliveryOptionsView::SURCHARGE, + 'basePrice' => $this->deliveryCosts->getBasePrice($this->quote), ]; } @@ -159,15 +165,16 @@ private function getPackageType(): string /** * Get delivery data * - * @param string|null $packageType + * @param string $packageType + * @param float $basePrice * @return array */ - private function getDeliveryData(?string $packageType = null): array + private function getDeliveryData(string $packageType, float $basePrice): array { $myParcelConfig = []; $activeCarriers = $this->getActiveCarriers(); $carrierPaths = Config::CARRIERS_XML_PATH_MAP; - $showTotalPrice = $this->configService->getConfigValue(Config::XML_PATH_GENERAL . 'shipping_methods/delivery_options_prices') === PriceDeliveryOptionsView::TOTAL; + $showTotalPrice = $this->config->getConfigValue(Config::XML_PATH_GENERAL . 'shipping_methods/delivery_options_prices') === PriceDeliveryOptionsView::TOTAL; foreach ($activeCarriers as $carrier) { $carrierPath = $carrierPaths[$carrier]; @@ -198,50 +205,49 @@ private function getDeliveryData(?string $packageType = null): array if ($canHaveMailbox) { $cc = $this->country ?? $this->quote->getShippingAddress()->getCountryId() ?? AbstractConsignment::CC_NL; if (AbstractConsignment::CC_NL === $cc) { - $mailboxFee = $this->configService->getFloatConfig($carrierPath, 'mailbox/fee'); + $mailboxFee = $this->config->getFloatConfig($carrierPath, 'mailbox/fee'); } else { - $mailboxFee = $this->configService->getFloatConfig($carrierPath, 'mailbox/international_fee'); + $mailboxFee = $this->config->getFloatConfig($carrierPath, 'mailbox/international_fee'); } } - $basePrice = $this->deliveryCostsService->getBasePrice($this->quote); $addBasePrice = ($showTotalPrice) ? $basePrice : 0; - $mondayFee = $canHaveMonday ? $this->configService->getFloatConfig($carrierPath, 'delivery/monday_fee') + $addBasePrice : 0; - $morningFee = $canHaveMorning ? $this->configService->getFloatConfig($carrierPath, 'morning/fee') + $addBasePrice : 0; - $eveningFee = $canHaveEvening ? $this->configService->getFloatConfig($carrierPath, 'evening/fee') + $addBasePrice : 0; - $sameDayFee = $canHaveSameDay ? (int) $this->configService->getFloatConfig($carrierPath, 'delivery/same_day_delivery_fee') + $addBasePrice : 0; - $signatureFee = $canHaveSignature ? $this->configService->getFloatConfig($carrierPath, 'delivery/signature_fee') : 0; - $collectFee = $canHaveCollect ? $this->configService->getFloatConfig($carrierPath, 'delivery/collect_fee', false) : 0; - $receiptCodeFee = $canHaveReceiptCode ? $this->configService->getFloatConfig($carrierPath, 'delivery/receipt_code_fee') : 0; - $onlyRecipientFee = $canHaveOnlyRecipient ? $this->configService->getFloatConfig($carrierPath, 'delivery/only_recipient_fee') : 0; + $mondayFee = $canHaveMonday ? $this->config->getFloatConfig($carrierPath, 'delivery/monday_fee') + $addBasePrice : 0; + $morningFee = $canHaveMorning ? $this->config->getFloatConfig($carrierPath, 'morning/fee') + $addBasePrice : 0; + $eveningFee = $canHaveEvening ? $this->config->getFloatConfig($carrierPath, 'evening/fee') + $addBasePrice : 0; + $sameDayFee = $canHaveSameDay ? (int) $this->config->getFloatConfig($carrierPath, 'delivery/same_day_delivery_fee') + $addBasePrice : 0; + $signatureFee = $canHaveSignature ? $this->config->getFloatConfig($carrierPath, 'delivery/signature_fee') : 0; + $collectFee = $canHaveCollect ? $this->config->getFloatConfig($carrierPath, 'delivery/collect_fee', false) : 0; + $receiptCodeFee = $canHaveReceiptCode ? $this->config->getFloatConfig($carrierPath, 'delivery/receipt_code_fee') : 0; + $onlyRecipientFee = $canHaveOnlyRecipient ? $this->config->getFloatConfig($carrierPath, 'delivery/only_recipient_fee') : 0; $isAgeCheckActive = $canHaveAgeCheck && $this->isAgeCheckActive($carrierPath); - $allowPickup = $this->configService->getBoolConfig($carrierPath, 'pickup/active'); - $allowStandardDelivery = $this->configService->getBoolConfig($carrierPath, 'delivery/active'); - $allowMorningDelivery = ! $isAgeCheckActive && $canHaveMorning && $this->configService->getBoolConfig($carrierPath, 'morning/active'); - $allowEveningDelivery = ! $isAgeCheckActive && $canHaveEvening && $this->configService->getBoolConfig($carrierPath, 'evening/active'); - $allowExpressDelivery = $canHaveExpress && $this->configService->getBoolConfig($carrierPath, 'express/active'); + $allowPickup = $this->config->getBoolConfig($carrierPath, 'pickup/active'); + $allowStandardDelivery = $this->config->getBoolConfig($carrierPath, 'delivery/active'); + $allowMorningDelivery = ! $isAgeCheckActive && $canHaveMorning && $this->config->getBoolConfig($carrierPath, 'morning/active'); + $allowEveningDelivery = ! $isAgeCheckActive && $canHaveEvening && $this->config->getBoolConfig($carrierPath, 'evening/active'); + $allowExpressDelivery = $canHaveExpress && $this->config->getBoolConfig($carrierPath, 'express/active'); $allowDeliveryOptions = ! $this->package->deliveryOptionsDisabled && ($allowPickup || $allowStandardDelivery || $allowMorningDelivery || $allowEveningDelivery); if ($allowDeliveryOptions && $packageType === AbstractConsignment::PACKAGE_TYPE_MAILBOX_NAME) { $this->package->setMailboxSettings($carrierPath); - $allowDeliveryOptions = $this->configService->getBoolConfig($carrierPath, 'mailbox/active') + $allowDeliveryOptions = $this->config->getBoolConfig($carrierPath, 'mailbox/active') && $this->package->getMaxMailboxWeight() >= $this->package->getWeight(); } $myParcelConfig['carrierSettings'][$carrier] = [ 'allowDeliveryOptions' => $allowDeliveryOptions, 'allowStandardDelivery' => $allowStandardDelivery, - 'allowSignature' => $canHaveSignature && $this->configService->getBoolConfig($carrierPath, 'delivery/signature_active'), - 'allowCollect' => $canHaveCollect && $this->configService->getBoolConfig($carrierPath, 'delivery/collect_active'), - 'allowReceiptCode' => $canHaveReceiptCode && $this->configService->getBoolConfig($carrierPath, 'delivery/receipt_code_active'), - 'allowOnlyRecipient' => $canHaveOnlyRecipient && $this->configService->getBoolConfig($carrierPath, 'delivery/only_recipient_active'), + 'allowSignature' => $canHaveSignature && $this->config->getBoolConfig($carrierPath, 'delivery/signature_active'), + 'allowCollect' => $canHaveCollect && $this->config->getBoolConfig($carrierPath, 'delivery/collect_active'), + 'allowReceiptCode' => $canHaveReceiptCode && $this->config->getBoolConfig($carrierPath, 'delivery/receipt_code_active'), + 'allowOnlyRecipient' => $canHaveOnlyRecipient && $this->config->getBoolConfig($carrierPath, 'delivery/only_recipient_active'), 'allowMorningDelivery' => $allowMorningDelivery, 'allowEveningDelivery' => $allowEveningDelivery, 'allowPickupLocations' => $canHavePickup && $this->isPickupAllowed($carrierPath), - 'allowMondayDelivery' => $canHaveMonday && $this->configService->getBoolConfig($carrierPath, 'delivery/monday_active'), - 'allowSameDayDelivery' => $canHaveSameDay && $this->configService->getBoolConfig($carrierPath, 'delivery/same_day_delivery_active'), + 'allowMondayDelivery' => $canHaveMonday && $this->config->getBoolConfig($carrierPath, 'delivery/monday_active'), + 'allowSameDayDelivery' => $canHaveSameDay && $this->config->getBoolConfig($carrierPath, 'delivery/same_day_delivery_active'), 'allowExpressDelivery' => $allowExpressDelivery, 'dropOffDays' => $this->getDropOffDays($carrierPath), @@ -255,17 +261,17 @@ private function getDeliveryData(?string $packageType = null): array 'priceMorningDelivery' => $morningFee, 'priceEveningDelivery' => $eveningFee, 'priceSameDayDelivery' => $sameDayFee, - 'priceExpressdelivery' => $allowExpressDelivery ? $this->configService->getFloatConfig($carrierPath, 'express/fee') : 0, + 'priceExpressdelivery' => $allowExpressDelivery ? $this->config->getFloatConfig($carrierPath, 'express/fee') : 0, 'priceSameDayDeliveryAndOnlyRecipient' => $sameDayFee + $onlyRecipientFee, 'priceMorningSignature' => ($morningFee + $signatureFee), 'priceEveningSignature' => ($eveningFee + $signatureFee), 'priceSignatureAndOnlyRecipient' => ($basePrice + $signatureFee + $onlyRecipientFee), - 'pricePickup' => $canHavePickup ? $this->configService->getFloatConfig($carrierPath, 'pickup/fee') + $basePrice : 0, + 'pricePickup' => $canHavePickup ? $this->config->getFloatConfig($carrierPath, 'pickup/fee') + $basePrice : 0, 'pricePackageTypeMailbox' => $mailboxFee, - 'pricePackageTypeDigitalStamp' => $canHaveDigitalStamp ? $this->configService->getFloatConfig($carrierPath, 'digital_stamp/fee') : 0, - 'pricePackageTypePackageSmall' => $canHavePackageSmall ? $this->configService->getFloatConfig($carrierPath, 'package_small/fee') : 0, + 'pricePackageTypeDigitalStamp' => $canHaveDigitalStamp ? $this->config->getFloatConfig($carrierPath, 'digital_stamp/fee') : 0, + 'pricePackageTypePackageSmall' => $canHavePackageSmall ? $this->config->getFloatConfig($carrierPath, 'package_small/fee') : 0, ]; } @@ -281,8 +287,8 @@ public function getActiveCarriers(): array { $carriers = []; foreach (Config::CARRIERS_XML_PATH_MAP as $carrier => $path) { - if ($this->configService->getBoolConfig($path, 'delivery/active') || - $this->configService->getBoolConfig($path, 'pickup/active') + if ($this->config->getBoolConfig($path, 'delivery/active') || + $this->config->getBoolConfig($path, 'pickup/active') ) { $carriers[] = $carrier; } @@ -295,13 +301,13 @@ private function getDropOffDays(string $carrierPath): array { $dropOffDays = []; for ($weekday = 0; $weekday < 7; $weekday++) { - $cutoffTimeSameDay = $this->configService->getTimeConfig($carrierPath, "drop_off_days/cutoff_time_same_day_$weekday"); + $cutoffTimeSameDay = $this->config->getTimeConfig($carrierPath, "drop_off_days/cutoff_time_same_day_$weekday"); $sameDayTimeEntry = $cutoffTimeSameDay ? ['cutoffTimeSameDay' => $cutoffTimeSameDay] : []; - if ($this->configService->getBoolConfig($carrierPath, "drop_off_days/day_{$weekday}_active")) { + if ($this->config->getBoolConfig($carrierPath, "drop_off_days/day_{$weekday}_active")) { $dropOffDays[] = (object) array_merge( [ 'weekday' => $weekday, - 'cutoffTime' => $this->configService->getTimeConfig($carrierPath, "drop_off_days/cutoff_time_$weekday"), + 'cutoffTime' => $this->config->getTimeConfig($carrierPath, "drop_off_days/cutoff_time_$weekday"), ], $sameDayTimeEntry ); @@ -319,22 +325,22 @@ private function getDropOffDays(string $carrierPath): array private function getDeliveryOptionsStrings(): array { return [ - 'deliveryTitle' => $this->configService->getGeneralConfig('delivery_titles/delivery_title') ?: __('delivery_title'), - 'deliveryStandardTitle' => $this->configService->getGeneralConfig('delivery_titles/standard_delivery_title') ?: __('standard_delivery'), - 'deliveryMorningTitle' => $this->configService->getGeneralConfig('delivery_titles/morning_title') ?: __('morning_title'), - 'deliveryEveningTitle' => $this->configService->getGeneralConfig('delivery_titles/evening_title') ?: __('evening_title'), - 'deliveryPickupTitle' => $this->configService->getGeneralConfig('delivery_titles/pickup_title') ?: __('pickup_title'), - 'pickupTitle' => $this->configService->getGeneralConfig('delivery_titles/pickup_title') ?: __('pickup_title'), - 'deliverySameDayTitle' => $this->configService->getGeneralConfig('delivery_titles/same_day_title') ?: __('same_day_title'), - 'hideSenderTitle' => $this->configService->getGeneralConfig('delivery_titles/hide_sender_title') ?: __('hide_sender_title'), - 'list' => $this->configService->getGeneralConfig('delivery_titles/pickup_list_button_title') ?: __('list_title'), - 'map' => $this->configService->getGeneralConfig('delivery_titles/pickup_map_button_title') ?: __('map_title'), - 'packageTypeMailbox' => $this->configService->getGeneralConfig('delivery_titles/mailbox_title') ?: __('mailbox_title'), - 'packageTypeDigitalStamp' => $this->configService->getGeneralConfig('delivery_titles/digital_stamp_title') ?: __('digital_stamp_title'), - 'packageTypePackageSmall' => $this->configService->getGeneralConfig('delivery_titles/package_small_title') ?: __('packet_title'), - 'signatureTitle' => $this->configService->getGeneralConfig('delivery_titles/signature_title') ?: __('signature_title'), - 'onlyRecipientTitle' => $this->configService->getGeneralConfig('delivery_titles/only_recipient_title') ?: __('only_recipient_title'), - 'saturdayDeliveryTitle' => $this->configService->getGeneralConfig('delivery_titles/saturday_title') ?: __('saturday_delivery_title'), + 'deliveryTitle' => $this->config->getGeneralConfig('delivery_titles/delivery_title') ?: __('delivery_title'), + 'deliveryStandardTitle' => $this->config->getGeneralConfig('delivery_titles/standard_delivery_title') ?: __('standard_delivery'), + 'deliveryMorningTitle' => $this->config->getGeneralConfig('delivery_titles/morning_title') ?: __('morning_title'), + 'deliveryEveningTitle' => $this->config->getGeneralConfig('delivery_titles/evening_title') ?: __('evening_title'), + 'deliveryPickupTitle' => $this->config->getGeneralConfig('delivery_titles/pickup_title') ?: __('pickup_title'), + 'pickupTitle' => $this->config->getGeneralConfig('delivery_titles/pickup_title') ?: __('pickup_title'), + 'deliverySameDayTitle' => $this->config->getGeneralConfig('delivery_titles/same_day_title') ?: __('same_day_title'), + 'hideSenderTitle' => $this->config->getGeneralConfig('delivery_titles/hide_sender_title') ?: __('hide_sender_title'), + 'list' => $this->config->getGeneralConfig('delivery_titles/pickup_list_button_title') ?: __('list_title'), + 'map' => $this->config->getGeneralConfig('delivery_titles/pickup_map_button_title') ?: __('map_title'), + 'packageTypeMailbox' => $this->config->getGeneralConfig('delivery_titles/mailbox_title') ?: __('mailbox_title'), + 'packageTypeDigitalStamp' => $this->config->getGeneralConfig('delivery_titles/digital_stamp_title') ?: __('digital_stamp_title'), + 'packageTypePackageSmall' => $this->config->getGeneralConfig('delivery_titles/package_small_title') ?: __('packet_title'), + 'signatureTitle' => $this->config->getGeneralConfig('delivery_titles/signature_title') ?: __('signature_title'), + 'onlyRecipientTitle' => $this->config->getGeneralConfig('delivery_titles/only_recipient_title') ?: __('only_recipient_title'), + 'saturdayDeliveryTitle' => $this->config->getGeneralConfig('delivery_titles/saturday_title') ?: __('saturday_delivery_title'), 'wrongPostalCodeCity' => __('Postcode/city combination unknown'), 'addressNotFound' => __('Address details are not entered'), @@ -393,17 +399,17 @@ public function checkPackageType(string $carrier, ?string $country = null): stri if ($canHaveMailbox) { if (AbstractConsignment::CC_NL === $country) { - $this->package->setMailboxActive($this->configService->getBoolConfig($carrierPath, 'mailbox/active')); + $this->package->setMailboxActive($this->config->getBoolConfig($carrierPath, 'mailbox/active')); } else { - $this->package->setMailboxActive($this->configService->getBoolConfig($carrierPath, 'mailbox/international_active')); + $this->package->setMailboxActive($this->config->getBoolConfig($carrierPath, 'mailbox/international_active')); } } else { $this->package->setMailboxActive(false); } $this->package->setCurrentCountry($country); - $this->package->setDigitalStampActive($canHaveDigitalStamp && $this->configService->getBoolConfig($carrierPath, 'digital_stamp/active')); - $this->package->setPackageSmallActive($canHavePackageSmall && $this->configService->getBoolConfig($carrierPath, 'package_small/active')); + $this->package->setDigitalStampActive($canHaveDigitalStamp && $this->config->getBoolConfig($carrierPath, 'digital_stamp/active')); + $this->package->setPackageSmallActive($canHavePackageSmall && $this->config->getBoolConfig($carrierPath, 'package_small/active')); return $this->package->selectPackageType($products, $carrierPath); } @@ -430,7 +436,7 @@ public function getDropOffDelay(string $carrierPath, string $key): int { $products = $this->quote->getAllItems(); $productDelay = (int) $this->package->getProductDropOffDelay($products); - $configDelay = $this->configService->getIntegerConfig($carrierPath, $key); + $configDelay = $this->config->getIntegerConfig($carrierPath, $key); return max($productDelay, $configDelay); } @@ -454,8 +460,8 @@ public function hideDeliveryOptionsForProduct() private function isPickupAllowed(string $carrier): bool { $isMailboxPackage = AbstractConsignment::PACKAGE_TYPE_MAILBOX_NAME === $this->getPackageType(); - $pickupEnabled = $this->configService->getBoolConfig($carrier, 'pickup/active'); - $showPickupForMailbox = $this->configService->getBoolConfig($carrier, 'mailbox/pickup_mailbox'); + $pickupEnabled = $this->config->getBoolConfig($carrier, 'pickup/active'); + $showPickupForMailbox = $this->config->getBoolConfig($carrier, 'mailbox/pickup_mailbox'); $showPickup = ! $isMailboxPackage || $showPickupForMailbox; return ! $this->package->deliveryOptionsDisabled && $pickupEnabled && $showPickup; diff --git a/Model/Sales/Repository/PackageRepository.php b/Model/Sales/Repository/PackageRepository.php index 200de250..ce6c4ae0 100755 --- a/Model/Sales/Repository/PackageRepository.php +++ b/Model/Sales/Repository/PackageRepository.php @@ -20,6 +20,7 @@ use MyParcelNL\Magento\Model\Sales\Package; use MyParcelNL\Magento\Model\Settings\AccountSettings; +use MyParcelNL\Magento\Service\Weight; use MyParcelNL\Sdk\src\Model\Carrier\AbstractCarrier; use MyParcelNL\Sdk\src\Model\Carrier\CarrierFactory; use MyParcelNL\Sdk\src\Model\Carrier\CarrierPostNL; @@ -149,7 +150,8 @@ static function ($carrierOptions) { */ public function fitInDigitalStamp(): bool { - $orderWeight = $this->convertToGrams($this->getWeight()); + // TODO temporary weight calculation since PackageRepository will be removed alltogether + $orderWeight = (new Weight($this))->convertToGrams($this->getWeight()); $maximumDigitalStampWeight = $this->getMaxDigitalStampWeight(); return $this->getCurrentCountry() === AbstractConsignment::CC_NL diff --git a/Service/NeedsQuoteProps.php b/Service/NeedsQuoteProps.php index 75866dc4..ad681e5e 100644 --- a/Service/NeedsQuoteProps.php +++ b/Service/NeedsQuoteProps.php @@ -4,12 +4,17 @@ namespace MyParcelNL\Magento\Service; +use Magento\Checkout\Model\Session; +use Magento\Framework\App\ObjectManager; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Exception\StateException; use Magento\Quote\Model\Quote; use Magento\Quote\Model\Quote\Address\RateRequest; use MyParcelNL\Magento\Facade\Logger; use MyParcelNL\Sdk\src\Adapter\DeliveryOptions\AbstractDeliveryOptionsAdapter; use MyParcelNL\Sdk\src\Adapter\DeliveryOptions\DeliveryOptionsV3Adapter; use MyParcelNL\Sdk\src\Factory\DeliveryOptionsAdapterFactory; +use Magento\Quote\Api\ShippingMethodManagementInterface; /** * Use this trait when you need to get the quote independently of session and have easy access to its properties @@ -44,6 +49,18 @@ protected function getQuoteFromRateRequest(RateRequest $request): ?Quote return $quote; } + public function getQuoteFromCurrentSession(): ?Quote + { + $checkoutSession = ObjectManager::getInstance()->get(Session::class); + $quote = $checkoutSession->getQuote(); + + if (!($quote instanceof Quote)) { + return null; + } + + return $quote; + } + protected function getDeliveryOptionsFromQuote(Quote $quote): AbstractDeliveryOptionsAdapter { if (isset($this->deliveryOptions)) { @@ -65,4 +82,57 @@ protected function getDeliveryOptionsFromQuote(Quote $quote): AbstractDeliveryOp return $this->deliveryOptions; } + + /** + * Get shipping method array [method_title => amount] from quote + * + * @param Quote $quote + * @return array Associative array by method title holding the amount for that method + * @throws LocalizedException + */ + public function getShippingMethodsFromQuote(Quote $quote): array + { + $quoteId = $quote->getId(); + file_put_contents('/Applications/MAMP/htdocs/magento246/var/log/joeri.log', 'quoteId: ' . var_export($quoteId, true) . "\n", FILE_APPEND); + + try { + $shippingMethodManagement = ObjectManager::getInstance()->get(ShippingMethodManagementInterface::class); + $getShippingMethods = $shippingMethodManagement->getList($quoteId); + + $methods = []; + foreach ($getShippingMethods as $method) { + $methods[$method->getMethodTitle()] = $method->getAmount(); + } + } catch (StateException $stateException) { + throw new LocalizedException(__($stateException->getMessage())); + } catch (\Exception $exception) { + throw new LocalizedException(__($exception->getMessage())); + } + + return $methods; + } + + /** + * If free shipping is available for this quote, will return true. + * + * @param Quote $quote + * @return bool + */ + public function isFreeShippingAvailable(Quote $quote): bool + { + try { + $shippingMethods = $this->getShippingMethodsFromQuote($quote); +file_put_contents('/Applications/MAMP/htdocs/magento246/var/log/joeri.log', 'shippingMethods: ' . var_export($shippingMethods, true) . "\n", FILE_APPEND); + // loop through the methods to see if one is free (price = 0) + foreach ($shippingMethods as $methodName => $methodAmount) { + if (0.0 === $methodAmount) { + return true; + } + } + } catch (LocalizedException $e) { + Logger::critical($e->getMessage()); + } + + return false; + } } diff --git a/i18n/nl_NL.csv b/i18n/nl_NL.csv index 4e2e3ed1..5b4d21c8 100755 --- a/i18n/nl_NL.csv +++ b/i18n/nl_NL.csv @@ -310,7 +310,7 @@ Already exported, Reeds geëxporteerd delivery_title, Bezorgopties standard_title, Standaard bezorging -morning_title, Maandag levering +morning_title, Ochtend levering evening_title, Avond levering pickup_title, Afhaal locaties same_day_title, Zelfde dag levering diff --git a/view/frontend/web/js/model/checkout.js b/view/frontend/web/js/model/checkout.js index 0921fc2f..e560849c 100644 --- a/view/frontend/web/js/model/checkout.js +++ b/view/frontend/web/js/model/checkout.js @@ -76,6 +76,7 @@ function( * Initialize by requesting the MyParcel settings configuration from Magento. */ initialize: function() { + console.error(' Joeri debugging '); Model.compute = ko.computed(function() { var configuration = Model.configuration(); var rates = Model.rates(); @@ -152,9 +153,7 @@ function( */ findOriginalRateByCarrierCode: function(carrierCode) { return Model.rates().find(function(rate) { - if (-1 === rate.method_code.indexOf('myparcel')) { - return rate.carrier_code === carrierCode; - } + return rate.carrier_code === carrierCode; }); }, @@ -290,7 +289,6 @@ function( isAllowed = true; } }); - Model.hasDeliveryOptions(isAllowed); Model.hideShippingMethods(); } diff --git a/view/frontend/web/js/view/delivery-options.js b/view/frontend/web/js/view/delivery-options.js index 82366ffd..0db8751a 100644 --- a/view/frontend/web/js/view/delivery-options.js +++ b/view/frontend/web/js/view/delivery-options.js @@ -211,6 +211,7 @@ define( * @param {string} identifier - Name of the event. */ triggerEvent: function(identifier) { + //document.body.dispatchEvent(new CustomEvent(identifier, { bubbles: true, cancelable: false })); var event = document.createEvent('HTMLEvents'); event.initEvent(identifier, true, false); document.querySelector('body').dispatchEvent(event); @@ -302,7 +303,7 @@ define( */ var cacheObject = JSON.parse(localStorage.getItem('mage-cache-storage')); if (cacheObject.hasOwnProperty('checkout-data')) { - cacheObject['checkout-data']['selectedShippingRate'] = response[0].element_id; + cacheObject['checkout-data']['selectedShippingRate'] = 'TITLE YO JOERI';// response[0].element_id; localStorage.setItem('mage-cache-storage', JSON.stringify(cacheObject)); } /** diff --git a/view/frontend/web/js/view/shipping.js b/view/frontend/web/js/view/shipping.js index bde6fe5b..7d61ca50 100644 --- a/view/frontend/web/js/view/shipping.js +++ b/view/frontend/web/js/view/shipping.js @@ -34,7 +34,6 @@ define([ */ checkout.hasDeliveryOptions.subscribe(function(enabled) { checkout.hideShippingMethods(); - if (enabled) { deliveryOptions.initialize(); } else { From efcaf962356d54a2d0b97e47f9acc82c13d40091 Mon Sep 17 00:00:00 2001 From: Joeri van Veen Date: Tue, 31 Dec 2024 15:13:52 +0100 Subject: [PATCH 25/29] fix(checkout): save and retrieve chosen shipping method --- Model/Carrier/Carrier.php | 49 +++++++++++---- Model/Checkout/ShippingMethods.php | 59 ++++++------------- Model/Quote/Checkout.php | 4 +- Service/NeedsQuoteProps.php | 22 +++---- view/frontend/web/js/view/delivery-options.js | 17 +----- 5 files changed, 69 insertions(+), 82 deletions(-) diff --git a/Model/Carrier/Carrier.php b/Model/Carrier/Carrier.php index 5e49c7b9..a2435c9b 100644 --- a/Model/Carrier/Carrier.php +++ b/Model/Carrier/Carrier.php @@ -37,6 +37,7 @@ use MyParcelNL\Magento\Service\DeliveryCosts; use MyParcelNL\Magento\Service\NeedsQuoteProps; use MyParcelNL\Sdk\src\Adapter\DeliveryOptions\ShipmentOptionsV3Adapter; +use MyParcelNL\Sdk\src\Model\Carrier\CarrierFactory; use Psr\Log\LoggerInterface; class Carrier extends AbstractCarrier implements CarrierInterface @@ -124,6 +125,23 @@ public function collectRates(RateRequest $request) return $result; } + public function getMethodAsArray(Quote $quote): array + { + //todo joeri inc / ex tax and, where is this specific structure / array coming from? Not method->toArray unfortunately + return [ + 'amount' => $this->getMethodAmount($quote), + 'available' => true, + 'base_amount' => $this->getMethodAmount($quote), + 'carrier_code' => $this->_code, + 'carrier_title' => $this->_title, + 'error_message' => '', + 'method_code' => $this->_name, + 'method_title' => $this->getMethodTitle($quote), + 'price_excl_tax' => $this->getMethodAmount($quote), + 'price_incl_tax' => $this->getMethodAmount($quote), + ]; + } + private function getMethodAmount(Quote $quote): float { $deliveryOptions = $this->getDeliveryOptionsFromQuote($quote); @@ -131,7 +149,7 @@ private function getMethodAmount(Quote $quote): float $shipmentOptions = $deliveryOptions->getShipmentOptions() ?? new ShipmentOptionsV3Adapter([]); $shipmentFees = [ "{$deliveryOptions->getDeliveryType()}/fee" => true, - //"{$this->deliveryOptions->getPackageType()}/fee" => true, + //"{$deliveryOptions->getPackageType()}/fee" => true, 'delivery/only_recipient_fee' => $shipmentOptions->hasOnlyRecipient(), 'delivery/signature_fee' => $shipmentOptions->hasSignature(), 'delivery/receipt_code_fee' => $shipmentOptions->hasReceiptCode(), @@ -142,7 +160,6 @@ private function getMethodAmount(Quote $quote): float } else { $amount = $this->deliveryCosts->getBasePrice($quote); } - file_put_contents('/Applications/MAMP/htdocs/magento246/var/log/joeri.log', 'DOEDOE: ' . var_export($amount, true) . "\n", FILE_APPEND); foreach ($shipmentFees as $key => $value) { if (!$value) { @@ -150,28 +167,37 @@ private function getMethodAmount(Quote $quote): float } $amount += (float)$this->config->getConfigValue("$configPath$key"); } + file_put_contents('/Applications/MAMP/htdocs/magento246/var/log/joeri.log', 'AMOUNT YO: ' . var_export($amount, true) . "\n", FILE_APPEND); return $amount; } private function getMethodTitle(Quote $quote): string { - $d = $this->getDeliveryOptionsFromQuote($quote); - $s = $d->getShipmentOptions() ?? new ShipmentOptionsV3Adapter([]); + // todo joeri netjes maken + $deliveryOptions = $this->getDeliveryOptionsFromQuote($quote); + $shipmentOptions = $deliveryOptions->getShipmentOptions() ?? new ShipmentOptionsV3Adapter([]); + $carrierName = $deliveryOptions->getCarrier(); + + if (null === $carrierName) { + return $this->_title; + } + + $carrierHuman = CarrierFactory::createFromName($carrierName)->getHuman(); ob_start(); - echo __("{$d->getDeliveryType()}_title"), ', '; + echo $carrierHuman, ' ', __("{$deliveryOptions->getDeliveryType()}_title"), ', '; - foreach ($s->toArray() as $key => $value) { + foreach ($shipmentOptions->toArray() as $key => $value) { if ($value) { echo __("{$key}_title"), ', '; } } - return substr(trim(ob_get_clean()), 0, -1); + return substr(trim(ob_get_clean()), 0, -1); // remove trailing comma } - public function proccessAdditionalValidation(DataObject $request) + public function processAdditionalValidation(DataObject $request): bool { return true; } @@ -200,6 +226,7 @@ public function isTrackingAvailable(): bool */ private function getShippingMethod($alias, string $settingPath) { + throw new \Exception('JOERI! We shouldn’t use this method anymore'); $title = $this->createTitle($settingPath); $price = $this->createPrice($alias, $settingPath); @@ -241,10 +268,8 @@ private function createTitle($settingPath) */ private function createPrice($alias, $settingPath) { - if ($this->_freeShipping->getConfigData('active')) { - return 0; - } + file_put_contents('/Applications/MAMP/htdocs/magento246/var/log/joeri.log', "CreatePrice is called on Carrier\n", FILE_APPEND); - return 10 + $this->config->getFloatConfig("{$settingPath}fee", $alias); + return 10.21; } } diff --git a/Model/Checkout/ShippingMethods.php b/Model/Checkout/ShippingMethods.php index 13446ea5..9428a6c3 100755 --- a/Model/Checkout/ShippingMethods.php +++ b/Model/Checkout/ShippingMethods.php @@ -4,7 +4,11 @@ use Exception; use Magento\Checkout\Model\Session; +use Magento\Framework\App\ObjectManager; +use Magento\Quote\Model\QuoteRepository\SaveHandler; use MyParcelNL\Magento\Api\ShippingMethodsInterface; +use MyParcelNL\Magento\Model\Carrier\Carrier; +use MyParcelNL\Magento\Service\Config; use MyParcelNL\Sdk\src\Factory\DeliveryOptionsAdapterFactory; /** @@ -12,19 +16,19 @@ */ class ShippingMethods implements ShippingMethodsInterface { - /** - * @var \Magento\Checkout\Model\Session - */ private Session $session; + private Carrier $carrier; /** * ShippingMethods constructor. * - * @param \Magento\Checkout\Model\Session $session + * @param Session $session + * @param Carrier $carrier */ - public function __construct(Session $session) + public function __construct(Session $session, Carrier $carrier) { $this->session = $session; + $this->carrier = $carrier; } /** @@ -35,47 +39,18 @@ public function __construct(Session $session) */ public function getFromDeliveryOptions($deliveryOptions): array { - if (! $deliveryOptions[0]) { + if (! isset($deliveryOptions[0]) || ! $deliveryOptions[0]) { return []; } - try { - //$shipping = new DeliveryOptionsToShippingMethods($deliveryOptions[0]); - - $response = [ - 'root' => [ - 'element_id' => 'myparcel-miep',//TODO get the user inputted title here //$shipping->getShippingMethod(), - ], - ]; - } catch (Exception $e) { - $response = [ - 'code' => '422', - 'message' => $e->getMessage(), - ]; - } - - $response[] = $this->persistDeliveryOptions($deliveryOptions[0]); - - return $response; - } - - /** - * @param array $deliveryOptions - * - * @return array - * @throws \Magento\Framework\Exception\LocalizedException - * @throws \Magento\Framework\Exception\NoSuchEntityException - */ - public function persistDeliveryOptions(array $deliveryOptions): array - { + // save the delivery options in the quote + $adapted = DeliveryOptionsAdapterFactory::create($deliveryOptions[0]); $quote = $this->session->getQuote(); - $adapted = DeliveryOptionsAdapterFactory::create($deliveryOptions); - $quote->addData(['myparcel_delivery_options' => json_encode($adapted->toArray())]); - $quote->save(); + $quote->addData([Config::FIELD_DELIVERY_OPTIONS => json_encode($adapted->toArray(), JSON_THROW_ON_ERROR)]); + $saver = ObjectManager::getInstance()->get(SaveHandler::class); + $saver->save($quote); - return [ - 'delivery_options' => $deliveryOptions, - 'message' => "Delivery options persisted in quote {$quote->getId()}", - ]; + // return a fresh method from the carrier + return ['root' => $this->carrier->getMethodAsArray($quote)]; } } diff --git a/Model/Quote/Checkout.php b/Model/Quote/Checkout.php index 779e7484..e61648ac 100644 --- a/Model/Quote/Checkout.php +++ b/Model/Quote/Checkout.php @@ -78,9 +78,7 @@ public function getDeliveryOptions(array $forAddress = []): array { $this->hideDeliveryOptionsForProduct(); /** - * Use 0.0 for baseprice when free shipping is available. - * Note that when free shipping is sorted before the MyParcel method, price will be 0 anyway. - * Sort it after the MyParcel method to be able to correctly apply surcharges from the checkout. + * Use 0.0 for base price when free shipping is available. */ if ($this->isFreeShippingAvailable($this->quote)) { $basePrice = 0.0; diff --git a/Service/NeedsQuoteProps.php b/Service/NeedsQuoteProps.php index ad681e5e..badfe7fb 100644 --- a/Service/NeedsQuoteProps.php +++ b/Service/NeedsQuoteProps.php @@ -8,6 +8,7 @@ use Magento\Framework\App\ObjectManager; use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Exception\StateException; +use Magento\Quote\Api\Data\ShippingMethodInterface; use Magento\Quote\Model\Quote; use Magento\Quote\Model\Quote\Address\RateRequest; use MyParcelNL\Magento\Facade\Logger; @@ -45,6 +46,7 @@ protected function getQuoteFromRateRequest(RateRequest $request): ?Quote if (!($quote instanceof Quote)) { return null; } + file_put_contents('/Applications/MAMP/htdocs/magento246/var/log/joeri.log', 'free shipping rate request: ' . var_export($this->isFreeShippingAvailable($quote), true) . "\n", FILE_APPEND); return $quote; } @@ -57,6 +59,7 @@ public function getQuoteFromCurrentSession(): ?Quote if (!($quote instanceof Quote)) { return null; } + file_put_contents('/Applications/MAMP/htdocs/magento246/var/log/joeri.log', 'free shipping current session: ' . var_export($this->isFreeShippingAvailable($quote), true) . "\n", FILE_APPEND); return $quote; } @@ -73,7 +76,7 @@ protected function getDeliveryOptionsFromQuote(Quote $quote): AbstractDeliveryOp try { $this->deliveryOptions = DeliveryOptionsAdapterFactory::create(json_decode($do, true, 512, JSON_THROW_ON_ERROR)); } catch (\Throwable $e) { - Logger::log('warning', 'Failed to retrieve delivery options from quote ' . $quote->getId(), (array)$do); + Logger::log('warning', "Failed to retrieve delivery options from quote {$quote->getId()}", (array)$do); $this->deliveryOptions = new DeliveryOptionsV3Adapter(); } } else { @@ -84,10 +87,8 @@ protected function getDeliveryOptionsFromQuote(Quote $quote): AbstractDeliveryOp } /** - * Get shipping method array [method_title => amount] from quote - * * @param Quote $quote - * @return array Associative array by method title holding the amount for that method + * @return array indexed array of ShippingMethodInterface objects * @throws LocalizedException */ public function getShippingMethodsFromQuote(Quote $quote): array @@ -97,11 +98,12 @@ public function getShippingMethodsFromQuote(Quote $quote): array try { $shippingMethodManagement = ObjectManager::getInstance()->get(ShippingMethodManagementInterface::class); - $getShippingMethods = $shippingMethodManagement->getList($quoteId); + $shippingMethods = $shippingMethodManagement->getList($quoteId); $methods = []; - foreach ($getShippingMethods as $method) { - $methods[$method->getMethodTitle()] = $method->getAmount(); + foreach ($shippingMethods as $method) { + /** @var ShippingMethodInterface $method */ + $methods[] = $method; } } catch (StateException $stateException) { throw new LocalizedException(__($stateException->getMessage())); @@ -122,10 +124,10 @@ public function isFreeShippingAvailable(Quote $quote): bool { try { $shippingMethods = $this->getShippingMethodsFromQuote($quote); -file_put_contents('/Applications/MAMP/htdocs/magento246/var/log/joeri.log', 'shippingMethods: ' . var_export($shippingMethods, true) . "\n", FILE_APPEND); // loop through the methods to see if one is free (price = 0) - foreach ($shippingMethods as $methodName => $methodAmount) { - if (0.0 === $methodAmount) { + foreach ($shippingMethods as $method) { + /** @var ShippingMethodInterface $method */ + if (0.0 === $method->getAmount()) { return true; } } diff --git a/view/frontend/web/js/view/delivery-options.js b/view/frontend/web/js/view/delivery-options.js index 0db8751a..e326e154 100644 --- a/view/frontend/web/js/view/delivery-options.js +++ b/view/frontend/web/js/view/delivery-options.js @@ -296,21 +296,7 @@ define( if (!response.length) { return; } - - /** - * For the cart summary to display the correct shipping method name on the - * second page of the standard checkout, we need to update the storage. - */ - var cacheObject = JSON.parse(localStorage.getItem('mage-cache-storage')); - if (cacheObject.hasOwnProperty('checkout-data')) { - cacheObject['checkout-data']['selectedShippingRate'] = 'TITLE YO JOERI';// response[0].element_id; - localStorage.setItem('mage-cache-storage', JSON.stringify(cacheObject)); - } - /** - * Set the method to null first, for the price of options to update in the cart summary. - */ - selectShippingMethodAction(null); - selectShippingMethodAction(deliveryOptions.getNewShippingMethod(response[0].element_id)); + selectShippingMethodAction(response[0]); }, }); }, @@ -393,6 +379,7 @@ define( * @returns {boolean} */ isMyParcelShippingMethod: function(shippingMethod) { + console.warn('JOERI NEWR',shippingMethod); // TODO this is what a shipping method looks like, but this is the wrong one return shippingMethod.available && shippingMethod.method_code.indexOf('myparcel') !== -1; }, From de6b59b8f4e048ea2a99cf9597b21d09929b4e3d Mon Sep 17 00:00:00 2001 From: Joeri van Veen Date: Tue, 31 Dec 2024 17:46:16 +0100 Subject: [PATCH 26/29] wip --- Model/Carrier/Carrier.php | 9 ++++---- Model/Quote/Checkout.php | 1 + Service/NeedsQuoteProps.php | 44 ++++++++++++++++++++++++------------- 3 files changed, 35 insertions(+), 19 deletions(-) diff --git a/Model/Carrier/Carrier.php b/Model/Carrier/Carrier.php index a2435c9b..0efe33c9 100644 --- a/Model/Carrier/Carrier.php +++ b/Model/Carrier/Carrier.php @@ -128,17 +128,18 @@ public function collectRates(RateRequest $request) public function getMethodAsArray(Quote $quote): array { //todo joeri inc / ex tax and, where is this specific structure / array coming from? Not method->toArray unfortunately + $amount = $this->getMethodAmount($quote); return [ - 'amount' => $this->getMethodAmount($quote), + 'amount' => $amount, 'available' => true, - 'base_amount' => $this->getMethodAmount($quote), + 'base_amount' => $amount, 'carrier_code' => $this->_code, 'carrier_title' => $this->_title, 'error_message' => '', 'method_code' => $this->_name, 'method_title' => $this->getMethodTitle($quote), - 'price_excl_tax' => $this->getMethodAmount($quote), - 'price_incl_tax' => $this->getMethodAmount($quote), + 'price_excl_tax' => $amount, + 'price_incl_tax' => $amount, ]; } diff --git a/Model/Quote/Checkout.php b/Model/Quote/Checkout.php index e61648ac..f122ffdb 100644 --- a/Model/Quote/Checkout.php +++ b/Model/Quote/Checkout.php @@ -80,6 +80,7 @@ public function getDeliveryOptions(array $forAddress = []): array /** * Use 0.0 for base price when free shipping is available. */ + file_put_contents('/Applications/MAMP/htdocs/magento246/var/log/joeri.log', "getDeliveryOptions \n", FILE_APPEND); if ($this->isFreeShippingAvailable($this->quote)) { $basePrice = 0.0; }else { diff --git a/Service/NeedsQuoteProps.php b/Service/NeedsQuoteProps.php index badfe7fb..461c31bb 100644 --- a/Service/NeedsQuoteProps.php +++ b/Service/NeedsQuoteProps.php @@ -46,7 +46,8 @@ protected function getQuoteFromRateRequest(RateRequest $request): ?Quote if (!($quote instanceof Quote)) { return null; } - file_put_contents('/Applications/MAMP/htdocs/magento246/var/log/joeri.log', 'free shipping rate request: ' . var_export($this->isFreeShippingAvailable($quote), true) . "\n", FILE_APPEND); + file_put_contents('/Applications/MAMP/htdocs/magento246/var/log/joeri.log', "free shipping rate request: \n", FILE_APPEND); + file_put_contents('/Applications/MAMP/htdocs/magento246/var/log/joeri.log', 'RESULT: ' . var_export($this->isFreeShippingAvailable($quote), true) . "\n", FILE_APPEND); return $quote; } @@ -59,7 +60,8 @@ public function getQuoteFromCurrentSession(): ?Quote if (!($quote instanceof Quote)) { return null; } - file_put_contents('/Applications/MAMP/htdocs/magento246/var/log/joeri.log', 'free shipping current session: ' . var_export($this->isFreeShippingAvailable($quote), true) . "\n", FILE_APPEND); + file_put_contents('/Applications/MAMP/htdocs/magento246/var/log/joeri.log', "free shipping current session:\n", FILE_APPEND); + file_put_contents('/Applications/MAMP/htdocs/magento246/var/log/joeri.log', 'RESULT: ' . var_export($this->isFreeShippingAvailable($quote), true) . "\n", FILE_APPEND); return $quote; } @@ -94,7 +96,6 @@ protected function getDeliveryOptionsFromQuote(Quote $quote): AbstractDeliveryOp public function getShippingMethodsFromQuote(Quote $quote): array { $quoteId = $quote->getId(); - file_put_contents('/Applications/MAMP/htdocs/magento246/var/log/joeri.log', 'quoteId: ' . var_export($quoteId, true) . "\n", FILE_APPEND); try { $shippingMethodManagement = ObjectManager::getInstance()->get(ShippingMethodManagementInterface::class); @@ -105,8 +106,6 @@ public function getShippingMethodsFromQuote(Quote $quote): array /** @var ShippingMethodInterface $method */ $methods[] = $method; } - } catch (StateException $stateException) { - throw new LocalizedException(__($stateException->getMessage())); } catch (\Exception $exception) { throw new LocalizedException(__($exception->getMessage())); } @@ -122,19 +121,34 @@ public function getShippingMethodsFromQuote(Quote $quote): array */ public function isFreeShippingAvailable(Quote $quote): bool { - try { - $shippingMethods = $this->getShippingMethodsFromQuote($quote); - // loop through the methods to see if one is free (price = 0) - foreach ($shippingMethods as $method) { - /** @var ShippingMethodInterface $method */ - if (0.0 === $method->getAmount()) { - return true; - } + $address = $quote->getShippingAddress(); + $resource = ObjectManager::getInstance()->get(\Magento\Framework\App\ResourceConnection::class); + $connection = $resource->getConnection(); + $tableName = $resource->getTableName('quote_shipping_rate'); + $sql = "SELECT code FROM " . $tableName . " WHERE address_id = " . $address->getId(); + $rates = $connection->fetchAll($sql); + // TODO get code from quote_shipping_rate table where address_id = $address->getId() + foreach ($rates as $row) { + file_put_contents('/Applications/MAMP/htdocs/magento246/var/log/joeri.log', 'shppingaddress: ' . var_export($row, true) . "\n", FILE_APPEND); + if ('freeshipping_freeshipping' === $row['code']) { + return true; } - } catch (LocalizedException $e) { - Logger::critical($e->getMessage()); } +// try { +// $shippingMethods = $this->getShippingMethodsFromQuote($quote); +// // loop through the methods to see if free shipping is available +// foreach ($shippingMethods as $method) { +// file_put_contents('/Applications/MAMP/htdocs/magento246/var/log/joeri.log', 'joeri shipping method: ' . var_export($method->getCarrierCode(), true) . "\n", FILE_APPEND); +// /** @var ShippingMethodInterface $method */ +// if ('freeshipping' === $method->getCarrierCode()) { +// return true; +// } +// } +// } catch (LocalizedException $e) { +// Logger::critical($e->getMessage()); +// } + return false; } } From cf15a44f71dbd163705a190cfd182811deebdef3 Mon Sep 17 00:00:00 2001 From: Joeri van Veen Date: Thu, 2 Jan 2025 10:36:40 +0100 Subject: [PATCH 27/29] fix: remember free shipping available during checkout --- Service/NeedsQuoteProps.php | 74 +++++++++++++++++++++---------------- 1 file changed, 43 insertions(+), 31 deletions(-) diff --git a/Service/NeedsQuoteProps.php b/Service/NeedsQuoteProps.php index 461c31bb..7be9c757 100644 --- a/Service/NeedsQuoteProps.php +++ b/Service/NeedsQuoteProps.php @@ -7,7 +7,6 @@ use Magento\Checkout\Model\Session; use Magento\Framework\App\ObjectManager; use Magento\Framework\Exception\LocalizedException; -use Magento\Framework\Exception\StateException; use Magento\Quote\Api\Data\ShippingMethodInterface; use Magento\Quote\Model\Quote; use Magento\Quote\Model\Quote\Address\RateRequest; @@ -46,22 +45,23 @@ protected function getQuoteFromRateRequest(RateRequest $request): ?Quote if (!($quote instanceof Quote)) { return null; } - file_put_contents('/Applications/MAMP/htdocs/magento246/var/log/joeri.log', "free shipping rate request: \n", FILE_APPEND); - file_put_contents('/Applications/MAMP/htdocs/magento246/var/log/joeri.log', 'RESULT: ' . var_export($this->isFreeShippingAvailable($quote), true) . "\n", FILE_APPEND); + file_put_contents('/Applications/MAMP/htdocs/magento246/var/log/joeri.log', "free shipping rate request:\n", FILE_APPEND); return $quote; } public function getQuoteFromCurrentSession(): ?Quote { - $checkoutSession = ObjectManager::getInstance()->get(Session::class); - $quote = $checkoutSession->getQuote(); + $session = ObjectManager::getInstance()->get(Session::class); + $quote = $session->getQuote(); if (!($quote instanceof Quote)) { return null; } + // remove free shipping flag, so it can be calculated anew + $session->unsMyParcelFreeShippingIsAvailable(); + file_put_contents('/Applications/MAMP/htdocs/magento246/var/log/joeri.log', "free shipping current session:\n", FILE_APPEND); - file_put_contents('/Applications/MAMP/htdocs/magento246/var/log/joeri.log', 'RESULT: ' . var_export($this->isFreeShippingAvailable($quote), true) . "\n", FILE_APPEND); return $quote; } @@ -93,7 +93,7 @@ protected function getDeliveryOptionsFromQuote(Quote $quote): AbstractDeliveryOp * @return array indexed array of ShippingMethodInterface objects * @throws LocalizedException */ - public function getShippingMethodsFromQuote(Quote $quote): array + protected function getShippingMethodsFromQuote(Quote $quote): array { $quoteId = $quote->getId(); @@ -121,34 +121,46 @@ public function getShippingMethodsFromQuote(Quote $quote): array */ public function isFreeShippingAvailable(Quote $quote): bool { - $address = $quote->getShippingAddress(); - $resource = ObjectManager::getInstance()->get(\Magento\Framework\App\ResourceConnection::class); - $connection = $resource->getConnection(); - $tableName = $resource->getTableName('quote_shipping_rate'); - $sql = "SELECT code FROM " . $tableName . " WHERE address_id = " . $address->getId(); - $rates = $connection->fetchAll($sql); - // TODO get code from quote_shipping_rate table where address_id = $address->getId() - foreach ($rates as $row) { - file_put_contents('/Applications/MAMP/htdocs/magento246/var/log/joeri.log', 'shppingaddress: ' . var_export($row, true) . "\n", FILE_APPEND); - if ('freeshipping_freeshipping' === $row['code']) { - return true; - } + // todo: if free shipping flag is set, return its value + $session = ObjectManager::getInstance()->get(Session::class); + $freeShippingIsAvailable = $session->getMyParcelFreeShippingIsAvailable(); + file_put_contents('/Applications/MAMP/htdocs/magento246/var/log/joeri.log', 'SESSION VALUE:' . var_export($freeShippingIsAvailable, true)."\n", FILE_APPEND); +if (NULL !== $freeShippingIsAvailable) { + return $freeShippingIsAvailable; } - -// try { -// $shippingMethods = $this->getShippingMethodsFromQuote($quote); -// // loop through the methods to see if free shipping is available -// foreach ($shippingMethods as $method) { -// file_put_contents('/Applications/MAMP/htdocs/magento246/var/log/joeri.log', 'joeri shipping method: ' . var_export($method->getCarrierCode(), true) . "\n", FILE_APPEND); -// /** @var ShippingMethodInterface $method */ -// if ('freeshipping' === $method->getCarrierCode()) { -// return true; -// } + // else check if free shipping is available based on quote + // if free shipping is available, set flag to true +// $address = $quote->getShippingAddress(); +// $resource = ObjectManager::getInstance()->get(\Magento\Framework\App\ResourceConnection::class); +// $connection = $resource->getConnection(); +// $tableName = $resource->getTableName('quote_shipping_rate'); +// $sql = "SELECT code FROM " . $tableName . " WHERE address_id = " . $address->getId(); +// $rates = $connection->fetchAll($sql); +// // TODO get code from quote_shipping_rate table where address_id = $address->getId() +// foreach ($rates as $row) { +// file_put_contents('/Applications/MAMP/htdocs/magento246/var/log/joeri.log', 'shppingaddress: ' . var_export($row, true) . "\n", FILE_APPEND); +// if ('freeshipping_freeshipping' === $row['code']) { +// return true; // } -// } catch (LocalizedException $e) { -// Logger::critical($e->getMessage()); // } + try { + $shippingMethods = $this->getShippingMethodsFromQuote($quote); + // loop through the methods to see if free shipping is available + foreach ($shippingMethods as $method) { + file_put_contents('/Applications/MAMP/htdocs/magento246/var/log/joeri.log', 'joeri shipping method: ' . var_export($method->getCarrierCode(), true) . "\n", FILE_APPEND); + /** @var ShippingMethodInterface $method */ + if ('freeshipping' === $method->getCarrierCode()) { + file_put_contents('/Applications/MAMP/htdocs/magento246/var/log/joeri.log', 'HET is true zet te session: ' . "\n", FILE_APPEND); + $session->setMyParcelFreeShippingIsAvailable(true); + return true; + } + } + } catch (LocalizedException $e) { + Logger::critical($e->getMessage()); + } + + $session->setMyParcelFreeShippingIsAvailable(false); return false; } } From d4dc31356e9c83162530d76ea0b2fedd965a356d Mon Sep 17 00:00:00 2001 From: Joeri van Veen Date: Thu, 2 Jan 2025 11:11:07 +0100 Subject: [PATCH 28/29] refactor: improve inline documentation and code style --- Service/NeedsQuoteProps.php | 71 ++++++++++++++++--------------------- 1 file changed, 30 insertions(+), 41 deletions(-) diff --git a/Service/NeedsQuoteProps.php b/Service/NeedsQuoteProps.php index 7be9c757..754c8277 100644 --- a/Service/NeedsQuoteProps.php +++ b/Service/NeedsQuoteProps.php @@ -17,21 +17,23 @@ use Magento\Quote\Api\ShippingMethodManagementInterface; /** - * Use this trait when you need to get the quote independently of session and have easy access to its properties + * Use this trait when you need to get the quote in several scenarios and have easy access to its properties. + * During ‘raterequest’ the shipping methods are not always available, therefore we remember the availability of the + * free shipping method in a session variable. */ trait NeedsQuoteProps { protected AbstractDeliveryOptionsAdapter $deliveryOptions; + /** + * Use this method during raterequest, because getting it from there session will cause infinite loop for + * quotes with trigger_recollect = 1, see Quote::_afterLoad() + * https://magento.stackexchange.com/questions/340048/how-to-properly-get-current-quote-in-carrier-collect-rates-function + */ protected function getQuoteFromRateRequest(RateRequest $request): ?Quote { - /** - * Do not use checkoutSession->getQuote()!!! it will cause infinite loop for - * quotes with trigger_recollect = 1, see Quote::_afterLoad() - * https://magento.stackexchange.com/questions/340048/how-to-properly-get-current-quote-in-carrier-collect-rates-function - */ $items = $request->getAllItems(); - if (empty($items)) { + if (!$items) { return null; } @@ -45,12 +47,11 @@ protected function getQuoteFromRateRequest(RateRequest $request): ?Quote if (!($quote instanceof Quote)) { return null; } - file_put_contents('/Applications/MAMP/htdocs/magento246/var/log/joeri.log', "free shipping rate request:\n", FILE_APPEND); return $quote; } - public function getQuoteFromCurrentSession(): ?Quote + protected function getQuoteFromCurrentSession(): ?Quote { $session = ObjectManager::getInstance()->get(Session::class); $quote = $session->getQuote(); @@ -58,11 +59,12 @@ public function getQuoteFromCurrentSession(): ?Quote if (!($quote instanceof Quote)) { return null; } - // remove free shipping flag, so it can be calculated anew + /** + * The available shipping methods can be found in the quote from the session, so force re-checking + * of the availability of free shipping now, by unsetting the session variable. + */ $session->unsMyParcelFreeShippingIsAvailable(); - file_put_contents('/Applications/MAMP/htdocs/magento246/var/log/joeri.log', "free shipping current session:\n", FILE_APPEND); - return $quote; } @@ -72,13 +74,13 @@ protected function getDeliveryOptionsFromQuote(Quote $quote): AbstractDeliveryOp return $this->deliveryOptions; } - $do = $quote->getData(Config::FIELD_DELIVERY_OPTIONS); + $deliveryOptions = $quote->getData(Config::FIELD_DELIVERY_OPTIONS); - if (is_string($do)) { + if (is_string($deliveryOptions)) { try { - $this->deliveryOptions = DeliveryOptionsAdapterFactory::create(json_decode($do, true, 512, JSON_THROW_ON_ERROR)); + $this->deliveryOptions = DeliveryOptionsAdapterFactory::create(json_decode($deliveryOptions, true, 512, JSON_THROW_ON_ERROR)); } catch (\Throwable $e) { - Logger::log('warning', "Failed to retrieve delivery options from quote {$quote->getId()}", (array)$do); + Logger::log('warning', "Failed to retrieve delivery options from quote {$quote->getId()}", (array) $deliveryOptions); $this->deliveryOptions = new DeliveryOptionsV3Adapter(); } } else { @@ -121,46 +123,33 @@ protected function getShippingMethodsFromQuote(Quote $quote): array */ public function isFreeShippingAvailable(Quote $quote): bool { - // todo: if free shipping flag is set, return its value $session = ObjectManager::getInstance()->get(Session::class); + + // NULL when not set, boolean value when set $freeShippingIsAvailable = $session->getMyParcelFreeShippingIsAvailable(); - file_put_contents('/Applications/MAMP/htdocs/magento246/var/log/joeri.log', 'SESSION VALUE:' . var_export($freeShippingIsAvailable, true)."\n", FILE_APPEND); -if (NULL !== $freeShippingIsAvailable) { + + if (NULL !== $freeShippingIsAvailable) { return $freeShippingIsAvailable; } - // else check if free shipping is available based on quote - // if free shipping is available, set flag to true -// $address = $quote->getShippingAddress(); -// $resource = ObjectManager::getInstance()->get(\Magento\Framework\App\ResourceConnection::class); -// $connection = $resource->getConnection(); -// $tableName = $resource->getTableName('quote_shipping_rate'); -// $sql = "SELECT code FROM " . $tableName . " WHERE address_id = " . $address->getId(); -// $rates = $connection->fetchAll($sql); -// // TODO get code from quote_shipping_rate table where address_id = $address->getId() -// foreach ($rates as $row) { -// file_put_contents('/Applications/MAMP/htdocs/magento246/var/log/joeri.log', 'shppingaddress: ' . var_export($row, true) . "\n", FILE_APPEND); -// if ('freeshipping_freeshipping' === $row['code']) { -// return true; -// } -// } + + $freeShippingIsAvailable = false; try { $shippingMethods = $this->getShippingMethodsFromQuote($quote); - // loop through the methods to see if free shipping is available + foreach ($shippingMethods as $method) { - file_put_contents('/Applications/MAMP/htdocs/magento246/var/log/joeri.log', 'joeri shipping method: ' . var_export($method->getCarrierCode(), true) . "\n", FILE_APPEND); /** @var ShippingMethodInterface $method */ if ('freeshipping' === $method->getCarrierCode()) { - file_put_contents('/Applications/MAMP/htdocs/magento246/var/log/joeri.log', 'HET is true zet te session: ' . "\n", FILE_APPEND); - $session->setMyParcelFreeShippingIsAvailable(true); - return true; + $freeShippingIsAvailable = true; + break; } } } catch (LocalizedException $e) { Logger::critical($e->getMessage()); } - $session->setMyParcelFreeShippingIsAvailable(false); - return false; + $session->setMyParcelFreeShippingIsAvailable($freeShippingIsAvailable); + + return $freeShippingIsAvailable; } } From 00e1af5f09ad26d73cc5b5e2cf6c590e3359d266 Mon Sep 17 00:00:00 2001 From: Joeri van Veen Date: Thu, 2 Jan 2025 17:21:09 +0100 Subject: [PATCH 29/29] refactor: simplify javascript wip --- Model/Carrier/Carrier.php | 84 +++++++++-------- .../DeliveryOptionsToShippingMethods.php | 2 + Model/Quote/Checkout.php | 45 ++++----- Model/Source/ShippingMethods.php | 65 ------------- Service/Config.php | 3 +- Service/DeliveryCosts.php | 11 ++- Service/NeedsQuoteProps.php | 7 +- etc/adminhtml/system.xml | 8 +- view/frontend/web/js/model/checkout.js | 61 +++++-------- .../model/shipping-save-processor-default.js | 0 view/frontend/web/js/view/delivery-options.js | 91 +------------------ 11 files changed, 103 insertions(+), 274 deletions(-) delete mode 100755 Model/Source/ShippingMethods.php mode change 100755 => 100644 view/frontend/web/js/model/shipping-save-processor-default.js diff --git a/Model/Carrier/Carrier.php b/Model/Carrier/Carrier.php index 0efe33c9..50d3cb61 100644 --- a/Model/Carrier/Carrier.php +++ b/Model/Carrier/Carrier.php @@ -32,7 +32,6 @@ use Magento\Shipping\Model\Carrier\AbstractCarrier; use Magento\Shipping\Model\Carrier\CarrierInterface; use Magento\Shipping\Model\Rate\ResultFactory; -use MyParcelNL\Magento\Model\Sales\Repository\PackageRepository; use MyParcelNL\Magento\Service\Config; use MyParcelNL\Magento\Service\DeliveryCosts; use MyParcelNL\Magento\Service\NeedsQuoteProps; @@ -44,25 +43,25 @@ class Carrier extends AbstractCarrier implements CarrierInterface { use NeedsQuoteProps; - public const CODE = 'myparcel'; // same as in /etc/config.xml + public const CODE = 'myparcel'; // same as in /etc/config.xml and the carrier group in system.xml - protected $_code = self::CODE; // $_code is a mandatory property for a Magento carrier - protected $_name; - protected $_title; + protected $_code = self::CODE; // $_code is a mandatory property for a Magento carrier + protected $_name; + protected $_title; protected Freeshipping $_freeShipping; /** * Carrier constructor. * * @param ScopeConfigInterface $scopeConfig - * @param ErrorFactory $rateErrorFactory - * @param LoggerInterface $logger - * @param Config $config - * @param DeliveryCosts $deliveryCosts - * @param ResultFactory $rateFactory - * @param MethodFactory $rateMethodFactory - * @param Freeshipping $freeShipping - * @param array $data + * @param ErrorFactory $rateErrorFactory + * @param LoggerInterface $logger + * @param Config $config + * @param DeliveryCosts $deliveryCosts + * @param ResultFactory $rateFactory + * @param MethodFactory $rateMethodFactory + * @param Freeshipping $freeShipping + * @param array $data * * @throws Exception */ @@ -85,14 +84,14 @@ public function __construct( $data, ); - $this->_name = $config->getMagentoCarrierConfig('name') ?: self::CODE; + $this->_name = $config->getMagentoCarrierConfig('name') ?: self::CODE; $this->_title = $config->getMagentoCarrierConfig('title') ?: self::CODE; - $this->config = $config; + $this->config = $config; $this->rateResultFactory = $rateFactory; $this->rateMethodFactory = $rateMethodFactory; - $this->_freeShipping = $freeShipping; - $this->deliveryCosts = $deliveryCosts; + //$this->_freeShipping = $freeShipping; // todo joeri can we remove this? + $this->deliveryCosts = $deliveryCosts; } protected function _doShipmentRequest(DataObject $request) @@ -118,7 +117,7 @@ public function collectRates(RateRequest $request) $method->setCarrierTitle($this->_title); $method->setMethod($this->_name); $method->setMethodTitle($this->getMethodTitle($quote)); - $method->setPrice((string)$this->getMethodAmount($quote)); + $method->setPrice((string) $this->getMethodAmount($quote)); $result->append($method); @@ -130,14 +129,14 @@ public function getMethodAsArray(Quote $quote): array //todo joeri inc / ex tax and, where is this specific structure / array coming from? Not method->toArray unfortunately $amount = $this->getMethodAmount($quote); return [ - 'amount' => $amount, - 'available' => true, - 'base_amount' => $amount, - 'carrier_code' => $this->_code, - 'carrier_title' => $this->_title, - 'error_message' => '', - 'method_code' => $this->_name, - 'method_title' => $this->getMethodTitle($quote), + 'amount' => $amount, + 'available' => true, + 'base_amount' => $amount, + 'carrier_code' => $this->_code, + 'carrier_title' => $this->_title, + 'error_message' => '', + 'method_code' => $this->_name, + 'method_title' => $this->getMethodTitle($quote), 'price_excl_tax' => $amount, 'price_incl_tax' => $amount, ]; @@ -146,52 +145,51 @@ public function getMethodAsArray(Quote $quote): array private function getMethodAmount(Quote $quote): float { $deliveryOptions = $this->getDeliveryOptionsFromQuote($quote); - $configPath = Config::CARRIERS_XML_PATH_MAP[$deliveryOptions->getCarrier()] ?? ''; + $configPath = Config::CARRIERS_XML_PATH_MAP[$deliveryOptions->getCarrier()] ?? ''; $shipmentOptions = $deliveryOptions->getShipmentOptions() ?? new ShipmentOptionsV3Adapter([]); - $shipmentFees = [ + $shipmentFees = [ "{$deliveryOptions->getDeliveryType()}/fee" => true, //"{$deliveryOptions->getPackageType()}/fee" => true, - 'delivery/only_recipient_fee' => $shipmentOptions->hasOnlyRecipient(), - 'delivery/signature_fee' => $shipmentOptions->hasSignature(), - 'delivery/receipt_code_fee' => $shipmentOptions->hasReceiptCode(), + 'delivery/only_recipient_fee' => $shipmentOptions->hasOnlyRecipient(), + 'delivery/signature_fee' => $shipmentOptions->hasSignature(), + 'delivery/receipt_code_fee' => $shipmentOptions->hasReceiptCode(), ]; - if ($this->isFreeShippingAvailable($quote)) { - $amount = 0.0; - } else { - $amount = $this->deliveryCosts->getBasePrice($quote); - } + $amount = $this->deliveryCosts->getBasePrice($quote); foreach ($shipmentFees as $key => $value) { if (!$value) { continue; } - $amount += (float)$this->config->getConfigValue("$configPath$key"); + $amount += (float) $this->config->getConfigValue("$configPath$key"); } - file_put_contents('/Applications/MAMP/htdocs/magento246/var/log/joeri.log', 'AMOUNT YO: ' . var_export($amount, true) . "\n", FILE_APPEND); + file_put_contents('/Applications/MAMP/htdocs/magento246/var/log/joeri.log', 'AMOUNT (JOERIDEBUG): ' . var_export($amount, true) . "\n", FILE_APPEND); return $amount; } private function getMethodTitle(Quote $quote): string { - // todo joeri netjes maken $deliveryOptions = $this->getDeliveryOptionsFromQuote($quote); $shipmentOptions = $deliveryOptions->getShipmentOptions() ?? new ShipmentOptionsV3Adapter([]); - $carrierName = $deliveryOptions->getCarrier(); + $carrierName = $deliveryOptions->getCarrier(); if (null === $carrierName) { return $this->_title; } - $carrierHuman = CarrierFactory::createFromName($carrierName)->getHuman(); + try { + $carrierHuman = CarrierFactory::createFromName($carrierName)->getHuman(); + } catch (Exception $e) { + $carrierHuman = $carrierName; + } ob_start(); echo $carrierHuman, ' ', __("{$deliveryOptions->getDeliveryType()}_title"), ', '; foreach ($shipmentOptions->toArray() as $key => $value) { if ($value) { - echo __("{$key}_title"), ', '; + echo trim(__("{$key}_title")), ', '; } } @@ -220,7 +218,7 @@ public function isTrackingAvailable(): bool } /** - * @param $alias + * @param $alias * @param string $settingPath * * @return Method diff --git a/Model/Checkout/DeliveryOptionsToShippingMethods.php b/Model/Checkout/DeliveryOptionsToShippingMethods.php index 2014f006..bc1167ac 100755 --- a/Model/Checkout/DeliveryOptionsToShippingMethods.php +++ b/Model/Checkout/DeliveryOptionsToShippingMethods.php @@ -31,6 +31,8 @@ public function __construct(array $deliveryOptions) { $this->deliveryOptions = DeliveryOptionsAdapterFactory::create($deliveryOptions); $this->createShippingMethod(); + file_put_contents('/Applications/MAMP/htdocs/magento246/var/log/joeri.log', "DeliveryOptionsToShippingMethods is called / constructed and probably not working\n", FILE_APPEND); + throw new \Exception('DeliveryOptionsToShippingMethods is called, this is not working probably'); } /** diff --git a/Model/Quote/Checkout.php b/Model/Quote/Checkout.php index f122ffdb..289bd292 100644 --- a/Model/Quote/Checkout.php +++ b/Model/Quote/Checkout.php @@ -5,9 +5,9 @@ use Magento\Eav\Model\Entity\Collection\AbstractCollection; use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Exception\NoSuchEntityException; -use Magento\Quote\Model\Quote; use Magento\Store\Model\StoreManagerInterface; use MyParcelNL\Magento\Facade\Logger; +use MyParcelNL\Magento\Model\Carrier\Carrier; use MyParcelNL\Magento\Model\Sales\Repository\PackageRepository; use MyParcelNL\Magento\Model\Source\PriceDeliveryOptionsView; use MyParcelNL\Magento\Service\Config; @@ -42,14 +42,14 @@ class Checkout /** * @var string */ - private string $country; + private string $country; /** * Checkout constructor. * - * @param Config $config - * @param DeliveryCosts $deliveryCosts - * @param PackageRepository $package + * @param Config $config + * @param DeliveryCosts $deliveryCosts + * @param PackageRepository $package * @param StoreManagerInterface $currency */ public function __construct( @@ -77,15 +77,7 @@ public function __construct( public function getDeliveryOptions(array $forAddress = []): array { $this->hideDeliveryOptionsForProduct(); - /** - * Use 0.0 for base price when free shipping is available. - */ - file_put_contents('/Applications/MAMP/htdocs/magento246/var/log/joeri.log', "getDeliveryOptions \n", FILE_APPEND); - if ($this->isFreeShippingAvailable($this->quote)) { - $basePrice = 0.0; - }else { - $basePrice = $this->deliveryCosts->getBasePrice($this->quote); - } + $basePrice = $this->deliveryCosts->getBasePrice($this->quote); $packageType = $this->getPackageType(); if (isset($forAddress['countryId'])) { @@ -93,15 +85,14 @@ public function getDeliveryOptions(array $forAddress = []): array } $data = [ - /* the 'method' string here is actually the carrier_code of the method */ - 'methods' => explode(',', $this->config->getGeneralConfig('shipping_methods/methods') ?? ''), - 'config' => array_merge( + 'carrierCode' => Carrier::CODE, + 'config' => array_merge( $this->getGeneralData(), $this->getDeliveryData($packageType, $basePrice), ['packageType' => $packageType] ), - 'strings' => $this->getDeliveryOptionsStrings(), - 'forAddress' => $forAddress, + 'strings' => $this->getDeliveryOptionsStrings(), + 'forAddress' => $forAddress, ]; return [ @@ -165,7 +156,7 @@ private function getPackageType(): string * Get delivery data * * @param string $packageType - * @param float $basePrice + * @param float $basePrice * @return array */ private function getDeliveryData(string $packageType, float $basePrice): array @@ -223,16 +214,16 @@ private function getDeliveryData(string $packageType, float $basePrice): array $allowPickup = $this->config->getBoolConfig($carrierPath, 'pickup/active'); $allowStandardDelivery = $this->config->getBoolConfig($carrierPath, 'delivery/active'); - $allowMorningDelivery = ! $isAgeCheckActive && $canHaveMorning && $this->config->getBoolConfig($carrierPath, 'morning/active'); - $allowEveningDelivery = ! $isAgeCheckActive && $canHaveEvening && $this->config->getBoolConfig($carrierPath, 'evening/active'); + $allowMorningDelivery = !$isAgeCheckActive && $canHaveMorning && $this->config->getBoolConfig($carrierPath, 'morning/active'); + $allowEveningDelivery = !$isAgeCheckActive && $canHaveEvening && $this->config->getBoolConfig($carrierPath, 'evening/active'); $allowExpressDelivery = $canHaveExpress && $this->config->getBoolConfig($carrierPath, 'express/active'); - $allowDeliveryOptions = ! $this->package->deliveryOptionsDisabled - && ($allowPickup || $allowStandardDelivery || $allowMorningDelivery || $allowEveningDelivery); + $allowDeliveryOptions = !$this->package->deliveryOptionsDisabled + && ($allowPickup || $allowStandardDelivery || $allowMorningDelivery || $allowEveningDelivery); if ($allowDeliveryOptions && $packageType === AbstractConsignment::PACKAGE_TYPE_MAILBOX_NAME) { $this->package->setMailboxSettings($carrierPath); $allowDeliveryOptions = $this->config->getBoolConfig($carrierPath, 'mailbox/active') - && $this->package->getMaxMailboxWeight() >= $this->package->getWeight(); + && $this->package->getMaxMailboxWeight() >= $this->package->getWeight(); } $myParcelConfig['carrierSettings'][$carrier] = [ @@ -461,8 +452,8 @@ private function isPickupAllowed(string $carrier): bool $isMailboxPackage = AbstractConsignment::PACKAGE_TYPE_MAILBOX_NAME === $this->getPackageType(); $pickupEnabled = $this->config->getBoolConfig($carrier, 'pickup/active'); $showPickupForMailbox = $this->config->getBoolConfig($carrier, 'mailbox/pickup_mailbox'); - $showPickup = ! $isMailboxPackage || $showPickupForMailbox; + $showPickup = !$isMailboxPackage || $showPickupForMailbox; - return ! $this->package->deliveryOptionsDisabled && $pickupEnabled && $showPickup; + return !$this->package->deliveryOptionsDisabled && $pickupEnabled && $showPickup; } } diff --git a/Model/Source/ShippingMethods.php b/Model/Source/ShippingMethods.php deleted file mode 100755 index 3dda3b46..00000000 --- a/Model/Source/ShippingMethods.php +++ /dev/null @@ -1,65 +0,0 @@ - - * @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 - * @since File available since Release 0.1.0 - */ - -namespace MyParcelNL\Magento\Model\Source; - -use Magento\Framework\App\Config\ScopeConfigInterface; -use Magento\Shipping\Model\Config; - -class ShippingMethods implements \Magento\Framework\Option\ArrayInterface -{ - /** - * @var ScopeConfigInterface - */ - private $scopeConfig; - /** - * @var Config - */ - private $deliveryModelConfig; - - /** - * @param ScopeConfigInterface $scopeConfig - * @param Config $deliveryModelConfig - */ - public function __construct( - ScopeConfigInterface $scopeConfig, - Config $deliveryModelConfig - ) { - $this->scopeConfig = $scopeConfig; - $this->deliveryModelConfig = $deliveryModelConfig; - } - - /** - * Get all Drop off days - * - * @return array - */ - public function toOptionArray() - { - $methods = $this->deliveryModelConfig->getAllCarriers(); - - $aMethods = []; - - /** @var \Magento\OfflineShipping\Model\Carrier\Flatrate $method */ - foreach ($methods as $code => $method) { - $aMethods[] = ['value' => $code, 'label' => $code]; - } - - return $aMethods; - } -} diff --git a/Service/Config.php b/Service/Config.php index e4b37533..aadd6ac7 100644 --- a/Service/Config.php +++ b/Service/Config.php @@ -8,6 +8,7 @@ use Magento\Framework\App\Helper\Context; use Magento\Framework\Module\ModuleListInterface; use Magento\Store\Model\ScopeInterface; +use MyParcelNL\Magento\Model\Carrier\Carrier; use MyParcelNL\Sdk\src\Model\Carrier\CarrierDHLEuroplus; use MyParcelNL\Sdk\src\Model\Carrier\CarrierDHLForYou; use MyParcelNL\Sdk\src\Model\Carrier\CarrierDHLParcelConnect; @@ -20,7 +21,7 @@ class Config extends AbstractHelper { public const MODULE_NAME = 'MyParcelNL_Magento'; public const PLATFORM = 'myparcel'; - public const XML_PATH_MAGENTO_CARRIER = 'carriers/myparcel_delivery/'; + public const XML_PATH_MAGENTO_CARRIER = 'carriers/' . Carrier::CODE . '/'; public const XML_PATH_GENERAL = 'myparcelnl_magento_general/'; public const XML_PATH_POSTNL_SETTINGS = 'myparcelnl_magento_postnl_settings/'; public const XML_PATH_DHLFORYOU_SETTINGS = 'myparcelnl_magento_dhlforyou_settings/'; diff --git a/Service/DeliveryCosts.php b/Service/DeliveryCosts.php index 933d3877..f7568009 100644 --- a/Service/DeliveryCosts.php +++ b/Service/DeliveryCosts.php @@ -8,10 +8,12 @@ class DeliveryCosts { + use NeedsQuoteProps; + private Weight $weight; private Config $config; - public function __construct(Weight $weight , Config $config) + public function __construct(Weight $weight, Config $config) { $this->weight = $weight; $this->config = $config; @@ -23,8 +25,11 @@ public function getBasePrice(Quote $quote): float $countryCode = $quote->getShippingAddress()->getCountryId(); $packageType = 'package'; // todo get actual (chosen) package type $weight = $this->weight->getEmptyPackageWeightInGrams($packageType) - + $this->weight->getQuoteWeightInGrams($quote); + + $this->weight->getQuoteWeightInGrams($quote); + if ($this->isFreeShippingAvailable($quote)) { + return 0.0; + } // todo implement the actual logic based on configured multi dimensional object return (float) $this->config->getMagentoCarrierConfig('shipping_cost'); } @@ -36,6 +41,6 @@ public function getBasePrice(Quote $quote): float */ public static function getPriceInCents(float $price): int { - return (int)($price * 100); + return (int) ($price * 100); } } diff --git a/Service/NeedsQuoteProps.php b/Service/NeedsQuoteProps.php index 754c8277..af7a471b 100644 --- a/Service/NeedsQuoteProps.php +++ b/Service/NeedsQuoteProps.php @@ -20,6 +20,8 @@ * Use this trait when you need to get the quote in several scenarios and have easy access to its properties. * During ‘raterequest’ the shipping methods are not always available, therefore we remember the availability of the * free shipping method in a session variable. + * + * @property AbstractDeliveryOptionsAdapter $deliveryOptions */ trait NeedsQuoteProps { @@ -54,11 +56,12 @@ protected function getQuoteFromRateRequest(RateRequest $request): ?Quote protected function getQuoteFromCurrentSession(): ?Quote { $session = ObjectManager::getInstance()->get(Session::class); - $quote = $session->getQuote(); + $quote = $session->getQuote(); if (!($quote instanceof Quote)) { return null; } + /** * The available shipping methods can be found in the quote from the session, so force re-checking * of the availability of free shipping now, by unsetting the session variable. @@ -101,7 +104,7 @@ protected function getShippingMethodsFromQuote(Quote $quote): array try { $shippingMethodManagement = ObjectManager::getInstance()->get(ShippingMethodManagementInterface::class); - $shippingMethods = $shippingMethodManagement->getList($quoteId); + $shippingMethods = $shippingMethodManagement->getList($quoteId); $methods = []; foreach ($shippingMethods as $method) { diff --git a/etc/adminhtml/system.xml b/etc/adminhtml/system.xml index aeb1e2b8..48ce3dbb 100755 --- a/etc/adminhtml/system.xml +++ b/etc/adminhtml/system.xml @@ -91,12 +91,6 @@ - - - MyParcelNL\Magento\Model\Source\ShippingMethods - The extra myparcel options are added to this shipping method - 1 - MyParcelNL\Magento\Model\Source\PickupLocationsView @@ -1447,7 +1441,7 @@
- + diff --git a/view/frontend/web/js/model/checkout.js b/view/frontend/web/js/model/checkout.js index e560849c..539dcb23 100644 --- a/view/frontend/web/js/model/checkout.js +++ b/view/frontend/web/js/model/checkout.js @@ -71,6 +71,7 @@ function( * Best package type. */ bestPackageType: null, + carrierCode: 'myparcel', // default, may be overridden by carrierCode in configuration /** * Initialize by requesting the MyParcel settings configuration from Magento. @@ -78,13 +79,15 @@ function( initialize: function() { console.error(' Joeri debugging '); Model.compute = ko.computed(function() { - var configuration = Model.configuration(); - var rates = Model.rates(); + const configuration = Model.configuration(); + const rates = Model.rates(); if (!configuration || !rates.length) { return false; } + if (configuration.carrierCode) Model.carrierCode = configuration.carrierCode; + return {configuration: configuration, rates: rates}; }); @@ -131,19 +134,6 @@ function( Model.hideShippingMethods(); }, - /** - * Search the rates for the given method code. - * - * @param {string} methodCode - Method code to search for. - * - * @returns {Object} - The found rate, if any. - */ - findRateByMethodCode: function(methodCode) { - return Model.rates().find(function(rate) { - return rate.method_code === methodCode; - }); - }, - /** * Search the rates for the given carrier code. * @@ -161,32 +151,22 @@ function( * Hide the shipping methods the delivery options should replace. */ hideShippingMethods: function() { - var rowsToHide = []; - - Model.rates().forEach(function(rate) { - const hasDeliveryOptions = Model.hasDeliveryOptions(); - const myParcelMethods = hasDeliveryOptions ? Model.configuration().methods || [] : []; - const cell = document.getElementById('label_method_' + rate.method_code + '_' + rate.carrier_code) || null; + const row = Model.rowElement(); - if (!rate.available || !cell) { - return; - } + if (row && Model.hasDeliveryOptions) { + row.style.display = 'none'; + } + }, - const row = cell.parentElement; + rowElement: function() { + const rate = Model.findOriginalRateByCarrierCode(Model.carrierCode) || {}, + cell = document.getElementById('label_method_' + rate.method_code + '_' + rate.carrier_code); - /** - * Hide MyParcel-specific methods, and the parent methods delivery options are bound to - */ - if (rate.method_code.indexOf('myparcel') !== -1) { - rowsToHide.push(row); - } else if (myParcelMethods.includes(rate.carrier_code)) { - rowsToHide.push(row); - } - }); + if (!cell) { + return null; + } - rowsToHide.forEach(function(row) { - row.style.display = 'none'; - }); + return cell.parentElement; // or cell.closest('tr');? who knows how this is structured in different checkouts? }, /** @@ -274,9 +254,10 @@ function( * Filter the allowed shipping methods by checking if they are actually present in the checkout. If not they will * be left out. */ - Model.allowedShippingMethods(Model.configuration().methods.filter(function(carrierCode) { - return !!Model.findOriginalRateByCarrierCode(carrierCode); - })); + const allowed = [], + row = Model.rowElement(); + if (row) allowed.push(Model.carrierCode); + Model.allowedShippingMethods(allowed); } function updateHasDeliveryOptions() { diff --git a/view/frontend/web/js/model/shipping-save-processor-default.js b/view/frontend/web/js/model/shipping-save-processor-default.js old mode 100755 new mode 100644 diff --git a/view/frontend/web/js/view/delivery-options.js b/view/frontend/web/js/view/delivery-options.js index e326e154..d273ff17 100644 --- a/view/frontend/web/js/view/delivery-options.js +++ b/view/frontend/web/js/view/delivery-options.js @@ -57,48 +57,6 @@ define( */ hiddenDataInput: '[name="myparcel_delivery_options"]', - methodCodeStandardDelivery: 'myparcelnl_magento_postnl_settings/delivery', - - /** - * Maps shipping method codes to prices in the delivery options config. - */ - methodCodeDeliveryOptionsConfigMap: { - 'myparcelnl_magento_postnl_settings/delivery': 'config.carrierSettings.postnl.priceStandardDelivery', - 'myparcelnl_magento_postnl_settings/mailbox': 'config.carrierSettings.postnl.pricePackageTypeMailbox', - 'myparcelnl_magento_postnl_settings/package_small': 'config.carrierSettings.postnl.pricePackageTypePackageSmall', - 'myparcelnl_magento_postnl_settings/digital_stamp': 'config.carrierSettings.postnl.pricePackageTypeDigitalStamp', - 'myparcelnl_magento_postnl_settings/morning': 'config.carrierSettings.postnl.priceMorningDelivery', - 'myparcelnl_magento_postnl_settings/evening': 'config.carrierSettings.postnl.priceEveningDelivery', - 'myparcelnl_magento_postnl_settings/morning/only_recipient': 'config.carrierSettings.postnl.priceMorningDelivery', - 'myparcelnl_magento_postnl_settings/evening/only_recipient': 'config.carrierSettings.postnl.priceEveningDelivery', - 'myparcelnl_magento_postnl_settings/pickup': 'config.carrierSettings.postnl.pricePickup', - 'myparcelnl_magento_postnl_settings/morning/only_recipient/signature': 'config.carrierSettings.postnl.priceMorningSignature', - 'myparcelnl_magento_postnl_settings/evening/only_recipient/signature': 'config.carrierSettings.postnl.priceEveningSignature', - 'myparcelnl_magento_postnl_settings/delivery/only_recipient/signature': 'config.carrierSettings.postnl.priceSignatureAndOnlyRecipient', - 'myparcelnl_magento_dhlforyou_settings/delivery': 'config.carrierSettings.dhlforyou.priceStandardDelivery', - 'myparcelnl_magento_dhlforyou_settings/mailbox': 'config.carrierSettings.dhlforyou.pricePackageTypeMailbox', - 'myparcelnl_magento_dhlforyou_settings/pickup': 'config.carrierSettings.dhlforyou.pricePickup', - 'myparcelnl_magento_dhlforyou_settings/delivery/same_day_delivery': 'config.carrierSettings.dhlforyou.priceSameDayDelivery', - 'myparcelnl_magento_dhlforyou_settings/delivery/only_recipient/same_day_delivery': 'config.carrierSettings.dhlforyou.priceSameDayDeliveryAndOnlyRecipient', - 'myparcelnl_magento_dhleuroplus_settings/delivery': 'config.carrierSettings.dhleuroplus.priceStandardDelivery', - 'myparcelnl_magento_dhlparcelconnect_settings/delivery': 'config.carrierSettings.dhlparcelconnect.priceStandardDelivery', - 'myparcelnl_magento_ups_settings/delivery': 'config.carrierSettings.ups.priceStandardDelivery', - 'myparcelnl_magento_dpd_settings/delivery': 'config.carrierSettings.dpd.priceStandardDelivery', - 'myparcelnl_magento_dpd_settings/pickup': 'config.carrierSettings.dpd.pricePickup', - 'myparcelnl_magento_dpd_settings/mailbox': 'config.carrierSettings.dpd.pricePackageTypeMailbox', - }, - - /** - * Maps shipping method codes to prices in the delivery options config. - */ - methodCodeShipmentOptionsConfigMap: { - 'myparcelnl_magento_postnl_settings/delivery/signature': 'config.carrierSettings.postnl.priceSignature', - 'myparcelnl_magento_postnl_settings/delivery/only_recipient': 'config.carrierSettings.postnl.priceOnlyRecipient', - 'myparcelnl_magento_dhlforyou_settings/delivery/only_recipient': 'config.carrierSettings.dhlforyou.priceOnlyRecipient', - 'myparcelnl_magento_dhlforyou_settings/delivery/same_day_delivery': 'config.carrierSettings.dhlforyou.priceSameDayDelivery', - 'myparcelnl_magento_dhlforyou_settings/delivery/only_recipient/same_day_delivery': 'config.carrierSettings.dhlforyou.priceSameDayDeliveryAndOnlyRecipient', - }, - /** * Initialize the script. Render the delivery options div, request the plugin settings, then initialize listeners. */ @@ -324,17 +282,17 @@ define( * @param {Object} selectedShippingMethod - The shipping method that was selected. */ onShippingMethodUpdate: function(selectedShippingMethod) { - var newShippingMethod = selectedShippingMethod || {}; - var available = newShippingMethod.available || false; - var isMyParcelMethod = deliveryOptions.isMyParcelShippingMethod(newShippingMethod); - + const newShippingMethod = selectedShippingMethod || {}, + available = newShippingMethod.available || false, + carrierCode = newShippingMethod.carrier_code || '', + myparcelCarrierCode = checkout.carrierCode; checkout.hideShippingMethods(); if (!checkout.hasDeliveryOptions() || !available) { return; } - if (!isMyParcelMethod) { + if (carrierCode !== myparcelCarrierCode) { deliveryOptions.triggerEvent(deliveryOptions.disableDeliveryOptionsEvent); deliveryOptions.isUsingMyParcelMethod = false; return; @@ -344,45 +302,6 @@ define( deliveryOptions.isUsingMyParcelMethod = true; }, - /** - * Get the new shipping method that should be saved. - * - * @param {string} methodCode - Method code to use to find a method. - * - * @returns {Object} - */ - getNewShippingMethod: function(methodCode) { - var newShippingMethod = []; - var matchingShippingMethod = checkout.findRateByMethodCode(methodCode); - - if (matchingShippingMethod) { - return matchingShippingMethod; - } else { - /** - * If the method doesn't exist, loop through the allowed shipping methods and return the first one that - * matches. - */ - checkout.allowedShippingMethods().forEach(function(carrierCode) { - var foundRate = checkout.findOriginalRateByCarrierCode(carrierCode); - - if (foundRate) { - newShippingMethod.push(foundRate); - } - }); - - return newShippingMethod.length ? newShippingMethod[0] : null; - } - }, - - /** - * @param {Object} shippingMethod - * @returns {boolean} - */ - isMyParcelShippingMethod: function(shippingMethod) { - console.warn('JOERI NEWR',shippingMethod); // TODO this is what a shipping method looks like, but this is the wrong one - return shippingMethod.available && shippingMethod.method_code.indexOf('myparcel') !== -1; - }, - /** * For use when magic decimals appear... *