diff --git a/.travis.yml b/.travis.yml index d652a08d7..fb3b0bf5a 100644 --- a/.travis.yml +++ b/.travis.yml @@ -19,20 +19,20 @@ matrix: # PHP 7.1 is only supported in Magento 2.2.x # PHP 7.2 is only supported in Magento 2.3.x include: - - php: 7.0 - env: MAGENTO_VERSION=2.1.16 - php: 7.0 env: MAGENTO_VERSION=2.1.17 - php: 7.0 - env: MAGENTO_VERSION=2.2.7 - - php: 7.1 + env: MAGENTO_VERSION=2.1.18 + - php: 7.0 env: MAGENTO_VERSION=2.2.8 - php: 7.1 - env: MAGENTO_VERSION=2.3.0 + env: MAGENTO_VERSION=2.2.9 - php: 7.1 - env: MAGENTO_VERSION=2.3.1 # DI_COMPILE=true + env: MAGENTO_VERSION=2.3.1 + - php: 7.2 + env: MAGENTO_VERSION=2.3.2 # DI_COMPILE=true - php: 7.2 - env: MAGENTO_VERSION=2.3.1 CODE_COVERAGE=true + env: MAGENTO_VERSION=2.3.2 CODE_COVERAGE=true before_script: - export PATH=$PATH:$HOME/.composer/vendor/bin diff --git a/Api/Data/ShipmentInterface.php b/Api/Data/ShipmentInterface.php index c4389a6ba..44c75bf66 100644 --- a/Api/Data/ShipmentInterface.php +++ b/Api/Data/ShipmentInterface.php @@ -108,7 +108,19 @@ public function setShipmentType($value); * @return string|null */ public function getShipmentType(); - + + /** + * @param $value + * + * @return mixed + */ + public function setShipmentCountry($value); + + /** + * @return mixed + */ + public function getShipmentCountry(); + /** * @param $value * @@ -320,6 +332,11 @@ public function getOriginalShippingAddress(); * @return \Magento\Sales\Api\Data\ShipmentInterface */ public function getShipment(); + + /** + * @return mixed + */ + public function getShippingAddress(); /** * @return bool diff --git a/Block/Adminhtml/Config/Support/SupportTab.php b/Block/Adminhtml/Config/Support/SupportTab.php index 8b18a1b5b..f8efc55e8 100644 --- a/Block/Adminhtml/Config/Support/SupportTab.php +++ b/Block/Adminhtml/Config/Support/SupportTab.php @@ -38,7 +38,7 @@ class SupportTab extends Template implements RendererInterface { - const POSTNL_VERSION = '1.7.4'; + const POSTNL_VERSION = '1.8.0'; const XPATH_SUPPORTED_MAGENTO_VERSION = 'tig_postnl/supported_magento_version'; diff --git a/Config/CheckoutConfiguration/IsShippingOptionsActive.php b/Config/CheckoutConfiguration/IsShippingOptionsActive.php index e15126e49..70af716d2 100644 --- a/Config/CheckoutConfiguration/IsShippingOptionsActive.php +++ b/Config/CheckoutConfiguration/IsShippingOptionsActive.php @@ -37,7 +37,7 @@ use TIG\PostNL\Service\Quote\CheckIfQuoteItemsAreInStock; use TIG\PostNL\Service\Quote\CheckIfQuoteItemsCanBackorder; use \TIG\PostNL\Service\Quote\CheckIfQuoteHasOption; -use TIG\PostNL\Service\Order\ProductCodeAndType; +use TIG\PostNL\Service\Order\ProductInfo; class IsShippingOptionsActive implements CheckoutConfigurationInterface { @@ -98,7 +98,7 @@ public function getValue() return false; } - if ($this->quoteHasOption->get(ProductCodeAndType::OPTION_EXTRAATHOME)) { + if ($this->quoteHasOption->get(ProductInfo::OPTION_EXTRAATHOME)) { return false; } diff --git a/Config/Provider/PepsConfiguration.php b/Config/Provider/PepsConfiguration.php new file mode 100644 index 000000000..7993709f2 --- /dev/null +++ b/Config/Provider/PepsConfiguration.php @@ -0,0 +1,58 @@ +getConfigFromXpath(static::XPATH_BARCODE_TYPE, $storeId); + } + + /** + * @param null $storeId + * + * @return mixed + */ + public function getBarcodeRange($storeId = null) + { + return $this->getConfigFromXpath(static::XPATH_BARCODE_RANGE, $storeId); + } +} diff --git a/Config/Provider/ProductOptions.php b/Config/Provider/ProductOptions.php index addd251fd..f2bdd201b 100644 --- a/Config/Provider/ProductOptions.php +++ b/Config/Provider/ProductOptions.php @@ -56,6 +56,7 @@ class ProductOptions extends AbstractConfigProvider const XPATH_DEFAULT_PACKAGE_DELIVERY_TYPE = 'tig_postnl/delivery_settings/default_package_type'; const XPATH_ALTERNATIVE_DEFAULT_PACKAGE_DELIVERY_TYPE = 'tig_postnl/delivery_settings/alternative_package_type'; const XPATH_DEFAULT_EPS_PRODUCT_OPTION = 'tig_postnl/delivery_settings/default_eps_option'; + const XPATH_DEFAULT_GP_PRODUCT_OPTION = 'tig_postnl/globalpack/default_gp_option'; /** * Since 1.5.1 all product options are automaticly supported. @@ -71,7 +72,7 @@ public function getSupportedProductOptions() */ public function getDefaultProductOption() { - return $this->getConfigFromXpath(self::XPATH_DEFAULT_PRODUCT_OPTION); + return $this->getConfigFromXpath(static::XPATH_DEFAULT_PRODUCT_OPTION); } /** @@ -79,7 +80,7 @@ public function getDefaultProductOption() */ public function getUseAlternativeDefault() { - return $this->getConfigFromXpath(self::XPATH_USE_ALTERNATIVE_DEFAULT_OPTION); + return $this->getConfigFromXpath(static::XPATH_USE_ALTERNATIVE_DEFAULT_OPTION); } /** @@ -91,7 +92,7 @@ public function getAlternativeDefaultMinAmount() return '0'; } - return $this->getConfigFromXpath(self::XPATH_ALTERNATIVE_DEFAULT_MIN_AMOUNT); + return $this->getConfigFromXpath(static::XPATH_ALTERNATIVE_DEFAULT_MIN_AMOUNT); } /** @@ -103,7 +104,7 @@ public function getAlternativeDefaultProductOption() return false; } - return $this->getConfigFromXpath(self::XPATH_ALTERNATIVE_DEFAULT_PRODUCT_OPTION); + return $this->getConfigFromXpath(static::XPATH_ALTERNATIVE_DEFAULT_PRODUCT_OPTION); } /** @@ -117,7 +118,7 @@ public function getDefaultEveningProductOption($country = null) return $this->getDefaultEveningBeProductOption(); } - return $this->getConfigFromXpath(self::XPATH_DEFAULT_EVENING_PRODUCT_OPTION); + return $this->getConfigFromXpath(static::XPATH_DEFAULT_EVENING_PRODUCT_OPTION); } /** @@ -125,7 +126,7 @@ public function getDefaultEveningProductOption($country = null) */ public function getDefaultExtraAtHomeProductOption() { - return $this->getConfigFromXpath(self::XPATH_DEFAULT_EXTRAATHOME_PRODUCT_OPTION); + return $this->getConfigFromXpath(static::XPATH_DEFAULT_EXTRAATHOME_PRODUCT_OPTION); } /** @@ -133,7 +134,7 @@ public function getDefaultExtraAtHomeProductOption() */ public function getDefaultEveningBeProductOption() { - return $this->getConfigFromXpath(self::XPATH_DEFAULT_EVENING_BE_PRODUCT_OPTION); + return $this->getConfigFromXpath(static::XPATH_DEFAULT_EVENING_BE_PRODUCT_OPTION); } /** @@ -141,7 +142,7 @@ public function getDefaultEveningBeProductOption() */ public function getDefaultBeProductOption() { - return $this->getConfigFromXpath(self::XPATH_DEFAULT_BE_PRODUCT_OPTION); + return $this->getConfigFromXpath(static::XPATH_DEFAULT_BE_PRODUCT_OPTION); } /** @@ -149,7 +150,15 @@ public function getDefaultBeProductOption() */ public function getDefaultEpsProductOption() { - return $this->getConfigFromXpath(self::XPATH_DEFAULT_EPS_PRODUCT_OPTION); + return $this->getConfigFromXpath(static::XPATH_DEFAULT_EPS_PRODUCT_OPTION); + } + + /** + * @return mixed + */ + public function getDefaultGlobalpackOption() + { + return $this->getConfigFromXpath(static::XPATH_DEFAULT_GP_PRODUCT_OPTION); } /** @@ -157,7 +166,7 @@ public function getDefaultEpsProductOption() */ public function getDefaultPakjeGemakProductOption() { - return $this->getConfigFromXpath(self::XPATH_DEFAULT_PAKJEGEMAK_PRODUCT_OPTION); + return $this->getConfigFromXpath(static::XPATH_DEFAULT_PAKJEGEMAK_PRODUCT_OPTION); } /** @@ -165,7 +174,7 @@ public function getDefaultPakjeGemakProductOption() */ public function getDefaultPakjeGemakEarlyProductOption() { - return $this->getConfigFromXpath(self::XPATH_DEFAULT_PAKJEGEMAK_EARLY_PRODUCT_OPTION); + return $this->getConfigFromXpath(static::XPATH_DEFAULT_PAKJEGEMAK_EARLY_PRODUCT_OPTION); } /** @@ -173,7 +182,7 @@ public function getDefaultPakjeGemakEarlyProductOption() */ public function getDefaultSundayProductOption() { - return $this->getConfigFromXpath(self::XPATH_DEFAULT_SUNDAY_PRODUCT_OPTION); + return $this->getConfigFromXpath(static::XPATH_DEFAULT_SUNDAY_PRODUCT_OPTION); } /** diff --git a/Config/Provider/ShippingOptions.php b/Config/Provider/ShippingOptions.php index a4ad16ad8..f5b9c0499 100644 --- a/Config/Provider/ShippingOptions.php +++ b/Config/Provider/ShippingOptions.php @@ -57,6 +57,8 @@ class ShippingOptions extends AbstractConfigProvider const XPATH_ITEM_OPTIONS_MANAGE_STOCK = 'cataloginventory/item_options/manage_stock'; const XPATH_SHIPPING_OPTION_CARGO_ACTIVE = 'tig_postnl/cargo/cargo_active'; const XPATH_SHIPPING_OPTION_EPS_BUSINESS_ACTIVE = 'tig_postnl/eps/business_active'; + const XPATH_SHIPPING_OPTIONS_PEPS_ACTIVE = 'tig_postnl/peps/active'; + const XPATH_SHIPPING_OPTIONS_GLOBALPACK_ACTIVE = 'tig_postnl/globalpack/enabled'; private $defaultMaxDeliverydays = '5'; @@ -241,6 +243,22 @@ public function canUseEpsBusinessProducts() { return (bool) $this->getConfigFromXpath(static::XPATH_SHIPPING_OPTION_EPS_BUSINESS_ACTIVE); } + + /** + * @return bool + */ + public function canUsePriority() + { + return (bool) $this->getConfigFromXpath(static::XPATH_SHIPPING_OPTIONS_PEPS_ACTIVE); + } + + /** + * @return bool + */ + public function canUseGlobalPack() + { + return (bool) $this->getConfigFromXpath(static::XPATH_SHIPPING_OPTIONS_GLOBALPACK_ACTIVE); + } } /** * @codingStandardsIgnoreEnd diff --git a/Config/Provider/Webshop.php b/Config/Provider/Webshop.php index fe6165f83..e8fd42bd3 100644 --- a/Config/Provider/Webshop.php +++ b/Config/Provider/Webshop.php @@ -59,11 +59,17 @@ class Webshop extends AbstractConfigProvider const XPATH_ADDRESS_CHECK_ENABLED = 'tig_postnl/addresscheck/enable_postcodecheck'; const XPATH_ADDRESS_CHECK_COMPATIBLE = 'tig_postnl/addresscheck/checkout_compatible'; + const XPATH_POSTCODE_ADDRESS_CHECK_ENABLED = 'tig_postcode/configuration/modus'; + /** * @return bool */ public function getIsAddressCheckEnabled() { + if ($this->getConfigFromXpath(self::XPATH_POSTCODE_ADDRESS_CHECK_ENABLED)) { + return false; + } + return $this->getConfigFromXpath(self::XPATH_ADDRESS_CHECK_ENABLED); } @@ -133,11 +139,10 @@ public function getCutOffTimeForDay($day) { switch ($day) { case '7': - case '0': return $this->getSundayCutOffTime(); case '6': return $this->getSaturdayCutOffTime(); - default : + default: return $this->getCutOffTime(); } } diff --git a/Config/Source/Options/DefaultOptions.php b/Config/Source/Options/DefaultOptions.php index 70e4d1a11..9088e9bce 100644 --- a/Config/Source/Options/DefaultOptions.php +++ b/Config/Source/Options/DefaultOptions.php @@ -34,6 +34,11 @@ use Magento\Framework\Option\ArrayInterface; use TIG\PostNL\Config\Provider\ShippingOptions; +/** + * @todo we need to move the getOption-methods to the ProductOptions class without + * creating a circular dependency. For now we allow CS to ignore this file. + */ +// @codingStandardsIgnoreFile class DefaultOptions implements ArrayInterface { /** @@ -79,7 +84,7 @@ public function toOptionArray() $flags['groups'][] = ['group' => 'eps_package_options']; } - return $this->productOptions->getProductoptions($flags); + return $this->productOptions->getProductOptions($flags); } /** @@ -87,22 +92,11 @@ public function toOptionArray() */ public function getBeProducts() { - $epsBusinessOptions = []; - if ($this->shippingOptions->canUseEpsBusinessProducts()) { - $epsBusinessOptions = $this->productOptions->getProductoptions( - ['isEvening' => false, 'group' => 'eps_package_options'] - ); - } - - $cargoProducts = []; - if ($this->shippingOptions->canUseCargoProducts()) { - $cargoProducts = $this->productOptions->getProductoptions( - ['countryLimitation' => 'BE', 'group' => 'cargo_options'] - ); - } - - $epsBusinessOptions = array_merge($epsBusinessOptions, $cargoProducts); - return array_merge($this->productOptions->getProductoptions(['group' => 'eu_options']), $epsBusinessOptions); + $beProducts[] = $this->shippingOptions->canUseEpsBusinessProducts() ? $this->productOptions->getEpsBusinessOptions() : []; + $beProducts[] = $this->shippingOptions->canUseCargoProducts() ? $this->productOptions->getCargoOptions() : []; + $beProducts[] = $this->productOptions->getEuOptions(); + + return call_user_func_array("array_merge", $beProducts); } /** @@ -110,18 +104,22 @@ public function getBeProducts() */ public function getEpsProducts() { - $epsOptions = $this->productOptions->getProductoptions( - ['isEvening' => false, 'countryLimitation' => false, 'group' => 'eu_options'] - ); - - $epsBusinessOptions = []; - if ($this->shippingOptions->canUseEpsBusinessProducts()) { - $epsBusinessOptions = $this->productOptions->getProductoptions( - ['isEvening' => false, 'countryLimitation' => false, 'group' => 'eps_package_options'] - ); - } + $epsProducts[] = $this->shippingOptions->canUsePriority() ? $this->productOptions->getPriorityOptions() : []; + $epsProducts[] = $this->shippingOptions->canUseEpsBusinessProducts() ? $this->productOptions->getEpsBusinessOptions() : []; + $epsProducts[] = $this->productOptions->getEpsOptions(); + + return call_user_func_array("array_merge", $epsProducts); + } + + /** + * @return array + */ + public function getGlobalProducts() + { + $globalProducts[] = $this->shippingOptions->canUsePriority() ? $this->productOptions->getPriorityOptions() : []; + $globalProducts[] = $this->productOptions->getGlobalPackOptions(); - return array_merge($epsOptions, $epsBusinessOptions); + return call_user_func_array("array_merge", $globalProducts); } /** @@ -147,12 +145,12 @@ public function getEveningOptionsBE() */ public function getEveningOptions($country = 'NL') { - $options = $this->productOptions->getProductoptions(['isEvening' => true, 'countryLimitation' => $country]); + $options = $this->productOptions->getProductOptions(['isEvening' => true, 'countryLimitation' => $country]); if ($this->shippingOptions->isIDCheckActive()) { return $options; } - $idOptions = $this->productOptions->getProductoptions( + $idOptions = $this->productOptions->getProductOptions( ['group' => 'id_check_options', 'countryLimitation' => $country] ); diff --git a/Config/Source/Options/ProductOptions.php b/Config/Source/Options/ProductOptions.php index 22b06cc9a..c27bf21a7 100644 --- a/Config/Source/Options/ProductOptions.php +++ b/Config/Source/Options/ProductOptions.php @@ -104,7 +104,7 @@ public function toOptionArray() */ public function getIsSundayOptions() { - return $this->getProductoptions(['isSunday' => true]); + return $this->getProductOptions(['isSunday' => true]); } /** @@ -116,7 +116,7 @@ public function getPakjeGemakOptions() $flags = []; $flags['groups'][] = ['group' => 'pakjegemak_options']; $flags['groups'][] = ['group' => 'id_check_pakjegemak_options']; - return $this->getProductoptions($flags); + return $this->getProductOptions($flags); } /** @@ -125,7 +125,7 @@ public function getPakjeGemakOptions() */ public function getPakjeGemakEarlyDeliveryOptions() { - return $this->getProductoptions(['pge' => true]); + return $this->getProductOptions(['pge' => true]); } /** @@ -139,7 +139,7 @@ public function getDefaultOptions() $flags['groups'][] = ['group' => 'id_check_options']; $flags['groups'][] = ['group' => 'cargo_options']; - return $this->getProductoptions($flags); + return $this->getProductOptions($flags); } /** @@ -147,7 +147,7 @@ public function getDefaultOptions() */ public function getExtraCoverProductOptions() { - return $this->getProductoptions(['isExtraCover' => true]); + return $this->getProductOptions(['isExtraCover' => true]); } /** @@ -160,7 +160,53 @@ public function getEpsProductOptions($address = false) if ($address && $address->getCountryId() === 'ES' && $this->canaryConverter->isCanaryIsland($address)) { return $this->getGlobalPackOptions(); } - return $this->getProductoptions(['isEvening' => false, 'countryLimitation' => false, 'group' => 'eu_options']); + return $this->getProductOptions(['isEvening' => false, 'countryLimitation' => false, 'group' => 'eu_options']); + } + + /** + * @return array + */ + public function getEuOptions() + { + $euOptions = $this->getProductOptions(['group' => 'eu_options']); + + return $euOptions; + } + + /** + * @return array + */ + public function getEpsOptions() + { + $epsOptions = $this->getProductOptions( + ['isEvening' => false, 'countryLimitation' => false, 'group' => 'eu_options'] + ); + return $epsOptions; + } + + /** + * @return array + */ + public function getPriorityOptions() + { + $priorityOptions = $this->getProductOptions(['group' => 'priority_options']); + + return $priorityOptions; + } + + /** + * @return array + */ + public function getEpsBusinessOptions() + { + $epsBusinessOptions = $this->getProductOptions( + [ + 'isEvening' => false, + 'group' => 'eps_package_options' + ] + ); + + return $epsBusinessOptions; } /** @@ -168,7 +214,7 @@ public function getEpsProductOptions($address = false) */ public function getGlobalPackOptions() { - return $this->getProductoptions(['group' => 'global_options']); + return $this->getProductOptions(['group' => 'global_options']); } /** @@ -176,7 +222,37 @@ public function getGlobalPackOptions() */ public function getExtraAtHomeOptions() { - return $this->getProductoptions(['group' => 'extra_at_home_options']); + return $this->getProductOptions(['group' => 'extra_at_home_options']); + } + + /** + * @return array + */ + public function getDefaultGPOption() + { + $productOptions = $this->getProductOptions(['isDefault' => 1, 'group' => 'global_options']); + return array_shift($productOptions); + } + + /** + * @return array + */ + public function getDefaultEUOption() + { + $productOptions = $this->getProductOptions(['isDefault' => 1, 'group' => 'eu_options']); + return array_shift($productOptions); + } + + /** + * @return array + */ + public function getCargoOptions() + { + $cargoProducts = $this->getProductOptions( + ['countryLimitation' => 'BE', 'group' => 'cargo_options'] + ); + + return $cargoProducts; } /** diff --git a/Config/Source/OptionsAbstract.php b/Config/Source/OptionsAbstract.php index c904436ca..9e5ce07ad 100644 --- a/Config/Source/OptionsAbstract.php +++ b/Config/Source/OptionsAbstract.php @@ -188,6 +188,7 @@ abstract class OptionsAbstract '4952' => [ 'value' => '4952', 'label' => 'EU Pack Special Consumer', + 'isDefault' => 1, 'isEvening' => false, 'isExtraCover' => false, 'isSunday' => false, @@ -239,6 +240,7 @@ abstract class OptionsAbstract '4945' => [ 'value' => '4945', 'label' => 'GlobalPack', + 'isDefault' => 1, 'isEvening' => false, 'isExtraCover' => false, 'isSunday' => false, @@ -594,32 +596,75 @@ abstract class OptionsAbstract 'countryLimitation' => false, 'group' => 'eps_package_options', ], + // Priority Products + '6350' => [ + 'value' => '6350', + 'label' => 'Priority packets tracked', + 'isExtraCover' => false, + 'isEvening' => false, + 'isSunday' => false, + 'isGuaranteedDelivery' => false, + 'countryLimitation' => false, + 'group' => 'priority_options', + ], + '6550' => [ + 'value' => '6550', + 'label' => 'Priority packets tracked bulk', + 'isExtraCover' => false, + 'isEvening' => false, + 'isSunday' => false, + 'isGuaranteedDelivery' => false, + 'countryLimitation' => false, + 'group' => 'priority_options', + ], + '6940' => [ + 'value' => '6940', + 'label' => 'Priority packets tracked sorted', + 'isExtraCover' => false, + 'isEvening' => false, + 'isSunday' => false, + 'isGuaranteedDelivery' => false, + 'countryLimitation' => false, + 'group' => 'priority_options', + ], + '6942' => [ + 'value' => '6942', + 'label' => 'Priority packets tracked boxable', + 'isExtraCover' => false, + 'isEvening' => false, + 'isSunday' => false, + 'isGuaranteedDelivery' => false, + 'countryLimitation' => false, + 'group' => 'priority_options', + ] ]; protected $groups = [ - 'standard_options' => 'Domestic options', - 'pakjegemak_options' => 'Post Office options', - 'eu_options' => 'EU options', - 'global_options' => 'Global options', - 'buspakje_options' => 'Letter Box Parcel options', - 'extra_at_home_options' => 'Extra@Home options', - 'id_check_options' => 'ID Check options', - 'id_check_pakjegemak_options' => 'ID Check Post Office options', - 'cargo_options' => 'Cargo options', - 'eps_package_options' => 'Package options' + 'standard_options' => 'Domestic options', + 'pakjegemak_options' => 'Post Office options', + 'eu_options' => 'EU options', + 'global_options' => 'Global options', + 'buspakje_options' => 'Letter Box Parcel options', + 'extra_at_home_options' => 'Extra@Home options', + 'id_check_options' => 'ID Check options', + 'id_check_pakjegemak_options' => 'ID Check Post Office options', + 'cargo_options' => 'Cargo options', + 'eps_package_options' => 'Package options', + 'priority_options' => 'Priority EPS' ]; - - protected $groupToLabel = [ - 'standard_options' => 'Domestic', - 'pakjegemak_options' => 'Post Office', - 'eu_options' => 'EPS', - 'global_options' => 'Global Pack', - 'buspakje_options' => 'Letter Box', - 'extra_at_home_options' => 'Extra@Home', - 'id_check_options' => 'ID Check', - 'id_check_pakjegemak_options' => 'ID Check Post Office', - 'cargo_options' => 'Cargo', - 'eps_package_options' => 'Package' + + protected $groupToLabel = [ + 'standard_options' => 'Domestic', + 'pakjegemak_options' => 'Post Office', + 'eu_options' => 'EPS', + 'global_options' => 'Global Pack', + 'buspakje_options' => 'Letter Box', + 'extra_at_home_options' => 'Extra@Home', + 'id_check_options' => 'ID Check', + 'id_check_pakjegemak_options' => 'ID Check Post Office', + 'cargo_options' => 'Cargo', + 'eps_package_options' => 'Package', + 'priority_options' => 'Priority (EPS / Globalpack)' ]; protected $typeToComment = [ @@ -635,9 +680,9 @@ abstract class OptionsAbstract ]; /** - * Property for filterd product options matched by account type and flags. + * Property for filtered product options matched by account type and flags. */ - private $filterdOptions; + private $filteredOptions; /** * Group options by group types @@ -657,10 +702,10 @@ public function get() * * @return array $availableOptions */ - public function getProductoptions($flags = false) + public function getProductOptions($flags = false) { if (false !== $flags && is_array($flags)) { - $this->setFilterdOptions($flags); + $this->setFilteredOptions($flags); } return $this->getOptionArrayUsableForConfiguration(); @@ -671,9 +716,9 @@ public function getProductoptions($flags = false) * * @codingStandardsIgnoreLine */ - public function setFilterdOptions($flags) + public function setFilteredOptions($flags) { - $this->filterdOptions = []; + $this->filteredOptions = []; // Filter availableOptions on flags foreach ($this->availableOptions as $key => $option) { @@ -700,7 +745,7 @@ public function setOptionsByFlagFilters($flags, $option, $productCode) }, \Zend\Stdlib\ArrayUtils::ARRAY_FILTER_USE_BOTH); if (count($filterFlags) == count($flags)) { - $this->filterdOptions[$productCode] = $this->availableOptions[$productCode]; + $this->filteredOptions[$productCode] = $this->availableOptions[$productCode]; } } @@ -720,7 +765,7 @@ public function setOptionsByMultipleFlagFilters($flags, $option, $productCode) }, \Zend\Stdlib\ArrayUtils::ARRAY_FILTER_USE_BOTH); if (count($filterFlags) == count($flags)) { - $this->filterdOptions[$productCode] = $this->availableOptions[$productCode]; + $this->filteredOptions[$productCode] = $this->availableOptions[$productCode]; } } } @@ -730,13 +775,13 @@ public function setOptionsByMultipleFlagFilters($flags, $option, $productCode) */ public function getOptionArrayUsableForConfiguration() { - if (count($this->filterdOptions) == 0) { + if (count($this->filteredOptions) == 0) { // @codingStandardsIgnoreLine return [['value' => 0, 'label' => __('There are no available options')]]; } $options = []; - foreach ($this->filterdOptions as $key => $option) { + foreach ($this->filteredOptions as $key => $option) { // @codingStandardsIgnoreLine $options[] = ['value' => $option['value'], 'label' => __($option['label'])]; } diff --git a/Controller/Adminhtml/LabelAbstract.php b/Controller/Adminhtml/LabelAbstract.php index 071152113..a5879b09b 100644 --- a/Controller/Adminhtml/LabelAbstract.php +++ b/Controller/Adminhtml/LabelAbstract.php @@ -118,6 +118,9 @@ public function __construct( protected function setLabel($shipmentId) { $labels = $this->getLabels->get($shipmentId); + if (isset($labels['errors'])) { + $this->handleRequestErrors($labels['errors']); + } if (empty($labels)) { return; @@ -135,6 +138,10 @@ protected function setLabel($shipmentId) protected function setPackingslip($shipmentId, $withLabels = true, $confirm = true) { $packingslip = $this->getPackingSlip->get($shipmentId, $withLabels, $confirm); + if (is_array($packingslip) && isset($packingslip['errors'])) { + $this->handleRequestErrors($packingslip['errors']); + return; + } if (strlen($packingslip) <= 0) { return; @@ -153,4 +160,15 @@ protected function setTracks($shipment) $this->track->set($shipment); } } + + /** + * @param $errors + */ + //@codingStandardsIgnoreLine + protected function handleRequestErrors($errors) + { + foreach ($errors as $error) { + $this->messageManager->addWarningMessage($error); + } + } } diff --git a/Controller/Adminhtml/PdfDownload.php b/Controller/Adminhtml/PdfDownload.php index f836d478a..98ea2bfcd 100644 --- a/Controller/Adminhtml/PdfDownload.php +++ b/Controller/Adminhtml/PdfDownload.php @@ -40,7 +40,7 @@ use TIG\PostNL\Service\Shipment\Label\Generate as LabelGenerate; use TIG\PostNL\Service\Shipment\Packingslip\Generate as PackingslipGenerate; use TIG\PostNL\Service\Shipment\ShipmentService as Shipment; -use TIG\PostNL\Service\Order\ProductCodeAndType; +use TIG\PostNL\Service\Order\ProductInfo; // @codingStandardsIgnoreFile class PdfDownload @@ -154,8 +154,13 @@ public function get($labels, $filename = 'ShippingLabels') private function filterLabel($labels) { return array_filter($labels, function ($label) { + + if (is_array($label)) { + return false; + } + /** @var ShipmentLabelInterface $label */ - if (strtoupper($label->getType()) == ProductCodeAndType::SHIPMENT_TYPE_GP) { + if (strtoupper($label->getType()) == ProductInfo::SHIPMENT_TYPE_GP) { $this->filteredLabels[] = $label->getParentId(); return false; } diff --git a/Controller/Adminhtml/Shipment/ConfirmAndPrintShippingLabel.php b/Controller/Adminhtml/Shipment/ConfirmAndPrintShippingLabel.php index 89ac1f306..9751b57c7 100644 --- a/Controller/Adminhtml/Shipment/ConfirmAndPrintShippingLabel.php +++ b/Controller/Adminhtml/Shipment/ConfirmAndPrintShippingLabel.php @@ -93,6 +93,9 @@ public function __construct( public function execute() { $labels = $this->getLabels(); + if (isset($labels['errors'])) { + $this->handleRequestErrors($labels['errors']); + } if (empty($labels)) { $this->messageManager->addErrorMessage( diff --git a/Controller/Adminhtml/Shipment/ConfirmShipping.php b/Controller/Adminhtml/Shipment/ConfirmShipping.php index 70c39f563..083764cd9 100644 --- a/Controller/Adminhtml/Shipment/ConfirmShipping.php +++ b/Controller/Adminhtml/Shipment/ConfirmShipping.php @@ -104,7 +104,7 @@ public function execute() $this->setConfirmedAt($shipmentId); $this->setTrack($shipmentId); - $this->messageManager->addComplexSuccessMessage( + $this->messageManager->addSuccessMessage( // @codingStandardsIgnoreLine __('Shipment successfully confirmed')->getText() ); @@ -123,7 +123,7 @@ private function confirm() } catch (Exception $exception) { $this->messageManager->addErrorMessage( // @codingStandardsIgnoreLine - __('Could not confirm shipment : %1', $exception->getLogMessage())->getText() + __('Could not confirm shipment: %1', $exception->getLogMessage())->getText() ); return $this->_redirect($this->_redirect->getRefererUrl()); } diff --git a/Controller/Adminhtml/Shipment/PrintShippingLabel.php b/Controller/Adminhtml/Shipment/PrintShippingLabel.php index 878b3e6de..9a76fe3d1 100644 --- a/Controller/Adminhtml/Shipment/PrintShippingLabel.php +++ b/Controller/Adminhtml/Shipment/PrintShippingLabel.php @@ -85,6 +85,9 @@ public function __construct( public function execute() { $labels = $this->getLabels(); + if (isset($labels['errors'])) { + $this->handleRequestErrors($labels['errors']); + } if (empty($labels)) { $this->messageManager->addErrorMessage( diff --git a/Controller/DeliveryOptions/Save.php b/Controller/DeliveryOptions/Save.php index 0b4050872..54365edca 100644 --- a/Controller/DeliveryOptions/Save.php +++ b/Controller/DeliveryOptions/Save.php @@ -146,7 +146,8 @@ private function saveDeliveryOption($params) */ private function addSessionDataToParams($params) { - if (!isset($params['date']) && $params['type'] == 'pickup') { + if (!isset($params['date']) && $params['type'] == 'pickup' + || !isset($params['date']) && $params['type'] == 'fallback') { $params['date'] = $this->checkoutSession->getPostNLDeliveryDate(); } diff --git a/Controller/DeliveryOptions/Timeframes.php b/Controller/DeliveryOptions/Timeframes.php index 6f978a9a8..2b82b7be7 100644 --- a/Controller/DeliveryOptions/Timeframes.php +++ b/Controller/DeliveryOptions/Timeframes.php @@ -132,7 +132,7 @@ public function execute() * * @return array|\Magento\Framework\Phrase */ - private function getPosibleDeliveryDays($address) + private function getPossibleDeliveryDays($address) { $startDate = $this->getDeliveryDay($address); @@ -158,7 +158,7 @@ private function getValidResponeType($price) return [ 'price' => $price, - 'timeframes' => $this->getPosibleDeliveryDays($address) + 'timeframes' => $this->getPossibleDeliveryDays($address) ]; } diff --git a/Helper/Data.php b/Helper/Data.php index c08098fc5..7d47fcd0c 100644 --- a/Helper/Data.php +++ b/Helper/Data.php @@ -150,12 +150,30 @@ public function getDayOrWeekNumber($date, $format = 'w') } if ($format === 'w') { - return $number % 7; + return $this->formatDayNumber($number); } return $number; } + /** + * Make sure that day 7 (Sunday) is actually returned as 7 rather than 0 + * + * @param $number + * + * @return int + */ + private function formatDayNumber($number) + { + $formattedNumber = $number % 7; + + if ($formattedNumber == 0) { + $formattedNumber = 7; + } + + return $formattedNumber; + } + /** * @return bool|string */ diff --git a/Helper/DeliveryOptions/OrderParams.php b/Helper/DeliveryOptions/OrderParams.php index 7a323acb8..0408d04a9 100644 --- a/Helper/DeliveryOptions/OrderParams.php +++ b/Helper/DeliveryOptions/OrderParams.php @@ -29,47 +29,57 @@ * @copyright Copyright (c) Total Internet Group B.V. https://tig.nl/copyright * @license http://creativecommons.org/licenses/by-nc-nd/3.0/nl/deed.en_US */ + +// @codingStandardsIgnoreFile namespace TIG\PostNL\Helper\DeliveryOptions; use TIG\PostNL\Exception as PostnlException; use TIG\PostNL\Service\Order\FeeCalculator; -use TIG\PostNL\Service\Order\ProductCodeAndType; +use TIG\PostNL\Service\Order\ProductInfo; use TIG\PostNL\Service\Shipment\ProductOptions; class OrderParams { private $optionParams = [ 'quote_id' => [ - 'pickup' => true, - 'delivery' => true + 'pickup' => true, + 'delivery' => true, + 'fallback' => false ], 'delivery_date' => [ - 'pickup' => true, - 'delivery' => true + 'pickup' => true, + 'delivery' => true, + 'fallback' => true ], 'expected_delivery_time_start' => [ - 'pickup' => false, - 'delivery' => true + 'pickup' => false, + 'delivery' => true, + 'fallback' => false ], 'expected_delivery_time_end' => [ - 'pickup' => false, - 'delivery' => true + 'pickup' => false, + 'delivery' => true, + 'fallback' => false ], 'is_pakjegemak' => [ - 'pickup' => true, - 'delivery' => false + 'pickup' => true, + 'delivery' => false, + 'fallback' => false ], 'pg_location_code' => [ - 'pickup' => true, - 'delivery' => false + 'pickup' => true, + 'delivery' => false, + 'fallback' => false ], 'pg_retail_network_id' => [ - 'pickup' => true, - 'delivery' => false + 'pickup' => true, + 'delivery' => false, + 'fallback' => false ], 'pg_address' => [ - 'pickup' => true, - 'delivery' => false + 'pickup' => true, + 'delivery' => false, + 'fallback' => false ] ]; /** @@ -78,30 +88,30 @@ class OrderParams private $feeCalculator; /** - * @var ProductCodeAndType + * @var ProductInfo */ - private $productCodeAndType; + private $productInfo; /** * @var ProductOptions */ private $productOptions; - + /** - * @param FeeCalculator $feeCalculator - * @param ProductCodeAndType $productCodeAndType + * @param FeeCalculator $feeCalculator + * @param ProductInfo $productInfo * @param ProductOptions $productOptions */ public function __construct( FeeCalculator $feeCalculator, - ProductCodeAndType $productCodeAndType, + ProductInfo $productInfo, ProductOptions $productOptions ) { - $this->feeCalculator = $feeCalculator; - $this->productCodeAndType = $productCodeAndType; - $this->productOptions = $productOptions; + $this->feeCalculator = $feeCalculator; + $this->productInfo = $productInfo; + $this->productOptions = $productOptions; } - + /** * @param $params * @@ -114,19 +124,17 @@ public function get($params) $params = $this->formatParamData($params); $params = array_merge($params, $this->getAcInformation($params)); $requiredOrderParams = $this->requiredOrderParamsMissing($type, $params); - + if (!empty($requiredOrderParams)) { throw new PostnlException( - // @codingStandardsIgnoreLine // @todo POSTNL-XXX toevoegen - // @codingStandardsIgnoreLine - __('Missing required parameters: %1', implode(', ',$requiredOrderParams)) + __('Missing required parameters: %1', implode(', ', $requiredOrderParams)) ); } - + return $params; } - + /** * @param string $type * @param array $params @@ -136,15 +144,16 @@ public function get($params) private function requiredOrderParamsMissing($type, $params) { $requiredList = $this->setRequiredList($type); - + $missing = array_filter($requiredList, function ($value, $key) use ($params) { $paramValue = isset($params[$key]) && !empty($params[$key]) ? $params[$key] : false; + return !$paramValue && true == $value; }, \Zend\Stdlib\ArrayUtils::ARRAY_FILTER_USE_BOTH); - + return array_keys($missing); } - + /** * @param $type * @@ -156,10 +165,10 @@ private function setRequiredList($type) foreach ($this->optionParams as $key => $value) { $list[$key] = $value[$type]; } - + return $list; } - + /** * If you want to store the param inside the tig_postnl_order table, * you need to give the keys the same name as the column names. @@ -167,11 +176,13 @@ private function setRequiredList($type) * @param $params * * @return array + * @throws PostnlException */ private function formatParamData($params) { - $productInfo = $this->productCodeAndType->get($params['type'], $params['option'], $params['country']); - + $option = isset($params['option']) ? $params['option'] : 'Daytime'; + $productInfo = $this->productInfo->get($params['type'], $option, $params['country']); + return [ 'quote_id' => isset($params['quote_id']) ? $params['quote_id'] : '', 'delivery_date' => isset($params['date']) ? $params['date'] : '', @@ -181,17 +192,18 @@ private function formatParamData($params) 'pg_location_code' => isset($params['LocationCode']) ? $params['LocationCode'] : '', 'pg_retail_network_id' => isset($params['RetailNetworkID']) ? $params['RetailNetworkID'] : '', 'pg_address' => $this->addExtraToAddress($params), - 'type' => $params['option'], + 'type' => $option, 'opening_hours' => isset($params['OpeningHours']) ? $params['OpeningHours'] : '', 'fee' => $this->feeCalculator->get($params), 'product_code' => $productInfo['code'], ]; } - + /** - * Get the AgentCodes for specifiec type consignments + * Get the AgentCodes for specific type consignments * * formatParamData + * * @param $params * * @return array @@ -202,13 +214,13 @@ private function getAcInformation($params) if (!$acOptions) { return []; } - + return [ 'ac_characteristic' => $acOptions['Characteristic'], 'ac_option' => $acOptions['Option'] ]; } - + /** * @param $params * @@ -220,18 +232,21 @@ private function addExtraToAddress($params) if (!isset($params['address'])) { return false; } - + + if ($params['type'] == 'fallback') { + $params['customerData'] = $params['address']; + } + $params['address']['Name'] = isset($params['name']) ? $params['name'] : ''; - - if (!isset($params['customerData'])) { + + if ($params['type'] == ProductInfo::TYPE_PICKUP && !isset($params['customerData'])) { throw new PostnlException( - // @codingStandardsIgnoreLine - __('Missing required parameters : customerData') + __('Missing required parameters: customerData') ); } - - $params['address']['customer'] = $params['customerData']; - + + $params['address']['customer'] = isset($params['customerData']) ? $params['customerData'] : $params['address']; + return $params['address']; } } diff --git a/Helper/Tracking/Mail.php b/Helper/Tracking/Mail.php index d1fa1bc9f..5dd65344e 100644 --- a/Helper/Tracking/Mail.php +++ b/Helper/Tracking/Mail.php @@ -31,19 +31,19 @@ */ namespace TIG\PostNL\Helper\Tracking; -use TIG\PostNL\Helper\AbstractTracking; -use TIG\PostNL\Helper\Data as PostNLHelper; -use TIG\PostNL\Model\ShipmentRepository as PostNLShipmentRepository; -use TIG\PostNL\Config\Provider\Webshop; -use TIG\PostNL\Logging\Log; +use Magento\Framework\Api\SearchCriteriaBuilder; use Magento\Framework\App\Helper\Context; -use Magento\Framework\Mail\Template\TransportBuilder; use Magento\Framework\Exception\LocalizedException; -use Magento\Framework\Api\SearchCriteriaBuilder; -use Magento\Framework\Mail\TransportInterface; use Magento\Framework\Exception\MailException; -use Magento\Sales\Model\Order\Shipment; +use Magento\Framework\Mail\Template\TransportBuilder; +use Magento\Framework\Mail\TransportInterface; use Magento\Framework\View\Asset\Repository as AssetRepository; +use Magento\Sales\Model\Order\Shipment; +use TIG\PostNL\Config\Provider\Webshop; +use TIG\PostNL\Helper\AbstractTracking; +use TIG\PostNL\Helper\Data as PostNLHelper; +use TIG\PostNL\Logging\Log; +use TIG\PostNL\Model\ShipmentRepository as PostNLShipmentRepository; class Mail extends AbstractTracking { @@ -69,8 +69,8 @@ class Mail extends AbstractTracking /** * @param Context $context - * @param SearchCriteriaBuilder $searchCriteriaBuilder * @param PostNLShipmentRepository $postNLShipmentRepository + * @param SearchCriteriaBuilder $searchCriteriaBuilder * @param TransportBuilder $transportBuilder * @param PostNLHelper $data * @param Webshop $webshop @@ -115,8 +115,10 @@ public function send() /** * @param Shipment $shipment - * @param string $url + * @param string $url * + * @throws LocalizedException + * @throws MailException */ // @codingStandardsIgnoreStart public function set($shipment, $url) @@ -135,10 +137,14 @@ public function set($shipment, $url) ); $transport->setFrom('general'); + if (method_exists($transport, 'setFromByScope')) { + $transport->setFromByScope('general', $shipment->getStoreId()); + } + $address = $shipment->getShippingAddress(); - $transport->addTo($address->getEmail(), $address->getFirstname() . ' '. $address->getLastname()); + $transport->addTo($address->getEmail(), $address->getFirstname() . ' ' . $address->getLastname()); $transport = $this->addBccEmail($transport); - $this->logging->addInfo('Track And Trace email build for :'. $address->getEmail()); + $this->logging->addInfo('Track And Trace email build for :' . $address->getEmail()); $this->trackAndTraceEmail = $transport->getTransport(); } // @codingStandardsIgnoreEnd diff --git a/Model/Shipment.php b/Model/Shipment.php index ac07a0059..19c9f88dd 100644 --- a/Model/Shipment.php +++ b/Model/Shipment.php @@ -67,6 +67,8 @@ class Shipment extends AbstractModel implements ShipmentInterface, IdentityInter const FIELD_SHIPMENT_TYPE = 'shipment_type'; + const FIELD_SHIPMENT_COUNTRY = 'shipment_country'; + const FIELD_AC_CHARACTERISTIC = 'ac_characteristic'; const FIELD_AC_OPTION = 'ac_option'; @@ -445,6 +447,24 @@ public function getShipmentType() return $this->getData(static::FIELD_SHIPMENT_TYPE); } + /** + * @return string + */ + public function getShipmentCountry() + { + return $this->getData(static::FIELD_SHIPMENT_COUNTRY); + } + + /** + * @param $value + * + * @return \TIG\PostNL\Api\Data\ShipmentInterface + */ + public function setShipmentCountry($value) + { + return $this->setData(static::FIELD_SHIPMENT_COUNTRY, $value); + } + /** * @param $value * diff --git a/Observer/SalesOrderSaveAfter/CreatePostNLOrder.php b/Observer/SalesOrderSaveAfter/CreatePostNLOrder.php index 06933ee66..8d952ec2d 100644 --- a/Observer/SalesOrderSaveAfter/CreatePostNLOrder.php +++ b/Observer/SalesOrderSaveAfter/CreatePostNLOrder.php @@ -35,7 +35,7 @@ use TIG\PostNL\Api\Data\OrderInterface; use TIG\PostNL\Helper\Data; use TIG\PostNL\Model\OrderRepository; -use TIG\PostNL\Service\Order\ProductCodeAndType; +use TIG\PostNL\Service\Order\ProductInfo; use Magento\Framework\Event\Observer; use Magento\Framework\Event\ObserverInterface; use Magento\Sales\Model\Order as MagentoOrder; @@ -60,9 +60,9 @@ class CreatePostNLOrder implements ObserverInterface private $helper; /** - * @var ProductCodeAndType + * @var ProductInfo */ - private $productCode; + private $productInfo; /** * @var ItemsToOption @@ -70,24 +70,24 @@ class CreatePostNLOrder implements ObserverInterface private $itemsToOption; /** - * @param OrderRepository $orderRepository - * @param ParcelCount $count - * @param ItemsToOption $itemsToOption - * @param ProductCodeAndType $productCode - * @param Data $helper + * @param OrderRepository $orderRepository + * @param ParcelCount $count + * @param ItemsToOption $itemsToOption + * @param ProductInfo $productInfo + * @param Data $helper */ public function __construct( OrderRepository $orderRepository, ParcelCount $count, ItemsToOption $itemsToOption, - ProductCodeAndType $productCode, + ProductInfo $productInfo, Data $helper ) { $this->orderRepository = $orderRepository; - $this->parcelCount = $count; - $this->itemsToOption = $itemsToOption; - $this->helper = $helper; - $this->productCode = $productCode; + $this->parcelCount = $count; + $this->itemsToOption = $itemsToOption; + $this->helper = $helper; + $this->productInfo = $productInfo; } /** @@ -178,12 +178,12 @@ private function setProductCode(OrderInterface $postnlOrder, MagentoOrder $magen { /** * If the product code is not set by the user then calculate it and save it also. It is possible that it is not - * set because the deliveryoptions are disabled or this is an EPS shipment. + * set because the delivery options are disabled or this is an EPS shipment. */ if (!$postnlOrder->getProductCode()) { $option = $this->itemsToOption->get($magentoOrder->getItems()); $shippingAddress = $magentoOrder->getShippingAddress(); - $productInfo = $this->productCode->get('', $option, $shippingAddress); + $productInfo = $this->productInfo->get('', $option, $shippingAddress); $postnlOrder->setProductCode($productInfo['code']); $postnlOrder->setType($productInfo['type']); } diff --git a/Observer/TIGPostNLOrderSaveBefore/SetDefaultData.php b/Observer/TIGPostNLOrderSaveBefore/SetDefaultData.php index a093767cd..100e19a1b 100644 --- a/Observer/TIGPostNLOrderSaveBefore/SetDefaultData.php +++ b/Observer/TIGPostNLOrderSaveBefore/SetDefaultData.php @@ -34,7 +34,7 @@ use TIG\PostNL\Api\Data\OrderInterface; use TIG\PostNL\Logging\Log; use TIG\PostNL\Service\Order\ShipAt; -use TIG\PostNL\Service\Order\ProductCodeAndType; +use TIG\PostNL\Service\Order\ProductInfo; use TIG\PostNL\Service\Order\FirstDeliveryDate; use TIG\PostNL\Service\Options\ItemsToOption; use TIG\PostNL\Service\Order\MagentoOrder; @@ -46,9 +46,9 @@ class SetDefaultData implements ObserverInterface { /** - * @var ProductCodeAndType + * @var ProductInfo */ - private $productCodeAndType; + private $productInfo; /** * @var FirstDeliveryDate @@ -84,22 +84,22 @@ class SetDefaultData implements ObserverInterface * @var array */ private $shouldUpdateByOption = [ - ProductCodeAndType::OPTION_EXTRAATHOME + ProductInfo::OPTION_EXTRAATHOME ]; /** * SetDefaultData constructor. * - * @param ProductCodeAndType $productCodeAndType - * @param FirstDeliveryDate $firstDeliveryDate - * @param ShipAt $shipAt - * @param Log $log - * @param ItemsToOption $itemsToOption - * @param MagentoOrder $magentoOrder - * @param ShippingDuration $shippingDuration + * @param ProductInfo $productInfo + * @param FirstDeliveryDate $firstDeliveryDate + * @param ShipAt $shipAt + * @param Log $log + * @param ItemsToOption $itemsToOption + * @param MagentoOrder $magentoOrder + * @param ShippingDuration $shippingDuration */ public function __construct( - ProductCodeAndType $productCodeAndType, + ProductInfo $productInfo, FirstDeliveryDate $firstDeliveryDate, ShipAt $shipAt, Log $log, @@ -107,13 +107,13 @@ public function __construct( MagentoOrder $magentoOrder, ShippingDuration $shippingDuration ) { - $this->productCodeAndType = $productCodeAndType; - $this->firstDeliveryDate = $firstDeliveryDate; - $this->shipAt = $shipAt; - $this->log = $log; - $this->itemsToOption = $itemsToOption; - $this->magentoOrder = $magentoOrder; - $this->shippingDuration = $shippingDuration; + $this->productInfo = $productInfo; + $this->firstDeliveryDate = $firstDeliveryDate; + $this->shipAt = $shipAt; + $this->log = $log; + $this->itemsToOption = $itemsToOption; + $this->magentoOrder = $magentoOrder; + $this->shippingDuration = $shippingDuration; } /** @@ -132,15 +132,17 @@ public function execute(Observer $observer) $this->log->critical($exception->getTraceAsString()); } } - - /** - * @param $order - */ + + /** + * @param \TIG\PostNL\Api\Data\OrderInterface $order + * + * @throws \Magento\Framework\Exception\NoSuchEntityException + */ private function setData(OrderInterface $order) { $option = $this->getOptionFromQuote(); $address = $this->checkByAddressData($order); - $productInfo = $this->productCodeAndType->get('', $option, $address); + $productInfo = $this->productInfo->get('', $option, $address); $duration = $this->shippingDuration->get(); if (!$order->getProductCode() || $this->canUpdate($order->getProductCode(), $productInfo['code'], $option)) { @@ -200,6 +202,7 @@ private function getOptionFromQuote() */ private function checkByAddressData(OrderInterface $order) { + $address = null; $country = null; /** @noinspection PhpUndefinedMethodInspection */ diff --git a/Plugin/Postcodecheck/LayoutProcessor.php b/Plugin/Postcodecheck/LayoutProcessor.php index d9341f330..bc629f774 100644 --- a/Plugin/Postcodecheck/LayoutProcessor.php +++ b/Plugin/Postcodecheck/LayoutProcessor.php @@ -31,10 +31,11 @@ */ namespace TIG\PostNL\Plugin\Postcodecheck; -use TIG\PostNL\Plugin\Postcodecheck\Fields\Factory; -use TIG\PostNL\Config\Provider\Webshop; use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Store\Model\ScopeInterface; +use TIG\PostNL\Config\Provider\AccountConfiguration; +use TIG\PostNL\Config\Provider\Webshop; +use TIG\PostNL\Plugin\Postcodecheck\Fields\Factory; // @codingStandardsIgnoreFile class LayoutProcessor @@ -43,23 +44,38 @@ class LayoutProcessor * @var Factory */ private $fieldFactory; - + + /** + * @var AccountConfiguration + */ + private $accountConfig; + /** * @var Webshop */ private $webshopConfig; - + /** * @var ScopeConfigInterface */ private $scopeConfig; - + + /** + * LayoutProcessor constructor. + * + * @param Factory $factory + * @param AccountConfiguration $accountConfig + * @param Webshop $webshop + * @param ScopeConfigInterface $scopeConfig + */ public function __construct( Factory $factory, + AccountConfiguration $accountConfig, Webshop $webshop, ScopeConfigInterface $scopeConfig ) { $this->fieldFactory = $factory; + $this->accountConfig = $accountConfig; $this->webshopConfig = $webshop; $this->scopeConfig = $scopeConfig; } @@ -72,7 +88,7 @@ public function __construct( */ public function afterProcess($subject, array $jsLayout) { - if (!$this->webshopConfig->getIsAddressCheckEnabled()) { + if (!$this->webshopConfig->getIsAddressCheckEnabled() || $this->accountConfig->isModusOff()) { return $jsLayout; } diff --git a/Service/Carrier/Price/Calculator.php b/Service/Carrier/Price/Calculator.php index a96e3eb06..cf17ed712 100644 --- a/Service/Carrier/Price/Calculator.php +++ b/Service/Carrier/Price/Calculator.php @@ -177,7 +177,7 @@ private function getTableratePrice(RateRequest $request) return [ 'price' => $ratePrice['price'], - 'cost' => $ratePrice['cost'], + 'cost' => $ratePrice['price'], ]; } diff --git a/Service/Carrier/Price/Tablerate.php b/Service/Carrier/Price/Tablerate.php index 0cb2c2399..3353d69b7 100644 --- a/Service/Carrier/Price/Tablerate.php +++ b/Service/Carrier/Price/Tablerate.php @@ -171,7 +171,7 @@ private function getRate(RateRequest $request) $oldWeight = $request->getPackageWeight(); $oldQty = $request->getPackageQty(); - $request->setPackageWeight($request->getFreeMethodWeight()); + $request->setPackageWeight($request->getFreeMethodWeight() ?: $oldWeight); $request->setPackageQty($oldQty - $this->getFreeBoxes->get($request)); /** @var TablerateModel $tablerate */ diff --git a/Service/Handler/BarcodeHandler.php b/Service/Handler/BarcodeHandler.php index e9ec996de..364b2e87c 100644 --- a/Service/Handler/BarcodeHandler.php +++ b/Service/Handler/BarcodeHandler.php @@ -39,7 +39,9 @@ use TIG\PostNL\Webservices\Endpoints\Barcode as BarcodeEndpoint; use TIG\PostNL\Model\ResourceModel\ShipmentBarcode\CollectionFactory; use \Magento\Framework\Exception\LocalizedException; +use TIG\PostNL\Config\Provider\ProductOptions as ProductOptionsConfiguration; +// @codingStandardsIgnoreFile class BarcodeHandler { /** @@ -62,6 +64,11 @@ class BarcodeHandler */ private $shipmentRepository; + /** + * @var ProductOptionsConfiguration + */ + private $productOptionsConfiguration; + /** * @var string */ @@ -77,17 +84,20 @@ class BarcodeHandler * @param ShipmentRepositoryInterface $shipmentRepository * @param ShipmentBarcodeFactory $shipmentBarcodeFactory * @param CollectionFactory $shipmentBarcodeCollectionFactory + * @param ProductOptionsConfiguration $productOptionsConfiguration */ public function __construct( BarcodeEndpoint $barcodeEndpoint, ShipmentRepositoryInterface $shipmentRepository, ShipmentBarcodeFactory $shipmentBarcodeFactory, - CollectionFactory $shipmentBarcodeCollectionFactory + CollectionFactory $shipmentBarcodeCollectionFactory, + ProductOptionsConfiguration $productOptionsConfiguration ) { $this->barcodeEndpoint = $barcodeEndpoint; $this->shipmentBarcodeCollectionFactory = $shipmentBarcodeCollectionFactory; $this->shipmentBarcodeFactory = $shipmentBarcodeFactory; $this->shipmentRepository = $shipmentRepository; + $this->productOptionsConfiguration = $productOptionsConfiguration; } /** @@ -106,7 +116,7 @@ public function prepareShipment($magentoShipmentId, $countryId) $magentoShipment = $shipment->getShipment(); $this->storeId = $magentoShipment->getStoreId(); - $mainBarcode = $this->generate(); + $mainBarcode = $this->generate($shipment); $shipment->setMainBarcode($mainBarcode); $this->shipmentRepository->save($shipment); @@ -136,7 +146,9 @@ public function addBarcodes(ShipmentInterface $shipment, $mainBarcode) $parcelCount = $shipment->getParcelCount(); for ($count = 2; $count <= $parcelCount; $count++) { - $barcodeModelCollection->addItem($this->createBarcode($shipment->getId(), $count, $this->generate())); + $barcodeModelCollection->addItem( + $this->createBarcode($shipment->getId(), $count, $this->generate($shipment)) + ); } $barcodeModelCollection->save(); @@ -145,13 +157,18 @@ public function addBarcodes(ShipmentInterface $shipment, $mainBarcode) /** * CIF call to generate a new barcode * + * @param ShipmentInterface $shipment + * * @return string * @throws \Magento\Framework\Exception\LocalizedException */ - private function generate() + private function generate(ShipmentInterface $shipment) { + $magentoShipment = $shipment->getShipment(); + $this->barcodeEndpoint->setCountryId($this->countryId); - $this->barcodeEndpoint->setStoreId($this->storeId); + $this->barcodeEndpoint->setStoreId($magentoShipment->getStoreId()); + $this->setTypeByProductCode($shipment->getProductCode()); $response = $this->barcodeEndpoint->call(); if (!is_object($response) || !isset($response->Barcode)) { @@ -164,6 +181,20 @@ private function generate() return (string) $response->Barcode; } + /** + * @param $code + */ + private function setTypeByProductCode($code) + { + if ($this->productOptionsConfiguration->checkProductByFlags($code, 'group', 'priority_options')) { + $this->barcodeEndpoint->setType('PEPS'); + + return; + } + + $this->barcodeEndpoint->setType(''); + } + /** * @param $shipmentId * @param $count diff --git a/Service/Handler/PostcodecheckHandler.php b/Service/Handler/PostcodecheckHandler.php index 5893f5619..ffcbc4aeb 100644 --- a/Service/Handler/PostcodecheckHandler.php +++ b/Service/Handler/PostcodecheckHandler.php @@ -58,8 +58,10 @@ public function __construct( */ public function convertResponse($params) { - if (is_string($params)) { - $params = json_decode($params, true); + $params = $this->formatParams($params); + + if (empty($params)) { + return false; } if (isset($params['errors']) || isset($params['fault']) || !isset($params[0])) { @@ -75,6 +77,24 @@ public function convertResponse($params) return false; } + /** + * @param $params + * + * @return array + */ + private function formatParams($params) + { + if (is_string($params)) { + $params = json_decode($params, true); + } + + if (!is_array($params)) { + $params = [$params]; + } + + return $params; + } + /** * @param $params * diff --git a/Service/Options/ItemsToOption.php b/Service/Options/ItemsToOption.php index 40bb1d8be..236c35c1d 100644 --- a/Service/Options/ItemsToOption.php +++ b/Service/Options/ItemsToOption.php @@ -32,7 +32,7 @@ namespace TIG\PostNL\Service\Options; use TIG\PostNL\Config\Provider\ProductType; -use TIG\PostNL\Service\Order\ProductCodeAndType; +use TIG\PostNL\Service\Order\ProductInfo; use TIG\PostNL\Service\Wrapper\QuoteInterface; use Magento\Sales\Api\Data\ShipmentItemInterface; use Magento\Quote\Model\ResourceModel\Quote\Item as QuoteItem; @@ -41,7 +41,7 @@ class ItemsToOption { private $typeToOption = [ - ProductType::PRODUCT_TYPE_EXTRA_AT_HOME => ProductCodeAndType::OPTION_EXTRAATHOME, + ProductType::PRODUCT_TYPE_EXTRA_AT_HOME => ProductInfo::OPTION_EXTRAATHOME, ProductType::PRODUCT_TYPE_REGULAR => '', ]; diff --git a/Service/Options/ShipmentSupported.php b/Service/Options/ShipmentSupported.php index 9e4b8bad6..17ddc8d50 100644 --- a/Service/Options/ShipmentSupported.php +++ b/Service/Options/ShipmentSupported.php @@ -29,11 +29,13 @@ * @copyright Copyright (c) Total Internet Group B.V. https://tig.nl/copyright * @license http://creativecommons.org/licenses/by-nc-nd/3.0/nl/deed.en_US */ + namespace TIG\PostNL\Service\Options; use TIG\PostNL\Config\Source\Options\ProductOptions; use TIG\PostNL\Config\Provider\ProductOptions as OptionsProvider; use TIG\PostNL\Service\Shipment\EpsCountries; +use TIG\PostNL\Service\Shipment\PriorityCountries; class ShipmentSupported { @@ -41,17 +43,17 @@ class ShipmentSupported * @var ProductOptions */ private $productOptions; - + /** * @var OptionsProvider */ private $optionsProvider; - + /** * @var array */ private $allowedCountries = ['NL', 'BE']; - + public function __construct( ProductOptions $productOptions, OptionsProvider $optionsProvider @@ -59,17 +61,19 @@ public function __construct( $this->productOptions = $productOptions; $this->optionsProvider = $optionsProvider; } - + /** * @param \Magento\Sales\Api\Data\OrderInterface|\Magento\Sales\Model\Order $order + * * @return array */ public function get($order) { $address = $order->getShippingAddress(); + return $this->availableOptions($address->getCountryId()); } - + /** * @param $country * @@ -79,37 +83,46 @@ private function availableOptions($country) { // These are the options selected in the configuration by user. $supportedOptions = $this->optionsProvider->getSupportedProductOptions(); - + $optionsAllowed = $this->getProductOptionsByCountry($country); - + $availableOptions = array_filter($supportedOptions, function ($value) use ($optionsAllowed) { $available = false; foreach ($optionsAllowed as $option) { $available = ($available || (isset($option['value']) && $option['value'] == $value)); } - + return $available; }); - + return $availableOptions; } - + + // @codingStandardsIgnoreStart private function getProductOptionsByCountry($country) { if (in_array($country, $this->allowedCountries)) { - $options = $this->getProductOptions($country); - return $options; + $options[] = $this->getProductOptions($country); } - + if (in_array($country, EpsCountries::ALL)) { - $options = $this->productOptions->getEpsProductOptions(); - return $options; + $options[] = $this->productOptions->getEpsProductOptions(); } - - $options = $this->productOptions->getGlobalPackOptions(); + + if (in_array($country, array_merge(PriorityCountries::GLOBALPACK, PriorityCountries::EPS))) { + $options[] = $this->productOptions->getPriorityOptions(); + } + + if (!in_array($country, EpsCountries::ALL)) { + $options[] = $this->productOptions->getGlobalPackOptions(); + } + + $options = call_user_func_array("array_merge", $options); + return $options; } - + // @codingStandardsIgnoreEnd + /** * @param $country * @@ -118,6 +131,7 @@ private function getProductOptionsByCountry($country) private function getProductOptions($country) { $options = $this->productOptions->get(); + return array_filter($options, function ($value) use ($country) { return ($value['countryLimitation'] == $country); }); diff --git a/Service/Order/ProductCodeAndType.php b/Service/Order/ProductCodeAndType.php deleted file mode 100644 index b8f3169c9..000000000 --- a/Service/Order/ProductCodeAndType.php +++ /dev/null @@ -1,248 +0,0 @@ -productOptionsConfiguration = $productOptionsConfiguration; - $this->productOptionsFinder = $productOptionsFinder; - $this->quote = $quote; - } - - /** - * This function translates the chosen option to the correct product code for the shipment. - * - * @param string $type - * @param string $option - * @param SalesAddress|QuoteAddress $address - * - * @return array - */ - // @codingStandardsIgnoreStart - public function get($type = '', $option = '', $address = null) - { - $country = null; - if ($address && is_object($address)) { - $country = $address->getCountryId(); - } - - if (is_string($address)) { - $country = $address; - } - - $country = $country ?: $this->getCountryCode(); - $type = strtolower($type); - $option = strtolower($option); - - if (!in_array($country, EpsCountries::ALL) && !in_array($country, ['BE', 'NL'])) { - $this->getGlobalPackOption(); - return $this->response(); - } - - // EPS also uses delivery options in some cases. For Daytime there is no default EPS option. - if ((empty($type) || $option == static::OPTION_DAYTIME) && !in_array($country, ['BE', 'NL'])) { - $this->getEpsOption($address); - return $this->response(); - } - - if ($type == static::TYPE_PICKUP) { - $this->getPakjegemakProductOption($option); - return $this->response(); - } - - $this->getProductCode($option, $country); - return $this->response(); - } - // @codingStandardsIgnoreEnd - - /** - * Get the product code for the delivery options. - * - * @param string $option - * @param string $country - */ - private function getProductCode($option, $country) - { - switch ($option) { - case static::OPTION_EVENING: - $this->code = $this->productOptionsConfiguration->getDefaultEveningProductOption($country); - $this->type = static::SHIPMENT_TYPE_EVENING; - return; - case static::OPTION_SUNDAY: - $this->code = $this->productOptionsConfiguration->getDefaultSundayProductOption(); - $this->type = static::SHIPMENT_TYPE_SUNDAY; - return; - case static::OPTION_EXTRAATHOME: - $this->code = $this->productOptionsConfiguration->getDefaultExtraAtHomeProductOption(); - $this->type = static::SHIPMENT_TYPE_EXTRAATHOME; - return; - } - - $this->getDefaultProductOption($country); - } - - /** - * @param $country - */ - private function getDefaultProductOption($country) - { - $this->code = $this->productOptionsConfiguration->getDefaultProductOption(); - if ($country == 'BE') { - $this->code = $this->productOptionsConfiguration->getDefaultBeProductOption(); - } - - $this->type = static::SHIPMENT_TYPE_DAYTIME; - - /** @var Quote $magentoQuote */ - $magentoQuote = $this->quote->getQuote(); - $quoteTotal = $magentoQuote->getBaseGrandTotal(); - $alternativeActive = $this->productOptionsConfiguration->getUseAlternativeDefault(); - $alternativeMinAmount = $this->productOptionsConfiguration->getAlternativeDefaultMinAmount(); - - if ($alternativeActive && $quoteTotal >= $alternativeMinAmount) { - $this->code = $this->productOptionsConfiguration->getAlternativeDefaultProductOption(); - } - } - - /** - * @param string $option - */ - private function getPakjegemakProductOption($option) - { - if ($option == static::OPTION_PGE) { - $this->code = $this->productOptionsConfiguration->getDefaultPakjeGemakEarlyProductOption(); - $this->type = static::SHIPMENT_TYPE_PGE; - return; - } - - $this->code = $this->productOptionsConfiguration->getDefaultPakjeGemakProductOption(); - $this->type = static::SHIPMENT_TYPE_PG; - } - - /** - * Parse EPS options. - * @param $address - */ - private function getEpsOption($address) - { - $options = $this->productOptionsFinder->getEpsProductOptions($address); - $firstOption = array_shift($options); - - $this->code = $this->productOptionsConfiguration->getDefaultEpsProductOption(); - $this->type = static::SHIPMENT_TYPE_EPS; - // Force type Global Pack (mainly used for Canary Islands) - if (in_array('4945', $firstOption)) { - $this->code = $firstOption; - $this->type = static::SHIPMENT_TYPE_GP; - } - } - - /** - * Parse Globalpack options. - */ - private function getGlobalPackOption() - { - $options = $this->productOptionsFinder->getGlobalPackOptions(); - $firstOption = array_shift($options); - - $this->code = $firstOption['value']; - $this->type = static::SHIPMENT_TYPE_GP; - } - - /** - * @return array - */ - private function response() - { - return ['code' => $this->code, 'type' => $this->type]; - } - - /** - * @return string - */ - private function getCountryCode() - { - $address = $this->quote->getShippingAddress(); - return $address->getCountryId(); - } -} diff --git a/Service/Order/ProductInfo.php b/Service/Order/ProductInfo.php new file mode 100644 index 000000000..e03860f42 --- /dev/null +++ b/Service/Order/ProductInfo.php @@ -0,0 +1,296 @@ +productOptionsConfiguration = $productOptionsConfiguration; + $this->productOptionsFinder = $productOptionsFinder; + $this->quote = $quote; + } + + /** + * This function translates the chosen option to the correct product code for the shipment. + * + * @param string $type + * @param string $option + * @param SalesAddress|QuoteAddress $address + * + * @return array + */ + public function get($type = '', $option = '', $address = null) { + $country = $this->getCountryCode($address); + $type = strtolower($type); + $option = strtolower($option); + + if (!in_array($country, EpsCountries::ALL) + && !in_array($country, ['BE', 'NL'])) { + $this->setGlobalPackOption($country); + + return $this->getInfo(); + } + + // EPS also uses delivery options in some cases. For Daytime there is no default EPS option. + if ((empty($type) || $option == static::OPTION_DAYTIME) + && !in_array($country, ['BE', 'NL'])) { + $this->setEpsOption($address, $country); + + return $this->getInfo(); + } + + if ($type == static::TYPE_PICKUP) { + $this->setPakjegemakProductOption($option); + + return $this->getInfo(); + } + + $this->setProductCode($option, $country); + + return $this->getInfo(); + } + + /** + * @param SalesAddress|QuoteAddress|string $address + * + * @return string + */ + private function getCountryCode($address) { + if ($address && is_object($address)) { + return $address->getCountryId(); + } + + /** + * \TIG\PostNL\Helper\DeliveryOptions\OrderParams::formatParamData + * Request is done with country code only. + */ + if (is_string($address)) { + return $address; + } + + $address = $this->quote->getShippingAddress(); + + return $address->getCountryId(); + } + + /** + * @param null $country + */ + private function setGlobalPackOption($country = null) { + $this->type = static::SHIPMENT_TYPE_GP; + $this->code = $this->productOptionsConfiguration->getDefaultGlobalpackOption(); + + if (in_array($country, PriorityCountries::GLOBALPACK) + && $this->isPriorityProduct($this->code) + ) { + return; + } + + $this->code = $this->productOptionsFinder->getDefaultGPOption()['value']; + } + + /** + * @param $address + * @param $country + */ + private function setEpsOption($address, $country) { + $this->type = static::SHIPMENT_TYPE_EPS; + + // Force type Global Pack (mainly used for Canary Islands) + $options = $this->productOptionsFinder->getEpsProductOptions($address); + $firstOption = array_shift($options); + $globalPackOption = $this->productOptionsFinder->getDefaultGPOption()['value']; + if (in_array($globalPackOption, $firstOption)) { + $this->setGlobalPackOption(); + + return; + } + + $this->code = $this->productOptionsConfiguration->getDefaultEpsProductOption(); + if (in_array($country, PriorityCountries::EPS) + && $this->isPriorityProduct($this->code) + ) { + return; + } + + $this->code = $this->productOptionsFinder->getDefaultEUOption()['value']; + } + + /** + * Check whether current product code is a Priority (GlobalPack|EPS) Product + * + * @param $code + * + * @return bool|null + */ + private function isPriorityProduct($code) { + return $this->productOptionsConfiguration->checkProductByFlags($code, 'group', 'priority_options'); + } + + /** + * @param string $option + */ + private function setPakjegemakProductOption($option) { + if ($option == static::OPTION_PGE) { + $this->code = $this->productOptionsConfiguration->getDefaultPakjeGemakEarlyProductOption(); + $this->type = static::SHIPMENT_TYPE_PGE; + + return; + } + + $this->code = $this->productOptionsConfiguration->getDefaultPakjeGemakProductOption(); + $this->type = static::SHIPMENT_TYPE_PG; + } + + /** + * Set the product code for the delivery options. + * + * @param string $option + * @param string $country + */ + private function setProductCode($option, $country) { + switch ($option) { + case static::OPTION_EVENING: + $this->code = $this->productOptionsConfiguration->getDefaultEveningProductOption($country); + $this->type = static::SHIPMENT_TYPE_EVENING; + + return; + case static::OPTION_SUNDAY: + $this->code = $this->productOptionsConfiguration->getDefaultSundayProductOption(); + $this->type = static::SHIPMENT_TYPE_SUNDAY; + + return; + case static::OPTION_EXTRAATHOME: + $this->code = $this->productOptionsConfiguration->getDefaultExtraAtHomeProductOption(); + $this->type = static::SHIPMENT_TYPE_EXTRAATHOME; + + return; + } + + $this->setDefaultProductOption($country); + } + + /** + * @param $country + */ + private function setDefaultProductOption($country) { + $this->code = $this->productOptionsConfiguration->getDefaultProductOption(); + if ($country == 'BE') { + $this->code = $this->productOptionsConfiguration->getDefaultBeProductOption(); + } + + $this->type = static::SHIPMENT_TYPE_DAYTIME; + + /** @var Quote $magentoQuote */ + $magentoQuote = $this->quote->getQuote(); + $quoteTotal = $magentoQuote->getBaseGrandTotal(); + $alternativeActive = $this->productOptionsConfiguration->getUseAlternativeDefault(); + $alternativeMinAmount = $this->productOptionsConfiguration->getAlternativeDefaultMinAmount(); + + if ($alternativeActive && $quoteTotal >= $alternativeMinAmount) { + $this->code = $this->productOptionsConfiguration->getAlternativeDefaultProductOption(); + } + } + + /** + * @return array + */ + private function getInfo() { + return ['code' => $this->code, 'type' => $this->type]; + } +} diff --git a/Service/Shipment/Barcode/Range.php b/Service/Shipment/Barcode/Range.php index 6051832ec..fee28571e 100644 --- a/Service/Shipment/Barcode/Range.php +++ b/Service/Shipment/Barcode/Range.php @@ -33,7 +33,7 @@ use TIG\PostNL\Config\Provider\AccountConfiguration; use TIG\PostNL\Config\Provider\Globalpack; - +use TIG\PostNL\Config\Provider\PepsConfiguration; use TIG\PostNL\Exception as PostnlException; use TIG\PostNL\Service\Shipment\EpsCountries; @@ -58,52 +58,67 @@ class Range */ private $globalpackConfiguration; + /** + * @var PepsConfiguration + */ + private $pepsConfiguration; + /** * @var int */ private $storeId; + /** + * @var array + */ + private $response = [ + 'type' => '', + 'range' => '', + 'serie' => '' + ]; + /** * @param AccountConfiguration $accountConfiguration * @param Globalpack $globalpack + * @param PepsConfiguration $pepsConfiguration */ public function __construct( AccountConfiguration $accountConfiguration, - Globalpack $globalpack + Globalpack $globalpack, + PepsConfiguration $pepsConfiguration ) { $this->accountConfiguration = $accountConfiguration; $this->globalpackConfiguration = $globalpack; + $this->pepsConfiguration = $pepsConfiguration; } - + /** - * Gets data for the barcode that's requested. Depending on the destination of the shipment several barcode types - * may be requested. + * @param $barcodeType * - * @param string $barcodeType * @return array - * @throws PostnlException + * @throws \TIG\PostNL\Exception */ public function get($barcodeType) { - $barcodeType = strtoupper($barcodeType); - - $barcodeData = $this->getBarcodeData($barcodeType); - - $this->validateBarcodeData($barcodeData); - - return $barcodeData; + $this->set(strtoupper($barcodeType)); + return $this->response; } /** - * @param $countryId - * @param $storeId + * @param $countryId + * @param null $storeId + * @param string $type * - * @return array + * @return array|string */ - public function getByCountryId($countryId, $storeId = null) + public function getByCountryId($countryId, $storeId = null, $type = '') { $this->storeId = $storeId; + if ($type) { + return $this->get($type); + } + if ($countryId == 'NL') { return $this->get('NL'); } @@ -112,100 +127,64 @@ public function getByCountryId($countryId, $storeId = null) return $this->get('EU'); } - return $this->get('global'); + return $this->get('GLOBAL'); } - + /** - * @return array + * @param $type + * + * @throws \TIG\PostNL\Exception */ - private function getNlBarcode() + public function set($type) { - $type = '3S'; - $range = $this->accountConfiguration->getCustomerCode($this->storeId); - $serie = static::NL_BARCODE_SERIE_LONG; - - if (strlen($range) > 3) { - $serie = static::NL_BARCODE_SERIE_SHORT; + $this->response['type'] = '3S'; + $this->response['range'] = $this->accountConfiguration->getCustomerCode($this->storeId); + switch ($type) { + case 'NL': + $this->setNlSerie(); + return; + case 'EU': + $this->setEuSerie(); + return; + case 'GLOBAL': + $this->setGlobalPackOptions(); + return; + case 'PEPS': + $this->setPepsOptions(); + return; } - return [ - 'type' => $type, - 'range' => $range, - 'serie' => $serie, - ]; + $this->noBarcodeDataError($type); } - /** - * @return array - */ - private function getEuBarcode() + private function setNlSerie() { - $type = '3S'; - $range = $this->accountConfiguration->getCustomerCode($this->storeId); - $serie = static::EU_BARCODE_SERIE_LONG; - - if (strlen($range) > 3) { - $serie = static::EU_BARCODE_SERIE_SHORT; + $this->response['serie'] = static::NL_BARCODE_SERIE_LONG; + if (strlen($this->response['range']) > 3) { + $this->response['serie'] = static::NL_BARCODE_SERIE_SHORT; } - - return [ - 'type' => $type, - 'range' => $range, - 'serie' => $serie, - ]; } - /** - * @return array - */ - private function getGlobalBarcode() + private function setEuSerie() { - $type = $this->globalpackConfiguration->getBarcodeType(); - $range = $this->globalpackConfiguration->getBarcodeRange(); - $serie = static::GLOBAL_BARCODE_SERIE; - - return [ - 'type' => $type, - 'range' => $range, - 'serie' => $serie, - ]; + $this->response['serie'] = static::EU_BARCODE_SERIE_LONG; + if (strlen($this->response['range']) > 3) { + $this->response['serie'] = static::EU_BARCODE_SERIE_SHORT; + } } - /** - * @param $barcodeData - * @throws PostnlException - */ - private function validateBarcodeData($barcodeData) + private function setGlobalPackOptions() { - if (!$barcodeData['type'] || !$barcodeData['range']) { - throw new PostnlException( - // @codingStandardsIgnoreLine - __('Unable to retrieve barcode data.'), - 'POSTNL-0111' - ); - } + $this->response['type'] = $this->globalpackConfiguration->getBarcodeType(); + $this->response['range'] = $this->globalpackConfiguration->getBarcodeRange(); + $this->response['serie'] = static::GLOBAL_BARCODE_SERIE; } - /** - * @param $barcodeType - * @return array - * @throws PostnlException - */ - private function getBarcodeData($barcodeType) + private function setPepsOptions() { - if ($barcodeType == 'NL') { - return $this->getNlBarcode(); - } - - if ($barcodeType == 'EU') { - return $this->getEuBarcode(); - } - - if ($barcodeType == 'GLOBAL') { - return $this->getGlobalBarcode(); - } - - $this->noBarcodeDataError($barcodeType); + $this->response['type'] = $this->pepsConfiguration->getBarcodeType(); + $this->response['range'] = $this->pepsConfiguration->getBarcodeRange(); + $this->response['serie'] = static::EU_BARCODE_SERIE_LONG; } /** diff --git a/Service/Shipment/CreateShipment.php b/Service/Shipment/CreateShipment.php index 5e0f85f59..d3c0bf97f 100644 --- a/Service/Shipment/CreateShipment.php +++ b/Service/Shipment/CreateShipment.php @@ -31,16 +31,21 @@ */ namespace TIG\PostNL\Service\Shipment; +use Magento\Sales\Model\Convert\Order as ConvertOrder; use Magento\Sales\Model\Order; use Magento\Sales\Model\Order\Item as OrderItem; use Magento\Sales\Model\Order\Shipment; -use Magento\Sales\Model\Convert\Order as ConvertOrder; -use TIG\PostNL\Model\ShipmentRepository; use TIG\PostNL\Helper\Data; +use TIG\PostNL\Model\ShipmentRepository; //@codingStandardsIgnoreFile class CreateShipment { + /** + * @var InventorySource + */ + private $inventorySource; + /** * @var ConvertOrder */ @@ -72,18 +77,21 @@ class CreateShipment private $errors = []; /** - * @param ConvertOrder $convertOrder + * @param ConvertOrder $convertOrder * @param ShipmentRepository $shipmentRepository - * @param Data $postnlHelper + * @param Data $postnlHelper + * @param InventorySource $inventorySource */ public function __construct( ConvertOrder $convertOrder, ShipmentRepository $shipmentRepository, - Data $postnlHelper + Data $postnlHelper, + InventorySource $inventorySource ) { - $this->convertOrder = $convertOrder; + $this->convertOrder = $convertOrder; $this->shipmentRepository = $shipmentRepository; - $this->postNLHelper = $postnlHelper; + $this->postNLHelper = $postnlHelper; + $this->inventorySource = $inventorySource; } /** @@ -219,6 +227,8 @@ private function saveShipment() { $this->shipment->register(); $order = $this->shipment->getOrder(); + $this->inventorySource->setSource($order, $this->getShippingItems()); + $order->setState(Order::STATE_PROCESSING); $order->setStatus('processing'); @@ -226,7 +236,7 @@ private function saveShipment() $this->shipment->save(); $order->save(); } catch (\Exception $exception) { - $message = $this->handleExceptionForPosibleSoapErrors($exception); + $message = $this->handleExceptionForPossibleSoapErrors($exception); $localizedErrorMessage = __($message)->render(); $this->errors[] = $localizedErrorMessage; $this->shipment = false; @@ -235,20 +245,31 @@ private function saveShipment() return $this; } + private function getShippingItems() + { + $shippingItems = []; + + foreach ($this->shipment->getItems() as $shipmentItem) { + $shippingItems[$shipmentItem->getProductId()] = (string)$shipmentItem->getQty(); + } + + return $shippingItems; + } + /** * @param \Exception $exception * * @return \Magento\Framework\Phrase|string */ - private function handleExceptionForPosibleSoapErrors(\Exception $exception) + private function handleExceptionForPossibleSoapErrors(\Exception $exception) { - if (!$exception->getErrors() || !is_array($exception->getErrors())) { + if (!method_exists($exception, 'getErrors') || !$exception->getErrors() || !is_array($exception->getErrors())) { return $exception->getMessage(); } $message = __('[POSTNL-0010] - An error occurred while processing this action.'); foreach ($exception->getErrors() as $error) { - $message .= ' '. (string) $error; + $message .= ' ' . (string) $error; } return $message; diff --git a/Service/Shipment/Customs.php b/Service/Shipment/Customs.php index 52c889857..6cea7a544 100644 --- a/Service/Shipment/Customs.php +++ b/Service/Shipment/Customs.php @@ -56,7 +56,7 @@ class Customs 'Invoice' => 'false', 'Certificate' => 'false', 'License' => 'false', - 'Currency' => 'EUR', + 'Currency' => 'EUR' ]; /** diff --git a/Service/Shipment/EpsCountries.php b/Service/Shipment/EpsCountries.php index d673bd70c..9cdf34cba 100644 --- a/Service/Shipment/EpsCountries.php +++ b/Service/Shipment/EpsCountries.php @@ -51,8 +51,6 @@ class EpsCountries * 'GL', // Greenland * * ==== SPAIN ==== - * @codingStandardsIgnoreLine - * @todo: Not in the Magento Country list, customer will use ES which will cause the shipment to be EPS. * 'IC', // Las Palmas, Santa Cruz and Melilla * * ==== Italy ==== @@ -90,6 +88,6 @@ class EpsCountries 'SI', // Slovenia 'ES', // Spain (Including Balearic Islands. Excluding Canary Islands, Melilla and Ceuta) 'SE', // Sweden - 'MC', // Monaco (Is it's own country, Is EPS because France is EPS) + 'MC', // Monaco (Is its own country, Is EPS because France is EPS) ]; } diff --git a/Service/Shipment/InventorySource.php b/Service/Shipment/InventorySource.php new file mode 100644 index 000000000..b34d224ee --- /dev/null +++ b/Service/Shipment/InventorySource.php @@ -0,0 +1,74 @@ +shipmentFactory = $shipmentFactory; + } + + /** + * Magento uses an afterCreate plugin on the shipmentFactory to set the SourceCode. In the default flow Magento + * runs this code when you open the Create Shipment page. This behaviour doesn't occur in this flow, so we force + * that flow to happen here. + * + * @param $order + * @param $shipmentItems + * + * @return Shipment + */ + public function setSource($order, $shipmentItems) + { + /** @var Shipment $shipment */ + $shipment = $this->shipmentFactory->create( + $order, + $shipmentItems + ); + + return $shipment; + } +} diff --git a/Service/Shipment/Label/Generate.php b/Service/Shipment/Label/Generate.php index ba84b6fda..490407f7b 100644 --- a/Service/Shipment/Label/Generate.php +++ b/Service/Shipment/Label/Generate.php @@ -31,7 +31,7 @@ */ namespace TIG\PostNL\Service\Shipment\Label; -use TIG\PostNL\Service\Order\ProductCodeAndType; +use TIG\PostNL\Service\Order\ProductInfo; use TIG\PostNL\Api\Data\ShipmentLabelInterface; class Generate @@ -45,7 +45,10 @@ class Generate * @var Merge */ private $merge; - + + /** + * @var array + */ private $globalPackLabels = []; /** @@ -91,12 +94,14 @@ public function run(array $labels, $createNewPdf = false) public function orderLabels($labels) { $otherLabels = array_filter($labels, function ($label) { - /** @var ShipmentLabelInterface $label */ - if (strtoupper($label->getType()) == ProductCodeAndType::SHIPMENT_TYPE_GP) { + /** @var array|ShipmentLabelInterface $label */ + if (is_array($label)) { + return false; + } + if (strtoupper($label->getType()) == ProductInfo::SHIPMENT_TYPE_GP) { $this->globalPackLabels[] = $label; return false; } - return true; }); diff --git a/Service/Shipment/Label/Prepare.php b/Service/Shipment/Label/Prepare.php index 0598432ab..2aa8167be 100644 --- a/Service/Shipment/Label/Prepare.php +++ b/Service/Shipment/Label/Prepare.php @@ -33,6 +33,9 @@ use TIG\PostNL\Api\Data\ShipmentLabelInterface; use TIG\PostNL\Exception as PostNLException; +use TIG\PostNL\Service\Shipment\Label\Type\DomesticFactory; +use TIG\PostNL\Service\Shipment\Label\Type\EPSFactory; +use TIG\PostNL\Service\Shipment\Label\Type\GlobalPackFactory; use TIG\PostNL\Service\Shipment\Type; use TIG\PostNL\Service\Shipment\Label\Type\TypeInterface; use TIG\PostNL\Service\Shipment\Label\Type\TypeInterfaceFactory; @@ -54,17 +57,41 @@ class Prepare */ private $isValidated = false; + /** + * @var DomesticFactory + */ + private $domesticFactory; + + /** + * @var EPSFactory + */ + private $epsFactory; + + /** + * @var GlobalPackFactory + */ + private $globalPackFactory; + /** * @param Type $typeConverter + * @param DomesticFactory $domesticFactory + * @param EPSFactory $epsFactory + * @param GlobalPackFactory $globalPackFactory * @param array $types * * @throws PostNLException */ public function __construct( Type $typeConverter, + DomesticFactory $domesticFactory, + EPSFactory $epsFactory, + GlobalPackFactory $globalPackFactory, $types = [] ) { $this->typeConverter = $typeConverter; + $this->domesticFactory = $domesticFactory; + $this->epsFactory = $epsFactory; + $this->globalPackFactory = $globalPackFactory; $this->types = $types; } diff --git a/Service/Shipment/Label/Type/AbstractType.php b/Service/Shipment/Label/Type/AbstractType.php index 33d67f86d..395b8ea55 100644 --- a/Service/Shipment/Label/Type/AbstractType.php +++ b/Service/Shipment/Label/Type/AbstractType.php @@ -92,10 +92,9 @@ public function cleanup() } /** - * This function prevents that the fpdi->create() method is called multiple times. + * This function prevents that the $fpdi->create() method is called multiple times. */ - // @codingStandardsIgnoreLine - protected function createPdf() + public function createPdf() { if ($this->pdf) { return; diff --git a/Service/Shipment/Label/Type/EPS.php b/Service/Shipment/Label/Type/EPS.php index 9d451fdd1..d65c58db9 100644 --- a/Service/Shipment/Label/Type/EPS.php +++ b/Service/Shipment/Label/Type/EPS.php @@ -39,17 +39,29 @@ class EPS extends Domestic /** * These are combiLabel products, these codes are returned by PostNL in the label response (ProductCodeDelivery) */ - private $shouldRotate = [4940, 4950, 4983, 4985, 4986, 3622, 3642, 3659]; + private $rotated = [4940, 4950, 4983, 4985, 4986, 3622, 3642, 3659]; + + /** + * The product codes, returned by the label response, to alter label generation for priority products. + * + * @var array + */ + private $priority = [6350, 6550, 6940, 6942]; /** * @var bool */ private $templateInserted = false; - + /** * @param ShipmentLabelInterface $label * * @return \FPDF + * @throws \setasign\Fpdi\PdfParser\CrossReference\CrossReferenceException + * @throws \setasign\Fpdi\PdfParser\Filter\FilterException + * @throws \setasign\Fpdi\PdfParser\PdfParserException + * @throws \setasign\Fpdi\PdfParser\Type\PdfTypeException + * @throws \setasign\Fpdi\PdfReader\PdfReaderException */ public function process(ShipmentLabelInterface $label) { @@ -58,42 +70,85 @@ public function process(ShipmentLabelInterface $label) $this->createPdf(); $this->pdf->AddPage('P', Fpdi::PAGE_SIZE_A6); $this->pdf->setSourceFile($filename); + + $productCode = $label->getProductCode(); - if ($this->isRotated() || in_array($label->getProductCode(), $this->shouldRotate)) { + if ($this->isRotated() + || ($this->isRotatedProduct($productCode) && !$this->isPriorityProduct($productCode)) + ) { $this->insertRotated(); } - if (!$this->templateInserted) { + if (!$this->getTemplateInserted()) { $this->insertRegular(); } return $this->pdf; } - + + /** + * @param $code + * + * @return bool + */ + public function isRotatedProduct($code) + { + return in_array($code, $this->rotated); + } + /** - * This is a label that is standing, so rotate is before pasting. + * This is a label with a vertical orientation, so rotate it before inserting. + * + * @param bool $importPage + * + * @throws \setasign\Fpdi\PdfParser\CrossReference\CrossReferenceException + * @throws \setasign\Fpdi\PdfParser\Filter\FilterException + * @throws \setasign\Fpdi\PdfParser\PdfParserException + * @throws \setasign\Fpdi\PdfParser\Type\PdfTypeException + * @throws \setasign\Fpdi\PdfReader\PdfReaderException */ private function insertRotated() { - $this->templateInserted = true; + $this->setTemplateInserted(true); $pageId = $this->pdf->importPage(1); $this->pdf->Rotate(90); $this->pdf->useTemplate($pageId, - 130, 0); $this->pdf->Rotate(0); } - + /** * This is a default label, it does not need any modification. + * + * @throws \setasign\Fpdi\PdfParser\CrossReference\CrossReferenceException + * @throws \setasign\Fpdi\PdfParser\Filter\FilterException + * @throws \setasign\Fpdi\PdfParser\PdfParserException + * @throws \setasign\Fpdi\PdfParser\Type\PdfTypeException + * @throws \setasign\Fpdi\PdfReader\PdfReaderException */ private function insertRegular() { - $this->templateInserted = true; + $this->setTemplateInserted(true); $pageId = $this->pdf->importPage(1); $this->pdf->useTemplate($pageId, 0, 0, Fpdi::PAGE_SIZE_A6_WIDTH, Fpdi::PAGE_SIZE_A6_HEIGHT); } - + + /** + * @param $code + * + * @return bool + */ + public function isPriorityProduct($code) + { + return in_array($code, $this->priority); + } + /** * @return bool + * @throws \setasign\Fpdi\PdfParser\CrossReference\CrossReferenceException + * @throws \setasign\Fpdi\PdfParser\Filter\FilterException + * @throws \setasign\Fpdi\PdfParser\PdfParserException + * @throws \setasign\Fpdi\PdfParser\Type\PdfTypeException + * @throws \setasign\Fpdi\PdfReader\PdfReaderException */ public function isRotated() { @@ -106,4 +161,20 @@ public function isRotated() return false; } + + /** + * @param $value + */ + public function setTemplateInserted($value) + { + $this->templateInserted = $value; + } + + /** + * @return bool + */ + public function getTemplateInserted() + { + return $this->templateInserted; + } } diff --git a/Service/Shipment/Label/Type/GlobalPack.php b/Service/Shipment/Label/Type/GlobalPack.php index a18ec4a83..3bf5e623b 100644 --- a/Service/Shipment/Label/Type/GlobalPack.php +++ b/Service/Shipment/Label/Type/GlobalPack.php @@ -29,32 +29,131 @@ * @copyright Copyright (c) Total Internet Group B.V. https://tig.nl/copyright * @license http://creativecommons.org/licenses/by-nc-nd/3.0/nl/deed.en_US */ + namespace TIG\PostNL\Service\Shipment\Label\Type; +use TIG\PostNL\Api\Data\ShipmentInterface; use TIG\PostNL\Api\Data\ShipmentLabelInterface; +use TIG\PostNL\Service\Pdf\Fpdi; -class GlobalPack extends AbstractType implements TypeInterface +class GlobalPack extends EPS { + /** + * The labels of these Priority GP countries are not supposed to be rotated. + * + * @var array + */ + private $excludedCountries = ["US"]; + /** * @param ShipmentLabelInterface $label * - * @return \TIG\PostNL\Service\Pdf\Fpdi + * @return \FPDF|Fpdi + * @throws \setasign\Fpdi\PdfParser\CrossReference\CrossReferenceException + * @throws \setasign\Fpdi\PdfParser\Filter\FilterException + * @throws \setasign\Fpdi\PdfParser\PdfParserException + * @throws \setasign\Fpdi\PdfParser\Type\PdfTypeException + * @throws \setasign\Fpdi\PdfReader\PdfReaderException */ public function process(ShipmentLabelInterface $label) { - $filename = $this->saveTempLabel($label); - - $this->pdf = $this->fpdi->create(); + $productCode = $label->getProductCode(); + $shipment = $label->getShipment(); + $filename = $this->saveTempLabel($label); + + $this->createPdf(); $count = $this->pdf->setSourceFile($filename); + for ($pageNo = 1; $pageNo <= $count; $pageNo++) { - $templateId = $this->pdf->importPage($pageNo); - $templateSize = $this->pdf->getTemplateSize($templateId); - $orientation = $templateSize['width'] > $templateSize['height'] ? 'L' :'P'; - - $this->pdf->AddPage($orientation, [$templateSize['width'], $templateSize['height']]); - $this->pdf->useTemplate($templateId); + $this->processLabels($shipment, $pageNo, $productCode); } - + return $this->pdf; } + + /** + * @param ShipmentInterface $shipment + * @param $page + * @param $code + * + * @throws \setasign\Fpdi\PdfParser\CrossReference\CrossReferenceException + * @throws \setasign\Fpdi\PdfParser\Filter\FilterException + * @throws \setasign\Fpdi\PdfParser\PdfParserException + * @throws \setasign\Fpdi\PdfParser\Type\PdfTypeException + * @throws \setasign\Fpdi\PdfReader\PdfReaderException + */ + private function processLabels(ShipmentInterface $shipment, $page, $code) + { + if (!$this->isRotatedProduct($code) + && $this->isPriorityProduct($code) + ) { + $countryId = $shipment->getShipmentCountry(); + $this->insertRotated($page, $countryId); + } + + if (!$this->getTemplateInserted()) { + $this->insertRegular($page); + } + } + + /** + * @param $country string + * + * @return bool + */ + public function isExcludedCountry($country) + { + return in_array($country, $this->excludedCountries); + } + + /** + * Since Priority GP has its own resolution and size, we override this + * method. + * + * @throws \setasign\Fpdi\PdfParser\CrossReference\CrossReferenceException + * @throws \setasign\Fpdi\PdfParser\Filter\FilterException + * @throws \setasign\Fpdi\PdfParser\PdfParserException + * @throws \setasign\Fpdi\PdfParser\Type\PdfTypeException + * @throws \setasign\Fpdi\PdfReader\PdfReaderException + */ + private function insertRotated($page, $countryId) + { + $this->setTemplateInserted(true); + $this->pdf->AddPage('P', Fpdi::PAGE_SIZE_A6); + + $pageId = $this->pdf->importPage($page); + + if (!$this->isExcludedCountry($countryId)) { + $this->pdf->Rotate(90); + $this->pdf->useTemplate($pageId, -130, 0, 150, 210); + $this->pdf->Rotate(0); + + return; + } + + $this->pdf->useTemplate($pageId, 0, 0, 103, 150); + } + + /** + * This method is used for regular GlobalPack labels. + * + * @param $page + * + * @throws \setasign\Fpdi\PdfParser\CrossReference\CrossReferenceException + * @throws \setasign\Fpdi\PdfParser\Filter\FilterException + * @throws \setasign\Fpdi\PdfParser\PdfParserException + * @throws \setasign\Fpdi\PdfParser\Type\PdfTypeException + * @throws \setasign\Fpdi\PdfReader\PdfReaderException + */ + private function insertRegular($page) + { + $this->setTemplateInserted(true); + + $templateId = $this->pdf->importPage($page); + $templateSize = $this->pdf->getTemplateSize($templateId); + $orientation = $templateSize['width'] > $templateSize['height'] ? 'L' : 'P'; + + $this->pdf->AddPage($orientation, [$templateSize['width'], $templateSize['height']]); + $this->pdf->useTemplate($templateId, 0, 0, $templateSize['width'], $templateSize['height']); + } } diff --git a/Service/Shipment/Label/Validator.php b/Service/Shipment/Label/Validator.php index 89f9bc929..297785ae2 100644 --- a/Service/Shipment/Label/Validator.php +++ b/Service/Shipment/Label/Validator.php @@ -32,9 +32,46 @@ namespace TIG\PostNL\Service\Shipment\Label; use TIG\PostNL\Api\Data\ShipmentLabelInterface; +use TIG\PostNL\Api\Data\ShipmentInterface; +use TIG\PostNL\Config\Provider\ProductOptions; +use TIG\PostNL\Config\Provider\ShippingOptions; class Validator { + /** + * @var ProductOptions + */ + private $productOptions; + + /** + * @var ShippingOptions + */ + private $shippingOptions; + + /** + * @var array + */ + private $errors = []; + + /** + * @var bool + */ + private $priorityError = false; + + /** + * Validator constructor. + * + * @param ProductOptions $productOptions + * @param ShippingOptions $shippingOptions + */ + public function __construct( + ProductOptions $productOptions, + ShippingOptions $shippingOptions + ) { + $this->productOptions = $productOptions; + $this->shippingOptions = $shippingOptions; + } + /** * Removes all labels that are empty or not a string. If a shipment has no valid labels, the shipment will be * removed from the stack. @@ -52,7 +89,7 @@ public function validate($input) return array_values($filtered); } - + /** * @param ShipmentLabelInterface|null $model * @@ -63,16 +100,82 @@ private function filterInput(ShipmentLabelInterface $model = null) if ($model === null) { return false; } - + $label = $model->getLabel(); - + if (!is_string($label) || empty($label)) { return false; } - + $start = substr($label, 0, strlen('invalid')); $start = strtolower($start); - + return $start != 'invalid'; } + + /** + * @return array + */ + public function getErrors() + { + return $this->errors; + } + + /** + * @param ShipmentInterface $shipment + * + * @return bool + */ + public function validateProduct(ShipmentInterface $shipment) + { + if ($shipment->isGlobalPack()) { + return $this->validateGlobalPack($shipment); + } + + return $this->validatePriority($shipment); + } + + /** + * @param $shipment + * + * @return bool + */ + private function validateGlobalPack(ShipmentInterface $shipment) + { + if (!$this->shippingOptions->canUseGlobalPack()) { + $magentoShipment = $shipment->getShipment(); + // @codingStandardsIgnoreLine + $this->errors[] = __('Could not print labels for shipment %1. Worldwide (Globalpack) Delivery is disabled. Please contact your PostNL account manager before you enable this method.', $magentoShipment->getIncrementId()); + return false; + } + + return $this->validatePriority($shipment); + } + + /** + * @param $shipment + * + * @return bool + */ + private function validatePriority(ShipmentInterface $shipment) + { + $code = $shipment->getProductCode(); + $isPriority = $this->productOptions->checkProductByFlags($code, 'group', 'priority_options'); + + if ($isPriority && !$this->shippingOptions->canUsePriority()) { + $magentoShipment = $shipment->getShipment(); + // @codingStandardsIgnoreLine + $this->errors[] = __('Could not print labels for shipment %1. Priority Delivery is disabled. Please contact your PostNL account manager before you enable this method.', $magentoShipment->getIncrementId()); + return false; + } + + /** We want to show this notification for every Priority Shipment */ + if ($isPriority && $this->priorityError == false) { + // @codingStandardsIgnoreLine + $this->errors[] = __('Tracked Parcels can only be used if 5 packages or more are delivered in a domestic mail bag with an attached bag label specific for priority parcels.'); + $this->priorityError = true; + } + + return true; + } } diff --git a/Service/Shipment/Labelling/GenerateAbstract.php b/Service/Shipment/Labelling/GenerateAbstract.php index 70bce000e..52eb246c1 100644 --- a/Service/Shipment/Labelling/GenerateAbstract.php +++ b/Service/Shipment/Labelling/GenerateAbstract.php @@ -114,16 +114,18 @@ public function getLabel(ShipmentInterface $shipment, $currentShipmentNumber, $c if ($responseShipments) { $this->saveDownpartnerData($shipment, $responseShipments); + $this->saveCountryId($shipment); } - $labelModels = $this->handleLabels($shipment, $responseShipments, $currentShipmentNumber); - if ($confirm) { $shipment->setConfirmedAt($this->date); $shipment->setConfirmed(true); - $this->shipmentRepository->save($shipment); } + $labelModels = $this->handleLabels($shipment, $responseShipments, $currentShipmentNumber); + + $this->shipmentRepository->save($shipment); + return $labelModels; } @@ -140,7 +142,17 @@ private function saveDownpartnerData(ShipmentInterface $shipment, $response) $shipment->setDownpartnerBarcode($downPartnerBarcode); $shipment->setDownpartnerId($downPartnerId); $shipment->setDownpartnerLocation($downPartnerLocation); - $this->shipmentRepository->save($shipment); + } + + /** + * @param ShipmentInterface $shipment + */ + private function saveCountryId(ShipmentInterface $shipment) + { + $shippingAddress = $shipment->getShippingAddress(); + $countryId = $shippingAddress->getCountryId(); + + $shipment->setShipmentCountry($countryId); } /** @@ -221,7 +233,6 @@ private function getLabelModels($labelItem, ShipmentInterface $shipment, $curren */ if ($labelItem->ProductCodeDelivery !== $shipment->getProductCode()) { $shipment->setProductCode($labelItem->ProductCodeDelivery); - $this->shipmentRepository->save($shipment); } return $labelModels; diff --git a/Service/Shipment/Labelling/GetLabels.php b/Service/Shipment/Labelling/GetLabels.php index 2e62c8f5d..22de267e1 100644 --- a/Service/Shipment/Labelling/GetLabels.php +++ b/Service/Shipment/Labelling/GetLabels.php @@ -99,8 +99,12 @@ public function get($shipmentId, $confirm = true) return []; } + /** Validate products and generate error/warning messages */ + $this->labelValidator->validateProduct($shipment); + $labels = $this->getLabels($shipment, $confirm); $labels = $this->labelValidator->validate($labels); + $labels['errors'] = $this->labelValidator->getErrors(); return $labels; } diff --git a/Service/Shipment/Labelling/Handler.php b/Service/Shipment/Labelling/Handler.php index 7be0a3257..b63d0dae0 100644 --- a/Service/Shipment/Labelling/Handler.php +++ b/Service/Shipment/Labelling/Handler.php @@ -32,6 +32,7 @@ namespace TIG\PostNL\Service\Shipment\Labelling; use TIG\PostNL\Service\Shipment\Labelling\Handler\HandlerInterfaceFactory; +use TIG\PostNL\Service\Shipment\Labelling\Handler\GlobalpackFactory; use TIG\PostNL\Service\Shipment\Labelling\Handler\HandlerInterface; use TIG\PostNL\Service\Shipment\Type; use TIG\PostNL\Exception as PostNLException; @@ -53,17 +54,25 @@ class Handler */ private $typeConverter; + /** + * @var GlobalpackFactory + */ + private $globalpackFactory; + /** * Handler constructor. * - * @param Type $type - * @param array $handlers + * @param Type $type + * @param GlobalpackFactory $globalpackFactory + * @param array $handlers */ public function __construct( Type $type, + GlobalpackFactory $globalpackFactory, $handlers = [] ) { $this->typeConverter = $type; + $this->globalpackFactory = $globalpackFactory; $this->handlers = $handlers; } diff --git a/Service/Shipment/Packingslip/GetPackingslip.php b/Service/Shipment/Packingslip/GetPackingslip.php index 9b58851af..8dfc087a0 100644 --- a/Service/Shipment/Packingslip/GetPackingslip.php +++ b/Service/Shipment/Packingslip/GetPackingslip.php @@ -92,7 +92,7 @@ public function __construct( * @param bool $withLabels * @param bool $confirm * - * @return string + * @return string|array */ public function get($shipmentId, $withLabels = true, $confirm = true) { diff --git a/Service/Shipment/Packingslip/MergeWithLabels.php b/Service/Shipment/Packingslip/MergeWithLabels.php index f8d090eee..5634b3d5e 100644 --- a/Service/Shipment/Packingslip/MergeWithLabels.php +++ b/Service/Shipment/Packingslip/MergeWithLabels.php @@ -32,7 +32,7 @@ namespace TIG\PostNL\Service\Shipment\Packingslip; use TIG\PostNL\Api\Data\ShipmentLabelInterface; -use TIG\PostNL\Service\Order\ProductCodeAndType; +use TIG\PostNL\Service\Order\ProductInfo; use TIG\PostNL\Service\Pdf\Fpdi; use TIG\PostNL\Service\Pdf\FpdiFactory; use TIG\PostNL\Service\Shipment\Label\File; @@ -118,6 +118,7 @@ public function setY($packingslipYPos) * * @return string */ + // @codingStandardsIgnoreStart public function merge($shipmentId, $packingslip, $mergeFirstLabel = false, $confirm = true) { $labels = $this->getLabels->get($shipmentId, $confirm); @@ -125,9 +126,12 @@ public function merge($shipmentId, $packingslip, $mergeFirstLabel = false, $conf return $packingslip; } + if (isset($labels['errors']) && count($labels['errors']) > 0) { + return $labels['errors']; + } + if ($mergeFirstLabel && $this->canMergeFirstLabel($labels[0])) { $firstLabel = array_shift($labels); - // @codingStandardsIgnoreLine $label = base64_decode($firstLabel->getLabel()); $packingslip = $this->mergeFirstLabel($label, $packingslip, $firstLabel->getType()); } @@ -139,6 +143,7 @@ public function merge($shipmentId, $packingslip, $mergeFirstLabel = false, $conf $packingslipPdf = $this->addLabelsToPackingslip($packingslip, $labels); return $packingslipPdf; } + // @codingStandardsIgnoreEnd /** * @param ShipmentLabelInterface $firstLabel @@ -147,7 +152,7 @@ public function merge($shipmentId, $packingslip, $mergeFirstLabel = false, $conf */ private function canMergeFirstLabel($firstLabel) { - $labelTypeGP = strtolower(ProductCodeAndType::SHIPMENT_TYPE_GP); + $labelTypeGP = strtolower(ProductInfo::SHIPMENT_TYPE_GP); if ($this->packingslipYPos <= 400 || $firstLabel->getType() == $labelTypeGP) { return false; } @@ -199,7 +204,7 @@ private function mergeFirstLabel($label, $packingslip, $type = null) */ private function addLabelToPdf($labelFile, Fpdi $pdf, $type) { - if ($type == strtolower(ProductCodeAndType::SHIPMENT_TYPE_EPS)) { + if ($type == strtolower(ProductInfo::SHIPMENT_TYPE_EPS)) { $this->setEpsPosition(); } diff --git a/Service/Shipment/PriorityCountries.php b/Service/Shipment/PriorityCountries.php new file mode 100644 index 000000000..e4fbb0e1a --- /dev/null +++ b/Service/Shipment/PriorityCountries.php @@ -0,0 +1,102 @@ +Date; $dayOfWeek = $this->helper->getDayOrWeekNumber($date, 'w'); - return $dayOfWeek !== 0; + return $dayOfWeek !== 7; }); return array_values($filtered); diff --git a/Service/Timeframe/Options.php b/Service/Timeframe/Options.php index 2e4157aa8..f33664a83 100644 --- a/Service/Timeframe/Options.php +++ b/Service/Timeframe/Options.php @@ -84,7 +84,9 @@ public function get($countryId = 'NL') $deliveryTimeframesOptions[] = self::EVENING_DELIVERY_OPTION; } - if ($this->shippingOptions->isSundayDeliveryActive() && $this->hasSaturdayAsShippingDay()) { + // Sunday Delivery is only available for the Netherlands + if ($this->shippingOptions->isSundayDeliveryActive() + && $this->hasSaturdayAsShippingDay() && $countryId == 'NL') { $deliveryTimeframesOptions[] = self::SUNDAY_DELIVERY_OPTION; } diff --git a/Setup/UpgradeSchema.php b/Setup/UpgradeSchema.php index aaf31410e..90474814f 100644 --- a/Setup/UpgradeSchema.php +++ b/Setup/UpgradeSchema.php @@ -86,6 +86,10 @@ public function upgrade(SchemaSetupInterface $setup, ModuleContextInterface $con if (version_compare($context->getVersion(), '1.7.4', '<')) { $this->upgradeSchemas($this->upgradeSchemaObjects['v1.7.4'], $setup, $context); } + + if (version_compare($context->getVersion(), '1.8.0', '<')) { + $this->upgradeSchemas($this->upgradeSchemaObjects['v1.8.0'], $setup, $context); + } $setup->endSetup(); } diff --git a/Setup/V110/Data/ApiKeyConfiguration.php b/Setup/V110/Data/ApiKeyConfiguration.php deleted file mode 100644 index 9d3a49ea3..000000000 --- a/Setup/V110/Data/ApiKeyConfiguration.php +++ /dev/null @@ -1,92 +0,0 @@ -scopeConfig = $scopeConfig; - $this->resourceConfig = $resourceConfig; - $this->encryptor = $encryptor; - } - - /** - * The api key is normally encrypted before it gets saved in the database. But for testing purposes we want to add - * a default API key in the test configuration. If we put this in the config.xml the system will try to decrypt - * an plain text value, resulting in an invalid api key. That's why we read the default value, encrypt it, and - * save it to the database. - * - * @param ModuleDataSetupInterface $setup - * @param ModuleContextInterface $context - * - * @return void - */ - // @codingStandardsIgnoreLine - public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context) - { - $originalValue = $this->scopeConfig->getValue('tig_postnl/generalconfiguration_extension_status/api_key_test'); - $encryptedValue = $this->encryptor->encrypt($originalValue); - - $this->resourceConfig->saveConfig( - 'tig_postnl/generalconfiguration_extension_status/api_key_test', - $encryptedValue, - 'default', - 0 - ); - } -} diff --git a/Setup/V180/Schema/InstallPriorityAttribute.php b/Setup/V180/Schema/InstallPriorityAttribute.php new file mode 100644 index 000000000..dc537a986 --- /dev/null +++ b/Setup/V180/Schema/InstallPriorityAttribute.php @@ -0,0 +1,58 @@ + \Magento\Framework\DB\Ddl\Table::TYPE_TEXT, + 'length' => 12, + 'nullable' => true, + 'default' => null, + 'comment' => 'Country', + 'after' => 'shipment_type' + ]; + } +} diff --git a/Test/Fixtures/Timeframes/Days/DataProvider.php b/Test/Fixtures/Timeframes/Days/DataProvider.php index 1f5b5688f..9fee9cf09 100644 --- a/Test/Fixtures/Timeframes/Days/DataProvider.php +++ b/Test/Fixtures/Timeframes/Days/DataProvider.php @@ -96,7 +96,7 @@ public function shipmentDays() { return [ 'Wednesday is not a shippingday' => [ - '0,1,2,4,5,6', + '1,2,4,5,6,7', $this->getDaysForTwoWeeks(), '1', $this->getDaysForTwoWeeksWednesdayDisabled() @@ -684,6 +684,27 @@ private function getDaysForTwoWeeksWednesdayDisabled() ] ] ], + (object)[ // Sunday + 'Date' => '20-11-2016', + 'Timeframes' => (object)[ + 'TimeframeTimeFrame' => [ + (object)[ + 'From' => '13:00:00', + 'Options' => (object)[ + 'string' => ['Sunday'] + ], + 'To' => '15:30:00' + ], + (object)[ + 'From' => '18:00:00', + 'Options' => (object)[ + 'string' => ['Sunday'] + ], + 'To' => '22:30:00' + ] + ] + ] + ], (object)[ // Monday 'Date' => '21-11-2016', 'Timeframes' => (object)[ @@ -768,6 +789,20 @@ private function getDaysForTwoWeeksWednesdayDisabled() ] ] ], + (object)[ // Sunday + 'Date' => '27-11-2016', + 'Timeframes' => (object)[ + 'TimeframeTimeFrame' => [ + (object)[ + 'From' => '13:00:00', + 'Options' => (object)[ + 'string' => ['Sunday'] + ], + 'To' => '15:30:00' + ] + ] + ] + ], (object)[ // Monday 'Date' => '28-11-2016', 'Timeframes' => (object)[ diff --git a/Test/Integration/Observer/SetDefaultDataTest.php b/Test/Integration/Observer/SetDefaultDataTest.php index 787f7964c..4f8ea9195 100644 --- a/Test/Integration/Observer/SetDefaultDataTest.php +++ b/Test/Integration/Observer/SetDefaultDataTest.php @@ -38,7 +38,7 @@ use TIG\PostNL\Webservices\Endpoints\SentDate; use TIG\PostNL\Webservices\Endpoints\DeliveryDate; use TIG\PostNL\Service\Options\ItemsToOption; -use TIG\PostNL\Service\Order\ProductCodeAndType; +use TIG\PostNL\Service\Order\ProductInfo; use Magento\Framework\Event\Observer; use TIG\PostNL\Service\Order\MagentoOrder; use TIG\PostNL\Service\Quote\ShippingDuration; @@ -71,9 +71,9 @@ public function testExecute() $itemsToOptions->disableOriginalConstructor(); $itemsToOptions = $itemsToOptions->getMock(); - $productCodeAndType = $this->getMockBuilder(ProductCodeAndType::class); - $productCodeAndType->disableOriginalConstructor(); - $productCodeAndType = $productCodeAndType->getMock(); + $productInfo = $this->getMockBuilder(ProductInfo::class); + $productInfo->disableOriginalConstructor(); + $productInfo = $productInfo->getMock(); $magentoOrderService = $this->getMockBuilder(MagentoOrder::class); $magentoOrderService->disableOriginalConstructor(); @@ -85,9 +85,9 @@ public function testExecute() $this->objectManager->configure([ 'preferences' => [ - ProductCodeAndType::class => get_class($productCodeAndType), - ItemsToOption::class => get_class($itemsToOptions), - MagentoOrder::class => get_class($magentoOrderService), + ProductInfo::class => get_class($productInfo), + ItemsToOption::class => get_class($itemsToOptions), + MagentoOrder::class => get_class($magentoOrderService), ShippingDuration::class => get_class($shippingDuration) ], ]); @@ -102,11 +102,11 @@ public function testExecute() $magentoServiceGetAddress->method('getShippingAddress')->willReturn($address); $getFromQuote = $this->objectManager->get(ItemsToOption::class); - $getFromQuote->method('getFromQuote')->willReturn(ProductCodeAndType::OPTION_EXTRAATHOME); + $getFromQuote->method('getFromQuote')->willReturn(ProductInfo::OPTION_EXTRAATHOME); - $getProductInfo = $this->objectManager->get(ProductCodeAndType::class); + $getProductInfo = $this->objectManager->get(ProductInfo::class); $getProductInfo->method('get')->willReturn([ - 'type' => ProductCodeAndType::SHIPMENT_TYPE_EXTRAATHOME, + 'type' => ProductInfo::SHIPMENT_TYPE_EXTRAATHOME, 'code' => 3085 ]); @@ -123,7 +123,7 @@ public function testExecute() $this->getInstance()->execute($observer); $this->assertEquals(3085, $postNLOrder->getProductCode()); - $this->assertEquals(ProductCodeAndType::SHIPMENT_TYPE_EXTRAATHOME, $postNLOrder->getType()); + $this->assertEquals(ProductInfo::SHIPMENT_TYPE_EXTRAATHOME, $postNLOrder->getType()); } /** @@ -138,7 +138,7 @@ private function getPostNLOrder() if (!$postNLOrder) { $postNLOrder = $orderRepository->create(); $postNLOrder->setProductCode(3085); - $postNLOrder->setType(ProductCodeAndType::SHIPMENT_TYPE_DAYTIME); + $postNLOrder->setType(ProductInfo::SHIPMENT_TYPE_DAYTIME); } $postNLOrder->setDeliveryDate('2017-11-06 01:00:00'); diff --git a/Test/Integration/Service/Options/ItemsToOptionTest.php b/Test/Integration/Service/Options/ItemsToOptionTest.php index ac8aa7fd1..dff01be10 100644 --- a/Test/Integration/Service/Options/ItemsToOptionTest.php +++ b/Test/Integration/Service/Options/ItemsToOptionTest.php @@ -34,7 +34,7 @@ use TIG\PostNL\Test\Integration\TestCase; use Magento\Sales\Model\ResourceModel\Order\Collection; use TIG\PostNL\Service\Options\ItemsToOption; -use TIG\PostNL\Service\Order\ProductCodeAndType; +use TIG\PostNL\Service\Order\ProductInfo; class ItemsToOptionTest extends TestCase { @@ -48,7 +48,7 @@ public function testGetWithExtraAtHomeOrder() $order = $this->getOrder(); $result = $this->getInstance()->get($order->getItems()); - $this->assertEquals(ProductCodeAndType::OPTION_EXTRAATHOME, $result); + $this->assertEquals(ProductInfo::OPTION_EXTRAATHOME, $result); } public function testReqularOrder() diff --git a/Test/Unit/Config/CheckoutConfiguration/IsShippingOptionsActiveTest.php b/Test/Unit/Config/CheckoutConfiguration/IsShippingOptionsActiveTest.php index 1be0c1223..3ba6fe20c 100644 --- a/Test/Unit/Config/CheckoutConfiguration/IsShippingOptionsActiveTest.php +++ b/Test/Unit/Config/CheckoutConfiguration/IsShippingOptionsActiveTest.php @@ -36,7 +36,7 @@ use TIG\PostNL\Config\Provider\AccountConfiguration; use TIG\PostNL\Config\Provider\ShippingOptions; use TIG\PostNL\Service\Quote\CheckIfQuoteHasOption; -use TIG\PostNL\Service\Order\ProductCodeAndType; +use TIG\PostNL\Service\Order\ProductInfo; use TIG\PostNL\Test\TestCase; class IsShippingOptionsActiveTest extends TestCase @@ -680,7 +680,7 @@ public function testGetValue( $quoteHasOption = $this->getFakeMock(CheckIfQuoteHasOption::class)->getMock(); $extraAtHomeGetValueExpects = $quoteHasOption->method('get'); - $extraAtHomeGetValueExpects->with(ProductCodeAndType::OPTION_EXTRAATHOME); + $extraAtHomeGetValueExpects->with(ProductInfo::OPTION_EXTRAATHOME); $extraAtHomeGetValueExpects->willReturn($isExtraAtHome); /** @var IsShippingOptionsActive $instance */ diff --git a/Test/Unit/Config/Provider/WebshopTest.php b/Test/Unit/Config/Provider/WebshopTest.php index 12d2d4758..22eacf95d 100644 --- a/Test/Unit/Config/Provider/WebshopTest.php +++ b/Test/Unit/Config/Provider/WebshopTest.php @@ -118,9 +118,6 @@ public function testGetAllowedShippingMethods() public function cutoffTimeForDayProvider() { return [ - 'CutoffTime for sundays, day number 0' => [ - '0', Webshop::XPATH_WEBSHOP_SUNDAY_CUTOFFTIME, '10:00:00' - ], 'CutoffTime for sundays, day number 7' => [ '7', Webshop::XPATH_WEBSHOP_SUNDAY_CUTOFFTIME, '10:00:00' ], diff --git a/Test/Unit/Helper/DeliveryOptions/OrderParamsTest.php b/Test/Unit/Helper/DeliveryOptions/OrderParamsTest.php index 36eb05c1d..9f89ea8d0 100644 --- a/Test/Unit/Helper/DeliveryOptions/OrderParamsTest.php +++ b/Test/Unit/Helper/DeliveryOptions/OrderParamsTest.php @@ -34,7 +34,7 @@ use TIG\PostNL\Test\TestCase; use TIG\PostNL\Helper\DeliveryOptions\OrderParams; use TIG\PostNL\Service\Order\FeeCalculator; -use TIG\PostNL\Service\Order\ProductCodeAndType; +use TIG\PostNL\Service\Order\ProductInfo; use TIG\PostNL\Service\Shipment\ProductOptions; class OrderParamsTest extends TestCase @@ -53,13 +53,13 @@ class OrderParamsTest extends TestCase public function testGet() { - $productInfo = [ + $productMock = [ 'code' => '3085', 'type' => 'Daytime', ]; - $productCodeAndTypeMock = $this->getFakeMock(ProductCodeAndType::class)->getMock(); - $productCodeAndTypeMock->expects($this->once())->method('get')->willReturn($productInfo); + $productInfoMock = $this->getFakeMock(ProductInfo::class)->getMock(); + $productInfoMock->expects($this->once())->method('get')->willReturn($productMock); $feeCalculatorMock = $this->getFakeMock(FeeCalculator::class)->getMock(); $feeCalculatorMock->expects($this->once())->method('get')->willReturn(0.0); @@ -69,7 +69,7 @@ public function testGet() $instance = $this->getInstance([ 'feeCalculator' => $feeCalculatorMock, - 'productCodeAndType' => $productCodeAndTypeMock, + 'productInfo' => $productInfoMock, 'productOptions' => $productOptionsMock ]); diff --git a/Test/Unit/Service/Carrier/ParcelTypeFinderTest.php b/Test/Unit/Service/Carrier/ParcelTypeFinderTest.php index 714113fc5..d0dd94166 100644 --- a/Test/Unit/Service/Carrier/ParcelTypeFinderTest.php +++ b/Test/Unit/Service/Carrier/ParcelTypeFinderTest.php @@ -34,7 +34,7 @@ use TIG\PostNL\Api\Data\OrderInterface; use TIG\PostNL\Api\OrderRepositoryInterface; -use TIG\PostNL\Service\Order\ProductCodeAndType; +use TIG\PostNL\Service\Order\ProductInfo; use TIG\PostNL\Test\TestCase; class ParcelTypeFinderTest extends TestCase @@ -43,13 +43,13 @@ class ParcelTypeFinderTest extends TestCase public function testFindsExtraAtHome() { - $itemsToOption = $this->mockItemsToOption(ProductCodeAndType::OPTION_EXTRAATHOME); + $itemsToOption = $this->mockItemsToOption(ProductInfo::OPTION_EXTRAATHOME); $instance = $this->getInstance([ 'itemsToOption' => $itemsToOption, ]); - $this->assertEquals(ProductCodeAndType::OPTION_EXTRAATHOME, $instance->get()); + $this->assertEquals(ProductInfo::OPTION_EXTRAATHOME, $instance->get()); } public function testPakjegemakIsReturned() diff --git a/Test/Unit/Service/Handler/BarcodeHandlerTest.php b/Test/Unit/Service/Handler/BarcodeHandlerTest.php index a5c3eee46..a667360b2 100644 --- a/Test/Unit/Service/Handler/BarcodeHandlerTest.php +++ b/Test/Unit/Service/Handler/BarcodeHandlerTest.php @@ -34,6 +34,7 @@ use Magento\Framework\Phrase; use TIG\PostNL\Service\Handler\BarcodeHandler; use TIG\PostNL\Test\TestCase; +use TIG\PostNL\Api\Data\ShipmentInterface; class BarcodeHandlerTest extends TestCase { @@ -63,7 +64,7 @@ public function testGenerate($callReturnValue, $expected) $barcodeMock = $this->getBarcodeMock($callReturnValue); $instance = $this->getInstance(['barcodeEndpoint' => $barcodeMock]); - $result = $this->invoke('generate', $instance); + $result = $this->invokeArgs('generate', [$this->getShippmentMock()], $instance); if ($result instanceof Phrase) { $result = $result->render(); @@ -79,7 +80,7 @@ public function testShouldThrowExceptionWhenInvalidResponse() try { $instance = $this->getInstance(['barcodeEndpoint' => $barcodeMock]); - $result = $this->invoke('generate', $instance); + $result = $this->invokeArgs('generate', [$this->getShippmentMock()], $instance); if ($result instanceof Phrase) { $result->render(); } @@ -88,6 +89,18 @@ public function testShouldThrowExceptionWhenInvalidResponse() } } + protected function getShippmentMock() + { + $magentoShipmentMock = $this->getFakeMock('\Magento\Sales\Api\Data\ShipmentInterface')->getMock(); + $magentoShipmentMock->method('getStoreId')->willReturn(0); + + $shipmentMock = $this->getFakeMock(ShipmentInterface::class)->getMock(); + $shipmentMock->method('getProductCode')->willReturn('3085'); + $shipmentMock->method('getShipment')->willReturn($magentoShipmentMock); + + return $shipmentMock; + } + /** * @param $callReturnValue * diff --git a/Test/Unit/Service/Handler/PostcodecheckHandlerTest.php b/Test/Unit/Service/Handler/PostcodecheckHandlerTest.php index 7543aa0bb..97cb6dddf 100644 --- a/Test/Unit/Service/Handler/PostcodecheckHandlerTest.php +++ b/Test/Unit/Service/Handler/PostcodecheckHandlerTest.php @@ -74,6 +74,26 @@ public function responseDataProvider() 'In correct Response Data' => [ '[{"status":1,"city":"Amsterdam"}]', false, + ], + 'errors param set' => [ + '{"0":{"status":1,"streetName":"Kabelweg","city":"Amsterdam"},"errors":"error message"}', + 'error', + ], + 'fault param set' => [ + '{"0":{"status":1,"streetName":"Kabelweg","city":"Amsterdam"},"fault":"fault message"}', + 'error', + ], + 'no error, fault or 0 param set' => [ + '{"random":"different params than expected"}', + 'error', + ], + 'empty param array' => [ + '[]', + false, + ], + 'empty params' => [ + '', + 'error', ] ]; } diff --git a/Test/Unit/Service/Order/ProductCodeTest.php b/Test/Unit/Service/Order/ProductCodeTest.php index 5424a19b0..c7c6d6e21 100644 --- a/Test/Unit/Service/Order/ProductCodeTest.php +++ b/Test/Unit/Service/Order/ProductCodeTest.php @@ -33,7 +33,7 @@ use Magento\Quote\Model\Quote; use TIG\PostNL\Config\Provider\ProductOptions; -use TIG\PostNL\Service\Order\ProductCodeAndType; +use TIG\PostNL\Service\Order\ProductInfo; use TIG\PostNL\Service\Wrapper\QuoteInterface; use TIG\PostNL\Test\TestCase; @@ -44,7 +44,7 @@ class ProductCodeTest extends TestCase { const PRODUCT_OPTION_DEFAULT = 'default_product_option'; const PRODUCT_OPTION_BE_DEFAULT = 'default_be_product_option'; - const PRODUCT_OPTION_EPS_DEFAULT = 'default_eps_product_option'; + const PRODUCT_OPTION_EPS_DEFAULT = '4952'; const PRODUCT_OPTION_ALTERNATIVE_DEFAULT = 'alternative_default_product_option'; const PRODUCT_OPTION_EVENING = 'evening_product_option'; const PRODUCT_OPTION_EXTRAATHOME = 'extraathome_product_option'; @@ -62,7 +62,7 @@ class ProductCodeTest extends TestCase */ private $quoteInterfaceMock; - public $instanceClass = ProductCodeAndType::class; + public $instanceClass = ProductInfo::class; public function setUp() { @@ -201,7 +201,7 @@ public function testGetDefaultProductOption($useAlternative, $alternativeMinAmou $this->productOptionsMock->method('getAlternativeDefaultMinAmount')->willReturn($alternativeMinAmount); $instance = $this->getInstance(); - $this->invokeArgs('getDefaultProductOption', ['country' => 'NL'], $instance); + $this->invokeArgs('setDefaultProductOption', ['country' => 'NL'], $instance); $resultCode = $this->getProperty('code', $instance); $resultType = $this->getProperty('type', $instance); diff --git a/Test/Unit/Service/Quote/CheckIfQuoteHasOptionTest.php b/Test/Unit/Service/Quote/CheckIfQuoteHasOptionTest.php index 56bfa4139..9574e323f 100644 --- a/Test/Unit/Service/Quote/CheckIfQuoteHasOptionTest.php +++ b/Test/Unit/Service/Quote/CheckIfQuoteHasOptionTest.php @@ -34,7 +34,7 @@ use TIG\PostNL\Service\Quote\CheckIfQuoteHasOption; use Magento\Checkout\Model\Session as CheckoutSession; use TIG\PostNL\Service\Options\ItemsToOption; -use TIG\PostNL\Service\Order\ProductCodeAndType; +use TIG\PostNL\Service\Order\ProductInfo; use TIG\PostNL\Test\TestCase; class CheckIfQuoteHasOptionTest extends TestCase @@ -47,8 +47,8 @@ class CheckIfQuoteHasOptionTest extends TestCase public function getDataProvider() { return [ - 'Extra@Home with quote' => [ProductCodeAndType::OPTION_EXTRAATHOME, true, true], - 'Extra@Home no quote' => [ProductCodeAndType::OPTION_EXTRAATHOME, false, false] + 'Extra@Home with quote' => [ProductInfo::OPTION_EXTRAATHOME, true, true], + 'Extra@Home no quote' => [ProductInfo::OPTION_EXTRAATHOME, false, false] ]; } diff --git a/Test/Unit/Service/Shipment/CreateShipmentTest.php b/Test/Unit/Service/Shipment/CreateShipmentTest.php index a849ad077..41f9131ff 100644 --- a/Test/Unit/Service/Shipment/CreateShipmentTest.php +++ b/Test/Unit/Service/Shipment/CreateShipmentTest.php @@ -162,4 +162,69 @@ public function testOrderHasShipment($size, $expected) $result = $this->invoke('orderHasShipment', $instance); $this->assertEquals($expected, $result); } + + /** + * @return array + */ + public function handleExceptionForPossibleSoapErrorsProvider() + { + return [ + 'no errors, no message' => [ + null, + null, + '' + ], + 'no errors, has message' => [ + null, + 'exception message', + 'exception message' + ], + 'string errors, no message' => [ + 'error by string', + null, + '' + ], + 'string errors, has message' => [ + 'error by string', + 'exception message', + 'exception message' + ], + 'array errors, no message' => [ + ['first error by array.', 'another error.'], + null, + '[POSTNL-0010] - An error occurred while processing this action. first error by array. another error.' + ], + 'array errors, has message' => [ + ['first error by array.', 'another error.'], + 'exception message', + '[POSTNL-0010] - An error occurred while processing this action. first error by array. another error.' + ], + ]; + } + + /** + * @param $errors + * @param $message + * @param $expected + * + * @dataProvider handleExceptionForPossibleSoapErrorsProvider + */ + public function testHandleExceptionForPossibleSoapErrors($errors, $message, $expected) + { + $exceptionMockBuilder = $this->getMockBuilder(\Exception::class)->setConstructorArgs([$message]); + + if (null !== $errors) { + $exceptionMockBuilder->setMethods(['getErrors']); + } + + $exceptionMock = $exceptionMockBuilder->getMock(); + + if (null !== $errors) { + $exceptionMock->method('getErrors')->willReturn($errors); + } + + $instance = $this->getInstance(); + $result = $this->invokeArgs('handleExceptionForPossibleSoapErrors', [$exceptionMock], $instance); + $this->assertEquals($expected, $result); + } } diff --git a/Test/Unit/Service/Shipment/Label/Type/EPSTest.php b/Test/Unit/Service/Shipment/Label/Type/EPSTest.php new file mode 100644 index 000000000..44898e340 --- /dev/null +++ b/Test/Unit/Service/Shipment/Label/Type/EPSTest.php @@ -0,0 +1,68 @@ +getInstance(); + $result = $instance->isPriorityProduct(6350); + $expected = true; + + $this->assertEquals($expected, $result); + } + + /** + * @throws \Exception + */ + public function testIsRotatedProduct() + { + /** @var EPS $instance */ + $instance = $this->getInstance(); + $result = $instance->isRotatedProduct(4940); + $expected = true; + + $this->assertEquals($expected, $result); + } +} diff --git a/Test/Unit/Service/Shipment/Label/Type/GlobalPackTest.php b/Test/Unit/Service/Shipment/Label/Type/GlobalPackTest.php new file mode 100644 index 000000000..2a8f45528 --- /dev/null +++ b/Test/Unit/Service/Shipment/Label/Type/GlobalPackTest.php @@ -0,0 +1,55 @@ +getInstance(); + $result = $instance->isExcludedCountry("US"); + $expected = true; + + $this->assertEquals($expected, $result); + } +} diff --git a/Test/Unit/Webservices/Endpoints/SentDateTest.php b/Test/Unit/Webservices/Endpoints/SentDateTest.php index f0ab00e2a..4f31aa169 100644 --- a/Test/Unit/Webservices/Endpoints/SentDateTest.php +++ b/Test/Unit/Webservices/Endpoints/SentDateTest.php @@ -29,6 +29,7 @@ * @copyright Copyright (c) Total Internet Group B.V. https://tig.nl/copyright * @license http://creativecommons.org/licenses/by-nc-nd/3.0/nl/deed.en_US */ + namespace TIG\PostNL\Test\Unit\Webservices\Endpoints; use Magento\Framework\Stdlib\DateTime\TimezoneInterface; @@ -62,7 +63,7 @@ public function theParametersAreSetCorrectlyProvider() ['country' => 'DE', 'postcode' => '10179', 'delivery_date' => null], ['country' => 'NL', 'postcode' => '2132WT', 'delivery_date' => '19-11-2016'], ], - 'Reverse date' => [ + 'Reverse date' => [ ['country' => 'NL', 'postcode' => '1014 BA', 'delivery_date' => '2016-11-19'], ['country' => 'NL', 'postcode' => '1014BA', 'delivery_date' => '19-11-2016'], ], @@ -89,10 +90,12 @@ public function testTheParametersAreSetCorrectly($input, $expected) $orderMock = $this->getMock(OrderInterface::class); $this->mockFunction($orderMock, 'getDeliveryDate', $input['delivery_date']); - $falbackMock = $this->deliveryDateFallbackMock(); + $fallbackMock = $this->deliveryDateFallbackMock(); + $optionsMock = $this->optionsMock(); $instance = $this->getInstance([ - 'dateFallback' => $falbackMock + 'dateFallback' => $fallbackMock, + 'timeframeOptions' => $optionsMock ]); $instance->setParameters($address, 1, $orderMock); @@ -103,20 +106,32 @@ public function testTheParametersAreSetCorrectly($input, $expected) $this->assertEquals($expected['delivery_date'], $result['GetSentDate']['DeliveryDate']); } + /** + * @return \PHPUnit_Framework_MockObject_MockObject + */ + private function optionsMock() + { + $optionsMock = $this->getFakeMock(\TIG\PostNL\Service\Timeframe\Options::class)->getMock(); + $optionsExpected = $optionsMock->expects($this->any()); + $optionsExpected->method('get'); + $optionsExpected->willReturn(['Daytime']); + + return $optionsMock; + } + /** * @return \PHPUnit_Framework_MockObject_MockObject */ private function deliveryDateFallbackMock() { $fallbackMock = $this->getFakeMock(DeliveryDateFallback::class)->getMock(); - $getFalback = $fallbackMock->expects($this->any()); - $getFalback->method('get'); - $getFalback->willReturn('19-11-2016'); - - $getFalback2 = $fallbackMock->expects($this->any()); - $getFalback2->method('getDate'); - $getFalback2->willReturn('19-11-2016'); + $getFallback = $fallbackMock->expects($this->any()); + $getFallback->method('get'); + $getFallback->willReturn('19-11-2016'); + $getFallback2 = $fallbackMock->expects($this->any()); + $getFallback2->method('getDate'); + $getFallback2->willReturn('19-11-2016'); return $fallbackMock; } diff --git a/Webservices/Api/DeliveryDateFallback.php b/Webservices/Api/DeliveryDateFallback.php index 96cc22592..21b2609e5 100644 --- a/Webservices/Api/DeliveryDateFallback.php +++ b/Webservices/Api/DeliveryDateFallback.php @@ -71,7 +71,7 @@ public function get() $date = $this->getDate($nextDay); $day = $this->helper->getDayOrWeekNumber($nextDay); - if ($day == 0 || $day == 7) { + if ($day == 7) { $nextDay = $date .'+1 day'; } diff --git a/Webservices/Endpoints/Barcode.php b/Webservices/Endpoints/Barcode.php index eb38e2656..c7009b8c9 100644 --- a/Webservices/Endpoints/Barcode.php +++ b/Webservices/Endpoints/Barcode.php @@ -80,6 +80,11 @@ class Barcode extends AbstractEndpoint * @var string */ private $countryId; + + /** + * @var string + */ + private $type = ''; /** * Barcode constructor. @@ -116,7 +121,7 @@ public function call() { $this->validateRequiredValues(); - $barcode = $this->barcodeRange->getByCountryId($this->countryId, $this->storeId); + $barcode = $this->barcodeRange->getByCountryId($this->countryId, $this->storeId, $this->type); $parameters = [ 'Message' => $this->message->get(''), @@ -149,6 +154,14 @@ public function setCountryId($countryId) $this->countryId = $countryId; } + /** + * @param $type + */ + public function setType($type) + { + $this->type = $type; + } + /** * @param int $storeId */ diff --git a/Webservices/Endpoints/Confirming.php b/Webservices/Endpoints/Confirming.php index a63133bdc..801bcb28a 100644 --- a/Webservices/Endpoints/Confirming.php +++ b/Webservices/Endpoints/Confirming.php @@ -60,7 +60,7 @@ class Confirming extends AbstractEndpoint /** * @var string */ - private $version = 'v1_10'; + private $version = 'v2'; /** * @var string @@ -94,9 +94,11 @@ public function __construct( $shipmentData ); } - + /** - * {@inheritdoc} + * @return mixed + * @throws \Magento\Framework\Webapi\Exception + * @throws \TIG\PostNL\Webservices\Api\Exception */ public function call() { @@ -115,9 +117,9 @@ public function setParameters($shipment, $currentShipmentNumber = 1) 'Shipments' => $this->getShipments($shipment, $currentShipmentNumber), ]; } - + /** - * {@inheritdoc} + * @return string */ public function getLocation() { diff --git a/Webservices/Endpoints/Labelling.php b/Webservices/Endpoints/Labelling.php index cb55c8e31..7156bf78a 100644 --- a/Webservices/Endpoints/Labelling.php +++ b/Webservices/Endpoints/Labelling.php @@ -29,7 +29,6 @@ * @copyright Copyright (c) Total Internet Group B.V. https://tig.nl/copyright * @license http://creativecommons.org/licenses/by-nc-nd/3.0/nl/deed.en_US */ - namespace TIG\PostNL\Webservices\Endpoints; use TIG\PostNL\Model\Shipment; @@ -47,7 +46,7 @@ class Labelling extends AbstractEndpoint * @var Soap */ private $soap; - + /** * @var Customer */ @@ -61,8 +60,8 @@ class Labelling extends AbstractEndpoint /** * @var string */ - private $version = 'v2_1'; - + private $version = 'v2_2'; + /** * @var string */ @@ -97,7 +96,9 @@ public function __construct( } /** - * {@inheritdoc} + * @return mixed + * @throws \Magento\Framework\Webapi\Exception + * @throws \TIG\PostNL\Webservices\Api\Exception */ public function call() { @@ -126,7 +127,7 @@ public function setParameters($shipment, $currentShipmentNumber = 1) } /** - * {@inheritdoc} + * @return string */ public function getLocation() { diff --git a/Webservices/Endpoints/LabellingWithoutConfirm.php b/Webservices/Endpoints/LabellingWithoutConfirm.php index bd9830bf0..cdb4b5551 100644 --- a/Webservices/Endpoints/LabellingWithoutConfirm.php +++ b/Webservices/Endpoints/LabellingWithoutConfirm.php @@ -60,7 +60,7 @@ class LabellingWithoutConfirm extends AbstractEndpoint /** * @var string */ - private $version = 'v2_1'; + private $version = 'v2_2'; /** * @var string @@ -94,9 +94,11 @@ public function __construct( $shipmentData ); } - + /** - * {@inheritdoc} + * @return mixed + * @throws \Magento\Framework\Webapi\Exception + * @throws \TIG\PostNL\Webservices\Api\Exception */ public function call() { @@ -119,9 +121,9 @@ public function setParameters($shipment, $currentShipmentNumber = 1) 'Shipments' => $this->getShipments($shipment, $currentShipmentNumber), ]; } - + /** - * {@inheritdoc} + * @return string */ public function getLocation() { diff --git a/Webservices/Endpoints/SentDate.php b/Webservices/Endpoints/SentDate.php index a84c58dfd..2b2539d44 100644 --- a/Webservices/Endpoints/SentDate.php +++ b/Webservices/Endpoints/SentDate.php @@ -34,6 +34,7 @@ use Magento\Customer\Model\Address\AbstractAddress as Address; use TIG\PostNL\Api\Data\OrderInterface as PostNLOrder; +use TIG\PostNL\Service\Order\ProductInfo; use TIG\PostNL\Service\Timeframe\Options; use TIG\PostNL\Webservices\AbstractEndpoint; use TIG\PostNL\Webservices\Api\Message; @@ -47,7 +48,7 @@ class SentDate extends AbstractEndpoint /** * @var string */ - private $version = 'v2_1'; + private $version = 'v2_2'; /** * @var string @@ -158,12 +159,36 @@ public function setParameters($address, $storeId, PostNLOrder $postNLOrder) 'DeliveryDate' => $this->getDeliveryDate($address, $postNLOrder), 'ShippingDuration' => '1', // Request by PostNL not to use $postNLOrder->getShippingDuration() 'AllowSundaySorting' => $this->timeframeOptions->isSundaySortingAllowed(), - 'Options' => $this->timeframeOptions->get($this->getCountryId()) + 'Options' => [$this->getOption($postNLOrder)] ], 'Message' => $this->message ]; } + /** + * GetSentDate 2.2 doesn't support multiple options for requests. That's why we send + * along the option actually selected. + * + * @param PostNLOrder $postNLOrder + * + * @return string + */ + private function getOption(PostNLOrder $postNLOrder) + { + $availableOptions = $this->timeframeOptions->get($this->getCountryId()); + $currentType = $postNLOrder->getType(); + + if (in_array($currentType, $availableOptions)) { + return $currentType; + } + + if ($currentType == ProductInfo::SHIPMENT_TYPE_PG) { + return ucfirst(ProductInfo::TYPE_PICKUP); + } + + return ProductInfo::SHIPMENT_TYPE_DAYTIME; + } + /** * This endpoint is only available for dutch addresses. * diff --git a/Webservices/Endpoints/TimeFrame.php b/Webservices/Endpoints/TimeFrame.php index 00efa4792..5787bb12c 100644 --- a/Webservices/Endpoints/TimeFrame.php +++ b/Webservices/Endpoints/TimeFrame.php @@ -109,12 +109,14 @@ public function __construct( $shipmentData ); } - + /** * @param bool $parseTimeFrames * - * @return mixed + * @return array|mixed + * @throws \Magento\Framework\Exception\LocalizedException * @throws \Magento\Framework\Webapi\Exception + * @throws \TIG\PostNL\Webservices\Api\Exception */ public function call($parseTimeFrames = true) { diff --git a/composer.json b/composer.json index 33b564daf..dc68ee9c8 100644 --- a/composer.json +++ b/composer.json @@ -6,11 +6,11 @@ "ext-soap": "*", "magento/framework": ">=100.1.0,<=100.1.17|>=101.0.0,<=101.0.8|>=102.0.0,<=102.0.1|102.0.2-p2", "setasign/fpdi-fpdf": "2.1", - "zendframework/zend-barcode" : "2.7" + "zendframework/zend-barcode" : "2.5.2|2.7" }, "type": "magento2-module", "license": "CC-BY-NC-ND-3.0", - "version": "1.7.4", + "version": "1.8.0", "authors": [ { "name": "TIG", diff --git a/etc/adminhtml/system/globalpack.xml b/etc/adminhtml/system/globalpack.xml index 87427904b..5a8b30bb7 100644 --- a/etc/adminhtml/system/globalpack.xml +++ b/etc/adminhtml/system/globalpack.xml @@ -40,13 +40,24 @@ 1 \TIG\PostNL\Block\Adminhtml\Config\Globalpack\UsingGlobalpack + - + Worldwide shipping uses the PostNL GlobalPack product. Magento\Config\Model\Config\Source\Yesno tig_postnl/globalpack/enabled + + + + TIG\PostNL\Config\Source\Options\DefaultOptions::getGlobalProducts + tig_postnl/globalpack/default_gp_option + + 1 + + + tig_postnl-sub-section diff --git a/etc/adminhtml/system/postnlsettings.xml b/etc/adminhtml/system/postnlsettings.xml index 28ddd489d..8524e670a 100644 --- a/etc/adminhtml/system/postnlsettings.xml +++ b/etc/adminhtml/system/postnlsettings.xml @@ -86,7 +86,7 @@ TIG\PostNL\Block\Adminhtml\Config\Form\Field\Fieldset tig_postnl-sub-section - PostNL product options.]]> + PostNL product options.]]> @@ -196,14 +196,15 @@ - - + + + diff --git a/etc/adminhtml/system/postnlsettings/peps.xml b/etc/adminhtml/system/postnlsettings/peps.xml new file mode 100644 index 000000000..abdd40ac1 --- /dev/null +++ b/etc/adminhtml/system/postnlsettings/peps.xml @@ -0,0 +1,57 @@ + + + + + + + + TIG\PostNL\Block\Adminhtml\Config\Form\Field\Fieldset + tig_postnl-sub-sub-section + + + These products can only be used for an order which contains five or more parcels (colli). Each of these parcels should have a maximum weight of 2kg. + + Magento\Config\Model\Config\Source\Yesno + tig_postnl/peps/active + + + + The current PEPS barcode type as supplied by PostNL. Must contain 2 letters. + tig_postnl/peps/barcode_type + + 1 + + + + diff --git a/etc/config.xml b/etc/config.xml index a1ca545da..17a3370f1 100644 --- a/etc/config.xml +++ b/etc/config.xml @@ -50,10 +50,6 @@ 2.1.0 - 2.1.16, 2.2.0 - 2.2.7, 2.3.0 - 2.3.1 0 - 11223344 - TOTA - GXRgqbUdNxL1xWLaGNR77cWeWWIGDSJw - 103861 @@ -102,13 +98,13 @@ - 3089 + 3385 1 2 - 4938 + 4941 0 2 @@ -116,6 +112,7 @@ 1 0 + 2 3533 3543 @@ -167,6 +164,12 @@ + + 0 + LA + NL + + diff --git a/etc/di.xml b/etc/di.xml index 5748c6767..c26da29e6 100644 --- a/etc/di.xml +++ b/etc/di.xml @@ -105,6 +105,9 @@ + + TIG\PostNL\Setup\V180\Schema\InstallPriorityAttribute + TIG\PostNL\Setup\V174\Schema\InstallDownpartnerAttributes @@ -146,9 +149,6 @@ - - TIG\PostNL\Setup\V110\Data\ApiKeyConfiguration - TIG\PostNL\Setup\V120\Data\CustomProductAttributes diff --git a/etc/module.xml b/etc/module.xml index 285b7be1a..68682a8ad 100644 --- a/etc/module.xml +++ b/etc/module.xml @@ -32,7 +32,7 @@ * --> - + diff --git a/i18n/en_US.csv b/i18n/en_US.csv index 1d5797272..91279b154 100644 --- a/i18n/en_US.csv +++ b/i18n/en_US.csv @@ -181,7 +181,7 @@ Percent,Percent "Post office delivery","Post office delivery" "Post office early delivery","Post office early delivery" "In order to use this extension you need to be a contract customer of PostNL. If you are not a customer of PostNL, you can register yourself here.","In order to use this extension you need to be a contract customer of PostNL. If you are not a customer of PostNL, you can register yourself here." -"You will then receive all necessary information in order to configure the extension. If you cannot find the email containing this information, please contact PostNL support at 058-2333343.","You will then receive all necessary information in order to configure the extension. If you cannot find the email containing this information, please contact PostNL support at 058-2333343." +"You will then receive all necessary information in order to configure the extension. If you cannot find the email containing this information, please contact PostNL support at 088-2255651.","You will then receive all necessary information in order to configure the extension. If you cannot find the email containing this information, please contact PostNL support at 088-2255651." "If you want to test the extension, but do not have any test mode credentials you can use the account credentials found here.","If you want to test the extension, but do not have any test mode credentials you can use the account credentials found here." "If you are unsure which options to select, ask your PostNL account manager. Read more about PostNL product options.","If you are unsure which options to select, ask your PostNL account manager. Read more about PostNL product options." "Select the PostNL product that you want to use for your shipments.","Select the PostNL product that you want to use for your shipments." @@ -416,3 +416,4 @@ Percent,Percent "Maximum weight per parcel","Maximum weight per parcel" "Defines the maximum weight per parcel. Uses the Weight Unit as defined in: General > General > Local Options > Weight Unit","Defines the maximum weight per parcel. Uses the Weight Unit as defined in: General > General > Local Options > Weight Unit" "If the total weight of the order exceeds the value defined here, it will be divided into multiple parcels. A separate label will be generated for each parcel.","If the total weight of the order exceeds the value defined here, it will be divided into multiple parcels. A separate label will be generated for each parcel." +"Packets Tracked can only be used if 5 packages or more are delivered in a domestic mail bag with an attached bag label specific for priority parcels.","Packets Tracked can only be used if 5 packages or more are delivered in a domestic mail bag with an attached bag label specific for priority parcels." diff --git a/i18n/nl_NL.csv b/i18n/nl_NL.csv index 5d8716c33..4d024adcb 100644 --- a/i18n/nl_NL.csv +++ b/i18n/nl_NL.csv @@ -196,7 +196,7 @@ Percent,Percentage "PostNL - Generate Label","PostNL - Genereer Label" "Default postoffice early pickup option","Standaard ophalen bij PostNL locatie extra vroeg optie" "In order to use this extension you need to be a contract customer of PostNL. If you are not a customer of PostNL, you can register yourself here.","Om deze extensie te kunnen gebruiken dient u een contract met PostNL af te sluiten. Indien u geen klant bent van PostNL dan kunt u zichzelf hier aanmelden." -"You will then receive all necessary information in order to configure the extension. If you cannot find the email containing this information, please contact PostNL support at 058-2333343.","U ontvangt de benodigde informatie om deze extensie te configureren. Indien u deze e-mail met informatie niet heeft ontvangen, neem dan contact met PostNL support op 058-2333343." +"You will then receive all necessary information in order to configure the extension. If you cannot find the email containing this information, please contact PostNL support at 088-2255651.","U ontvangt de benodigde informatie om deze extensie te configureren. Indien u deze e-mail met informatie niet heeft ontvangen, neem dan contact met PostNL support op 088-2255651." "If you want to test the extension, but do not have any test mode credentials you can use the account credentials found here.","Indien u deze extensie wilt uitproberen, maar geen testgegevens heeft, dan kunt u hier testgegevens vinden." "If you are unsure which options to select, ask your PostNL account manager. Read more about PostNL product options.","Indien u niet zeker weet welke opties voor uw webshop van toepassing zijn, dan kunt u dit vragen aan uw PostNL account manager. Lees meer over PostNL productopties." "Select the PostNL product that you want to use for your shipments.","Selecteer de PostNL producten die u wilt gebruiken voor uw verzendingen. " @@ -436,3 +436,4 @@ Percent,Percentage "Maximum weight per parcel","Maximaal gewicht per pakket" "Defines the maximum weight per parcel. Uses the Weight Unit as defined in: General > General > Local Options > Weight Unit","Bepaald het maximale gewicht per pakket. Gebruikt de eenheid, zoals ingesteld onder Algemeen > Algemeen > Lokalisatie-opties > Gewichtseenheid" "If the total weight of the order exceeds the value defined here, it will be divided into multiple parcels. A separate label will be generated for each parcel.","Als het totale gewicht deze waarde overschrijdt, zal de bestelling opgedeeld worden in meerdere pakketten. Voor ieder pakket zal een apart label worden gegenereerd." +"Packets Tracked can only be used if 5 packages or more are delivered in a domestic mail bag with an attached bag label specific for priority parcels.","Pakjes Tracked kunnen alleen gebruikt worden als 5 pakketten of meer aangeleverd worden in een binnenlandse postzak met een aangehecht zaklabel specifiek voor Priority Parcels." \ No newline at end of file diff --git a/view/adminhtml/templates/config/general/accountSettings.phtml b/view/adminhtml/templates/config/general/accountSettings.phtml index 0e9afb085..7913041bb 100644 --- a/view/adminhtml/templates/config/general/accountSettings.phtml +++ b/view/adminhtml/templates/config/general/accountSettings.phtml @@ -40,7 +40,7 @@

