Skip to content

Commit

Permalink
Add expected delivery dates for PostNL and DHL (#20)
Browse files Browse the repository at this point in the history
  • Loading branch information
LucaScorpion authored Jan 25, 2024
1 parent 4342aff commit bba6a55
Show file tree
Hide file tree
Showing 6 changed files with 182 additions and 22 deletions.
1 change: 1 addition & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,6 @@ jobs:
- uses: php-actions/composer@v6
with:
args: --ignore-platform-reqs
php_version: 8.2
- run: composer cs:check
- run: composer md
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# Changelog

## 2.18.0 - 2024-01-25

### New

- Optie om verwachte bezorgdatum voor PostNL en DHL weer te geven toegevoegd

## 2.17.2 - 2024-01-18

### Fixes
Expand Down
164 changes: 147 additions & 17 deletions Model/Carrier/Parcelpro.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,37 +2,38 @@

namespace Parcelpro\Shipment\Model\Carrier;

use DateInterval;
use DateTime;
use Magento\Quote\Model\Quote\Address\RateRequest;
use Magento\Shipping\Model\Rate\Result;

/**
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class Parcelpro extends \Magento\Shipping\Model\Carrier\AbstractCarrier implements
\Magento\Shipping\Model\Carrier\CarrierInterface
{
/**
* @var string
*/
protected $_code = 'parcelpro';

/**
* @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
* @param \Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory $rateErrorFactory
* @param \Psr\Log\LoggerInterface $logger
* @param \Magento\Shipping\Model\Rate\ResultFactory $rateResultFactory
* @param \Magento\Quote\Model\Quote\Address\RateResult\MethodFactory $rateMethodFactory
* @param array $data
*/
/** @var \Magento\Framework\Locale\Resolver */
protected $localeResolver;

private $apiUrl = 'https://login.parcelpro.nl';

public function __construct(
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
\Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory $rateErrorFactory,
\Psr\Log\LoggerInterface $logger,
\Magento\Shipping\Model\Rate\ResultFactory $rateResultFactory,
\Magento\Quote\Model\Quote\Address\RateResult\MethodFactory $rateMethodFactory,
\Magento\Framework\Serialize\Serializer\Json $serialize,
\Magento\Framework\Locale\Resolver $localeResolver,
array $data = []
) {
$this->_rateResultFactory = $rateResultFactory;
$this->_rateMethodFactory = $rateMethodFactory;
$this->serialize = $serialize;
$this->localeResolver = $localeResolver;
parent::__construct($scopeConfig, $rateErrorFactory, $logger, $data);
}

Expand Down Expand Up @@ -110,19 +111,24 @@ public function collectRates(RateRequest $request)
return false;
}

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

/** @var \Magento\Checkout\Model\Session $checkoutSession */
$checkoutSession = $objectManager->create('\Magento\Checkout\Model\Session');
$shippingAddress = $checkoutSession->getQuote()->getShippingAddress();

