Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
263 changes: 0 additions & 263 deletions app/code/Magento/Dhl/Model/Carrier.php
Original file line number Diff line number Diff line change
Expand Up @@ -1638,269 +1638,6 @@ protected function _addRestRate(array $product, array $exchangeRates): self
return $this;
}

/**
* DHL REST API for Quote Data
*
* @return Result\ProxyDeferred
* @throws LocalizedException
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
protected function _getQuotesRest()
{
$rawRequest = $this->_rawRequest;
$url = $this->getGatewayURL();
$packageWeightUnit = $this->_getRestPackageWeightUnit();

/** Dutiable */
$dutiable = ["isCustomsDeclarable" => false];
if ($this->isDutiable($rawRequest->getOrigCountryId(), $rawRequest->getDestCountryId())) {
$declaredValue = (int) $rawRequest->getValue();
$baseCurrencyCode = $this->_storeManager
->getWebsite($this->_request->getWebsiteId())
->getBaseCurrencyCode();
$dutiable = [
"isCustomsDeclarable" => true,
"monetaryAmount" => [
[
"typeCode" => "declaredValue",
"value" => $declaredValue,
"currency" => $baseCurrencyCode
]
]
];
}

$rateParams = array_merge([
"customerDetails" => [
"shipperDetails" => [
"postalCode" => $rawRequest->getOrigPostal(),
"cityName" => $rawRequest->getOrigCity(),
"countryCode" => $rawRequest->getOrigCountryId()
],
"receiverDetails" => [
"postalCode" => $rawRequest->getDestPostal(),
"cityName" => $rawRequest->getDestCity(),
"countryCode" => $rawRequest->getDestCountryId()
]
],
"accounts" => [
[
"typeCode" => "shipper",
"number" => $this->getConfigData('account')
]
],
"plannedShippingDateAndTime" => date('Y-m-d\TH:i:s\Z', strtotime($this->_getShipDate())),
"unitOfMeasurement" => $packageWeightUnit,
"getAdditionalInformation" => [
[
"typeCode" => "allValueAddedServices",
"isRequested" => true
]
],
"packages" => [
[
"typeCode" => "3BX",
"weight" => (float) $this->_getWeight($rawRequest->getWeight()),
"dimensions" => [
// If no value is provided for the dimension, a default size of 3 will be used
"length" => $this->_getDimension(max(3, $this->getConfigData('depth'))),
"width" => $this->_getDimension(max(3, $this->getConfigData('width'))),
"height" => $this->_getDimension(max(3, $this->getConfigData('height')))
]
]
]
], $dutiable);

$ratePayload = json_encode($rateParams, JSON_PRETTY_PRINT);

$httpResponse = $this->httpClient->request(
new Request($url . '/rates', Request::METHOD_POST, $this->getRestHeaders(), $ratePayload)
);
$debugData['request'] = $ratePayload;

return $this->proxyDeferredFactory->create(
[
'deferred' => new CallbackDeferred(
function () use ($httpResponse, $debugData) {
$responseResult = null;
$jsonResponse = '';
try {
$responseResult = $httpResponse->get();
} catch (HttpException $e) {
$debugData['result'] = ['error' => $e->getMessage(), 'code' => $e->getCode()];
$this->_logger->critical($e);
}
if ($responseResult) {
$jsonResponse = $responseResult->getStatusCode() >= 400 ? '' : $responseResult->getBody();
}
$debugData['result'] = $jsonResponse;
$this->_debug($debugData);
return $this->_parseRestResponse($jsonResponse);
}
)
]
);
}

/**
* DHL REST Auth Token
*
* @return string
*/
private function getDhlAccessToken() : string
{
$username = (string) $this->getConfigData('api_key');
$password = (string) $this->getConfigData('api_secret');
$access_token = base64_encode($username . ":" . $password);
return $access_token;
}

/**
* Rest API Headers
*
* @return string[]
*/
private function getRestHeaders(): array
{
return [
"Authorization" => "Basic " . $this->getDhlAccessToken(),
"Content-Type" => "application/json",
"x-version" => self::DHL_REST_API_VERSION
];
}