register yourself here.', [$block->getInfoUrlForDeliveryoptions()]); ?>

- +

diff --git a/view/adminhtml/templates/config/support/supportTab.phtml b/view/adminhtml/templates/config/support/supportTab.phtml index 545869580..20e5a373f 100644 --- a/view/adminhtml/templates/config/support/supportTab.phtml +++ b/view/adminhtml/templates/config/support/supportTab.phtml @@ -129,7 +129,7 @@ escapeHtml(__('Phone:'));?> -
  • +31 (0)88-2255652
  • +
  • +31 (0)88-2255651
    • diff --git a/view/adminhtml/templates/shipment/view/javascript.phtml b/view/adminhtml/templates/shipment/view/javascript.phtml index ea872a8a2..fb3c024ae 100644 --- a/view/adminhtml/templates/shipment/view/javascript.phtml +++ b/view/adminhtml/templates/shipment/view/javascript.phtml @@ -31,8 +31,24 @@ */ ?> diff --git a/view/adminhtml/web/css/adminhtml_config.css b/view/adminhtml/web/css/adminhtml_config.css index 380d8da8a..d2aab8e65 100644 --- a/view/adminhtml/web/css/adminhtml_config.css +++ b/view/adminhtml/web/css/adminhtml_config.css @@ -351,7 +351,6 @@ float:left; width: 50px; height: 37px; - content: ' '; background-image: url(../images/postnl_logo_50.png) !important; background-position: 0 2px; @@ -390,6 +389,9 @@ background-size: auto 29px; } +.postnl-config-page .page-main-actions .page-actions:not(._fixed) .page-actions-inner:before { + margin-left: 80px; +} .postnl-config-page .page-main-actions .page-actions .page-actions-inner:after { background-image: url(../images/logo_tig.png) !important; diff --git a/view/frontend/web/js/Helper/AddressFinder.js b/view/frontend/web/js/Helper/AddressFinder.js index b83dfd217..d75b00c62 100644 --- a/view/frontend/web/js/Helper/AddressFinder.js +++ b/view/frontend/web/js/Helper/AddressFinder.js @@ -95,9 +95,14 @@ define([ * The street is not always available on the first run. */ var shippingAddress = quote.shippingAddress(); - if (customer.isLoggedIn() && shippingAddress && shippingAddress.street) { + var quoteStreet = []; + if (shippingAddress) { + quoteStreet = (typeof shippingAddress.street === 'undefined') ? [] : shippingAddress.street; + } + + if (customer.isLoggedIn() && shippingAddress && quoteStreet.length > 0) { address = { - street: shippingAddress.street, + street: quoteStreet, postcode: shippingAddress.postcode, lastname: shippingAddress.lastname, firstname: shippingAddress.firstname, diff --git a/view/frontend/web/js/Helper/State.js b/view/frontend/web/js/Helper/State.js index e8ca26e97..f78611b8a 100644 --- a/view/frontend/web/js/Helper/State.js +++ b/view/frontend/web/js/Helper/State.js @@ -57,6 +57,10 @@ define([ return; } + if (shippingMethod.carrier_code !== 'tig_postnl') { + currentSelectedShipmentType(shippingMethod.carrier_code); + } + if (shippingMethod.carrier_code === 'tig_postnl') { return; } diff --git a/view/frontend/web/js/Renderer/DeliveryOptions/Delivery.js b/view/frontend/web/js/Renderer/DeliveryOptions/Delivery.js index 8d82ccf68..23a430590 100644 --- a/view/frontend/web/js/Renderer/DeliveryOptions/Delivery.js +++ b/view/frontend/web/js/Renderer/DeliveryOptions/Delivery.js @@ -109,13 +109,11 @@ define([ State.currentSelectedShipmentType('delivery'); State.selectShippingMethod(); - if (value.fallback) { - return; - } - var fee = null; - if (value.hasFee()) { - fee = value.getFee(); + if (!value.fallback) { + if (value.hasFee()) { + fee = value.getFee(); + } } State.fee(fee); @@ -126,12 +124,13 @@ define([ method : 'POST', url : window.checkoutConfig.shipping.postnl.urls.deliveryoptions_save, data : { - type : 'delivery', + address: AddressFinder(), + type : (typeof value.fallback !== 'undefined') ? 'fallback' : 'delivery', date : value.date, option : value.option, from : value.from, to : value.to, - country: value.address.country + country: (typeof value.address !== 'undefined') ? value.address.country : AddressFinder().country } }).done(function (response) { $(document).trigger('compatible_postnl_deliveryoptions_save_done', {response: response}); diff --git a/view/frontend/web/js/view/form/fields.js b/view/frontend/web/js/view/form/fields.js index 03aaab736..b07280022 100644 --- a/view/frontend/web/js/view/form/fields.js +++ b/view/frontend/web/js/view/form/fields.js @@ -222,32 +222,25 @@ define([ $("input[name*='street[0]']").trigger('change'); $("input[name*='city']").trigger('change'); - return; + errorMessage = null; + } + + if (data.error) { + console.error(data.error); } - console.error(data.error); self.handleError(errorMessage); }, handleError : function (errorMessage) { var self = this; var error = $('.tig-postnl-validation-message'); + error.hide(); if (errorMessage) { self.enableAddressFields(true); error.html(errorMessage).show(); - - var timer; - if (typeof timer !== 'undefined') { - clearTimeout(timer); - } - - timer = setTimeout(function () { - error.hide(100); - }, 16000); - } else { - error.hide(); } },