$result = $this->_rateResultFactory->create();
$am = $this->getAllowedMethods();
foreach ($am as $key => $_) {
if ($this->getConfigData($key)) {
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
/** @var \Magento\Framework\App\State $state */
$state = $objectManager->get('\Magento\Framework\App\State');
$_pricIncl = $this->getConfigData('price_incl');
if ($state->getAreaCode() == \Magento\Framework\App\Area::AREA_ADMINHTML) {
$object = $objectManager->create('\Magento\Sales\Model\AdminOrder\Create');
$total = $object->getQuote()->getSubtotal();
$grandTotal = $object->getQuote()->getGrandTotal();
} else {
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$total = $objectManager->create('\Magento\Checkout\Model\Session')
->getQuote()->getSubtotal();

Expand Down Expand Up @@ -153,7 +159,7 @@ public function collectRates(RateRequest $request)
if (is_null($pricerule['btw_tarief'])) {
$pricerule['btw_tarief'] = 0;
}
$shippingPrice = ( (float)$pricerule['btw_tarief'] ? ( (float)$pricerule['price'] + ((float)$pricerule['price'] / 100 ) * (float)$pricerule['btw_tarief'] ) : (float)$pricerule['price'] );
$shippingPrice = ((float)$pricerule['btw_tarief'] ? ((float)$pricerule['price'] + ((float)$pricerule['price'] / 100) * (float)$pricerule['btw_tarief']) : (float)$pricerule['price']);
break;
}
}
Expand All @@ -164,9 +170,45 @@ public function collectRates(RateRequest $request)
$method->setCarrier($this->_code);

if (strpos(strtolower($key), 'postnl') !== false) {
$method->setCarrierTitle('PostNL');
$carrierTitle = 'PostNL';

if ($this->getConfigData('postnl_show_expected_delivery_date')) {
$sendDay = new DateTime();
if (!$this->isBeforeLastShippingTime($this->getConfigData('postnl_last_shipping_time'))) {
$sendDay->add(new DateInterval('P1D'));
}

$deliveryDate = $this->getDeliveryDate(
'PostNL',
$sendDay,
$shippingAddress->getPostcode()
);

if ($deliveryDate) {
$carrierTitle .= ' (' . $this->formatDeliveryDate($deliveryDate) . ')';
}
}
$method->setCarrierTitle($carrierTitle);
} elseif (strpos(strtolower($key), 'dhl') !== false) {
$method->setCarrierTitle('DHL');
$carrierTitle = 'DHL';

if ($this->getConfigData('dhl_show_expected_delivery_date')) {
$sendDay = new DateTime();
if (!$this->isBeforeLastShippingTime($this->getConfigData('dhl_last_shipping_time'))) {
$sendDay->add(new DateInterval('P1D'));
}

$deliveryDate = $this->getDeliveryDate(
'DHL',
$sendDay,
$shippingAddress->getPostcode()
);

if ($deliveryDate) {
$carrierTitle .= ' (' . $this->formatDeliveryDate($deliveryDate) . ')';
}
}
$method->setCarrierTitle($carrierTitle);
} elseif (strpos(strtolower($key), 'vsp') !== false) {
$method->setCarrierTitle('Van Straaten Post');
} elseif (strpos(strtolower($key), 'sameday') !== false) {
Expand All @@ -192,7 +234,7 @@ public function collectRates(RateRequest $request)
if (is_null($pricerule['btw_tarief'])) {
$pricerule['btw_tarief'] = 0;
}
$shippingPrice = ( (float)$pricerule['btw_tarief'] ? ( (float)$pricerule['price'] + ((float)$pricerule['price'] / 100 ) * (float)$pricerule['btw_tarief'] ) : (float)$pricerule['price'] );
$shippingPrice = ((float)$pricerule['btw_tarief'] ? ((float)$pricerule['price'] + ((float)$pricerule['price'] / 100) * (float)$pricerule['btw_tarief']) : (float)$pricerule['price']);

if ($shippingPrice !== false) {
$method = $this->_rateMethodFactory->create();
Expand All @@ -217,4 +259,92 @@ public function collectRates(RateRequest $request)
}
return $result;
}

private function getDeliveryDate(string $carrier, \DateTimeInterface $dateTime, $postcode)
{
if (!$postcode) {
return false;
}

$date = $dateTime->format('Y-m-d');
$userId = $this->getConfigData('gebruiker_id');
$apiKey = $this->getConfigData('api_key');

$query = http_build_query([
'Startdatum' => $date,
'Postcode' => $postcode,
'GebruikerId' => $userId,
'Map' => true,
]);

$curlHandle = curl_init();
curl_setopt_array($curlHandle, [
CURLOPT_URL => $this->apiUrl . '/api/v3/timeframes.php?' . $query,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'Digest: ' . hash_hmac(
"sha256",
sprintf('GebruikerId=%sPostcode=%sStartdatum=%s', $userId, $postcode, $date),
$apiKey
),
],
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HEADER => false,
CURLOPT_RETURNTRANSFER => true,
]);

$responseBody = curl_exec($curlHandle);
$responseCode = curl_getinfo($curlHandle, CURLINFO_RESPONSE_CODE);

curl_close($curlHandle);

if ($responseCode !== 200) {
$this->_logger->error(sprintf(
'Failed to get expected delivery date, response code %s, body:\n%s',
$responseCode,
$responseBody
));
return false;
}

$responseJson = json_decode($responseBody, true);
$rawDate = $responseJson[$carrier]['Date'] ?? false;

if (!$rawDate) {
$this->_logger->error(sprintf(
'Failed to get expected delivery date, body:\n%s',
$responseBody
));
return false;
}

return \DateTimeImmutable::createFromFormat('Y-m-d', $rawDate);
}

private function formatDeliveryDate(\DateTimeInterface $date)
{
$locale = $this->localeResolver->getLocale();
return \IntlDateFormatter::formatObject($date, 'd MMMM', $locale);
}

