Carrier.php 76 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Dhl\Model;
  7. use Magento\Catalog\Model\Product\Type;
  8. use Magento\Framework\App\ProductMetadataInterface;
  9. use Magento\Framework\Module\Dir;
  10. use Magento\Sales\Exception\DocumentValidationException;
  11. use Magento\Sales\Model\Order\Shipment;
  12. use Magento\Quote\Model\Quote\Address\RateRequest;
  13. use Magento\Quote\Model\Quote\Address\RateResult\Error;
  14. use Magento\Shipping\Model\Carrier\AbstractCarrier;
  15. use Magento\Shipping\Model\Rate\Result;
  16. use Magento\Framework\Xml\Security;
  17. use Magento\Dhl\Model\Validator\XmlValidator;
  18. /**
  19. * DHL International (API v1.4)
  20. * @SuppressWarnings(PHPMD.TooManyFields)
  21. * @SuppressWarnings(PHPMD.ExcessiveClassComplexity)
  22. * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
  23. */
  24. class Carrier extends \Magento\Dhl\Model\AbstractDhl implements \Magento\Shipping\Model\Carrier\CarrierInterface
  25. {
  26. /**#@+
  27. * Carrier Product indicator
  28. */
  29. const DHL_CONTENT_TYPE_DOC = 'D';
  30. const DHL_CONTENT_TYPE_NON_DOC = 'N';
  31. /**#@-*/
  32. /**#@+
  33. * Minimum allowed values for shipping package dimensions
  34. */
  35. const DIMENSION_MIN_CM = 3;
  36. const DIMENSION_MIN_IN = 1;
  37. /**#@-*/
  38. /**
  39. * Config path to UE country list
  40. */
  41. const XML_PATH_EU_COUNTRIES_LIST = 'general/country/eu_countries';
  42. /**
  43. * Container types that could be customized
  44. *
  45. * @var string[]
  46. */
  47. protected $_customizableContainerTypes = [self::DHL_CONTENT_TYPE_NON_DOC];
  48. /**
  49. * Code of the carrier
  50. */
  51. const CODE = 'dhl';
  52. /**
  53. * DHL service prefixes used for message reference
  54. */
  55. private const SERVICE_PREFIX_QUOTE = 'QUOT';
  56. private const SERVICE_PREFIX_SHIPVAL = 'SHIP';
  57. private const SERVICE_PREFIX_TRACKING = 'TRCK';
  58. /**
  59. * Rate request data
  60. *
  61. * @var RateRequest|null
  62. */
  63. protected $_request;
  64. /**
  65. * Rate result data
  66. *
  67. * @var Result|null
  68. */
  69. protected $_result;
  70. /**
  71. * Countries parameters data
  72. *
  73. * @var \Magento\Shipping\Model\Simplexml\Element|null
  74. */
  75. protected $_countryParams;
  76. /**
  77. * Errors placeholder
  78. *
  79. * @var string[]
  80. */
  81. protected $_errors = [];
  82. /**
  83. * Dhl rates result
  84. *
  85. * @var array
  86. */
  87. protected $_rates = [];
  88. /**
  89. * Carrier's code
  90. *
  91. * @var string
  92. */
  93. protected $_code = self::CODE;
  94. /**
  95. * Free Method config path
  96. *
  97. * @var string
  98. */
  99. protected $_freeMethod = 'free_method_nondoc';
  100. /**
  101. * Max weight without fee
  102. *
  103. * @var int
  104. */
  105. protected $_maxWeight = 70;
  106. /**
  107. * Flag if response is for shipping label creating
  108. *
  109. * @var bool
  110. */
  111. protected $_isShippingLabelFlag = false;
  112. /**
  113. * Request variables array
  114. *
  115. * @var array
  116. */
  117. protected $_requestVariables = [
  118. 'id' => ['code' => 'dhl_id', 'setCode' => 'id'],
  119. 'password' => ['code' => 'dhl_password', 'setCode' => 'password'],
  120. 'account' => ['code' => 'dhl_account', 'setCode' => 'account_nbr'],
  121. 'shipping_key' => ['code' => 'dhl_shipping_key', 'setCode' => 'shipping_key'],
  122. 'shipping_intlkey' => ['code' => 'dhl_shipping_intl_key', 'setCode' => 'shipping_intl_key'],
  123. 'shipment_type' => ['code' => 'dhl_shipment_type', 'setCode' => 'shipment_type'],
  124. 'dutiable' => ['code' => 'dhl_dutiable', 'setCode' => 'dutiable'],
  125. 'dutypaymenttype' => ['code' => 'dhl_duty_payment_type', 'setCode' => 'duty_payment_type'],
  126. 'contentdesc' => ['code' => 'dhl_content_desc', 'setCode' => 'content_desc'],
  127. ];
  128. /**
  129. * Flag that shows if shipping is domestic
  130. *
  131. * @var bool
  132. */
  133. protected $_isDomestic = false;
  134. /**
  135. * Core string
  136. *
  137. * @var \Magento\Framework\Stdlib\StringUtils
  138. */
  139. protected $string;
  140. /**
  141. * Carrier helper
  142. *
  143. * @var \Magento\Shipping\Helper\Carrier
  144. */
  145. protected $_carrierHelper;
  146. /**
  147. * @var \Magento\Framework\Stdlib\DateTime\DateTime
  148. */
  149. protected $_coreDate;
  150. /**
  151. * @var \Magento\Store\Model\StoreManagerInterface
  152. */
  153. protected $_storeManager;
  154. /**
  155. * @var \Magento\Framework\Module\Dir\Reader
  156. */
  157. protected $_configReader;
  158. /**
  159. * @var \Magento\Framework\Math\Division
  160. */
  161. protected $mathDivision;
  162. /**
  163. * @var \Magento\Framework\Filesystem\Directory\ReadFactory
  164. */
  165. protected $readFactory;
  166. /**
  167. * @var \Magento\Framework\Stdlib\DateTime
  168. */
  169. protected $_dateTime;
  170. /**
  171. * @var \Magento\Framework\HTTP\ZendClientFactory
  172. */
  173. protected $_httpClientFactory;
  174. /**
  175. * @inheritdoc
  176. */
  177. protected $_debugReplacePrivateDataKeys = [
  178. 'SiteID', 'Password'
  179. ];
  180. /**
  181. * Xml response validator
  182. *
  183. * @var \Magento\Dhl\Model\Validator\XmlValidator
  184. */
  185. private $xmlValidator;
  186. /**
  187. * @var ProductMetadataInterface
  188. */
  189. private $productMetadata;
  190. /**
  191. * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
  192. * @param \Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory $rateErrorFactory
  193. * @param \Psr\Log\LoggerInterface $logger
  194. * @param Security $xmlSecurity
  195. * @param \Magento\Shipping\Model\Simplexml\ElementFactory $xmlElFactory
  196. * @param \Magento\Shipping\Model\Rate\ResultFactory $rateFactory
  197. * @param \Magento\Quote\Model\Quote\Address\RateResult\MethodFactory $rateMethodFactory
  198. * @param \Magento\Shipping\Model\Tracking\ResultFactory $trackFactory
  199. * @param \Magento\Shipping\Model\Tracking\Result\ErrorFactory $trackErrorFactory
  200. * @param \Magento\Shipping\Model\Tracking\Result\StatusFactory $trackStatusFactory
  201. * @param \Magento\Directory\Model\RegionFactory $regionFactory
  202. * @param \Magento\Directory\Model\CountryFactory $countryFactory
  203. * @param \Magento\Directory\Model\CurrencyFactory $currencyFactory
  204. * @param \Magento\Directory\Helper\Data $directoryData
  205. * @param \Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry
  206. * @param \Magento\Shipping\Helper\Carrier $carrierHelper
  207. * @param \Magento\Framework\Stdlib\DateTime\DateTime $coreDate
  208. * @param \Magento\Framework\Module\Dir\Reader $configReader
  209. * @param \Magento\Store\Model\StoreManagerInterface $storeManager
  210. * @param \Magento\Framework\Stdlib\StringUtils $string
  211. * @param \Magento\Framework\Math\Division $mathDivision
  212. * @param \Magento\Framework\Filesystem\Directory\ReadFactory $readFactory
  213. * @param \Magento\Framework\Stdlib\DateTime $dateTime
  214. * @param \Magento\Framework\HTTP\ZendClientFactory $httpClientFactory
  215. * @param array $data
  216. * @param \Magento\Dhl\Model\Validator\XmlValidator|null $xmlValidator
  217. * @param ProductMetadataInterface|null $productMetadata
  218. * @SuppressWarnings(PHPMD.ExcessiveParameterList)
  219. */
  220. public function __construct(
  221. \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
  222. \Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory $rateErrorFactory,
  223. \Psr\Log\LoggerInterface $logger,
  224. Security $xmlSecurity,
  225. \Magento\Shipping\Model\Simplexml\ElementFactory $xmlElFactory,
  226. \Magento\Shipping\Model\Rate\ResultFactory $rateFactory,
  227. \Magento\Quote\Model\Quote\Address\RateResult\MethodFactory $rateMethodFactory,
  228. \Magento\Shipping\Model\Tracking\ResultFactory $trackFactory,
  229. \Magento\Shipping\Model\Tracking\Result\ErrorFactory $trackErrorFactory,
  230. \Magento\Shipping\Model\Tracking\Result\StatusFactory $trackStatusFactory,
  231. \Magento\Directory\Model\RegionFactory $regionFactory,
  232. \Magento\Directory\Model\CountryFactory $countryFactory,
  233. \Magento\Directory\Model\CurrencyFactory $currencyFactory,
  234. \Magento\Directory\Helper\Data $directoryData,
  235. \Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry,
  236. \Magento\Shipping\Helper\Carrier $carrierHelper,
  237. \Magento\Framework\Stdlib\DateTime\DateTime $coreDate,
  238. \Magento\Framework\Module\Dir\Reader $configReader,
  239. \Magento\Store\Model\StoreManagerInterface $storeManager,
  240. \Magento\Framework\Stdlib\StringUtils $string,
  241. \Magento\Framework\Math\Division $mathDivision,
  242. \Magento\Framework\Filesystem\Directory\ReadFactory $readFactory,
  243. \Magento\Framework\Stdlib\DateTime $dateTime,
  244. \Magento\Framework\HTTP\ZendClientFactory $httpClientFactory,
  245. array $data = [],
  246. \Magento\Dhl\Model\Validator\XmlValidator $xmlValidator = null,
  247. ProductMetadataInterface $productMetadata = null
  248. ) {
  249. $this->readFactory = $readFactory;
  250. $this->_carrierHelper = $carrierHelper;
  251. $this->_coreDate = $coreDate;
  252. $this->_storeManager = $storeManager;
  253. $this->_configReader = $configReader;
  254. $this->string = $string;
  255. $this->mathDivision = $mathDivision;
  256. $this->_dateTime = $dateTime;
  257. $this->_httpClientFactory = $httpClientFactory;
  258. parent::__construct(
  259. $scopeConfig,
  260. $rateErrorFactory,
  261. $logger,
  262. $xmlSecurity,
  263. $xmlElFactory,
  264. $rateFactory,
  265. $rateMethodFactory,
  266. $trackFactory,
  267. $trackErrorFactory,
  268. $trackStatusFactory,
  269. $regionFactory,
  270. $countryFactory,
  271. $currencyFactory,
  272. $directoryData,
  273. $stockRegistry,
  274. $data
  275. );
  276. if ($this->getConfigData('content_type') == self::DHL_CONTENT_TYPE_DOC) {
  277. $this->_freeMethod = 'free_method_doc';
  278. }
  279. $this->xmlValidator = $xmlValidator
  280. ?: \Magento\Framework\App\ObjectManager::getInstance()->get(XmlValidator::class);
  281. $this->productMetadata = $productMetadata
  282. ?: \Magento\Framework\App\ObjectManager::getInstance()->get(ProductMetadataInterface::class);
  283. }
  284. /**
  285. * Returns value of given variable
  286. *
  287. * @param string|int $origValue
  288. * @param string $pathToValue
  289. * @return string|int|null
  290. */
  291. protected function _getDefaultValue($origValue, $pathToValue)
  292. {
  293. if (!$origValue) {
  294. $origValue = $this->_scopeConfig->getValue(
  295. $pathToValue,
  296. \Magento\Store\Model\ScopeInterface::SCOPE_STORE,
  297. $this->getStore()
  298. );
  299. }
  300. return $origValue;
  301. }
  302. /**
  303. * Collect and get rates
  304. *
  305. * @param RateRequest $request
  306. * @return bool|Result|Error
  307. */
  308. public function collectRates(RateRequest $request)
  309. {
  310. if (!$this->canCollectRates()) {
  311. return $this->getErrorMessage();
  312. }
  313. $requestDhl = clone $request;
  314. $this->setStore($requestDhl->getStoreId());
  315. $origCompanyName = $this->_getDefaultValue(
  316. $requestDhl->getOrigCompanyName(),
  317. \Magento\Store\Model\Information::XML_PATH_STORE_INFO_NAME
  318. );
  319. $origCountryId = $this->_getDefaultValue($requestDhl->getOrigCountryId(), Shipment::XML_PATH_STORE_COUNTRY_ID);
  320. $origState = $this->_getDefaultValue($requestDhl->getOrigState(), Shipment::XML_PATH_STORE_REGION_ID);
  321. $origCity = $this->_getDefaultValue($requestDhl->getOrigCity(), Shipment::XML_PATH_STORE_CITY);
  322. $origPostcode = $this->_getDefaultValue($requestDhl->getOrigPostcode(), Shipment::XML_PATH_STORE_ZIP);
  323. $requestDhl->setOrigCompanyName($origCompanyName)
  324. ->setCountryId($origCountryId)
  325. ->setOrigState($origState)
  326. ->setOrigCity($origCity)
  327. ->setOrigPostal($origPostcode);
  328. $this->setRequest($requestDhl);
  329. $this->_result = $this->_getQuotes();
  330. $this->_updateFreeMethodQuote($request);
  331. return $this->_result;
  332. }
  333. /**
  334. * Set Free Method Request
  335. *
  336. * @param string $freeMethod
  337. * @return void
  338. */
  339. protected function _setFreeMethodRequest($freeMethod)
  340. {
  341. $this->_rawRequest->setFreeMethodRequest(true);
  342. $freeWeight = $this->getTotalNumOfBoxes($this->_rawRequest->getFreeMethodWeight());
  343. $this->_rawRequest->setWeight($freeWeight);
  344. $this->_rawRequest->setService($freeMethod);
  345. }
  346. /**
  347. * Returns request result
  348. *
  349. * @return Result|null
  350. */
  351. public function getResult()
  352. {
  353. return $this->_result;
  354. }
  355. /**
  356. * Fills request object with Dhl config parameters
  357. *
  358. * @param \Magento\Framework\DataObject $requestObject
  359. * @return \Magento\Framework\DataObject
  360. */
  361. protected function _addParams(\Magento\Framework\DataObject $requestObject)
  362. {
  363. foreach ($this->_requestVariables as $code => $objectCode) {
  364. if ($this->_request->getDhlId()) {
  365. $value = $this->_request->getData($objectCode['code']);
  366. } else {
  367. $value = $this->getConfigData($code);
  368. }
  369. $requestObject->setData($objectCode['setCode'], $value);
  370. }
  371. return $requestObject;
  372. }
  373. /**
  374. * Prepare and set request in property of current instance
  375. *
  376. * @param \Magento\Framework\DataObject $request
  377. * @return $this
  378. * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  379. * @SuppressWarnings(PHPMD.NPathComplexity)
  380. */
  381. public function setRequest(\Magento\Framework\DataObject $request)
  382. {
  383. $this->_request = $request;
  384. $this->setStore($request->getStoreId());
  385. $requestObject = new \Magento\Framework\DataObject();
  386. $requestObject->setIsGenerateLabelReturn($request->getIsGenerateLabelReturn());
  387. $requestObject->setStoreId($request->getStoreId());
  388. if ($request->getLimitMethod()) {
  389. $requestObject->setService($request->getLimitMethod());
  390. }
  391. $requestObject = $this->_addParams($requestObject);
  392. if ($request->getDestPostcode()) {
  393. $requestObject->setDestPostal($request->getDestPostcode());
  394. }
  395. $requestObject->setOrigCountry(
  396. $this->_getDefaultValue($request->getOrigCountry(), Shipment::XML_PATH_STORE_COUNTRY_ID)
  397. )->setOrigCountryId(
  398. $this->_getDefaultValue($request->getOrigCountryId(), Shipment::XML_PATH_STORE_COUNTRY_ID)
  399. );
  400. $shippingWeight = $request->getPackageWeight();
  401. $requestObject->setValue(sprintf('%.2f', $request->getPackageValue()))
  402. ->setValueWithDiscount($request->getPackageValueWithDiscount())
  403. ->setCustomsValue($request->getPackageCustomsValue())
  404. ->setDestStreet($this->string->substr(str_replace("\n", '', $request->getDestStreet()), 0, 35))
  405. ->setDestStreetLine2($request->getDestStreetLine2())
  406. ->setDestCity($request->getDestCity())
  407. ->setOrigCompanyName($request->getOrigCompanyName())
  408. ->setOrigCity($request->getOrigCity())
  409. ->setOrigPhoneNumber($request->getOrigPhoneNumber())
  410. ->setOrigPersonName($request->getOrigPersonName())
  411. ->setOrigEmail(
  412. $this->_scopeConfig->getValue(
  413. 'trans_email/ident_general/email',
  414. \Magento\Store\Model\ScopeInterface::SCOPE_STORE,
  415. $requestObject->getStoreId()
  416. )
  417. )
  418. ->setOrigCity($request->getOrigCity())
  419. ->setOrigPostal($request->getOrigPostal())
  420. ->setOrigStreetLine2($request->getOrigStreetLine2())
  421. ->setDestPhoneNumber($request->getDestPhoneNumber())
  422. ->setDestPersonName($request->getDestPersonName())
  423. ->setDestCompanyName($request->getDestCompanyName());
  424. $originStreet2 = $this->_scopeConfig->getValue(
  425. Shipment::XML_PATH_STORE_ADDRESS2,
  426. \Magento\Store\Model\ScopeInterface::SCOPE_STORE,
  427. $requestObject->getStoreId()
  428. );
  429. $requestObject->setOrigStreet($request->getOrigStreet() ? $request->getOrigStreet() : $originStreet2);
  430. if (is_numeric($request->getOrigState())) {
  431. $requestObject->setOrigState($this->_regionFactory->create()->load($request->getOrigState())->getCode());
  432. } else {
  433. $requestObject->setOrigState($request->getOrigState());
  434. }
  435. if ($request->getDestCountryId()) {
  436. $destCountry = $request->getDestCountryId();
  437. } else {
  438. $destCountry = self::USA_COUNTRY_ID;
  439. }
  440. // for DHL, Puerto Rico state for US will assume as Puerto Rico country
  441. // for Puerto Rico, dhl will ship as international
  442. if ($destCountry == self::USA_COUNTRY_ID
  443. && ($request->getDestPostcode() == '00912' || $request->getDestRegionCode() == self::PUERTORICO_COUNTRY_ID)
  444. ) {
  445. $destCountry = self::PUERTORICO_COUNTRY_ID;
  446. }
  447. $requestObject->setDestCountryId($destCountry)
  448. ->setDestState($request->getDestRegionCode())
  449. ->setWeight($shippingWeight)
  450. ->setFreeMethodWeight($request->getFreeMethodWeight())
  451. ->setOrderShipment($request->getOrderShipment());
  452. if ($request->getPackageId()) {
  453. $requestObject->setPackageId($request->getPackageId());
  454. }
  455. $requestObject->setBaseSubtotalInclTax($request->getBaseSubtotalInclTax());
  456. $this->setRawRequest($requestObject);
  457. return $this;
  458. }
  459. /**
  460. * Get allowed shipping methods
  461. *
  462. * @return string[]
  463. * @throws \Magento\Framework\Exception\LocalizedException
  464. */
  465. public function getAllowedMethods()
  466. {
  467. $contentType = $this->getConfigData('content_type');
  468. if ($this->_isDomestic) {
  469. $allowedMethods = array_merge(
  470. explode(',', $this->getConfigData('doc_methods')),
  471. explode(',', $this->getConfigData('nondoc_methods'))
  472. );
  473. } else {
  474. switch ($contentType) {
  475. case self::DHL_CONTENT_TYPE_DOC:
  476. $allowedMethods = explode(',', $this->getConfigData('doc_methods'));
  477. break;
  478. case self::DHL_CONTENT_TYPE_NON_DOC:
  479. $allowedMethods = explode(',', $this->getConfigData('nondoc_methods'));
  480. break;
  481. default:
  482. throw new \Magento\Framework\Exception\LocalizedException(__('Wrong Content Type'));
  483. }
  484. }
  485. $methods = [];
  486. foreach ($allowedMethods as $method) {
  487. $methods[$method] = $this->getDhlProductTitle($method);
  488. }
  489. return $methods;
  490. }
  491. /**
  492. * Get configuration data of carrier
  493. *
  494. * @param string $type
  495. * @param string $code
  496. * @return array|bool
  497. */
  498. public function getCode($type, $code = '')
  499. {
  500. $codes = [
  501. 'unit_of_measure' => ['L' => __('Pounds'), 'K' => __('Kilograms')],
  502. 'unit_of_dimension' => ['I' => __('Inches'), 'C' => __('Centimeters')],
  503. 'unit_of_dimension_cut' => ['I' => __('inch'), 'C' => __('cm')],
  504. 'dimensions' => ['HEIGHT' => __('Height'), 'DEPTH' => __('Depth'), 'WIDTH' => __('Width')],
  505. 'size' => ['0' => __('Regular'), '1' => __('Specific')],
  506. 'dimensions_variables' => [
  507. 'L' => \Zend_Measure_Weight::POUND,
  508. 'LB' => \Zend_Measure_Weight::POUND,
  509. 'POUND' => \Zend_Measure_Weight::POUND,
  510. 'K' => \Zend_Measure_Weight::KILOGRAM,
  511. 'KG' => \Zend_Measure_Weight::KILOGRAM,
  512. 'KILOGRAM' => \Zend_Measure_Weight::KILOGRAM,
  513. 'I' => \Zend_Measure_Length::INCH,
  514. 'IN' => \Zend_Measure_Length::INCH,
  515. 'INCH' => \Zend_Measure_Length::INCH,
  516. 'C' => \Zend_Measure_Length::CENTIMETER,
  517. 'CM' => \Zend_Measure_Length::CENTIMETER,
  518. 'CENTIMETER' => \Zend_Measure_Length::CENTIMETER,
  519. ],
  520. ];
  521. if (!isset($codes[$type])) {
  522. return false;
  523. } elseif ('' === $code) {
  524. return $codes[$type];
  525. }
  526. $code = strtoupper($code);
  527. if (!isset($codes[$type][$code])) {
  528. return false;
  529. } else {
  530. return $codes[$type][$code];
  531. }
  532. }
  533. /**
  534. * Returns DHL shipment methods (depending on package content type, if necessary)
  535. *
  536. * @param string $doc Package content type (doc/non-doc) see DHL_CONTENT_TYPE_* constants
  537. * @return array
  538. */
  539. public function getDhlProducts($doc)
  540. {
  541. $docType = [
  542. '2' => __('Easy shop'),
  543. '5' => __('Sprintline'),
  544. '6' => __('Secureline'),
  545. '7' => __('Express easy'),
  546. '9' => __('Europack'),
  547. 'B' => __('Break bulk express'),
  548. 'C' => __('Medical express'),
  549. 'D' => __('Express worldwide'),
  550. 'U' => __('Express worldwide'),
  551. 'K' => __('Express 9:00'),
  552. 'L' => __('Express 10:30'),
  553. 'G' => __('Domestic economy select'),
  554. 'W' => __('Economy select'),
  555. 'I' => __('Domestic express 9:00'),
  556. 'N' => __('Domestic express'),
  557. 'O' => __('Others'),
  558. 'R' => __('Globalmail business'),
  559. 'S' => __('Same day'),
  560. 'T' => __('Express 12:00'),
  561. 'X' => __('Express envelope'),
  562. ];
  563. $nonDocType = [
  564. '1' => __('Domestic express 12:00'),
  565. '3' => __('Easy shop'),
  566. '4' => __('Jetline'),
  567. '8' => __('Express easy'),
  568. 'P' => __('Express worldwide'),
  569. 'Q' => __('Medical express'),
  570. 'E' => __('Express 9:00'),
  571. 'F' => __('Freight worldwide'),
  572. 'H' => __('Economy select'),
  573. 'J' => __('Jumbo box'),
  574. 'M' => __('Express 10:30'),
  575. 'V' => __('Europack'),
  576. 'Y' => __('Express 12:00'),
  577. ];
  578. if ($this->_isDomestic) {
  579. return $docType + $nonDocType;
  580. }
  581. if ($doc == self::DHL_CONTENT_TYPE_DOC) {
  582. // Documents shipping
  583. return $docType;
  584. } else {
  585. // Services for shipping non-documents cargo
  586. return $nonDocType;
  587. }
  588. }
  589. /**
  590. * Returns title of DHL shipping method by its code
  591. *
  592. * @param string $code One-symbol code (see getDhlProducts())
  593. * @return bool
  594. * @SuppressWarnings(PHPMD.BooleanGetMethodName)
  595. */
  596. public function getDhlProductTitle($code)
  597. {
  598. $contentType = $this->getConfigData('content_type');
  599. $dhlProducts = $this->getDhlProducts($contentType);
  600. return isset($dhlProducts[$code]) ? $dhlProducts[$code] : false;
  601. }
  602. /**
  603. * Convert item weight to needed weight based on config weight unit dimensions
  604. *
  605. * @param float $weight
  606. * @param bool $maxWeight
  607. * @param string|bool $configWeightUnit
  608. * @return float
  609. */
  610. protected function _getWeight($weight, $maxWeight = false, $configWeightUnit = false)
  611. {
  612. if ($maxWeight) {
  613. $configWeightUnit = \Zend_Measure_Weight::KILOGRAM;
  614. } elseif ($configWeightUnit) {
  615. $configWeightUnit = $this->getCode('dimensions_variables', $configWeightUnit);
  616. } else {
  617. $configWeightUnit = $this->getCode(
  618. 'dimensions_variables',
  619. (string)$this->getConfigData('unit_of_measure')
  620. );
  621. }
  622. $countryWeightUnit = $this->getCode('dimensions_variables', $this->_getWeightUnit());
  623. if ($configWeightUnit != $countryWeightUnit) {
  624. $weight = $this->_carrierHelper->convertMeasureWeight(
  625. (float)$weight,
  626. $configWeightUnit,
  627. $countryWeightUnit
  628. );
  629. }
  630. return sprintf('%.3f', $weight);
  631. }
  632. /**
  633. * Prepare items to pieces
  634. *
  635. * @return array
  636. * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  637. * @SuppressWarnings(PHPMD.NPathComplexity)
  638. */
  639. protected function _getAllItems()
  640. {
  641. $allItems = $this->_request->getAllItems();
  642. $fullItems = [];
  643. foreach ($allItems as $item) {
  644. if ($item->getProductType() == Type::TYPE_BUNDLE && $item->getProduct()->getShipmentType()) {
  645. continue;
  646. }
  647. $qty = $item->getQty();
  648. $changeQty = true;
  649. $checkWeight = true;
  650. $decimalItems = [];
  651. if ($item->getParentItem()) {
  652. if (!$item->getParentItem()->getProduct()->getShipmentType()) {
  653. continue;
  654. }
  655. if ($item->getIsQtyDecimal()) {
  656. $qty = $item->getParentItem()->getQty();
  657. } else {
  658. $qty = $item->getParentItem()->getQty() * $item->getQty();
  659. }
  660. }
  661. $itemWeight = $item->getWeight();
  662. if ($item->getIsQtyDecimal() && $item->getProductType() != Type::TYPE_BUNDLE) {
  663. $productId = $item->getProduct()->getId();
  664. $stockItemDo = $this->stockRegistry->getStockItem($productId, $item->getStore()->getWebsiteId());
  665. $isDecimalDivided = $stockItemDo->getIsDecimalDivided();
  666. if ($isDecimalDivided) {
  667. if ($stockItemDo->getEnableQtyIncrements()
  668. && $stockItemDo->getQtyIncrements()
  669. ) {
  670. $itemWeight = $itemWeight * $stockItemDo->getQtyIncrements();
  671. $qty = round($item->getWeight() / $itemWeight * $qty);
  672. $changeQty = false;
  673. } else {
  674. $itemWeight = $this->_getWeight($itemWeight * $item->getQty());
  675. $maxWeight = $this->_getWeight($this->_maxWeight, true);
  676. if ($itemWeight > $maxWeight) {
  677. $qtyItem = floor($itemWeight / $maxWeight);
  678. $decimalItems[] = ['weight' => $maxWeight, 'qty' => $qtyItem];
  679. $weightItem = $this->mathDivision->getExactDivision($itemWeight, $maxWeight);
  680. if ($weightItem) {
  681. $decimalItems[] = ['weight' => $weightItem, 'qty' => 1];
  682. }
  683. $checkWeight = false;
  684. }
  685. }
  686. } else {
  687. $itemWeight = $itemWeight * $item->getQty();
  688. }
  689. }
  690. if ($checkWeight && $this->_getWeight($itemWeight) > $this->_getWeight($this->_maxWeight, true)) {
  691. return [];
  692. }
  693. if ($changeQty
  694. && !$item->getParentItem()
  695. && $item->getIsQtyDecimal()
  696. && $item->getProductType() != Type::TYPE_BUNDLE
  697. ) {
  698. $qty = 1;
  699. }
  700. if (!empty($decimalItems)) {
  701. foreach ($decimalItems as $decimalItem) {
  702. $fullItems = array_merge(
  703. $fullItems,
  704. array_fill(0, $decimalItem['qty'] * $qty, $decimalItem['weight'])
  705. );
  706. }
  707. } else {
  708. $fullItems = array_merge($fullItems, array_fill(0, $qty, $this->_getWeight($itemWeight)));
  709. }
  710. }
  711. sort($fullItems);
  712. return $fullItems;
  713. }
  714. /**
  715. * Make pieces
  716. *
  717. * @param \Magento\Shipping\Model\Simplexml\Element $nodeBkgDetails
  718. * @return void
  719. * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  720. */
  721. protected function _makePieces(\Magento\Shipping\Model\Simplexml\Element $nodeBkgDetails)
  722. {
  723. $divideOrderWeight = (string)$this->getConfigData('divide_order_weight');
  724. $nodePieces = $nodeBkgDetails->addChild('Pieces', '', '');
  725. $items = $this->_getAllItems();
  726. $numberOfPieces = 0;
  727. if ($divideOrderWeight && !empty($items)) {
  728. $maxWeight = $this->_getWeight($this->_maxWeight, true);
  729. $sumWeight = 0;
  730. $reverseOrderItems = $items;
  731. arsort($reverseOrderItems);
  732. foreach ($reverseOrderItems as $key => $weight) {
  733. if (!isset($items[$key])) {
  734. continue;
  735. }
  736. unset($items[$key]);
  737. $sumWeight = $weight;
  738. foreach ($items as $key => $weight) {
  739. if ($sumWeight + $weight < $maxWeight) {
  740. unset($items[$key]);
  741. $sumWeight += $weight;
  742. } elseif ($sumWeight + $weight > $maxWeight) {
  743. $numberOfPieces++;
  744. $nodePiece = $nodePieces->addChild('Piece', '', '');
  745. $nodePiece->addChild('PieceID', $numberOfPieces);
  746. $this->_addDimension($nodePiece);
  747. $nodePiece->addChild('Weight', sprintf('%.3f', $sumWeight));
  748. break;
  749. } else {
  750. unset($items[$key]);
  751. $numberOfPieces++;
  752. $sumWeight += $weight;
  753. $nodePiece = $nodePieces->addChild('Piece', '', '');
  754. $nodePiece->addChild('PieceID', $numberOfPieces);
  755. $this->_addDimension($nodePiece);
  756. $nodePiece->addChild('Weight', sprintf('%.3f', $sumWeight));
  757. $sumWeight = 0;
  758. break;
  759. }
  760. }
  761. }
  762. if ($sumWeight > 0) {
  763. $numberOfPieces++;
  764. $nodePiece = $nodePieces->addChild('Piece', '', '');
  765. $nodePiece->addChild('PieceID', $numberOfPieces);
  766. $this->_addDimension($nodePiece);
  767. $nodePiece->addChild('Weight', sprintf('%.3f', $sumWeight));
  768. }
  769. } else {
  770. $nodePiece = $nodePieces->addChild('Piece', '', '');
  771. $nodePiece->addChild('PieceID', 1);
  772. $this->_addDimension($nodePiece);
  773. $nodePiece->addChild('Weight', $this->_getWeight($this->_rawRequest->getWeight()));
  774. }
  775. $handlingAction = $this->getConfigData('handling_action');
  776. if ($handlingAction == AbstractCarrier::HANDLING_ACTION_PERORDER || !$numberOfPieces) {
  777. $numberOfPieces = 1;
  778. }
  779. $this->_numBoxes = $numberOfPieces;
  780. }
  781. /**
  782. * Convert item dimension to needed dimension based on config dimension unit of measure
  783. *
  784. * @param float $dimension
  785. * @param string|bool $configWeightUnit
  786. * @return float
  787. */
  788. protected function _getDimension($dimension, $configWeightUnit = false)
  789. {
  790. if (!$configWeightUnit) {
  791. $configWeightUnit = $this->getCode(
  792. 'dimensions_variables',
  793. (string)$this->getConfigData('unit_of_measure')
  794. );
  795. } else {
  796. $configWeightUnit = $this->getCode('dimensions_variables', $configWeightUnit);
  797. }
  798. if ($configWeightUnit == \Zend_Measure_Weight::POUND) {
  799. $configDimensionUnit = \Zend_Measure_Length::INCH;
  800. } else {
  801. $configDimensionUnit = \Zend_Measure_Length::CENTIMETER;
  802. }
  803. $countryDimensionUnit = $this->getCode('dimensions_variables', $this->_getDimensionUnit());
  804. if ($configDimensionUnit != $countryDimensionUnit) {
  805. $dimension = $this->_carrierHelper->convertMeasureDimension(
  806. (float)$dimension,
  807. $configDimensionUnit,
  808. $countryDimensionUnit
  809. );
  810. }
  811. return sprintf('%.3f', $dimension);
  812. }
  813. /**
  814. * Add dimension to piece
  815. *
  816. * @param \Magento\Shipping\Model\Simplexml\Element $nodePiece
  817. * @return void
  818. */
  819. protected function _addDimension($nodePiece)
  820. {
  821. $sizeChecker = (string)$this->getConfigData('size');
  822. $height = $this->_getDimension((float)$this->getConfigData('height'));
  823. $depth = $this->_getDimension((float)$this->getConfigData('depth'));
  824. $width = $this->_getDimension((float)$this->getConfigData('width'));
  825. if ($sizeChecker && $height && $depth && $width) {
  826. $nodePiece->addChild('Height', $height);
  827. $nodePiece->addChild('Depth', $depth);
  828. $nodePiece->addChild('Width', $width);
  829. }
  830. }
  831. /**
  832. * Get shipping quotes
  833. *
  834. * @return \Magento\Framework\Model\AbstractModel|Result
  835. */
  836. protected function _getQuotes()
  837. {
  838. $responseBody = '';
  839. try {
  840. for ($offset = 0; $offset <= self::UNAVAILABLE_DATE_LOOK_FORWARD; $offset++) {
  841. $debugPoint = [];
  842. $requestXml = $this->_buildQuotesRequestXml();
  843. $date = date(self::REQUEST_DATE_FORMAT, strtotime($this->_getShipDate() . " +{$offset} days"));
  844. $this->_setQuotesRequestXmlDate($requestXml, $date);
  845. $request = $requestXml->asXML();
  846. $debugPoint['request'] = $this->filterDebugData($request);
  847. $responseBody = $this->_getCachedQuotes($request);
  848. $debugPoint['from_cache'] = $responseBody === null;
  849. if ($debugPoint['from_cache']) {
  850. $responseBody = $this->_getQuotesFromServer($request);
  851. }
  852. $debugPoint['response'] = $this->filterDebugData($responseBody);
  853. $bodyXml = $this->_xmlElFactory->create(['data' => $responseBody]);
  854. $code = $bodyXml->xpath('//GetQuoteResponse/Note/Condition/ConditionCode');
  855. if (isset($code[0]) && (int)$code[0] == self::CONDITION_CODE_SERVICE_DATE_UNAVAILABLE) {
  856. $debugPoint['info'] = sprintf(__("DHL service is not available at %s date"), $date);
  857. } else {
  858. $this->_debug($debugPoint);
  859. break;
  860. }
  861. $this->_setCachedQuotes($request, $responseBody);
  862. $this->_debug($debugPoint);
  863. }
  864. } catch (\Exception $e) {
  865. $this->_errors[$e->getCode()] = $e->getMessage();
  866. }
  867. return $this->_parseResponse($responseBody);
  868. }
  869. /**
  870. * Get shipping quotes from DHL service
  871. *
  872. * @param string $request
  873. * @return string
  874. */
  875. protected function _getQuotesFromServer($request)
  876. {
  877. $client = $this->_httpClientFactory->create();
  878. $client->setUri((string)$this->getConfigData('gateway_url'));
  879. $client->setConfig(['maxredirects' => 0, 'timeout' => 30]);
  880. $client->setRawData(utf8_encode($request));
  881. return $client->request(\Zend_Http_Client::POST)->getBody();
  882. }
  883. /**
  884. * Build quotes request XML object
  885. *
  886. * @return \SimpleXMLElement
  887. */
  888. protected function _buildQuotesRequestXml()
  889. {
  890. $rawRequest = $this->_rawRequest;
  891. $xmlStr = '<?xml version="1.0" encoding = "UTF-8"?>' .
  892. '<req:DCTRequest schemaVersion="2.0" ' .
  893. 'xmlns:req="http://www.dhl.com" ' .
  894. 'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' .
  895. 'xsi:schemaLocation="http://www.dhl.com DCT-req_global-2.0.xsd"/>';
  896. $xml = $this->_xmlElFactory->create(['data' => $xmlStr]);
  897. $nodeGetQuote = $xml->addChild('GetQuote', '', '');
  898. $nodeRequest = $nodeGetQuote->addChild('Request');
  899. $nodeServiceHeader = $nodeRequest->addChild('ServiceHeader');
  900. $nodeServiceHeader->addChild('MessageTime', $this->buildMessageTimestamp());
  901. $nodeServiceHeader->addChild(
  902. 'MessageReference',
  903. $this->buildMessageReference(self::SERVICE_PREFIX_QUOTE)
  904. );
  905. $nodeServiceHeader->addChild('SiteID', (string) $this->getConfigData('id'));
  906. $nodeServiceHeader->addChild('Password', (string) $this->getConfigData('password'));
  907. $nodeMetaData = $nodeRequest->addChild('MetaData');
  908. $nodeMetaData->addChild('SoftwareName', $this->buildSoftwareName());
  909. $nodeMetaData->addChild('SoftwareVersion', $this->buildSoftwareVersion());
  910. $nodeFrom = $nodeGetQuote->addChild('From');
  911. $nodeFrom->addChild('CountryCode', $rawRequest->getOrigCountryId());
  912. $nodeFrom->addChild('Postalcode', $rawRequest->getOrigPostal());
  913. $nodeFrom->addChild('City', $rawRequest->getOrigCity());
  914. $nodeBkgDetails = $nodeGetQuote->addChild('BkgDetails');
  915. $nodeBkgDetails->addChild('PaymentCountryCode', $rawRequest->getOrigCountryId());
  916. $nodeBkgDetails->addChild(
  917. 'Date',
  918. (new \DateTime())->format(\Magento\Framework\Stdlib\DateTime::DATETIME_PHP_FORMAT)
  919. );
  920. $nodeBkgDetails->addChild('ReadyTime', 'PT' . (int)(string)$this->getConfigData('ready_time') . 'H00M');
  921. $nodeBkgDetails->addChild('DimensionUnit', $this->_getDimensionUnit());
  922. $nodeBkgDetails->addChild('WeightUnit', $this->_getWeightUnit());
  923. $this->_makePieces($nodeBkgDetails);
  924. $nodeBkgDetails->addChild('PaymentAccountNumber', (string)$this->getConfigData('account'));
  925. $nodeTo = $nodeGetQuote->addChild('To');
  926. $nodeTo->addChild('CountryCode', $rawRequest->getDestCountryId());
  927. $nodeTo->addChild('Postalcode', $rawRequest->getDestPostal());
  928. $nodeTo->addChild('City', $rawRequest->getDestCity());
  929. if ($this->isDutiable($rawRequest->getOrigCountryId(), $rawRequest->getDestCountryId())) {
  930. // IsDutiable flag and Dutiable node indicates that cargo is not a documentation
  931. $nodeBkgDetails->addChild('IsDutiable', 'Y');
  932. $nodeDutiable = $nodeGetQuote->addChild('Dutiable');
  933. $baseCurrencyCode = $this->_storeManager
  934. ->getWebsite($this->_request->getWebsiteId())
  935. ->getBaseCurrencyCode();
  936. $nodeDutiable->addChild('DeclaredCurrency', $baseCurrencyCode);
  937. $nodeDutiable->addChild('DeclaredValue', sprintf("%.2F", $rawRequest->getValue()));
  938. }
  939. return $xml;
  940. }
  941. /**
  942. * Set pick-up date in request XML object
  943. *
  944. * @param \SimpleXMLElement $requestXml
  945. * @param string $date
  946. * @return \SimpleXMLElement
  947. */
  948. protected function _setQuotesRequestXmlDate(\SimpleXMLElement $requestXml, $date)
  949. {
  950. $requestXml->GetQuote->BkgDetails->Date = $date;
  951. return $requestXml;
  952. }
  953. /**
  954. * Parse response from DHL web service
  955. *
  956. * @param string $response
  957. * @return bool|\Magento\Framework\DataObject|Result|Error
  958. * @throws \Magento\Framework\Exception\LocalizedException
  959. * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  960. */
  961. protected function _parseResponse($response)
  962. {
  963. $responseError = __('The response is in wrong format.');
  964. try {
  965. $this->xmlValidator->validate($response);
  966. $xml = simplexml_load_string($response);
  967. if (isset($xml->GetQuoteResponse->BkgDetails->QtdShp)) {
  968. foreach ($xml->GetQuoteResponse->BkgDetails->QtdShp as $quotedShipment) {
  969. $this->_addRate($quotedShipment);
  970. }
  971. } elseif (isset($xml->AirwayBillNumber)) {
  972. return $this->_prepareShippingLabelContent($xml);
  973. } else {
  974. $this->_errors[] = $responseError;
  975. }
  976. } catch (DocumentValidationException $e) {
  977. if ($e->getCode() > 0) {
  978. $this->_errors[$e->getCode()] = $e->getMessage();
  979. } else {
  980. $this->_errors[] = $e->getMessage();
  981. }
  982. }
  983. /* @var $result Result */
  984. $result = $this->_rateFactory->create();
  985. if ($this->_rates) {
  986. foreach ($this->_rates as $rate) {
  987. $method = $rate['service'];
  988. $data = $rate['data'];
  989. /* @var $rate \Magento\Quote\Model\Quote\Address\RateResult\Method */
  990. $rate = $this->_rateMethodFactory->create();
  991. $rate->setCarrier(self::CODE);
  992. $rate->setCarrierTitle($this->getConfigData('title'));
  993. $rate->setMethod($method);
  994. $rate->setMethodTitle($data['term']);
  995. $rate->setCost($data['price_total']);
  996. $rate->setPrice($data['price_total']);
  997. $result->append($rate);
  998. }
  999. } else {
  1000. if (!empty($this->_errors)) {
  1001. if ($this->_isShippingLabelFlag) {
  1002. throw new \Magento\Framework\Exception\LocalizedException($responseError);
  1003. }
  1004. $this->debugErrors($this->_errors);
  1005. }
  1006. $result->append($this->getErrorMessage());
  1007. }
  1008. return $result;
  1009. }
  1010. /**
  1011. * Add rate to DHL rates array
  1012. *
  1013. * @param \SimpleXMLElement $shipmentDetails
  1014. * @return $this
  1015. * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  1016. */
  1017. protected function _addRate(\SimpleXMLElement $shipmentDetails)
  1018. {
  1019. if (isset($shipmentDetails->ProductShortName)
  1020. && isset($shipmentDetails->ShippingCharge)
  1021. && isset($shipmentDetails->GlobalProductCode)
  1022. && isset($shipmentDetails->CurrencyCode)
  1023. && array_key_exists((string)$shipmentDetails->GlobalProductCode, $this->getAllowedMethods())
  1024. ) {
  1025. // DHL product code, e.g. '3', 'A', 'Q', etc.
  1026. $dhlProduct = (string)$shipmentDetails->GlobalProductCode;
  1027. $totalEstimate = (float)(string)$shipmentDetails->ShippingCharge;
  1028. $currencyCode = (string)$shipmentDetails->CurrencyCode;
  1029. $baseCurrencyCode = $this->_storeManager->getWebsite($this->_request->getWebsiteId())
  1030. ->getBaseCurrencyCode();
  1031. $dhlProductDescription = $this->getDhlProductTitle($dhlProduct);
  1032. if ($currencyCode != $baseCurrencyCode) {
  1033. /* @var $currency \Magento\Directory\Model\Currency */
  1034. $currency = $this->_currencyFactory->create();
  1035. $rates = $currency->getCurrencyRates($currencyCode, [$baseCurrencyCode]);
  1036. if (!empty($rates) && isset($rates[$baseCurrencyCode])) {
  1037. // Convert to store display currency using store exchange rate
  1038. $totalEstimate = $totalEstimate * $rates[$baseCurrencyCode];
  1039. } else {
  1040. $rates = $currency->getCurrencyRates($baseCurrencyCode, [$currencyCode]);
  1041. if (!empty($rates) && isset($rates[$currencyCode])) {
  1042. $totalEstimate = $totalEstimate / $rates[$currencyCode];
  1043. }
  1044. if (!isset($rates[$currencyCode]) || !$totalEstimate) {
  1045. $totalEstimate = false;
  1046. $this->_errors[] = __(
  1047. 'We had to skip DHL method %1 because we couldn\'t find exchange rate %2 (Base Currency).',
  1048. $currencyCode,
  1049. $baseCurrencyCode
  1050. );
  1051. }
  1052. }
  1053. }
  1054. if ($totalEstimate) {
  1055. $data = [
  1056. 'term' => $dhlProductDescription,
  1057. 'price_total' => $this->getMethodPrice($totalEstimate, $dhlProduct),
  1058. ];
  1059. if (!empty($this->_rates)) {
  1060. foreach ($this->_rates as $product) {
  1061. if ($product['data']['term'] == $data['term']
  1062. && $product['data']['price_total'] == $data['price_total']
  1063. ) {
  1064. return $this;
  1065. }
  1066. }
  1067. }
  1068. $this->_rates[] = ['service' => $dhlProduct, 'data' => $data];
  1069. } else {
  1070. $this->_errors[] = __("Zero shipping charge for '%1'", $dhlProductDescription);
  1071. }
  1072. } else {
  1073. $dhlProductDescription = false;
  1074. if (isset($shipmentDetails->GlobalProductCode)) {
  1075. $dhlProductDescription = $this->getDhlProductTitle((string)$shipmentDetails->GlobalProductCode);
  1076. }
  1077. $dhlProductDescription = $dhlProductDescription ? $dhlProductDescription : __("DHL");
  1078. $this->_errors[] = __("Zero shipping charge for '%1'", $dhlProductDescription);
  1079. }
  1080. return $this;
  1081. }
  1082. /**
  1083. * Returns dimension unit (cm or inch)
  1084. *
  1085. * @return string
  1086. * @throws \Magento\Framework\Exception\LocalizedException
  1087. */
  1088. protected function _getDimensionUnit()
  1089. {
  1090. $countryId = $this->_rawRequest->getOrigCountryId();
  1091. $measureUnit = $this->getCountryParams($countryId)->getMeasureUnit();
  1092. if (empty($measureUnit)) {
  1093. throw new \Magento\Framework\Exception\LocalizedException(
  1094. __("Cannot identify measure unit for %1", $countryId)
  1095. );
  1096. }
  1097. return $measureUnit;
  1098. }
  1099. /**
  1100. * Returns weight unit (kg or pound)
  1101. *
  1102. * @return string
  1103. * @throws \Magento\Framework\Exception\LocalizedException
  1104. */
  1105. protected function _getWeightUnit()
  1106. {
  1107. $countryId = $this->_rawRequest->getOrigCountryId();
  1108. $weightUnit = $this->getCountryParams($countryId)->getWeightUnit();
  1109. if (empty($weightUnit)) {
  1110. throw new \Magento\Framework\Exception\LocalizedException(
  1111. __("Cannot identify weight unit for %1", $countryId)
  1112. );
  1113. }
  1114. return $weightUnit;
  1115. }
  1116. /**
  1117. * Get Country Params by Country Code
  1118. *
  1119. * @param string $countryCode
  1120. * @return \Magento\Framework\DataObject
  1121. *
  1122. * @see $countryCode ISO 3166 Codes (Countries) A2
  1123. */
  1124. protected function getCountryParams($countryCode)
  1125. {
  1126. if (empty($this->_countryParams)) {
  1127. $etcPath = $this->_configReader->getModuleDir(Dir::MODULE_ETC_DIR, 'Magento_Dhl');
  1128. $directoryRead = $this->readFactory->create($etcPath);
  1129. $countriesXml = $directoryRead->readFile('countries.xml');
  1130. $this->_countryParams = $this->_xmlElFactory->create(['data' => $countriesXml]);
  1131. }
  1132. if (isset($this->_countryParams->{$countryCode})) {
  1133. $countryParams = new \Magento\Framework\DataObject($this->_countryParams->{$countryCode}->asArray());
  1134. }
  1135. return isset($countryParams) ? $countryParams : new \Magento\Framework\DataObject();
  1136. }
  1137. /**
  1138. * Do shipment request to carrier web service, obtain Print Shipping Labels and process errors in response
  1139. *
  1140. * @param \Magento\Framework\DataObject $request
  1141. * @return \Magento\Framework\DataObject
  1142. */
  1143. protected function _doShipmentRequest(\Magento\Framework\DataObject $request)
  1144. {
  1145. $this->_prepareShipmentRequest($request);
  1146. $this->_mapRequestToShipment($request);
  1147. $this->setRequest($request);
  1148. return $this->_doRequest();
  1149. }
  1150. /**
  1151. * Processing additional validation to check is carrier applicable.
  1152. *
  1153. * @param \Magento\Framework\DataObject $request
  1154. * @return $this|\Magento\Framework\DataObject|boolean
  1155. * @deprecated 100.2.3
  1156. */
  1157. public function proccessAdditionalValidation(\Magento\Framework\DataObject $request)
  1158. {
  1159. return $this->processAdditionalValidation($request);
  1160. }
  1161. /**
  1162. * Processing additional validation to check is carrier applicable.
  1163. *
  1164. * @param \Magento\Framework\DataObject $request
  1165. * @return $this|\Magento\Framework\DataObject|boolean
  1166. */
  1167. public function processAdditionalValidation(\Magento\Framework\DataObject $request)
  1168. {
  1169. //Skip by item validation if there is no items in request
  1170. if (!count($this->getAllItems($request))) {
  1171. $this->_errors[] = __('There is no items in this order');
  1172. }
  1173. $countryParams = $this->getCountryParams(
  1174. $this->_scopeConfig->getValue(
  1175. Shipment::XML_PATH_STORE_COUNTRY_ID,
  1176. \Magento\Store\Model\ScopeInterface::SCOPE_STORE,
  1177. $request->getStoreId()
  1178. )
  1179. );
  1180. if (!$countryParams->getData()) {
  1181. $this->_errors[] = __('Please specify origin country.');
  1182. }
  1183. if (!empty($this->_errors)) {
  1184. $this->debugErrors($this->_errors);
  1185. return false;
  1186. }
  1187. return $this;
  1188. }
  1189. /**
  1190. * Return container types of carrier
  1191. *
  1192. * @param \Magento\Framework\DataObject|null $params
  1193. * @return array
  1194. * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  1195. */
  1196. public function getContainerTypes(\Magento\Framework\DataObject $params = null)
  1197. {
  1198. return [
  1199. self::DHL_CONTENT_TYPE_DOC => __('Documents'),
  1200. self::DHL_CONTENT_TYPE_NON_DOC => __('Non Documents')
  1201. ];
  1202. }
  1203. /**
  1204. * Map request to shipment
  1205. *
  1206. * @param \Magento\Framework\DataObject $request
  1207. * @return void
  1208. * @throws \Magento\Framework\Exception\LocalizedException
  1209. */
  1210. protected function _mapRequestToShipment(\Magento\Framework\DataObject $request)
  1211. {
  1212. $request->setOrigCountryId($request->getShipperAddressCountryCode());
  1213. $this->setRawRequest($request);
  1214. $customsValue = 0;
  1215. $packageWeight = 0;
  1216. $packages = $request->getPackages();
  1217. foreach ($packages as &$piece) {
  1218. $params = $piece['params'];
  1219. if ($params['width'] || $params['length'] || $params['height']) {
  1220. $minValue = $this->_getMinDimension($params['dimension_units']);
  1221. if ($params['width'] < $minValue || $params['length'] < $minValue || $params['height'] < $minValue) {
  1222. $message = __('Height, width and length should be equal or greater than %1', $minValue);
  1223. throw new \Magento\Framework\Exception\LocalizedException($message);
  1224. }
  1225. }
  1226. $weightUnits = $piece['params']['weight_units'];
  1227. $piece['params']['height'] = $this->_getDimension($piece['params']['height'], $weightUnits);
  1228. $piece['params']['length'] = $this->_getDimension($piece['params']['length'], $weightUnits);
  1229. $piece['params']['width'] = $this->_getDimension($piece['params']['width'], $weightUnits);
  1230. $piece['params']['dimension_units'] = $this->_getDimensionUnit();
  1231. $piece['params']['weight'] = $this->_getWeight($piece['params']['weight'], false, $weightUnits);
  1232. $piece['params']['weight_units'] = $this->_getWeightUnit();
  1233. $customsValue += $piece['params']['customs_value'];
  1234. $packageWeight += $piece['params']['weight'];
  1235. }
  1236. $request->setPackages($packages)
  1237. ->setPackageWeight($packageWeight)
  1238. ->setPackageValue($customsValue)
  1239. ->setValueWithDiscount($customsValue)
  1240. ->setPackageCustomsValue($customsValue)
  1241. ->setFreeMethodWeight(0);
  1242. }
  1243. /**
  1244. * Retrieve minimum allowed value for dimensions in given dimension unit
  1245. *
  1246. * @param string $dimensionUnit
  1247. * @return int
  1248. */
  1249. protected function _getMinDimension($dimensionUnit)
  1250. {
  1251. return $dimensionUnit == "CENTIMETER" ? self::DIMENSION_MIN_CM : self::DIMENSION_MIN_IN;
  1252. }
  1253. /**
  1254. * Do rate request and handle errors
  1255. *
  1256. * @return Result|\Magento\Framework\DataObject
  1257. * @throws \Magento\Framework\Exception\LocalizedException
  1258. * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  1259. * @SuppressWarnings(PHPMD.NPathComplexity)
  1260. * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
  1261. */
  1262. protected function _doRequest()
  1263. {
  1264. $rawRequest = $this->_request;
  1265. $xmlStr = '<?xml version="1.0" encoding="UTF-8"?>' .
  1266. '<req:ShipmentRequest' .
  1267. ' xmlns:req="http://www.dhl.com"' .
  1268. ' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"' .
  1269. ' xsi:schemaLocation="http://www.dhl.com ship-val-global-req-6.0.xsd"' .
  1270. ' schemaVersion="6.0" />';
  1271. $xml = $this->_xmlElFactory->create(['data' => $xmlStr]);
  1272. $nodeRequest = $xml->addChild('Request', '', '');
  1273. $nodeServiceHeader = $nodeRequest->addChild('ServiceHeader');
  1274. $nodeServiceHeader->addChild('MessageTime', $this->buildMessageTimestamp());
  1275. // MessageReference must be 28 to 32 chars.
  1276. $nodeServiceHeader->addChild(
  1277. 'MessageReference',
  1278. $this->buildMessageReference(self::SERVICE_PREFIX_SHIPVAL)
  1279. );
  1280. $nodeServiceHeader->addChild('SiteID', (string)$this->getConfigData('id'));
  1281. $nodeServiceHeader->addChild('Password', (string)$this->getConfigData('password'));
  1282. $originRegion = $this->getCountryParams(
  1283. $this->_scopeConfig->getValue(
  1284. Shipment::XML_PATH_STORE_COUNTRY_ID,
  1285. \Magento\Store\Model\ScopeInterface::SCOPE_STORE,
  1286. $this->getStore()
  1287. )
  1288. )->getRegion();
  1289. if ($originRegion) {
  1290. $xml->addChild('RegionCode', $originRegion, '');
  1291. }
  1292. $xml->addChild('RequestedPickupTime', 'N', '');
  1293. $xml->addChild('NewShipper', 'N', '');
  1294. $xml->addChild('LanguageCode', 'EN', '');
  1295. $xml->addChild('PiecesEnabled', 'Y', '');
  1296. /** Billing */
  1297. $nodeBilling = $xml->addChild('Billing', '', '');
  1298. $nodeBilling->addChild('ShipperAccountNumber', (string)$this->getConfigData('account'));
  1299. /**
  1300. * Method of Payment:
  1301. * S (Shipper)
  1302. * R (Receiver)
  1303. * T (Third Party)
  1304. */
  1305. $nodeBilling->addChild('ShippingPaymentType', 'S');
  1306. /**
  1307. * Shipment bill to account – required if Shipping PaymentType is other than 'S'
  1308. */
  1309. $nodeBilling->addChild('BillingAccountNumber', (string)$this->getConfigData('account'));
  1310. $nodeBilling->addChild('DutyPaymentType', 'S');
  1311. $nodeBilling->addChild('DutyAccountNumber', (string)$this->getConfigData('account'));
  1312. /** Receiver */
  1313. $nodeConsignee = $xml->addChild('Consignee', '', '');
  1314. $companyName = $rawRequest->getRecipientContactCompanyName() ? $rawRequest
  1315. ->getRecipientContactCompanyName() : $rawRequest
  1316. ->getRecipientContactPersonName();
  1317. $nodeConsignee->addChild('CompanyName', substr($companyName, 0, 35));
  1318. $address = $rawRequest->getRecipientAddressStreet1() . ' ' . $rawRequest->getRecipientAddressStreet2();
  1319. $address = $this->string->split($address, 35, false, true);
  1320. if (is_array($address)) {
  1321. foreach ($address as $addressLine) {
  1322. $nodeConsignee->addChild('AddressLine', $addressLine);
  1323. }
  1324. } else {
  1325. $nodeConsignee->addChild('AddressLine', $address);
  1326. }
  1327. $nodeConsignee->addChild('City', $rawRequest->getRecipientAddressCity());
  1328. $recipientAddressStateOrProvinceCode = $rawRequest->getRecipientAddressStateOrProvinceCode();
  1329. if ($recipientAddressStateOrProvinceCode) {
  1330. $nodeConsignee->addChild('Division', $recipientAddressStateOrProvinceCode);
  1331. }
  1332. $nodeConsignee->addChild('PostalCode', $rawRequest->getRecipientAddressPostalCode());
  1333. $nodeConsignee->addChild('CountryCode', $rawRequest->getRecipientAddressCountryCode());
  1334. $nodeConsignee->addChild(
  1335. 'CountryName',
  1336. $this->getCountryParams($rawRequest->getRecipientAddressCountryCode())->getName()
  1337. );
  1338. $nodeContact = $nodeConsignee->addChild('Contact');
  1339. $nodeContact->addChild('PersonName', substr($rawRequest->getRecipientContactPersonName(), 0, 34));
  1340. $nodeContact->addChild('PhoneNumber', substr($rawRequest->getRecipientContactPhoneNumber(), 0, 24));
  1341. /**
  1342. * Commodity
  1343. * The CommodityCode element contains commodity code for shipment contents. Its
  1344. * value should lie in between 1 to 9999.This field is mandatory.
  1345. */
  1346. $nodeCommodity = $xml->addChild('Commodity', '', '');
  1347. $nodeCommodity->addChild('CommodityCode', '1');
  1348. /** Dutiable */
  1349. if ($this->isDutiable(
  1350. $rawRequest->getShipperAddressCountryCode(),
  1351. $rawRequest->getRecipientAddressCountryCode()
  1352. )) {
  1353. $nodeDutiable = $xml->addChild('Dutiable', '', '');
  1354. $nodeDutiable->addChild(
  1355. 'DeclaredValue',
  1356. sprintf("%.2F", $rawRequest->getOrderShipment()->getOrder()->getSubtotal())
  1357. );
  1358. $baseCurrencyCode = $this->_storeManager->getWebsite($rawRequest->getWebsiteId())->getBaseCurrencyCode();
  1359. $nodeDutiable->addChild('DeclaredCurrency', $baseCurrencyCode);
  1360. }
  1361. /**
  1362. * Reference
  1363. * This element identifies the reference information. It is an optional field in the
  1364. * shipment validation request. Only the first reference will be taken currently.
  1365. */
  1366. $nodeReference = $xml->addChild('Reference', '', '');
  1367. $nodeReference->addChild('ReferenceID', 'shipment reference');
  1368. $nodeReference->addChild('ReferenceType', 'St');
  1369. /** Shipment Details */
  1370. $this->_shipmentDetails($xml, $rawRequest);
  1371. /** Shipper */
  1372. $nodeShipper = $xml->addChild('Shipper', '', '');
  1373. $nodeShipper->addChild('ShipperID', (string)$this->getConfigData('account'));
  1374. $nodeShipper->addChild('CompanyName', $rawRequest->getShipperContactCompanyName());
  1375. $nodeShipper->addChild('RegisteredAccount', (string)$this->getConfigData('account'));
  1376. $address = $rawRequest->getShipperAddressStreet1() . ' ' . $rawRequest->getShipperAddressStreet2();
  1377. $address = $this->string->split($address, 35, false, true);
  1378. if (is_array($address)) {
  1379. foreach ($address as $addressLine) {
  1380. $nodeShipper->addChild('AddressLine', $addressLine);
  1381. }
  1382. } else {
  1383. $nodeShipper->addChild('AddressLine', $address);
  1384. }
  1385. $nodeShipper->addChild('City', $rawRequest->getShipperAddressCity());
  1386. $shipperAddressStateOrProvinceCode = $rawRequest->getShipperAddressStateOrProvinceCode();
  1387. if ($shipperAddressStateOrProvinceCode) {
  1388. $nodeShipper->addChild('Division', $shipperAddressStateOrProvinceCode);
  1389. }
  1390. $nodeShipper->addChild('PostalCode', $rawRequest->getShipperAddressPostalCode());
  1391. $nodeShipper->addChild('CountryCode', $rawRequest->getShipperAddressCountryCode());
  1392. $nodeShipper->addChild(
  1393. 'CountryName',
  1394. $this->getCountryParams($rawRequest->getShipperAddressCountryCode())->getName()
  1395. );
  1396. $nodeContact = $nodeShipper->addChild('Contact', '', '');
  1397. $nodeContact->addChild('PersonName', substr($rawRequest->getShipperContactPersonName(), 0, 34));
  1398. $nodeContact->addChild('PhoneNumber', substr($rawRequest->getShipperContactPhoneNumber(), 0, 24));
  1399. $xml->addChild('LabelImageFormat', 'PDF', '');
  1400. $request = $xml->asXML();
  1401. if (!$request && !(mb_detect_encoding($request) == 'UTF-8')) {
  1402. $request = utf8_encode($request);
  1403. }
  1404. $responseBody = $this->_getCachedQuotes($request);
  1405. if ($responseBody === null) {
  1406. $debugData = ['request' => $this->filterDebugData($request)];
  1407. try {
  1408. /** @var \Magento\Framework\HTTP\ZendClient $client */
  1409. $client = $this->_httpClientFactory->create();
  1410. $client->setUri((string)$this->getConfigData('gateway_url'));
  1411. $client->setConfig(['maxredirects' => 0, 'timeout' => 30]);
  1412. $client->setRawData($request);
  1413. $responseBody = $client->request(\Magento\Framework\HTTP\ZendClient::POST)->getBody();
  1414. $responseBody = utf8_decode($responseBody);
  1415. $debugData['result'] = $this->filterDebugData($responseBody);
  1416. $this->_setCachedQuotes($request, $responseBody);
  1417. } catch (\Exception $e) {
  1418. $this->_errors[$e->getCode()] = $e->getMessage();
  1419. $responseBody = '';
  1420. }
  1421. $this->_debug($debugData);
  1422. }
  1423. $this->_isShippingLabelFlag = true;
  1424. return $this->_parseResponse($responseBody);
  1425. }
  1426. /**
  1427. * Generation Shipment Details Node according to origin region
  1428. *
  1429. * @param \Magento\Shipping\Model\Simplexml\Element $xml
  1430. * @param RateRequest $rawRequest
  1431. * @param string $originRegion
  1432. * @return void
  1433. * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  1434. * @SuppressWarnings(PHPMD.NPathComplexity)
  1435. * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  1436. */
  1437. protected function _shipmentDetails($xml, $rawRequest, $originRegion = '')
  1438. {
  1439. $nodeShipmentDetails = $xml->addChild('ShipmentDetails', '', '');
  1440. $nodeShipmentDetails->addChild('NumberOfPieces', count($rawRequest->getPackages()));
  1441. $nodePieces = $nodeShipmentDetails->addChild('Pieces', '', '');
  1442. /*
  1443. * Package type
  1444. * EE (DHL Express Envelope), OD (Other DHL Packaging), CP (Custom Packaging)
  1445. * DC (Document), DM (Domestic), ED (Express Document), FR (Freight)
  1446. * BD (Jumbo Document), BP (Jumbo Parcel), JD (Jumbo Junior Document)
  1447. * JP (Jumbo Junior Parcel), PA (Parcel), DF (DHL Flyer)
  1448. */
  1449. $i = 0;
  1450. foreach ($rawRequest->getPackages() as $package) {
  1451. $nodePiece = $nodePieces->addChild('Piece', '', '');
  1452. $packageType = 'EE';
  1453. if ($package['params']['container'] == self::DHL_CONTENT_TYPE_NON_DOC) {
  1454. $packageType = 'CP';
  1455. }
  1456. $nodePiece->addChild('PieceID', ++$i);
  1457. $nodePiece->addChild('PackageType', $packageType);
  1458. $nodePiece->addChild('Weight', sprintf('%.3f', $package['params']['weight']));
  1459. $params = $package['params'];
  1460. if ($params['width'] && $params['length'] && $params['height']) {
  1461. $nodePiece->addChild('Width', round($params['width']));
  1462. $nodePiece->addChild('Height', round($params['height']));
  1463. $nodePiece->addChild('Depth', round($params['length']));
  1464. }
  1465. $content = [];
  1466. foreach ($package['items'] as $item) {
  1467. $content[] = $item['name'];
  1468. }
  1469. $nodePiece->addChild('PieceContents', substr(implode(',', $content), 0, 34));
  1470. }
  1471. $nodeShipmentDetails->addChild('Weight', sprintf('%.3f', $rawRequest->getPackageWeight()));
  1472. $nodeShipmentDetails->addChild('WeightUnit', substr($this->_getWeightUnit(), 0, 1));
  1473. $nodeShipmentDetails->addChild('GlobalProductCode', $rawRequest->getShippingMethod());
  1474. $nodeShipmentDetails->addChild('LocalProductCode', $rawRequest->getShippingMethod());
  1475. $nodeShipmentDetails->addChild(
  1476. 'Date',
  1477. $this->_coreDate->date('Y-m-d', strtotime('now + 1day'))
  1478. );
  1479. $nodeShipmentDetails->addChild('Contents', 'DHL Parcel');
  1480. /**
  1481. * The DoorTo Element defines the type of delivery service that applies to the shipment.
  1482. * The valid values are DD (Door to Door), DA (Door to Airport) , AA and DC (Door to
  1483. * Door non-compliant)
  1484. */
  1485. $nodeShipmentDetails->addChild('DoorTo', 'DD');
  1486. $nodeShipmentDetails->addChild('DimensionUnit', substr($this->_getDimensionUnit(), 0, 1));
  1487. if ($package['params']['container'] == self::DHL_CONTENT_TYPE_NON_DOC) {
  1488. $packageType = 'CP';
  1489. }
  1490. $nodeShipmentDetails->addChild('PackageType', $packageType);
  1491. if ($this->isDutiable($rawRequest->getOrigCountryId(), $rawRequest->getDestCountryId())) {
  1492. $nodeShipmentDetails->addChild('IsDutiable', 'Y');
  1493. }
  1494. $nodeShipmentDetails->addChild(
  1495. 'CurrencyCode',
  1496. $this->_storeManager->getWebsite($this->_request->getWebsiteId())->getBaseCurrencyCode()
  1497. );
  1498. }
  1499. /**
  1500. * Get tracking
  1501. *
  1502. * @param string|string[] $trackings
  1503. * @return \Magento\Shipping\Model\Tracking\Result|null
  1504. */
  1505. public function getTracking($trackings)
  1506. {
  1507. if (!is_array($trackings)) {
  1508. $trackings = [$trackings];
  1509. }
  1510. $this->_getXMLTracking($trackings);
  1511. return $this->_result;
  1512. }
  1513. /**
  1514. * Send request for tracking
  1515. *
  1516. * @param string[] $trackings
  1517. * @return void
  1518. */
  1519. protected function _getXMLTracking($trackings)
  1520. {
  1521. $xmlStr = '<?xml version="1.0" encoding="UTF-8"?>' .
  1522. '<req:KnownTrackingRequest' .
  1523. ' xmlns:req="http://www.dhl.com"' .
  1524. ' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"' .
  1525. ' xsi:schemaLocation="http://www.dhl.com TrackingRequestKnown-1.0.xsd"' .
  1526. ' schemaVersion="1.0" />';
  1527. $xml = $this->_xmlElFactory->create(['data' => $xmlStr]);
  1528. $requestNode = $xml->addChild('Request', '', '');
  1529. $serviceHeaderNode = $requestNode->addChild('ServiceHeader', '', '');
  1530. $serviceHeaderNode->addChild('MessageTime', $this->buildMessageTimestamp());
  1531. $serviceHeaderNode->addChild('MessageReference', $this->buildMessageReference(self::SERVICE_PREFIX_TRACKING));
  1532. $serviceHeaderNode->addChild('SiteID', (string)$this->getConfigData('id'));
  1533. $serviceHeaderNode->addChild('Password', (string)$this->getConfigData('password'));
  1534. $xml->addChild('LanguageCode', 'EN', '');
  1535. foreach ($trackings as $tracking) {
  1536. $xml->addChild('AWBNumber', $tracking, '');
  1537. }
  1538. /**
  1539. * Checkpoint details selection flag
  1540. * LAST_CHECK_POINT_ONLY
  1541. * ALL_CHECK_POINTS
  1542. */
  1543. $xml->addChild('LevelOfDetails', 'ALL_CHECK_POINTS', '');
  1544. /**
  1545. * Value that indicates for getting the tracking details with the additional
  1546. * piece details and its respective Piece Details, Piece checkpoints along with
  1547. * Shipment Details if queried.
  1548. *
  1549. * S-Only Shipment Details
  1550. * B-Both Shipment & Piece Details
  1551. * P-Only Piece Details
  1552. * Default is ‘S’
  1553. */
  1554. //$xml->addChild('PiecesEnabled', 'ALL_CHECK_POINTS');
  1555. $request = $xml->asXML();
  1556. $request = utf8_encode($request);
  1557. $responseBody = $this->_getCachedQuotes($request);
  1558. if ($responseBody === null) {
  1559. $debugData = ['request' => $this->filterDebugData($request)];
  1560. try {
  1561. /** @var \Magento\Framework\HTTP\ZendClient $client */
  1562. $client = $this->_httpClientFactory->create();
  1563. $client->setUri((string)$this->getConfigData('gateway_url'));
  1564. $client->setConfig(['maxredirects' => 0, 'timeout' => 30]);
  1565. $client->setRawData($request);
  1566. $responseBody = $client->request(\Magento\Framework\HTTP\ZendClient::POST)->getBody();
  1567. $debugData['result'] = $this->filterDebugData($responseBody);
  1568. $this->_setCachedQuotes($request, $responseBody);
  1569. } catch (\Exception $e) {
  1570. $this->_errors[$e->getCode()] = $e->getMessage();
  1571. $responseBody = '';
  1572. }
  1573. $this->_debug($debugData);
  1574. }
  1575. $this->_parseXmlTrackingResponse($trackings, $responseBody);
  1576. }
  1577. /**
  1578. * Parse xml tracking response
  1579. *
  1580. * @param string[] $trackings
  1581. * @param string $response
  1582. * @return void
  1583. * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  1584. * @SuppressWarnings(PHPMD.NPathComplexity)
  1585. */
  1586. protected function _parseXmlTrackingResponse($trackings, $response)
  1587. {
  1588. $errorTitle = __('Unable to retrieve tracking');
  1589. $resultArr = [];
  1590. if (strlen(trim($response)) > 0) {
  1591. $xml = $this->parseXml($response, \Magento\Shipping\Model\Simplexml\Element::class);
  1592. if (!is_object($xml)) {
  1593. $errorTitle = __('Response is in the wrong format');
  1594. }
  1595. if (is_object($xml)
  1596. && (isset($xml->Response->Status->ActionStatus)
  1597. && $xml->Response->Status->ActionStatus == 'Failure'
  1598. || isset($xml->GetQuoteResponse->Note->Condition))
  1599. ) {
  1600. if (isset($xml->Response->Status->Condition)) {
  1601. $nodeCondition = $xml->Response->Status->Condition;
  1602. }
  1603. $code = isset($nodeCondition->ConditionCode) ? (string)$nodeCondition->ConditionCode : 0;
  1604. $data = isset($nodeCondition->ConditionData) ? (string)$nodeCondition->ConditionData : '';
  1605. $this->_errors[$code] = __('Error #%1 : %2', $code, $data);
  1606. } elseif (is_object($xml) && is_object($xml->AWBInfo)) {
  1607. foreach ($xml->AWBInfo as $awbinfo) {
  1608. $awbinfoData = [];
  1609. $trackNum = isset($awbinfo->AWBNumber) ? (string)$awbinfo->AWBNumber : '';
  1610. if (!is_object($awbinfo) || !$awbinfo->ShipmentInfo) {
  1611. $this->_errors[$trackNum] = __('Unable to retrieve tracking');
  1612. continue;
  1613. }
  1614. $shipmentInfo = $awbinfo->ShipmentInfo;
  1615. if ($shipmentInfo->ShipmentDesc) {
  1616. $awbinfoData['service'] = (string)$shipmentInfo->ShipmentDesc;
  1617. }
  1618. $awbinfoData['weight'] = (string)$shipmentInfo->Weight . ' ' . (string)$shipmentInfo->WeightUnit;
  1619. $packageProgress = [];
  1620. if (isset($shipmentInfo->ShipmentEvent)) {
  1621. foreach ($shipmentInfo->ShipmentEvent as $shipmentEvent) {
  1622. $shipmentEventArray = [];
  1623. $shipmentEventArray['activity'] = (string)$shipmentEvent->ServiceEvent->EventCode
  1624. . ' ' . (string)$shipmentEvent->ServiceEvent->Description;
  1625. $shipmentEventArray['deliverydate'] = (string)$shipmentEvent->Date;
  1626. $shipmentEventArray['deliverytime'] = (string)$shipmentEvent->Time;
  1627. $shipmentEventArray['deliverylocation'] = (string)$shipmentEvent->ServiceArea
  1628. ->Description . ' [' . (string)$shipmentEvent->ServiceArea->ServiceAreaCode . ']';
  1629. $packageProgress[] = $shipmentEventArray;
  1630. }
  1631. $awbinfoData['progressdetail'] = $packageProgress;
  1632. }
  1633. $resultArr[$trackNum] = $awbinfoData;
  1634. }
  1635. }
  1636. }
  1637. $result = $this->_trackFactory->create();
  1638. if (!empty($resultArr)) {
  1639. foreach ($resultArr as $trackNum => $data) {
  1640. $tracking = $this->_trackStatusFactory->create();
  1641. $tracking->setCarrier($this->_code);
  1642. $tracking->setCarrierTitle($this->getConfigData('title'));
  1643. $tracking->setTracking($trackNum);
  1644. $tracking->addData($data);
  1645. $result->append($tracking);
  1646. }
  1647. }
  1648. if (!empty($this->_errors) || empty($resultArr)) {
  1649. $resultArr = !empty($this->_errors) ? $this->_errors : $trackings;
  1650. foreach ($resultArr as $trackNum => $err) {
  1651. $error = $this->_trackErrorFactory->create();
  1652. $error->setCarrier($this->_code);
  1653. $error->setCarrierTitle($this->getConfigData('title'));
  1654. $error->setTracking(!empty($this->_errors) ? $trackNum : $err);
  1655. $error->setErrorMessage(!empty($this->_errors) ? $err : $errorTitle);
  1656. $result->append($error);
  1657. }
  1658. }
  1659. $this->_result = $result;
  1660. }
  1661. /**
  1662. * Get final price for shipping method with handling fee per package
  1663. *
  1664. * @param float $cost
  1665. * @param string $handlingType
  1666. * @param float $handlingFee
  1667. * @return float
  1668. */
  1669. protected function _getPerpackagePrice($cost, $handlingType, $handlingFee)
  1670. {
  1671. if ($handlingType == AbstractCarrier::HANDLING_TYPE_PERCENT) {
  1672. return $cost + $cost * $this->_numBoxes * $handlingFee / 100;
  1673. }
  1674. return $cost + $this->_numBoxes * $handlingFee;
  1675. }
  1676. /**
  1677. * Do request to shipment
  1678. *
  1679. * @param \Magento\Shipping\Model\Shipment\Request $request
  1680. * @return array|\Magento\Framework\DataObject
  1681. * @throws \Magento\Framework\Exception\LocalizedException
  1682. */
  1683. public function requestToShipment($request)
  1684. {
  1685. $packages = $request->getPackages();
  1686. if (!is_array($packages) || !$packages) {
  1687. throw new \Magento\Framework\Exception\LocalizedException(__('No packages for request'));
  1688. }
  1689. $result = $this->_doShipmentRequest($request);
  1690. $response = new \Magento\Framework\DataObject(
  1691. [
  1692. 'info' => [
  1693. [
  1694. 'tracking_number' => $result->getTrackingNumber(),
  1695. 'label_content' => $result->getShippingLabelContent(),
  1696. ],
  1697. ],
  1698. ]
  1699. );
  1700. $request->setMasterTrackingId($result->getTrackingNumber());
  1701. return $response;
  1702. }
  1703. /**
  1704. * Check if shipping is domestic
  1705. *
  1706. * @param string $origCountryCode
  1707. * @param string $destCountryCode
  1708. * @return bool
  1709. */
  1710. protected function _checkDomesticStatus($origCountryCode, $destCountryCode)
  1711. {
  1712. $this->_isDomestic = false;
  1713. $origCountry = (string)$this->getCountryParams($origCountryCode)->getData('name');
  1714. $destCountry = (string)$this->getCountryParams($destCountryCode)->getData('name');
  1715. $isDomestic = (string)$this->getCountryParams($destCountryCode)->getData('domestic');
  1716. if (($origCountry == $destCountry && $isDomestic)
  1717. || ($this->_carrierHelper->isCountryInEU($origCountryCode)
  1718. && $this->_carrierHelper->isCountryInEU($destCountryCode)
  1719. )
  1720. ) {
  1721. $this->_isDomestic = true;
  1722. }
  1723. return $this->_isDomestic;
  1724. }
  1725. /**
  1726. * Prepare shipping label data
  1727. *
  1728. * @param \SimpleXMLElement $xml
  1729. * @return \Magento\Framework\DataObject
  1730. * @throws \Magento\Framework\Exception\LocalizedException
  1731. */
  1732. protected function _prepareShippingLabelContent(\SimpleXMLElement $xml)
  1733. {
  1734. $result = new \Magento\Framework\DataObject();
  1735. try {
  1736. if (!isset($xml->AirwayBillNumber) || !isset($xml->LabelImage->OutputImage)) {
  1737. throw new \Magento\Framework\Exception\LocalizedException(__('Unable to retrieve shipping label'));
  1738. }
  1739. $result->setTrackingNumber((string)$xml->AirwayBillNumber);
  1740. $labelContent = (string)$xml->LabelImage->OutputImage;
  1741. $result->setShippingLabelContent(base64_decode($labelContent));
  1742. } catch (\Exception $e) {
  1743. throw new \Magento\Framework\Exception\LocalizedException(__($e->getMessage()));
  1744. }
  1745. return $result;
  1746. }
  1747. /**
  1748. * Verify if the shipment is dutiable
  1749. *
  1750. * @param string $origCountryId
  1751. * @param string $destCountryId
  1752. *
  1753. * @return bool
  1754. */
  1755. protected function isDutiable($origCountryId, $destCountryId) : bool
  1756. {
  1757. $this->_checkDomesticStatus($origCountryId, $destCountryId);
  1758. return
  1759. self::DHL_CONTENT_TYPE_NON_DOC == $this->getConfigData('content_type')
  1760. || !$this->_isDomestic;
  1761. }
  1762. /**
  1763. * Builds a datetime string to be used as the MessageTime in accordance to the expected format.
  1764. *
  1765. * @param string|null $datetime
  1766. * @return string
  1767. */
  1768. private function buildMessageTimestamp(string $datetime = null): string
  1769. {
  1770. return $this->_coreDate->date(\DATE_RFC3339, $datetime);
  1771. }
  1772. /**
  1773. * Builds a string to be used as the MessageReference.
  1774. *
  1775. * @param string $servicePrefix
  1776. * @return string
  1777. * @throws \Magento\Framework\Exception\LocalizedException
  1778. */
  1779. private function buildMessageReference(string $servicePrefix): string
  1780. {
  1781. $validPrefixes = [
  1782. self::SERVICE_PREFIX_QUOTE,
  1783. self::SERVICE_PREFIX_SHIPVAL,
  1784. self::SERVICE_PREFIX_TRACKING
  1785. ];
  1786. if (!in_array($servicePrefix, $validPrefixes)) {
  1787. throw new \Magento\Framework\Exception\LocalizedException(
  1788. __("Invalid service prefix \"$servicePrefix\" provided while attempting to build MessageReference")
  1789. );
  1790. }
  1791. return str_replace('.', '', uniqid("MAGE_{$servicePrefix}_", true));
  1792. }
  1793. /**
  1794. * Builds a string to be used as the request SoftwareName.
  1795. *
  1796. * @return string
  1797. */
  1798. private function buildSoftwareName(): string
  1799. {
  1800. return substr($this->productMetadata->getName(), 0, 30);
  1801. }
  1802. /**
  1803. * Builds a string to be used as the request SoftwareVersion.
  1804. *
  1805. * @return string
  1806. */
  1807. private function buildSoftwareVersion(): string
  1808. {
  1809. return substr($this->productMetadata->getVersion(), 0, 10);
  1810. }
  1811. }