diff --git a/src/modules/mo/mo_dhl/Adapter/ParcelShippingConverter.php b/src/modules/mo/mo_dhl/Adapter/ParcelShippingConverter.php deleted file mode 100644 index 3499736..0000000 --- a/src/modules/mo/mo_dhl/Adapter/ParcelShippingConverter.php +++ /dev/null @@ -1,721 +0,0 @@ - - */ - protected const ISO2_TO_ISO3_COUNTRY_CODES = [ - "BD" => "BGD", - "BE" => "BEL", - "BF" => "BFA", - "BG" => "BGR", - "BA" => "BIH", - "BB" => "BRB", - "WF" => "WLF", - "BL" => "BLM", - "BM" => "BMU", - "BN" => "BRN", - "BO" => "BOL", - "BH" => "BHR", - "BI" => "BDI", - "BJ" => "BEN", - "BT" => "BTN", - "JM" => "JAM", - "BV" => "BVT", - "BW" => "BWA", - "WS" => "WSM", - "BQ" => "BES", - "BR" => "BRA", - "BS" => "BHS", - "JE" => "JEY", - "BY" => "BLR", - "BZ" => "BLZ", - "RU" => "RUS", - "RW" => "RWA", - "RS" => "SRB", - "TL" => "TLS", - "RE" => "REU", - "TM" => "TKM", - "TJ" => "TJK", - "RO" => "ROU", - "TK" => "TKL", - "GW" => "GNB", - "GU" => "GUM", - "GT" => "GTM", - "GS" => "SGS", - "GR" => "GRC", - "GQ" => "GNQ", - "GP" => "GLP", - "JP" => "JPN", - "GY" => "GUY", - "GG" => "GGY", - "GF" => "GUF", - "GE" => "GEO", - "GD" => "GRD", - "GB" => "GBR", - "GA" => "GAB", - "SV" => "SLV", - "GN" => "GIN", - "GM" => "GMB", - "GL" => "GRL", - "GI" => "GIB", - "GH" => "GHA", - "OM" => "OMN", - "TN" => "TUN", - "JO" => "JOR", - "HR" => "HRV", - "HT" => "HTI", - "HU" => "HUN", - "HK" => "HKG", - "HN" => "HND", - "HM" => "HMD", - "VE" => "VEN", - "PR" => "PRI", - "PS" => "PSE", - "PW" => "PLW", - "PT" => "PRT", - "SJ" => "SJM", - "PY" => "PRY", - "IQ" => "IRQ", - "PA" => "PAN", - "PF" => "PYF", - "PG" => "PNG", - "PE" => "PER", - "PK" => "PAK", - "PH" => "PHL", - "PN" => "PCN", - "PL" => "POL", - "PM" => "SPM", - "ZM" => "ZMB", - "EH" => "ESH", - "EE" => "EST", - "EG" => "EGY", - "ZA" => "ZAF", - "EC" => "ECU", - "IT" => "ITA", - "VN" => "VNM", - "SB" => "SLB", - "ET" => "ETH", - "SO" => "SOM", - "ZW" => "ZWE", - "SA" => "SAU", - "ES" => "ESP", - "ER" => "ERI", - "ME" => "MNE", - "MD" => "MDA", - "MG" => "MDG", - "MF" => "MAF", - "MA" => "MAR", - "MC" => "MCO", - "UZ" => "UZB", - "MM" => "MMR", - "ML" => "MLI", - "MO" => "MAC", - "MN" => "MNG", - "MH" => "MHL", - "MK" => "MKD", - "MU" => "MUS", - "MT" => "MLT", - "MW" => "MWI", - "MV" => "MDV", - "MQ" => "MTQ", - "MP" => "MNP", - "MS" => "MSR", - "MR" => "MRT", - "IM" => "IMN", - "UG" => "UGA", - "TZ" => "TZA", - "MY" => "MYS", - "MX" => "MEX", - "IL" => "ISR", - "FR" => "FRA", - "IO" => "IOT", - "SH" => "SHN", - "FI" => "FIN", - "FJ" => "FJI", - "FK" => "FLK", - "FM" => "FSM", - "FO" => "FRO", - "NI" => "NIC", - "NL" => "NLD", - "NO" => "NOR", - "NA" => "NAM", - "VU" => "VUT", - "NC" => "NCL", - "NE" => "NER", - "NF" => "NFK", - "NG" => "NGA", - "NZ" => "NZL", - "NP" => "NPL", - "NR" => "NRU", - "NU" => "NIU", - "CK" => "COK", - "XK" => "XKX", - "CI" => "CIV", - "CH" => "CHE", - "CO" => "COL", - "CN" => "CHN", - "CM" => "CMR", - "CL" => "CHL", - "CC" => "CCK", - "CA" => "CAN", - "CG" => "COG", - "CF" => "CAF", - "CD" => "COD", - "CZ" => "CZE", - "CY" => "CYP", - "CX" => "CXR", - "CR" => "CRI", - "CW" => "CUW", - "CV" => "CPV", - "CU" => "CUB", - "SZ" => "SWZ", - "SY" => "SYR", - "SX" => "SXM", - "KG" => "KGZ", - "KE" => "KEN", - "SS" => "SSD", - "SR" => "SUR", - "KI" => "KIR", - "KH" => "KHM", - "KN" => "KNA", - "KM" => "COM", - "ST" => "STP", - "SK" => "SVK", - "KR" => "KOR", - "SI" => "SVN", - "KP" => "PRK", - "KW" => "KWT", - "SN" => "SEN", - "SM" => "SMR", - "SL" => "SLE", - "SC" => "SYC", - "KZ" => "KAZ", - "KY" => "CYM", - "SG" => "SGP", - "SE" => "SWE", - "SD" => "SDN", - "DO" => "DOM", - "DM" => "DMA", - "DJ" => "DJI", - "DK" => "DNK", - "VG" => "VGB", - "DE" => "DEU", - "YE" => "YEM", - "DZ" => "DZA", - "US" => "USA", - "UY" => "URY", - "YT" => "MYT", - "UM" => "UMI", - "LB" => "LBN", - "LC" => "LCA", - "LA" => "LAO", - "TV" => "TUV", - "TW" => "TWN", - "TT" => "TTO", - "TR" => "TUR", - "LK" => "LKA", - "LI" => "LIE", - "LV" => "LVA", - "TO" => "TON", - "LT" => "LTU", - "LU" => "LUX", - "LR" => "LBR", - "LS" => "LSO", - "TH" => "THA", - "TF" => "ATF", - "TG" => "TGO", - "TD" => "TCD", - "TC" => "TCA", - "LY" => "LBY", - "VA" => "VAT", - "VC" => "VCT", - "AE" => "ARE", - "AD" => "AND", - "AG" => "ATG", - "AF" => "AFG", - "AI" => "AIA", - "VI" => "VIR", - "IS" => "ISL", - "IR" => "IRN", - "AM" => "ARM", - "AL" => "ALB", - "AO" => "AGO", - "AQ" => "ATA", - "AS" => "ASM", - "AR" => "ARG", - "AU" => "AUS", - "AT" => "AUT", - "AW" => "ABW", - "IN" => "IND", - "AX" => "ALA", - "AZ" => "AZE", - "IE" => "IRL", - "ID" => "IDN", - "UA" => "UKR", - "QA" => "QAT", - "MZ" => "MOZ", - ]; - - /** - * @param CreateShipmentOrderRequest $legacyShipmentOrderRequest - * @return array{ 0: array, 1: ShipmentOrderRequest } - */ - public function convertCreateShipmentOrderRequest(CreateShipmentOrderRequest $legacyShipmentOrderRequest): array - { - $shipments = array_map([$this, 'convertShipmentOrder'], $legacyShipmentOrderRequest->getShipmentOrder()); - $shipmentOrderRequest = new ShipmentOrderRequest(); - $shipmentOrderRequest->setShipments($shipments); - $shipmentOrderRequest->setProfile($legacyShipmentOrderRequest->getGroupProfileName() ?: GKVCreateShipmentOrderRequestBuilder::STANDARD_GRUPPENPROFIL); - return [$this->extractQueryParameters($legacyShipmentOrderRequest), $shipmentOrderRequest]; - } - - /** - * @param ValidateShipmentOrderRequest $legacyShipmentOrderRequest - * @return array{ 0: array, 1: ShipmentOrderRequest } - * @throws Exception - */ - public function convertValidateShipmentOrderRequest(ValidateShipmentOrderRequest $legacyShipmentOrderRequest): array - { - $shipment = $this->convertShipmentOrder($legacyShipmentOrderRequest->getShipmentOrder()); - $shipmentOrderRequest = new ShipmentOrderRequest(); - $shipmentOrderRequest->setProfile(GKVCreateShipmentOrderRequestBuilder::STANDARD_GRUPPENPROFIL); - $shipmentOrderRequest->setShipments([$shipment]); - return [['validate' => true], $shipmentOrderRequest]; - } - - /** - * @param array $payload - * @param int|false $index if specified only errors for the given index will be returned - * @return string[] - */ - public function extractErrorsFromResponsePayload(array $payload, $index = false): array - { - $errors = []; - $items = $index !== false ? [$payload['items'][$index]] : $payload['items']; - foreach ($items as $error) { - if (\array_key_exists('validationMessages', $error)) { - foreach ($error['validationMessages'] as $validationMessage) { - $errors[] = "{$validationMessage['validationMessage']} ({$validationMessage['property']})"; - } - continue; - } - if (\array_key_exists('message', $error)) { - $errors[] = "{$error['message']} ({$error['propertyPath']})"; - } - } - if ($errors !== []) { - return $errors; - } - return \array_key_exists('detail', $payload) && $index === false ? [$payload['detail']] : []; - } - - /** - * @param ShipmentOrderType|ValidateShipmentOrderType $legacyShipmentOrder - * @return Shipment - * @throws Exception - */ - protected function convertShipmentOrder($legacyShipmentOrder): Shipment - { - $shipment = new Shipment(); - $shipment->setShipper($this->buildShipper($this->extractContactAddressFromShipperType($legacyShipmentOrder->getShipment()->getShipper()))); - $shipment->setConsignee($this->extractConsignee($legacyShipmentOrder)); - $shipment->setDetails($this->extractShipmentDetails($legacyShipmentOrder)); - $shipment->setCreationSoftware(CsvExporter::CREATOR_TAG); - if ($exportDocument = $legacyShipmentOrder->getShipment()->getExportDocument()) { - $shipment->setCustoms($this->extractCustoms($exportDocument)); - } - if ($accountNumber = $legacyShipmentOrder->getShipment()->getShipmentDetails()->getAccountNumber()) { - $shipment->setBillingNumber($accountNumber); - } - if ($costCenter = $legacyShipmentOrder->getShipment()->getShipmentDetails()->getCostCentre()) { - $shipment->setCostCenter($costCenter); - } - if ($product = $legacyShipmentOrder->getShipment()->getShipmentDetails()->getProduct()) { - $shipment->setProduct($product); - } - if ($refNo = $legacyShipmentOrder->getShipment()->getShipmentDetails()->getCustomerReference()) { - $shipment->setRefNo($refNo); - } - if ($services = $this->extractServices($legacyShipmentOrder)) { - $shipment->setServices($services); - } - if ($shipmentDate = $legacyShipmentOrder->getShipment()->getShipmentDetails()->getShipmentDate()) { - $shipment->setShipDate(new DateTime($shipmentDate)); - } - return $shipment; - } - - /** - * @param ShipmentOrderType|ValidateShipmentOrderType $legacyShipmentOrder - * @return array - */ - protected function extractConsignee($legacyShipmentOrder): array - { - $legacyReceiver = $legacyShipmentOrder->getShipment()->getReceiver(); - - if ($legacyReceiver->getPackstation() !== null) { - return array_filter([ - 'city' => $legacyReceiver->getPackstation()->getCity(), - 'lockerID' => $legacyReceiver->getPackstation()->getPackstationNumber(), - 'postalCode' => $legacyReceiver->getPackstation()->getZip(), - 'postNumber' => $legacyReceiver->getPackstation()->getPostNumber(), - 'name' => $legacyReceiver->getName1(), - 'country' => $this->mapISO2ToISO3($legacyReceiver->getPackstation()->getOrigin()->getCountryISOCode()), - ]); - } - if ($legacyReceiver->getPostfiliale() !== null) { - return array_filter([ - 'city' => $legacyReceiver->getPostfiliale()->getCity(), - 'name' => $legacyReceiver->getName1(), - 'postalCode' => $legacyReceiver->getPostfiliale()->getZip(), - 'retailID' => $legacyReceiver->getPostfiliale()->getPostfilialNumber(), - 'postNumber' => $legacyReceiver->getPostfiliale()->getPostNumber(), - 'country' => $this->mapISO2ToISO3($legacyReceiver->getPostfiliale()->getOrigin()->getCountryISOCode()), - ]); - } - return array_filter([ - 'name1' => $legacyReceiver->getName1(), - 'name2' => $legacyReceiver->getAddress()->getName2(), - 'name3' => $legacyReceiver->getAddress()->getName3(), - 'dispatchingInformation' => $legacyReceiver->getAddress()->getDispatchingInformation(), - 'additionalAddressInformation1' => $legacyReceiver->getAddress()->getAddressAddition()[0] ?? null, - 'additionalAddressInformation2' => $legacyReceiver->getAddress()->getAddressAddition()[1] ?? null, - 'state' => $legacyReceiver->getAddress()->getProvince(), - 'contactName' => $legacyReceiver->getCommunication()->getContactPerson(), - 'phone' => $legacyReceiver->getCommunication()->getPhone(), - 'email' => $legacyReceiver->getCommunication()->getEmail(), - 'city' => $legacyReceiver->getAddress()->getCity(), - 'postalCode' => $legacyReceiver->getAddress()->getZip(), - 'addressStreet' => $legacyReceiver->getAddress()->getStreetName(), - 'addressHouse' => $legacyReceiver->getAddress()->getStreetNumber(), - 'country' => $this->mapISO2ToISO3($legacyReceiver->getAddress()->getOrigin()->getCountryISOCode()), - ]); - } - - /** - * @param ExportDocumentType $legacyExportDocument - * @return CustomsDetails - */ - protected function extractCustoms(ExportDocumentType $legacyExportDocument): CustomsDetails - { - $customsDetails = new CustomsDetails(); - $customsDetails->setExportType($legacyExportDocument->getExportType()); - if ($description = $legacyExportDocument->getExportTypeDescription()) { - $customsDetails->setExportDescription($description); - } - $customsDetails->setPostalCharges($this->createValue($legacyExportDocument->getAdditionalFee(), $legacyExportDocument->getCustomsCurrency())); - $customsDetails->setItems(array_map([$this, 'convertToCommodity'], $legacyExportDocument->getExportDocPosition())); - if ($attestationNo = $legacyExportDocument->getAttestationNumber()) { - $customsDetails->setAttestationNo($attestationNo); - } - if ($legacyExportDocument->getWithElectronicExportNtfctn() !== null && $legacyExportDocument->getWithElectronicExportNtfctn()->getActive()) { - $customsDetails->setHasElectronicExportNotification(true); - } - if ($invoiceNo = $legacyExportDocument->getInvoiceNumber()) { - $customsDetails->setInvoiceNo($invoiceNo); - } - if ($origin = $legacyExportDocument->getPlaceOfCommital()) { - $customsDetails->setOfficeOfOrigin($origin); - } - if ($permitNo = $legacyExportDocument->getPermitNumber()) { - $customsDetails->setPermitNo($permitNo); - } - if ($shippingConditions = $legacyExportDocument->getTermsOfTrade()) { - $customsDetails->setShippingConditions($shippingConditions); - } - return $customsDetails; - } - - /** - * @param ExportDocPosition $item - * @return Commodity - */ - protected function convertToCommodity(ExportDocPosition $item): Commodity - { - $commodity = new Commodity(); - $commodity->setItemDescription($item->getDescription()); - $commodity->setPackagedQuantity($item->getAmount()); - $commodity->setItemValue($this->createValue($item->getCustomsValue())); - $weight = new Weight(); - $weight->setUom('kg'); - $weight->setValue($item->getNetWeightInKG()); - $commodity->setItemWeight($weight); - if ($hsCode = $item->getCustomsTariffNumber()) { - $commodity->setHsCode($hsCode); - } - if ($origin = $item->getCountryCodeOrigin()) { - $commodity->setCountryOfOrigin($this->mapISO2ToISO3($origin)); - } - return $commodity; - } - - /** - * @param ContactAddress $address - * @return Shipper - */ - protected function buildShipper(ContactAddress $address): Shipper - { - $shipper = new Shipper(); - $shipper->setName1($address->getName1()); - if ($address->isInitialized('name2')) { - $shipper->setName2($address->getName2()); - } - if ($address->isInitialized('name3')) { - $shipper->setName3($address->getName3()); - } - $shipper->setCity($address->getCity()); - $shipper->setPostalCode($address->getPostalCode()); - $shipper->setAddressStreet($address->getAddressStreet()); - $shipper->setAddressHouse($address->getAddressHouse()); - $shipper->setCountry($address->getCountry()); - return $shipper; - } - - /** - * @param ShipperType|null $legacyShipper - * @return ContactAddress - */ - protected function extractContactAddressFromShipperType(?ShipperType $legacyShipper): ContactAddress - { - $contactAddress = new ContactAddress(); - $contactAddress->setName1($legacyShipper->getName()->getName1()); - if ($legacyShipper->getName()->getName2()) { - $contactAddress->setName2($legacyShipper->getName()->getName2()); - } - if ($legacyShipper->getName()->getName3()) { - $contactAddress->setName3($legacyShipper->getName()->getName3()); - } - $contactAddress->setCity($legacyShipper->getAddress()->getCity()); - if ($legacyShipper->getAddress()->getZip()) { - $contactAddress->setPostalCode($legacyShipper->getAddress()->getZip()); - } - $contactAddress->setAddressStreet($legacyShipper->getAddress()->getStreetName()); - if ($legacyShipper->getAddress()->getStreetNumber()) { - $contactAddress->setAddressHouse($legacyShipper->getAddress()->getStreetNumber()); - } - $contactAddress->setCountry($this->mapISO2ToISO3($legacyShipper->getAddress()->getOrigin()->getCountryISOCode())); - return $contactAddress; - } - - /** - * @param ShipmentOrderType|ValidateShipmentOrderType $legacyShipmentOrder - * @return ShipmentDetails - */ - protected function extractShipmentDetails($legacyShipmentOrder): ShipmentDetails - { - $shipmentDetails = new ShipmentDetails(); - $shipmentItem = $legacyShipmentOrder->getShipment()->getShipmentDetails()->getShipmentItem(); - - $dimensions = new Dimensions(); - if ($shipmentItem->getLengthInCM()) { - $dimensions->setLength($shipmentItem->getLengthInCM()); - $dimensions->setUom('cm'); - $shipmentDetails->setDim($dimensions); - } - if ($shipmentItem->getWidthInCM()) { - $dimensions->setWidth($shipmentItem->getWidthInCM()); - $dimensions->setUom('cm'); - $shipmentDetails->setDim($dimensions); - } - if ($shipmentItem->getHeightInCM()) { - $dimensions->setHeight($shipmentItem->getHeightInCM()); - $dimensions->setUom('cm'); - $shipmentDetails->setDim($dimensions); - } - - $weight = new Weight(); - if ($shipmentItem->getWeightInKG()) { - $weight->setUom('kg'); - $weight->setValue($shipmentItem->getWeightInKG()); - $shipmentDetails->setWeight($weight); - } - - return $shipmentDetails; - } - - /** - * @param ShipmentOrderType|ValidateShipmentOrderType $legacyShipmentOrder - * @return VAS|null - * @throws Exception - */ - protected function extractServices($legacyShipmentOrder): ?VAS - { - $legacyServices = $legacyShipmentOrder->getShipment()->getShipmentDetails()->getService(); - if ($legacyServices === null) { - return null; - } - - $services = new VAS(); - $initialized = false; - if ($legacyServices->getBulkyGoods() !== null && $legacyServices->getBulkyGoods()->getActive()) { - $services->setBulkyGoods(true); - $initialized = true; - } - if ($legacyServices->getEndorsement() !== null && $legacyServices->getEndorsement()->getActive()) { - $endorsement = $legacyServices->getEndorsement()->getType() === MoDHLService::MO_DHL__ENDORSEMENT_ABANDONMENT - ? 'ABANDON' - : 'RETURN'; - $services->setEndorsement($endorsement); - $initialized = true; - } - if ($legacyServices->getPreferredDay() !== null && $legacyServices->getPreferredDay()->getActive()) { - $services->setPreferredDay(new DateTime($legacyServices->getPreferredDay()->getDetails())); - $initialized = true; - } - if ($legacyServices->getPreferredLocation() !== null && $legacyServices->getPreferredLocation()->getActive()) { - $services->setPreferredLocation($legacyServices->getPreferredLocation()->getDetails()); - $initialized = true; - } - if ($legacyServices->getPreferredNeighbour() !== null && $legacyServices->getPreferredNeighbour()->getActive()) { - $services->setPreferredNeighbour($legacyServices->getPreferredNeighbour()->getDetails()); - $initialized = true; - } - if ($legacyServices->getVisualCheckOfAge() !== null && $legacyServices->getVisualCheckOfAge()->getActive()) { - $services->setVisualCheckOfAge($legacyServices->getVisualCheckOfAge()->getType()); - $initialized = true; - } - if ($returnAccountNumber = $legacyShipmentOrder->getShipment()->getShipmentDetails()->getReturnShipmentAccountNumber()) { - $dhlRetoure = new VASDhlRetoure(); - $dhlRetoure->setBillingNumber($returnAccountNumber); - $dhlRetoure->setReturnAddress($this->extractContactAddressFromShipperType($legacyShipmentOrder->getShipment()->getShipper())); - if ($refNo = $legacyShipmentOrder->getShipment()->getShipmentDetails()->getReturnShipmentReference()) { - $dhlRetoure->setRefNo($refNo); - } - - $services->setDhlRetoure($dhlRetoure); - $initialized = true; - } - if ($legacyServices->getAdditionalInsurance() !== null && $legacyServices->getAdditionalInsurance()->getActive()) { - $services->setAdditionalInsurance($this->createValue($legacyServices->getAdditionalInsurance()->getInsuranceAmount())); - $initialized = true; - } - if ($legacyServices->getCashOnDelivery() !== null && $legacyServices->getCashOnDelivery()->getActive()) { - $cashOnDelivery = new VASCashOnDelivery(); - $cashOnDelivery->setAmount($this->createValue($legacyServices->getCashOnDelivery()->getCodAmount())); - $services->setCashOnDelivery($cashOnDelivery); - $initialized = true; - } - if ($legacyServices->getIdentCheck() !== null && $legacyServices->getIdentCheck()->getActive()) { - $legacyIdent = $legacyServices->getIdentCheck()->getIdent(); - $identCheck = new VASIdentCheck(); - $identCheck->setDateOfBirth(new DateTime($legacyIdent->getDateOfBirth())); - $identCheck->setFirstName($legacyIdent->getGivenName()); - $identCheck->setLastName($legacyIdent->getSurname()); - $identCheck->setMinimumAge($legacyIdent->getMinimumAge()); - $services->setIdentCheck($identCheck); - $initialized = true; - } - if ($legacyServices->getIndividualSenderRequirement() && $legacyServices->getIndividualSenderRequirement()->getActive()) { - $services->setIndividualSenderRequirement($legacyServices->getIndividualSenderRequirement()->getDetails()); - $initialized = true; - } - if ($legacyServices->getNamedPersonOnly() !== null && $legacyServices->getNamedPersonOnly()->getActive()) { - $services->setNamedPersonOnly(true); - $initialized = true; - } - if ($legacyServices->getNoNeighbourDelivery() !== null && $legacyServices->getNoNeighbourDelivery()->getActive()) { - $services->setNoNeighbourDelivery(true); - $initialized = true; - } - if ($legacyServices->getSignedForByRecipient() !== null && $legacyServices->getSignedForByRecipient()->getActive()) { - $services->setSignedForByRecipient(true); - $initialized = true; - } - if ($legacyServices->getParcelOutletRouting() !== null && $legacyServices->getParcelOutletRouting()->getActive()) { - $services->setParcelOutletRouting($legacyServices->getParcelOutletRouting()->getDetails() ?: ''); - $initialized = true; - } - if ($legacyServices->getPDDP() !== null && $legacyServices->getPDDP()->getActive()) { - $services->setPostalDeliveryDutyPaid(true); - $initialized = true; - } - if ($legacyServices->getCDP() !== null && $legacyServices->getCDP()->getActive()) { - $services->setClosestDropPoint(true); - $initialized = true; - } - if ($legacyServices->getPremium() !== null && $legacyServices->getPremium()->getActive()) { - $services->setPremium(true); - $initialized = true; - } - - return $initialized ? $services : null; - } - - /** - * @param CreateShipmentOrderRequest $legacyShipmentOrderRequest - * @return array - */ - protected function extractQueryParameters(CreateShipmentOrderRequest $legacyShipmentOrderRequest): array - { - return [ - 'includeDocs' => 'URL', - 'combine' => (bool)$legacyShipmentOrderRequest->getCombinedPrinting(), - 'mustEncode' => \in_array(true, array_map(function ($shipment) use ($legacyShipmentOrderRequest) { - return $shipment->getPrintOnlyIfCodeable() !== null && $shipment->getPrintOnlyIfCodeable()->getActive(); - }, $legacyShipmentOrderRequest->getShipmentOrder()), true), - ]; - } - - /** - * @param string $iso2 - * @return string - */ - protected function mapISO2ToISO3(string $iso2): string - { - if (!\array_key_exists(\strtoupper($iso2), self::ISO2_TO_ISO3_COUNTRY_CODES)) { - throw new \InvalidArgumentException(\sprintf('Could not map ISO2 "%s" to ISO3', $iso2)); - } - return self::ISO2_TO_ISO3_COUNTRY_CODES[\strtoupper($iso2)]; - } - - /** - * This method will return a value with EUR as currency since the currency this class receives is EUR at the moment. - * - * @param float $amount - * @param string|null $currency - * @return Value - */ - protected function createValue(float $amount, ?string $currency = null): Value - { - $value = new Value(); - $value->setValue($amount); - $value->setCurrency($currency ?: 'EUR'); - return $value; - } -} diff --git a/src/modules/mo/mo_dhl/Adapter/ParcelShippingRequestBuilder.php b/src/modules/mo/mo_dhl/Adapter/ParcelShippingRequestBuilder.php new file mode 100644 index 0000000..80ee1b8 --- /dev/null +++ b/src/modules/mo/mo_dhl/Adapter/ParcelShippingRequestBuilder.php @@ -0,0 +1,562 @@ +setShipments($shipments); + $shipmentOrderRequest->setProfile(self::STANDARD_GRUPPENPROFIL); + return [$this->buildQueryParameters(), $shipmentOrderRequest]; + } + + /** + * @param string $orderId + * @return Shipment + * @throws \OxidEsales\Eshop\Core\Exception\SystemComponentException + * @throws \OxidEsales\Eshop\Core\Exception\DatabaseConnectionException + */ + public function buildShipment(string $orderId) + { + $order = \oxNew(Order::class); + $order->load($orderId); + $shipment = new Shipment(); + $shipment->setShipper($this->buildShipper()); + $shipment->setConsignee($this->buildReceiver($order)); + $shipment->setDetails($this->buildShipmentDetails($order)); + $shipment->setCreationSoftware(CsvExporter::CREATOR_TAG); + if ($this->isInternational($order)) { + $shipment->setCustoms( $this->buildExportDocument($order)); + } + $shipment->setBillingNumber($this->buildAccountNumber($order)); + $shipment->setProduct($this->getProcess($order)->getServiceIdentifier()); + $customerReference = Registry::getLang()->translateString('GENERAL_ORDERNUM') . ' ' . $order->getFieldData('oxordernr'); + $shipment->setRefNo($customerReference); + $shipment->setServices($this->buildService($order)); + $shipment->setShipDate($this->buildShipmentDate()); + return $shipment; + } + + /** + * @param Order $order + * @return ShipmentDetails + */ + protected function buildShipmentDetails(Order $order): ShipmentDetails + { + $shipmentDetails = new ShipmentDetails(); + $weight = new Weight(); + $weight->setUom('kg'); + $weight->setValue($this->calculateWeight($order)); + $shipmentDetails->setWeight($weight); + return $shipmentDetails; + } + + /** + * @param Order $order + * @return array + * @throws \OxidEsales\Eshop\Core\Exception\SystemComponentException + */ + protected function buildReceiver($order): array + { + $name = $this->convertSpecialChars($order->moDHLGetAddressData('fname')) + . ' ' . $this->convertSpecialChars($order->moDHLGetAddressData('lname')); + if (Branch::isPackstation($order->moDHLGetAddressData('street'))) { + return array_filter([ + 'city' => $order->moDHLGetAddressData('city'), + 'lockerID' => $order->moDHLGetAddressData('streetnr'), + 'postalCode' => $order->moDHLGetAddressData('zip'), + 'postNumber' => $order->moDHLGetAddressData('addinfo'), + 'name' => $name, + 'country' => $this->buildCountry($order->moDHLGetAddressData('countryid')), + ]); + } else if (Branch::isFiliale($order->moDHLGetAddressData('street'))) { + return array_filter([ + 'city' => $order->moDHLGetAddressData('city'), + 'name' => $name, + 'postalCode' => $order->moDHLGetAddressData('zip'), + 'retailID' => $order->moDHLGetAddressData('streetnr'), + 'postNumber' => $order->moDHLGetAddressData('addinfo'), + 'country' => $this->buildCountry($order->moDHLGetAddressData('countryid')), + ]); + } else { + return array_filter([ + 'name1' => $name, + 'name2' => $order->moDHLGetAddressData('company') + ? $this->convertSpecialChars($order->moDHLGetAddressData('company')) + : null, + 'name3' => $order->moDHLGetAddressData('addinfo') + ? $this->convertSpecialChars($order->moDHLGetAddressData('addinfo')) + : null, + 'state' => $this->getStateName($order->moDHLGetAddressData('stateid')) ?: null, + 'contactName' => $name, + 'phone' => $order->moDHLGetAddressData('fon'), + 'email' => $this->sendNotificationAllowed($order) ? $order->getFieldData('oxbillemail') : null, + 'city' => $this->convertSpecialChars($order->moDHLGetAddressData('city')), + 'postalCode' => $order->moDHLGetAddressData('zip'), + 'addressStreet' => $this->convertSpecialChars($order->moDHLGetAddressData('street')), + 'addressHouse' => $order->moDHLGetAddressData('streetnr'), + 'country' => $this->buildCountry($order->moDHLGetAddressData('countryid')), + ]); + } + } + + /** + * @param string|null $stateId + * @return string|null + */ + protected function getStateName(?string $stateId) + { + if (is_null($stateId)) { + return null; + } + + $state = \oxNew(State::class); + $state->load($stateId); + return $state->getFieldData('oxisoalpha2'); + } + + /** + * @param string $countryId + * @throws \OxidEsales\Eshop\Core\Exception\SystemComponentException + */ + protected function buildCountry($countryId): string + { + $country = \oxNew(\OxidEsales\Eshop\Application\Model\Country::class); + $country->load($countryId); + return $country->getFieldData('oxisoalpha3'); + } + + /** + * @param Order $order + * @return BillingNumber + */ + protected function buildAccountNumber(Order $order): BillingNumber + { + return new BillingNumber($this->getEkp($order), $this->getProcess($order), $this->getParticipation($order)); + } + + /** + * @param Order $order + * @return BillingNumber|null + */ + public function buildReturnAccountNumber(Order $order) + { + if (!$this->getReturnProcess($order)) { + return null; + } + return new BillingNumber($this->getEkp($order), $this->getReturnProcess($order), $this->getParticipation($order)); + } + + /** + * @return \DateTime + * @throws \Exception + */ + protected function buildShipmentDate(): \DateTime + { + $wunschpaket = Registry::get(\Mediaopt\DHL\Wunschpaket::class); + return $wunschpaket->getWunschpaket()->getTransferDay(); + } + + private function buildService(Order $order): ?VAS + { + $services = new VAS(); + $initialized = false; + + $process = $this->getProcess($order); + $remark = $order->oxorder__oxremark->value; + $wunschpaket = Registry::get(\Mediaopt\DHL\Wunschpaket::class); + + if ($wunschpaket->hasWunschtag($remark) && $process->supportsPreferredDay()) { + $wunschtag = $wunschpaket->extractWunschtag($remark); + $wunschtag = date('Y-m-d', strtotime($wunschtag)); + $services->setPreferredDay(new \DateTime($wunschtag)); + $initialized = true; + } + [$type, $locationPart1, $locationPart2] = $wunschpaket->extractLocation($remark); + if ($wunschpaket->hasWunschnachbar($remark) && $process->supportsPreferredNeighbour()) { + $services->setPreferredNeighbour("$locationPart2, $locationPart1"); + $initialized = true; + } + if ($wunschpaket->hasWunschort($remark) && $process->supportsPreferredLocation()) { + $services->setPreferredLocation($locationPart1); + $initialized = true; + } + if ($process->supportsParcelOutletRouting() && (int)Registry::getConfig()->getShopConfVar('mo_dhl__filialrouting_active')) { + $altEmail = Registry::getConfig()->getShopConfVar('mo_dhl__filialrouting_alternative_email') ?: ''; + $services->setParcelOutletRouting($altEmail); + $initialized = true; + } + if ($order->moDHLUsesService(MoDHLService::MO_DHL__IDENT_CHECK) && $process->supportsIdentCheck()) { + $services->setIdentCheck($this->createIdent($order)); + $initialized = true; + } elseif ($order->moDHLUsesService(MoDHLService::MO_DHL__VISUAL_AGE_CHECK18) && $process->supportsVisualAgeCheck()) { + $services->setVisualCheckOfAge('A18'); + $initialized = true; + } elseif ($order->moDHLUsesService(MoDHLService::MO_DHL__VISUAL_AGE_CHECK16) && $process->supportsVisualAgeCheck()) { + $services->setVisualCheckOfAge('A16'); + $initialized = true; + } + if ($process->supportsBulkyGood() && $order->moDHLUsesService(MoDHLService::MO_DHL__BULKY_GOOD)) { + $services->setBulkyGoods(true); + $initialized = true; + } + if ($process->supportsCashOnDelivery() && $order->moDHLUsesService(MoDHLService::MO_DHL__CASH_ON_DELIVERY)) { + $customerReference = Registry::getLang()->translateString('GENERAL_ORDERNUM') . ' ' . $order->getFieldData('oxordernr'); + $bankAccount = new BankAccount(); + $bankAccount->setAccountHolder(Registry::getConfig()->getShopConfVar('mo_dhl__cod_accountOwner')); + $bankAccount->setBankName(Registry::getConfig()->getShopConfVar('mo_dhl__cod_bankName')); + $bankAccount->setIban(Registry::getConfig()->getShopConfVar('mo_dhl__cod_iban')); + $cashOnDelivery = new VASCashOnDelivery(); + $cashOnDelivery->setAmount($this->createValue($this->getEURPrice($order, $order->oxorder__oxtotalordersum->value))); + $cashOnDelivery->setBankAccount($bankAccount); + $cashOnDelivery->setTransferNote1($customerReference); + $services->setCashOnDelivery($cashOnDelivery); + $initialized = true; + } + $orderBrutSum = $this->getEURPrice($order, $order->oxorder__oxtotalbrutsum->value); + if ($process->supportsAdditionalInsurance() && ($order->moDHLUsesService(MoDHLService::MO_DHL__ADDITIONAL_INSURANCE) && $orderBrutSum > 500)) { + $services->setAdditionalInsurance($this->createValue($orderBrutSum)); + $initialized = true; + } + if ($process->supportsPremium() && $order->moDHLUsesService(MoDHLService::MO_DHL__PREMIUM)) { + $services->setPremium(true); + $initialized = true; + } + if ($process->supportsCDP() && $order->moDHLUsesService(MoDHLService::MO_DHL__CDP)) { + $services->setClosestDropPoint(true); + $initialized = true; + } + if ($process->supportsEndorsement()) { + $abandonment = (bool)($order->moDHLUsesService(MoDHLService::MO_DHL__ENDORSEMENT)); + $services->setEndorsement($abandonment ? 'ABANDON' : 'RETURN'); + $initialized = true; + } + if ($process->supportsPDDP() && $order->moDHLUsesService(MoDHLService::MO_DHL__PDDP)) { + $services->setPostalDeliveryDutyPaid(true); + $initialized = true; + } + if ($process->supportsNoNeighbourDelivery() && Registry::getConfig()->getShopConfVar('mo_dhl__no_neighbour_delivery_active')) { + $services->setNoNeighbourDelivery(true); + $initialized = true; + } + if ($process->supportsNamedPersonOnly() && $order->moDHLUsesService(MoDHLService::MO_DHL__NAMED_PERSON_ONLY)) { + $services->setNamedPersonOnly(true); + $initialized = true; + } + if ($process->supportsSignedForByRecipient() && $order->moDHLUsesService(MoDHLService::MO_DHL__SIGNED_FOR_BY_RECIPIENT)) { + $services->setSignedForByRecipient(true); + $initialized = true; + } + if (Registry::getConfig()->getShopConfVar('mo_dhl__beilegerretoure_active') && $this->getProcess($order)->supportsDHLRetoure() && $returnAccountNumber = $this->buildReturnAccountNumber($order)) { + $dhlRetoure = new VASDhlRetoure(); + $dhlRetoure->setBillingNumber($returnAccountNumber); + $dhlRetoure->setReturnAddress($this->buildReturnReceiver()); + $services->setDhlRetoure($dhlRetoure); + $initialized = true; + } + + return $initialized ? $services : null; + } + + /** + * @param Order $order + * @return VASIdentCheck + */ + protected function createIdent(Order $order): VASIdentCheck + { + $identCheck = new VASIdentCheck(); + $identCheck->setDateOfBirth(new \DateTime($order->getFieldData('mo_dhl_ident_check_birthday'))); + $identCheck->setFirstName($order->moDHLGetAddressData('fname')); + $identCheck->setLastName($order->moDHLGetAddressData('lname')); + $identCheck->setMinimumAge( + Registry::getConfig()->getShopConfVar('mo_dhl__ident_check_min_age') + ? 'A' . Registry::getConfig()->getShopConfVar('mo_dhl__ident_check_min_age') + : null); + if ($order->moDHLUsesService(MoDHLService::MO_DHL__VISUAL_AGE_CHECK18)) { + $identCheck->setMinimumAge('A18'); + } elseif ($order->moDHLUsesService(MoDHLService::MO_DHL__VISUAL_AGE_CHECK16) && !$identCheck->getMinimumAge()) { + $identCheck->setMinimumAge('A16'); + } + return $identCheck; + } + + /** + * @return ContactAddress + */ + protected function buildReturnReceiver(): ContactAddress + { + $config = Registry::getConfig(); + if ($config->getShopConfVar('mo_dhl__retoure_receiver_use_sender')) { + $returnReceiver = new ContactAddress(); + $returnReceiver->setName1($this->convertSpecialChars($config->getShopConfVar('mo_dhl__sender_line1'))); + if ($name2 = $this->convertSpecialChars($config->getShopConfVar('mo_dhl__sender_line2'))) { + $returnReceiver->setName2($name2); + } + if ($name3 = $this->convertSpecialChars($config->getShopConfVar('mo_dhl__sender_line3'))) { + $returnReceiver->setName3($name3); + } + $returnReceiver->setCity($this->convertSpecialChars($config->getShopConfVar('mo_dhl__sender_city'))); + $returnReceiver->setPostalCode($config->getShopConfVar('mo_dhl__sender_zip')); + $returnReceiver->setAddressStreet($this->convertSpecialChars($config->getShopConfVar('mo_dhl__sender_street'))); + $returnReceiver->setAddressHouse($config->getShopConfVar('mo_dhl__sender_street_number')); + $returnReceiver->setCountry($config->getShopConfVar('mo_dhl__sender_country')); + return $returnReceiver; + } + $returnReceiver = new ContactAddress(); + $returnReceiver->setName1($this->convertSpecialChars($config->getShopConfVar('mo_dhl__retoure_receiver_line1'))); + if ($name2 = $this->convertSpecialChars($config->getShopConfVar('mo_dhl__retoure_receiver_line2'))) { + $returnReceiver->setName2($name2); + } + if ($name3 = $this->convertSpecialChars($config->getShopConfVar('mo_dhl__retoure_receiver_line3'))) { + $returnReceiver->setName3($name3); + } + $returnReceiver->setCity($this->convertSpecialChars($config->getShopConfVar('mo_dhl__retoure_receiver_city'))); + $returnReceiver->setPostalCode($config->getShopConfVar('mo_dhl__retoure_receiver_zip')); + $returnReceiver->setAddressStreet($this->convertSpecialChars($config->getShopConfVar('mo_dhl__retoure_receiver_street'))); + $returnReceiver->setAddressHouse($config->getShopConfVar('mo_dhl__retoure_receiver_street_number')); + $returnReceiver->setCountry($config->getShopConfVar('mo_dhl__retoure_receiver_country')); + return $returnReceiver; + } + + protected function buildShipper(): Shipper + { + $config = Registry::getConfig(); + $shipper = new Shipper(); + $shipper->setName1($this->convertSpecialChars($config->getShopConfVar('mo_dhl__sender_line1'))); + if ($name2 = $this->convertSpecialChars($config->getShopConfVar('mo_dhl__sender_line2'))) { + $shipper->setName2($name2); + } + if ($name3 = $this->convertSpecialChars($config->getShopConfVar('mo_dhl__sender_line3'))) { + $shipper->setName3($name3); + } + $shipper->setCity($this->convertSpecialChars($config->getShopConfVar('mo_dhl__sender_city'))); + $shipper->setPostalCode($config->getShopConfVar('mo_dhl__sender_zip')); + $shipper->setAddressStreet($this->convertSpecialChars($config->getShopConfVar('mo_dhl__sender_street'))); + $shipper->setAddressHouse($config->getShopConfVar('mo_dhl__sender_street_number')); + $shipper->setCountry($config->getShopConfVar('mo_dhl__sender_country')); + return $shipper; + } + + /** + * @param Order $order + * @return bool + */ + protected function sendNotificationAllowed(Order $order): bool + { + if (!$this->getProcess($order)->supportsNotification()) { + return false; + } + switch (Registry::getConfig()->getShopConfVar('mo_dhl__notification_mode')) { + case MoDHLNotificationMode::NEVER: + return false; + case MoDHLNotificationMode::ALWAYS: + return true; + default: + return (bool)$order->getFieldData('MO_DHL_ALLOW_NOTIFICATION'); + } + } + + /** + * @param Order $order + */ + protected function buildExportDocument(Order $order): CustomsDetails + { + $config = Registry::getConfig(); + + $receiverLanguages = $this->getReceiverLanguages($order); + + $exportDocuments = []; + + /** @var OrderArticle $orderArticle */ + foreach ($order->getOrderArticles() as $orderArticle) { + $commodity = new Commodity(); + $commodity->setItemDescription($this->getArticleTitle($orderArticle, $receiverLanguages)); + $commodity->setPackagedQuantity($orderArticle->getFieldData('oxamount')); + $commodity->setItemValue($this->createValue($this->getEURPrice($order, $orderArticle->getPrice()->getPrice()))); + $weight = new Weight(); + $weight->setUom('kg'); + $weight->setValue($this->getArticleWeight($orderArticle, $config)); + $commodity->setItemWeight($weight); + if ($hsCode = $orderArticle->getArticle()->getFieldData(MoDHLService::MO_DHL__ZOLLTARIF)) { + $commodity->setHsCode($hsCode); + } + if ($origin = $config->getShopConfVar('mo_dhl__sender_country')) { + $commodity->setCountryOfOrigin($origin); + } + $exportDocuments[] = $commodity; + } + + $customsDetails = new CustomsDetails(); + $customsDetails->setExportType('COMMERCIAL_GOODS'); + $customsDetails->setPostalCharges($this->createValue($this->getEURPrice($order, $order->oxorder__oxdelcost->value))); + $customsDetails->setItems($exportDocuments); + $customsDetails->setOfficeOfOrigin($this->convertSpecialChars($config->getShopConfVar('mo_dhl__sender_city'))); + return $customsDetails; + + } + + /** + * @param string $isoalpha3 + * @return false|string + * @throws \OxidEsales\Eshop\Core\Exception\DatabaseConnectionException + */ + protected function getIsoalpha2FromIsoalpha3($isoalpha3) + { + return \OxidEsales\Eshop\Core\DatabaseProvider::getDb() + ->getOne('SELECT OXISOALPHA2 from oxcountry where OXISOALPHA3 = ? ', [$isoalpha3]); + } + + /** + * @param Order $order + * @param float $price + * @return float + */ + protected function getEURPrice(Order $order, float $price): float + { + if ($order->oxorder__oxcurrency->value === Currency::MO_DHL__EUR) { + return $price; + } + + return round($price / $order->oxorder__oxcurrate->value, 2); + } + + /** + * @param Order $order + * @return array + * @throws \OxidEsales\Eshop\Core\Exception\SystemComponentException + */ + protected function getReceiverLanguages(Order $order): array + { + $country = \oxNew(\OxidEsales\Eshop\Application\Model\Country::class); + $country->load($order->moDHLGetAddressData('countryid')); + $receiverCountryISO2 = $country->getFieldData('oxisoalpha2'); + + $storeLanguages = []; + foreach (Registry::getLang()->getLanguageArray() as $language) { + $storeLanguages[$language->oxid] = $language->id; + } + + if (!array_key_exists($receiverCountryISO2, CountriesLanguages::$LIST)) { + // If we have no list of languages for receiver country we will use default language + return []; + } + + $receiverLanguages = []; + foreach (CountriesLanguages::$LIST[$receiverCountryISO2] as $language) { + if (array_key_exists($language, $storeLanguages)) { + $receiverLanguages[$language] = $storeLanguages[$language]; + } + } + + // If we have a list we will use receiver languages in order from CountriesLanguages + return $receiverLanguages; + } + + /** + * @param OrderArticle $orderArticle + * @param array $receiverLanguages + * @return false|string + */ + protected function getArticleTitle(OrderArticle $orderArticle, array $receiverLanguages) + { + $articleId = $orderArticle->getArticle()->getId(); + $articleModel = oxNew(\OxidEsales\EshopCommunity\Application\Model\Article::class); + + $title = ''; + foreach ($receiverLanguages as $languageId) { + $articleModel->loadInLang($languageId, $articleId); + $title = $articleModel->getFieldData('oxtitle'); + if (!empty($title)) { + break; + } + } + $title = $title + ?? $orderArticle->getArticle()->getFieldData('oxtitle') + ?? $orderArticle->getFieldData('oxtitle'); + + return mb_substr($this->convertSpecialChars($title), 0, 50); + } + + /** + * @param string $string + * @return string + */ + public static function convertSpecialChars($string = ''): string + { + return html_entity_decode($string); + } + + + /** + * This method will return a value with EUR as currency since the currency this class receives is EUR at the moment. + * + * @param float $amount + * @param string|null $currency + * @return Value + */ + protected function createValue(float $amount, ?string $currency = null): Value + { + $value = new Value(); + $value->setValue($amount); + $value->setCurrency($currency ?: 'EUR'); + return $value; + } + + public function buildQueryParameters(): array + { + return [ + 'includeDocs' => 'URL', + 'combine' => false, + 'mustEncode' => (bool) Registry::getConfig()->getShopConfVar('mo_dhl__only_with_leitcode'), + ]; + } +} diff --git a/src/modules/mo/mo_dhl/Application/Controller/Admin/ModuleConfiguration.php b/src/modules/mo/mo_dhl/Application/Controller/Admin/ModuleConfiguration.php index c351b6c..d8fbbc3 100644 --- a/src/modules/mo/mo_dhl/Application/Controller/Admin/ModuleConfiguration.php +++ b/src/modules/mo/mo_dhl/Application/Controller/Admin/ModuleConfiguration.php @@ -9,25 +9,17 @@ */ use Mediaopt\DHL\Adapter\DHLAdapter; -use Mediaopt\DHL\Adapter\ParcelShippingConverter; -use Mediaopt\DHL\Api\GKV\CountryType; -use Mediaopt\DHL\Api\GKV\NameType; -use Mediaopt\DHL\Api\GKV\CommunicationType; -use Mediaopt\DHL\Api\GKV\NativeAddressTypeNew; -use Mediaopt\DHL\Api\GKV\ReceiverNativeAddressType; -use Mediaopt\DHL\Api\GKV\ReceiverType; -use Mediaopt\DHL\Api\GKV\Shipment; -use Mediaopt\DHL\Api\GKV\ShipmentDetailsTypeType; -use Mediaopt\DHL\Api\GKV\ShipmentItemType; -use Mediaopt\DHL\Api\GKV\ShipperType; -use Mediaopt\DHL\Api\GKV\ValidateShipmentOrderRequest; -use Mediaopt\DHL\Api\GKV\ValidateShipmentOrderType; -use Mediaopt\DHL\Api\GKV\Version; +use Mediaopt\DHL\Adapter\ParcelShippingRequestBuilder; use Mediaopt\DHL\Api\Internetmarke; use Mediaopt\DHL\Api\MyAccount\Model\Detail; use Mediaopt\DHL\Api\ParcelShipping\Client; +use Mediaopt\DHL\Api\ParcelShipping\Model\ShipmentDetails; +use Mediaopt\DHL\Api\ParcelShipping\Model\ShipmentOrderRequest; +use Mediaopt\DHL\Api\ParcelShipping\Model\Shipper; +use Mediaopt\DHL\Api\ParcelShipping\Model\Weight; use Mediaopt\DHL\Application\Model\DeliverySetList; use Mediaopt\DHL\Controller\Admin\ErrorDisplayTrait; +use Mediaopt\DHL\Export\CsvExporter; use Mediaopt\DHL\Merchant\Ekp; use Mediaopt\DHL\Shipment\BillingNumber; use Mediaopt\DHL\Shipment\Participation; @@ -395,20 +387,18 @@ private function checkShippingAPIs(Client $parcelShipping, $deliveryset) if ($process->usesInternetMarke()) { return; } - $shipment = $this->createTestShipment($deliveryset); - $shipmentOrder = new ValidateShipmentOrderType('123456', $shipment); - $request = new ValidateShipmentOrderRequest(new Version(3, 4, 0), $shipmentOrder); + $shipmentOrderRequest = new ShipmentOrderRequest(); + $shipmentOrderRequest->setShipments([$this->createTestShipment($deliveryset)]); + $shipmentOrderRequest->setProfile(ParcelShippingRequestBuilder::STANDARD_GRUPPENPROFIL); - $converter = Registry::get(ParcelShippingConverter::class); - [$query, $request] = $converter->convertValidateShipmentOrderRequest($request); - $response = $parcelShipping->createOrders($request, $query, [], Client::FETCH_RESPONSE); + $response = $parcelShipping->createOrders($shipmentOrderRequest, ['validate' => true], [], Client::FETCH_RESPONSE); if ($response->getStatusCode() < 200 || $response->getStatusCode() >= 300) { $payload = json_decode($response->getBody()->getContents(), true); if ($payload['status'] == 401) { Registry::get(UtilsView::class)->addErrorToDisplay('MO_DHL__LOGIN_FAILED'); return; } - foreach ($converter->extractErrorsFromResponsePayload($payload) as $error) { + foreach ($this->extractErrorsFromResponsePayload($payload) as $error) { Registry::get(UtilsView::class)->addErrorToDisplay($error); } return; @@ -423,24 +413,42 @@ private function checkShippingAPIs(Client $parcelShipping, $deliveryset) /** * @param DeliverySet $deliveryset - * @return Shipment + * @return \Mediaopt\DHL\Api\ParcelShipping\Model\Shipment */ - protected function createTestShipment($deliveryset): Shipment + protected function createTestShipment($deliveryset): \Mediaopt\DHL\Api\ParcelShipping\Model\Shipment { $process = Process::build($deliveryset->oxdeliveryset__mo_dhl_process->value); - $receiverCountryCode = $process->isInternational() ? 'FR' : 'DE'; - $ShipmentDetails = new ShipmentDetailsTypeType($process->getServiceIdentifier(), new BillingNumber(Ekp::build($this->getEkp()), $process, Participation::build($deliveryset->oxdeliveryset__mo_dhl_participation->value)), (new \DateTime())->format('Y-m-d'), new ShipmentItemType(0.5)); - $Receiver = (new ReceiverType('a b'))->setAddress(new ReceiverNativeAddressType(null, null, 'Elbestr.', '28/29', '12045', 'Berlin', null, new CountryType($receiverCountryCode)))->setCommunication($this->createTestCommunication()); - $Shipper = (new ShipperType(new NameType('a b', null, null), new NativeAddressTypeNew('Elbestr.', '28', '12045', 'Berlin', new CountryType('DE')))); - $shipment = new Shipment($ShipmentDetails, $Shipper, $Receiver); + $receiverCountryCode = $process->isInternational() ? 'FRA' : 'DEU'; + + $shipment = new \Mediaopt\DHL\Api\ParcelShipping\Model\Shipment(); + $shipper = (new Shipper()) + ->setName1('a b') + ->setCity('Berlin') + ->setPostalCode('12045') + ->setAddressStreet('Elbestr.') + ->setAddressHouse('28/29') + ->setCountry('DEU'); + $shipment->setShipper($shipper); + $shipment->setConsignee([ + 'name1' => 'a b', + 'contactName' => 'a b', + 'city' => 'Berlin', + 'postalCode' => '12045', + 'addressStreet' => 'Elbestr.', + 'addressHouse' => '28/29', + 'country' => $receiverCountryCode, + ]); + $shipmentDetails = new ShipmentDetails(); + $weight = new Weight(); + $weight->setUom('kg'); + $weight->setValue('0.5'); + $shipmentDetails->setWeight($weight); + $shipment->setDetails($shipmentDetails); + $shipment->setCreationSoftware(CsvExporter::CREATOR_TAG); + $shipment->setBillingNumber(new BillingNumber(Ekp::build($this->getEkp()), $process, Participation::build($deliveryset->oxdeliveryset__mo_dhl_participation->value))); + $shipment->setProduct($process->getServiceIdentifier()); + $shipment->setRefNo('12345678'); + $shipment->setShipDate((new \DateTime())); return $shipment; } - - /** - * @return CommunicationType - */ - protected function createTestCommunication() - { - return (new CommunicationType())->setContactPerson('a b'); - } } diff --git a/src/modules/mo/mo_dhl/Cli/CreateLabels.php b/src/modules/mo/mo_dhl/Cli/CreateLabels.php index 82500c1..d2cb574 100644 --- a/src/modules/mo/mo_dhl/Cli/CreateLabels.php +++ b/src/modules/mo/mo_dhl/Cli/CreateLabels.php @@ -9,11 +9,10 @@ use Mediaopt\DHL\Adapter\DHLAdapter; -use Mediaopt\DHL\Adapter\GKVCreateShipmentOrderRequestBuilder; -use Mediaopt\DHL\Adapter\ParcelShippingConverter; -use Mediaopt\DHL\Api\GKV\CreateShipmentOrderRequest; +use Mediaopt\DHL\Adapter\ParcelShippingRequestBuilder; use Mediaopt\DHL\Api\ParcelShipping\Client; use Mediaopt\DHL\Application\Model\Order; +use Mediaopt\DHL\Controller\Admin\ErrorDisplayTrait; use Mediaopt\DHL\Model\MoDHLLabel; use OxidEsales\Eshop\Core\DatabaseProvider; use OxidEsales\Eshop\Core\Registry; @@ -28,6 +27,8 @@ class CreateLabels extends Command { + use ErrorDisplayTrait; + /** * @var OutputInterface */ @@ -58,37 +59,41 @@ protected function configure() */ protected function execute(InputInterface $input, OutputInterface $output) { - $this->output = $output; - foreach ($input->getOption('status') as $status) { - if (!in_array($status, $this->getOrderStatus())) { - $this->output->writeln($this->translate('%s is not an allowed order status status. Please use one of %s', [$status, implode(', ', $this->getOrderStatus())])); - return; + try { + $this->output = $output; + foreach ($input->getOption('status') as $status) { + if (!in_array($status, $this->getOrderStatus())) { + $this->output->writeln($this->translate('%s is not an allowed order status status. Please use one of %s', [$status, implode(', ', $this->getOrderStatus())])); + return self::FAILURE; + } } + if (!$orderIds = $this->getOrderIds($input->getOption('paid'), $input->getOption('status'))) { + return self::SUCCESS; + } + $request = Registry::get(ParcelShippingRequestBuilder::class)->build($orderIds); + + $this->createWithParcelShipping($orderIds, $request); + } catch (\Exception $e) { + $this->output->writeln($e->getMessage()); + return self::FAILURE; } - if (!$orderIds = $this->getOrderIds($input->getOption('paid'), $input->getOption('status'))) { - return; - } - $request = Registry::get(GKVCreateShipmentOrderRequestBuilder::class)->build($orderIds); - $this->createWithParcelShipping($request); + return self::SUCCESS; } - /** - * @param CreateShipmentOrderRequest $request - * @throws \Exception - */ - protected function createWithParcelShipping(CreateShipmentOrderRequest $request) + protected function createWithParcelShipping(array $orderIds, array $request) { - [$query, $request] = Registry::get(ParcelShippingConverter::class)->convertCreateShipmentOrderRequest($request); + [$query, $request] = $request; $response = Registry::get(DHLAdapter::class)->buildParcelShipping()->createOrders($request, $query, [], Client::FETCH_RESPONSE); $payload = \json_decode($response->getBody(), true); $createdLabels = 0; - foreach ($payload['items'] as $item) { + foreach ($payload['items'] as $index => $item) { $statusInformation = $item['sstatus']; $order = \oxNew(Order::class); - $order->load($item['shipmentRefNo']); + $order->load($orderIds[$index]); $order->storeCreationStatus($statusInformation['title']); - if ($detail = $statusInformation['detail']) { - $this->output->writeln($this->translate('MO_DHL__BATCH_ERROR_CREATION_ERROR', [$order->getFieldData('oxordernr'), $detail])); + if ($item['sstatus']['statusCode'] < 200 || $item['sstatus']['statusCode'] >= 300) { + $errors = $this->extractErrorsFromResponsePayload($payload, $index); + $this->output->writeln($this->translate('MO_DHL__BATCH_ERROR_CREATION_ERROR', [$order->getFieldData('oxordernr'), implode("\n", $errors)])); continue; } $label = MoDHLLabel::fromOrderAndParcelShippingResponseItem($order, $item); diff --git a/src/modules/mo/mo_dhl/Controller/Admin/ErrorDisplayTrait.php b/src/modules/mo/mo_dhl/Controller/Admin/ErrorDisplayTrait.php index c8f561f..2d6979d 100644 --- a/src/modules/mo/mo_dhl/Controller/Admin/ErrorDisplayTrait.php +++ b/src/modules/mo/mo_dhl/Controller/Admin/ErrorDisplayTrait.php @@ -33,4 +33,31 @@ protected function displayErrors($errors) } } } + + + /** + * @param array $payload + * @param int|false $index if specified only errors for the given index will be returned + * @return string[] + */ + public function extractErrorsFromResponsePayload(array $payload, $index = false): array + { + $errors = []; + $items = $index !== false ? [$payload['items'][$index]] : $payload['items']; + foreach ($items as $error) { + if (\array_key_exists('validationMessages', $error)) { + foreach ($error['validationMessages'] as $validationMessage) { + $errors[] = "{$validationMessage['validationMessage']} ({$validationMessage['property']})"; + } + continue; + } + if (\array_key_exists('message', $error)) { + $errors[] = "{$error['message']} ({$error['propertyPath']})"; + } + } + if ($errors !== []) { + return $errors; + } + return \array_key_exists('detail', $payload) && $index === false ? [$payload['detail']] : []; + } } \ No newline at end of file diff --git a/src/modules/mo/mo_dhl/Controller/Admin/OrderBatchController.php b/src/modules/mo/mo_dhl/Controller/Admin/OrderBatchController.php index 0d012c4..d7fe235 100644 --- a/src/modules/mo/mo_dhl/Controller/Admin/OrderBatchController.php +++ b/src/modules/mo/mo_dhl/Controller/Admin/OrderBatchController.php @@ -9,8 +9,7 @@ */ use Mediaopt\DHL\Adapter\DHLAdapter; -use Mediaopt\DHL\Adapter\GKVCreateShipmentOrderRequestBuilder; -use Mediaopt\DHL\Adapter\ParcelShippingConverter; +use Mediaopt\DHL\Adapter\ParcelShippingRequestBuilder; use Mediaopt\DHL\Api\ParcelShipping\Client; use Mediaopt\DHL\Application\Model\Order; use Mediaopt\DHL\Export\CsvExporter; @@ -222,8 +221,7 @@ public function createRetoureLabels() */ protected function callCreation(array $orderIds) { - $request = Registry::get(GKVCreateShipmentOrderRequestBuilder::class)->build($orderIds); - [$query, $shipmentOrderRequest] = Registry::get(ParcelShippingConverter::class)->convertCreateShipmentOrderRequest($request); + [$query, $shipmentOrderRequest] = Registry::get(ParcelShippingRequestBuilder::class)->build($orderIds); $response = Registry::get(DHLAdapter::class) ->buildParcelShipping() ->createOrders($shipmentOrderRequest, $query, [], Client::FETCH_RESPONSE); @@ -238,7 +236,7 @@ protected function handleCreationResponse(array $orderIds, ResponseInterface $re { $payload = \json_decode($response->getBody(), true); foreach ($payload['items'] as $index => $item) { - $errors = Registry::get(ParcelShippingConverter::class)->extractErrorsFromResponsePayload($payload, $index); + $errors = $this->extractErrorsFromResponsePayload($payload, $index); $order = \oxNew(Order::class); $order->load($orderIds[$index]); $order->storeCreationStatus($item['sstatus']['title']); @@ -246,10 +244,11 @@ protected function handleCreationResponse(array $orderIds, ResponseInterface $re $message = Registry::getLang()->translateString('MO_DHL__BATCH_ERROR_CREATION_ERROR'); $message = sprintf($message, $order->getFieldData('oxordernr'), implode(' ', $errors)); Registry::get(\OxidEsales\Eshop\Core\UtilsView::class)->addErrorToDisplay($message); - continue; } - $label = MoDHLLabel::fromOrderAndParcelShippingResponseItem($order, $item); - $label->save(); + if ($item['sstatus']['statusCode'] >= 200 && $item['sstatus']['statusCode'] < 300) { + $label = MoDHLLabel::fromOrderAndParcelShippingResponseItem($order, $item); + $label->save(); + } } } diff --git a/src/modules/mo/mo_dhl/Controller/Admin/OrderDHLController.php b/src/modules/mo/mo_dhl/Controller/Admin/OrderDHLController.php index e274e2e..8fbccc6 100755 --- a/src/modules/mo/mo_dhl/Controller/Admin/OrderDHLController.php +++ b/src/modules/mo/mo_dhl/Controller/Admin/OrderDHLController.php @@ -4,12 +4,10 @@ use GuzzleHttp\Exception\ClientException; use Mediaopt\DHL\Adapter\DHLAdapter; -use Mediaopt\DHL\Adapter\GKVCreateShipmentOrderRequestBuilder; use Mediaopt\DHL\Adapter\GKVCustomShipmentBuilder; use Mediaopt\DHL\Adapter\InternetmarkeRefundRetoureVouchersRequestBuilder; use Mediaopt\DHL\Adapter\InternetmarkeShoppingCartPDFRequestBuilder; -use Mediaopt\DHL\Adapter\ParcelShippingConverter; -use Mediaopt\DHL\Api\GKV\CreateShipmentOrderRequest; +use Mediaopt\DHL\Adapter\ParcelShippingRequestBuilder; use Mediaopt\DHL\Api\Internetmarke\ShoppingCartResponseType; use Mediaopt\DHL\Api\ParcelShipping\Client; use Mediaopt\DHL\Api\Wunschpaket; @@ -447,7 +445,7 @@ protected function handleInternetmarkeCreationResponse(ShoppingCartResponseType protected function handleParcelShippingPostResponse(ResponseInterface $response): void { $payload = \json_decode($response->getBody(), true); - $errors = Registry::get(ParcelShippingConverter::class)->extractErrorsFromResponsePayload($payload); + $errors = $this->extractErrorsFromResponsePayload($payload); if ($response->getStatusCode() >= 200 && $response->getStatusCode() < 300) { $this->getOrder()->storeCreationStatus($payload['status']['title']); $label = MoDHLLabel::fromOrderAndParcelShippingResponseItem($this->getOrder(), $payload['items'][0]); @@ -462,13 +460,13 @@ protected function handleParcelShippingPostResponse(ResponseInterface $response) } /** - * @return CreateShipmentOrderRequest + * @return array * @throws \OxidEsales\Eshop\Core\Exception\DatabaseConnectionException * @throws \OxidEsales\Eshop\Core\Exception\SystemComponentException */ - protected function buildShipmentOrderRequest(): CreateShipmentOrderRequest + protected function buildShipmentOrderRequest(): array { - return Registry::get(GKVCreateShipmentOrderRequestBuilder::class)->build([$this->getOrder()->getId()]); + return Registry::get(ParcelShippingRequestBuilder::class)->build([$this->getOrder()->getId()]); } /** @@ -516,13 +514,13 @@ protected function parseInternetmarkeException(\Exception $e): array } /** - * @param CreateShipmentOrderRequest $shipmentOrderRequest + * @param array $shipmentOrderRequest * @return void * @throws \Exception */ - protected function createShipmentOrderWithParcelShipping(CreateShipmentOrderRequest $shipmentOrderRequest): void + protected function createShipmentOrderWithParcelShipping(array $shipmentOrderRequest): void { - [$query, $shipmentOrderRequest] = Registry::get(ParcelShippingConverter::class)->convertCreateShipmentOrderRequest($shipmentOrderRequest); + [$query, $shipmentOrderRequest] = $shipmentOrderRequest; $response = Registry::get(DHLAdapter::class) ->buildParcelShipping() ->createOrders($shipmentOrderRequest, $query, [], Client::FETCH_RESPONSE); @@ -537,7 +535,7 @@ protected function deleteShipmentWithParcelShipping(MoDHLLabel $label) $label->getFieldData('shipmentNumber'); $response = Registry::get(DHLAdapter::class) ->buildParcelShipping() - ->ordersAccountDelete(['profile' => GKVCreateShipmentOrderRequestBuilder::STANDARD_GRUPPENPROFIL, 'shipment' => $label->getFieldData('shipmentNumber')], [], Client::FETCH_RESPONSE); + ->ordersAccountDelete(['profile' => ParcelShippingRequestBuilder::STANDARD_GRUPPENPROFIL, 'shipment' => $label->getFieldData('shipmentNumber')], [], Client::FETCH_RESPONSE); if ($response->getStatusCode() >= 200 && $response->getStatusCode() < 300) { $label->delete(); return;