private function isBeforeLastShippingTime($rawLastTime): bool
{
if (!$rawLastTime) {
return true;
}

try {
$parsed = new DateTime($rawLastTime);
} catch (\Exception $e) {
$this->_logger->error(sprintf(
'Failed to parse last shipping time (%s): %s',
$rawLastTime,
$e->getMessage()
));
return true;
}

$now = new DateTime();
return $now < $parsed;
}
}
9 changes: 6 additions & 3 deletions composer.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "parcelpro/shipment",
"description": "Verzendmodule om gemakkelijk orders in te laden in het verzendsysteem van Parcel Pro.",
"version": "2.17.2",
"version": "2.18.0",
"keywords": [
"verzenden",
"pakket",
Expand All @@ -11,7 +11,10 @@
],
"type": "magento2-module",
"require": {
"php": ">=7.1"
"php": ">=7.1",
"ext-json": "*",
"ext-curl": "*",
"ext-intl": "*"
},
"license": [
"OSL-3.0"
Expand All @@ -35,7 +38,7 @@
"require-dev": {
"squizlabs/php_codesniffer": "^3.7",
"magento/community-edition": "^2.4",
"phpmd/phpmd": "^2.14"
"phpmd/phpmd": "^2.15"
},
"config": {
"allow-plugins": {
Expand Down
22 changes: 21 additions & 1 deletion etc/adminhtml/system.xml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
<tooltip>
<![CDATA[Versie van onze plug-in]]>
</tooltip>
<comment>2.17.2</comment>
<comment>2.18.0</comment>
</field>
<field id="active" translate="label" type="select" sortOrder="20" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Enabled</label>
Expand Down Expand Up @@ -62,6 +62,16 @@
<field id="postnl_title" translate="label comment tooltip" type="text" sortOrder="200" showInDefault="1" showInWebsite="1" showInStore="1">
<label>PostNL versturen via parcelpro.nl</label>
</field>
<field id="postnl_show_expected_delivery_date" translate="label" type="select" sortOrder="201" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Geef verwachte PostNL bezorgdatum weer</label>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
</field>
<field id="postnl_last_shipping_time" translate="label" type="text" sortOrder="202" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Laatste verzendtijd (met tijdzone) voor huidige dag (bijv.: "22:00 Europe/Amsterdam")</label>
<tooltip>
<![CDATA[De laatste tijd waarop bestellingen verzonden kunnen worden. Na deze tijd wordt de verwachte bezorging vanaf de volgende dag genomen. Bijvoorbeeld: "22:00 Europe/Amsterdam".]]>
</tooltip>
</field>
<field id="postnl_afleveradres" translate="label comment tooltip" sortOrder="210" showInDefault="1" showInWebsite="1" showInStore="1">
<label>PostNL Afleveradres</label>
<frontend_model>Parcelpro\Shipment\Block\Adminhtml\System\Config\Form\Field\Countriesmap</frontend_model>
Expand Down Expand Up @@ -106,6 +116,16 @@
<field id="dhl_title" translate="label" type="text" sortOrder="300" showInDefault="1" showInWebsite="1" showInStore="1">
<label>DHL versturen via parcelpro.nl</label>
</field>
<field id="dhl_show_expected_delivery_date" translate="label" type="select" sortOrder="301" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Geef verwachte DHL bezorgdatum weer</label>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
</field>
<field id="dhl_last_shipping_time" translate="label" type="text" sortOrder="302" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Laatste verzendtijd (met tijdzone) voor huidige dag (bijv.: "22:00 Europe/Amsterdam")</label>
<tooltip>
<![CDATA[De laatste tijd waarop bestellingen verzonden kunnen worden. Na deze tijd wordt de verwachte bezorging vanaf de volgende dag genomen. Bijvoorbeeld: "22:00 Europe/Amsterdam".]]>
</tooltip>
</field>
<field id="dhl_afleveradres" translate="label" type="text" sortOrder="310" showInDefault="1" showInWebsite="1" showInStore="1">
<label>DHL Afleveradres</label>
<frontend_model>Parcelpro\Shipment\Block\Adminhtml\System\Config\Form\Field\Countriesmap</frontend_model>
Expand Down
2 changes: 1 addition & 1 deletion install.sh
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ dx php bin/magento module:enable --clear-static-content Parcelpro_Shipment
dx rm -r generated

# Update the Magento setup and flush the cache.
dx php bin/magento setup:upgrade
dx php bin/magento setup:di:compile
dx php bin/magento setup:upgrade
dx php bin/magento setup:static-content:deploy -f
dx php bin/magento cache:clean
dx php bin/magento cache:flush

0 comments on commit bba6a55

Please sign in to comment.