/**
* Parse response from DHL REST API
*
* @param string $rateResponse
* @return Result
* @throws LocalizedException
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/
protected function _parseRestResponse($rateResponse): Result
{
$responseError = __('The response is in wrong format.');
if ($rateResponse !== null && strlen($rateResponse) > 0) {
$rateResponseData = json_decode($rateResponse, true);
if (isset($rateResponseData['products']) && isset($rateResponseData['exchangeRates'])) {
foreach ($rateResponseData['products'] as $product) {
$this->_addRestRate($product, $rateResponseData['exchangeRates']);
}
} else {
$this->_errors[] = $responseError;
}
}

/* @var $result Result */
$result = $this->_rateFactory->create();
if ($this->_rates) {
foreach ($this->_rates as $rate) {
$method = $rate['service'];
$data = $rate['data'];
/* @var $rate Method */
$rate = $this->_rateMethodFactory->create();
$rate->setCarrier(self::CODE);
$rate->setCarrierTitle($this->getConfigData('title'));
$rate->setMethod($method);
$rate->setMethodTitle($data['term']);
$rate->setCost($data['price_total']);
$rate->setPrice($data['price_total']);
$result->append($rate);
}
} else {
if (!empty($this->_errors)) {
if ($this->_isShippingLabelFlag) {
throw new LocalizedException($responseError);
}
$this->debugErrors($this->_errors);
}
$result->append($this->getErrorMessage());
}

return $result;
}

/**
* DHL Quote Data calculating rates
*
* @param array $product
* @param array $exchangeRates
* @return $this
* @throws LocalizedException
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/
protected function _addRestRate(array $product, array $exchangeRates): self
{
if (isset($product['productName'])
&& isset($product['productCode'])
&& isset($exchangeRates[0]['currency'])
&& array_key_exists((string)$product['productCode'], $this->getAllowedMethods())
) {
// DHL product code, e.g. '3', 'A', 'N', etc.
$dhlProduct = (string)$product['productCode'];
$totalPrice = $product['totalPrice'];
$billic_price = array_column(
array_filter($totalPrice, fn ($price) => $price['currencyType'] === 'BILLC'),
'price'
);

$totalEstimate = (float)(string) $billic_price[0] ?? null;
$currencyCode = (string)$exchangeRates[0]['currency'];
$baseCurrencyCode = $this->_storeManager->getWebsite($this->_request->getWebsiteId())
->getBaseCurrencyCode();
$dhlProductDescription = $this->getDhlProductTitle($dhlProduct);

if ($currencyCode != $baseCurrencyCode) {
/* @var $currency Currency */
$currency = $this->_currencyFactory->create();
$rates = $currency->getCurrencyRates($currencyCode, [$baseCurrencyCode]);
if (!empty($rates) && isset($rates[$baseCurrencyCode])) {
// Convert to store display currency using store exchange rate
$totalEstimate = $totalEstimate * $rates[$baseCurrencyCode];
} else {
$rates = $currency->getCurrencyRates($baseCurrencyCode, [$currencyCode]);
if (!empty($rates) && isset($rates[$currencyCode])) {
$totalEstimate = $totalEstimate / $rates[$currencyCode];
}
if (!isset($rates[$currencyCode]) || !$totalEstimate) {
$totalEstimate = false;
$this->_errors[] = __(
'We had to skip DHL method %1 because we couldn\'t find exchange rate %2 (Base Currency).',
$currencyCode,
$baseCurrencyCode
);
}
}
}
if ($totalEstimate) {
$data = [
'term' => $dhlProductDescription,
'price_total' => $this->getMethodPrice($totalEstimate, $dhlProduct),
];
if (!empty($this->_rates)) {
foreach ($this->_rates as $product) {
if ($product['data']['term'] == $data['term']
&& $product['data']['price_total'] == $data['price_total']
) {
return $this;
}
}
}
$this->_rates[] = ['service' => $dhlProduct, 'data' => $data];
} else {
$this->_errors[] = __("Zero shipping charge for '%1'", $dhlProductDescription);
}
} else {
$dhlProductDescription = false;
if (isset($product['productCode'])) {
$dhlProductDescription = $this->getDhlProductTitle((string)$product['productCode']);
}
$dhlProductDescription = $dhlProductDescription ? $dhlProductDescription : __("DHL");
$this->_errors[] = __("Zero shipping charge for '%1'", $dhlProductDescription);
}
return $this;
}

/**
* Returns dimension unit (cm or inch)
*
Expand Down
Loading