From ae594d0896fac0d5fd2d6a0bbccc0bb685c03206 Mon Sep 17 00:00:00 2001 From: antu chaudhary Date: Wed, 17 Apr 2024 16:36:03 +0530 Subject: [PATCH] Added the further changes according to the code standard --- .../Webkul/UpsShipping/src/Carriers/Ups.php | 46 +-- .../src/Helpers/ShippingMethodHelper.php | 292 +++++++++--------- .../src/Repositories/UpsRepository.php | 43 ++- .../views/configurations/field-type.blade.php | 1 - 4 files changed, 194 insertions(+), 188 deletions(-) diff --git a/packages/Webkul/UpsShipping/src/Carriers/Ups.php b/packages/Webkul/UpsShipping/src/Carriers/Ups.php index d60bf78..279bda4 100644 --- a/packages/Webkul/UpsShipping/src/Carriers/Ups.php +++ b/packages/Webkul/UpsShipping/src/Carriers/Ups.php @@ -27,28 +27,30 @@ public function calculate() return false; } - $shippingMethods = []; + $shippingRates = []; $cart = Cart::getCart(); $address = $cart->shipping_address; - $data = app('Webkul\UpsShipping\Helpers\ShippingMethodHelper')->getAllCartProducts($address); + $shippingMethodHelper = app(ShippingMethodHelper::class); + + $cartProductsShippingData = $shippingMethodHelper->getAllCartProducts($address); - if (! $data) { + if (! $cartProductsShippingData) { return false; } - foreach ($data as $key => $fedexServices) { + foreach ($cartProductsShippingData as $sellerId => $shippingMethods) { $totalShippingCost = 0; + + $sellerRates = []; - $rates = []; - - foreach ($fedexServices as $methods => $upsRate) { - $itemShippingCost = $upsRate['rate'] * $upsRate['itemQuantity']; - $sellerId = $upsRate['marketplace_seller_id']; + foreach ($shippingMethods as $methodCode => $methodData) { + $itemShippingCost = $methodData['rate'] * $methodData['itemQuantity']; + $marketplaceSellerId = $methodData['marketplace_seller_id']; - $rates[$sellerId] = [ + $sellerRates[$marketplaceSellerId] = [ 'amount' => core()->convertPrice($itemShippingCost), 'base_amount' => $itemShippingCost, ]; @@ -56,30 +58,32 @@ public function calculate() $totalShippingCost += $itemShippingCost; } - $object = new CartShippingRate; + $cartShippingRate = new CartShippingRate; - $object->carrier = 'mpups'; + $cartShippingRate->carrier = 'mpups'; - $object->carrier_title = $this->getConfigData('title'); + $cartShippingRate->carrier_title = $this->getConfigData('title'); - $object->method = 'mpups_' . $key; + $cartShippingRate->method = 'mpups_' . $sellerId; - $object->method_title = $this->getConfigData('title'); + $cartShippingRate->method_title = $this->getConfigData('title'); - $object->method_description = $key; + $cartShippingRate->method_description = $sellerId; - $object->price = core()->convertPrice($totalShippingCost); + $cartShippingRate->price = core()->convertPrice($totalShippingCost); - $object->base_price = $totalShippingCost; + $cartShippingRate->base_price = $totalShippingCost; - $shippingMethods[] = $object; + $shippingRates[] = $cartShippingRate; + // Store rates in session $marketplaceShippingRates = session()->get('marketplace_shipping_rates', []); - $marketplaceShippingRates['mpupsshipping'][$key] = $rates; + $marketplaceShippingRates['mpupsshipping'][$sellerId] = $sellerRates; + session()->put('marketplace_shipping_rates', $marketplaceShippingRates); } - return $shippingMethods; + return $shippingRates; } } \ No newline at end of file diff --git a/packages/Webkul/UpsShipping/src/Helpers/ShippingMethodHelper.php b/packages/Webkul/UpsShipping/src/Helpers/ShippingMethodHelper.php index f329c10..d4bfe39 100644 --- a/packages/Webkul/UpsShipping/src/Helpers/ShippingMethodHelper.php +++ b/packages/Webkul/UpsShipping/src/Helpers/ShippingMethodHelper.php @@ -28,136 +28,136 @@ public function __construct( } /** - * display methods + * Get shipping methods for all products in the cart. * - * @return array - */ + * @param object $address + * @return array|false + */ public function getAllCartProducts($address) { - $data = $this->_createSoapClient($address); - - return $data; + return $this->getShippingRates($address); } /** - * Soap client for wsdl + * Retrieve shipping rates via SOAP client. * - * @param string $wsdl - * @param bool|int $trace - * @return \SoapClient + * @param object $address + * @return array|false */ - protected function _createSoapClient($address) + protected function getShippingRates($address) { if (! core()->getConfigData('sales.carriers.ups.ups_active')) { return false; } $cart = Cart::getCart(); - + $defaultChannel = core()->getCurrentChannelCode(); $adminData = $this->channel->findByField('code', $defaultChannel)->first(); $adminName = $adminData->name; - + $adminCompany = $adminData->hostname; - + $sellerAdminData = $this->upsRepository->getSellerAdminData($cart->items()->get(), 'ups_postcode'); $sellerAdminServices = $allServices = []; - + foreach ($sellerAdminData as $cartProduct) { $sellerAdminServices[0] = explode(",", core()->getConfigData('sales.carriers.ups.services')); } foreach ($sellerAdminData as $cartProduct) { - $weight = $this->getWeight($cartProduct->weight); - + $weight = $this->convertWeightToLbs($cartProduct->weight); $countryId = core()->getConfigData('sales.shipping.origin.country'); - + if (! empty($cartProduct->marketplace_seller_id)) { - //if admin's product $zoneInformation = core()->getConfigData('sales.shipping.origin.state'); $address1 = core()->getConfigData('sales.shipping.origin.address1'); $city = core()->getConfigData('sales.shipping.origin.city'); } - - // Get The User Credentials + $accessKey = core()->getConfigData('sales.carriers.ups.access_license_key'); $userId = core()->getConfigData('sales.carriers.ups.user_id'); $password = core()->getConfigData('sales.carriers.ups.password'); $shipperNumber = core()->getConfigData('sales.carriers.ups.shipper_number'); $shipperNumber = $shipperNumber ?? ''; - - // create a simple xml object for AccessRequest & RateRequest - $accessRequesttXML = new \SimpleXMLElement ( "" ); - $rateRequestXML = new \SimpleXMLElement ( "" ); - - // create AccessRequest XML - $accessRequesttXML->addChild ( "AccessLicenseNumber", $accessKey ); - $accessRequesttXML->addChild ( "UserId", $userId ); - $accessRequesttXML->addChild ( "Password", $password ); - - // create RateRequest XML - $request = $rateRequestXML->addChild ( 'Request' ); - $request->addChild ( "RequestAction", "Rate" ); - $request->addChild ( "RequestOption", "Shop" ); - - $shipment = $rateRequestXML->addChild ( 'Shipment' ); - $shipper = $shipment->addChild ( 'Shipper' ); - - if (! empty($cartProduct->marketplace_seller_id)) { - $shipper->addChild ( "Name", $adminName ); - $shipper->addChild ( "ShipperNumber", $shipperNumber ); - - $shipperddress = $shipper->addChild ( 'Address' ); - $shipperddress->addChild ( "AddressLine1", $address1 ? $address1 : '' ); - $shipperddress->addChild ( "City", $city ? $city : '' ); - $shipperddress->addChild ( "PostalCode", core()->getConfigData('sales.shipping.origin.zipcode') ); - $shipperddress->addChild ( "CountryCode", $countryId ); - - $shipFrom = $shipment->addChild ( 'ShipFrom' ); - $shipFrom->addChild ( "CompanyName", $adminCompany ); - $shipFromAddress = $shipFrom->addChild ( 'Address' ); - $shipFromAddress->addChild ( "AddressLine1", $address1 ? $address1 : '' ); - $shipFromAddress->addChild ( "City", $city ? $city : '' ); - $shipFromAddress->addChild ( "StateProvinceCode", $zoneInformation ); - $shipFromAddress->addChild ( "PostalCode", core()->getConfigData('sales.shipping.origin.zipcode') ); - $shipFromAddress->addChild ( "CountryCode", $countryId ); + + // Build XML request for SOAP + $accessRequestXML = new \SimpleXMLElement(""); + $rateRequestXML = new \SimpleXMLElement(""); + + // Build AccessRequest XML + $accessRequestXML->addChild("AccessLicenseNumber", $accessKey); + $accessRequestXML->addChild("UserId", $userId); + $accessRequestXML->addChild("Password", $password); + + // Build RateRequest XML + $request = $rateRequestXML->addChild('Request'); + $request->addChild("RequestAction", "Rate"); + $request->addChild("RequestOption", "Shop"); + + // Build Shipper section + $shipment = $rateRequestXML->addChild('Shipment'); + $shipper = $shipment->addChild('Shipper'); + + // Shipper details + if (!empty($cartProduct->marketplace_seller_id)) { + $shipper->addChild("Name", $adminName); + $shipper->addChild("ShipperNumber", $shipperNumber); + + $shipperAddress = $shipper->addChild('Address'); + $shipperAddress->addChild("AddressLine1", $address1 ? $address1 : ''); + $shipperAddress->addChild("City", $city ? $city : ''); + $shipperAddress->addChild("PostalCode", core()->getConfigData('sales.shipping.origin.zipcode')); + $shipperAddress->addChild("CountryCode", $countryId); + + $shipFrom = $shipment->addChild('ShipFrom'); + $shipFrom->addChild("CompanyName", $adminCompany); + + $shipFromAddress = $shipFrom->addChild('Address'); + $shipFromAddress->addChild("AddressLine1", $address1 ? $address1 : ''); + $shipFromAddress->addChild("City", $city ? $city : ''); + $shipFromAddress->addChild("StateProvinceCode", $zoneInformation); + $shipFromAddress->addChild("PostalCode", core()->getConfigData('sales.shipping.origin.zipcode')); + $shipFromAddress->addChild("CountryCode", $countryId); } - $shipTo = $shipment->addChild ( 'ShipTo' ); - $shipTo->addChild ( "CompanyName", $address->first_name . ' ' . $address->last_name ); - - $shipToAddress = $shipTo->addChild ( 'Address' ); - $shipToAddress->addChild ( "AddressLine1", $address->address1 ); - $shipToAddress->addChild ( "City", $address->city ); - + // ShipTo details + $shipTo = $shipment->addChild('ShipTo'); + $shipTo->addChild("CompanyName", $address->first_name . ' ' . $address->last_name); + + $shipToAddress = $shipTo->addChild('Address'); + $shipToAddress->addChild("AddressLine1", $address->address1); + $shipToAddress->addChild("City", $address->city); + if ($address->country == 'PR') { - $shipToAddress->addChild ( "PostalCode", '00'. $address->postcode ); + $shipToAddress->addChild("PostalCode", '00' . $address->postcode); } else { - $shipToAddress->addChild ( "PostalCode", $address->postcode ); + $shipToAddress->addChild("PostalCode", $address->postcode); } - - $shipToAddress->addChild ( "CountryCode", $address->country ); - $package = $shipment->addChild ( 'Package' ); - $packageType = $package->addChild ( 'PackagingType' ); - $packageType->addChild ( "Code", core()->getConfigData('sales.carriers.ups.container') ); - - $packageWeight = $package->addChild ( 'PackageWeight' ); - $unitOfMeasurement = $packageWeight->addChild ( 'UnitOfMeasurement' ); - $unitOfMeasurement->addChild ( "Code", "LBS" ); - $packageWeight->addChild ( "Weight", $weight ); - - $requestXML = $accessRequesttXML->asXML () . $rateRequestXML->asXML (); - + $shipToAddress->addChild("CountryCode", $address->country); + + // Package details + $package = $shipment->addChild('Package'); + $packageType = $package->addChild('PackagingType'); + $packageType->addChild("Code", core()->getConfigData('sales.carriers.ups.container')); + + $packageWeight = $package->addChild('PackageWeight'); + $unitOfMeasurement = $packageWeight->addChild('UnitOfMeasurement'); + $unitOfMeasurement->addChild("Code", "LBS"); + $packageWeight->addChild("Weight", $weight); + + $requestXML = $accessRequestXML->asXML() . $rateRequestXML->asXML(); + try { $url = 'https://onlinetools.ups.com/ups.app/xml/Rate'; - + $ch = curl_init(); - curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY); curl_setopt($ch, CURLOPT_TIMEOUT, 30); curl_setopt($ch, CURLOPT_POST, true); @@ -168,38 +168,39 @@ protected function _createSoapClient($address) "Cache-Control: no-cache", "Pragma: no-cache", )); - curl_setopt($ch, CURLOPT_POSTFIELDS,$requestXML); - + curl_setopt($ch, CURLOPT_POSTFIELDS, $requestXML); + $response = curl_exec($ch); curl_close($ch); - - $upsServiceArray = simplexml_load_string($response); - $upsServices = json_decode(json_encode($upsServiceArray)); + $upsServiceArray = simplexml_load_string($response); + $upsServices = json_decode(json_encode($upsServiceArray)); + $sellerId = 0; if (! empty($cartProduct->marketplace_seller_id)) { $sellerId = $cartProduct->marketplace_seller_id; } if ($response - && isset($upsServices->Response->ResponseStatusDescription) + && isset($upsServices->Response->ResponseStatusDescription) && $upsServices->Response->ResponseStatusDescription == 'Success' ) { + if (isset($upsServices->RatedShipment)) { - foreach ($upsServices->RatedShipment as $services) { - $serviceCode = $services->Service->Code; + foreach ($upsServices->RatedShipment as $service) { + $serviceCode = $service->Service->Code; $matchResult = $this->upsRepository->validateAllowedMethods($serviceCode, $sellerAdminServices); $serviceName = $this->getServiceName($serviceCode); if ($matchResult) { $cartProductServices[$serviceName] = [ 'classId' => $serviceCode, - 'rate' => $services->RatedPackage->TotalCharges->MonetaryValue, - 'currency' => $services->RatedPackage->TotalCharges->CurrencyCode, - 'weight' => $services->BillingWeight->Weight, - 'weightUnit' => $services->BillingWeight->UnitOfMeasurement->Code, + 'rate' => $service->RatedPackage->TotalCharges->MonetaryValue, + 'currency' => $service->RatedPackage->TotalCharges->CurrencyCode, + 'weight' => $service->BillingWeight->Weight, + 'weightUnit' => $service->BillingWeight->UnitOfMeasurement->Code, 'marketplace_seller_id' => $sellerId, 'itemQuantity' => $cartProduct->quantity, ]; @@ -212,7 +213,7 @@ protected function _createSoapClient($address) } } else { $errorLog = $this->getErrorLog($upsServices); - + return false; //to check the error generated in the method; } @@ -221,7 +222,7 @@ protected function _createSoapClient($address) } } - if (! empty($allServices) ) { + if (! empty($allServices)) { return $this->upsRepository->getCommonMethods($allServices); } else { return false; @@ -229,75 +230,40 @@ protected function _createSoapClient($address) } /** - * Map service code - * - * @param $serviceCode - */ - protected function getServiceName($serviceCode) - { - $mapServices = [ - '01' => 'Next Day Air', - '02' => '2nd Day Air', - '03' => 'Ups Ground', - '07' => 'Ups Worldwide Express', - '08' => 'Ups Worldwide Expedited', - '11' => 'Standard', - '12' => '3 Day Select', - '13' => 'Next Day Air Saver', - '14' => 'Next Day Air Early A.M.', - '54' => 'Ups Worldwide Express Plus', - '59' => '2nd Day Air A.M.', - '65' => 'UPS World Wide Saver', - '82' => 'Today Standard', - '83' => 'Today Dedicated Courier', - '84' => 'Today Intercity', - '85' => 'Today Express', - '86' => 'Today Express Saver', - '03' => 'Ups Ground', - ]; - - foreach ($mapServices as $key => $service) { - if ($key == $serviceCode) { - return $service; - } - } - - return $serviceCode; - } - - /** - * convert current weight unit to LBS + * Convert weight to LBS if necessary. * * @param string $weight - **/ - public function getWeight($weight) + * @return float + */ + public function convertWeightToLbs($weight) { $coreWeightUnit = strtoupper(core()->getConfigData('general.general.locale_options.weight_unit')); - + $upsWeightUnit = strtoupper(core()->getConfigData('sales.carriers.ups.weight_unit')); - + $convertedWeight = ''; if ($coreWeightUnit == 'LBS') { if ($upsWeightUnit == 'LBS') { $convertedWeight = $weight; } else { - //kgs to lbs - $convertedWeight = $weight/0.45359237; + // Convert kgs to lbs + $convertedWeight = $weight / 0.45359237; } } else { - $convertedWeight = $weight/0.45359237; + $convertedWeight = $weight / 0.45359237; } return $convertedWeight; } /** - * Get The Current Error + * Log the error. * - * @param string $error - **/ - public function getErrorLog($errors) + * @param object $errors + * @return bool + */ + public function getErrorLog($errors) { $exception = []; @@ -322,4 +288,42 @@ public function getErrorLog($errors) return true; } + + /** + * Map service code to service name. + * + * @param string $serviceCode + * @return string + */ + protected function getServiceName($serviceCode) + { + $mapServices = [ + '01' => 'Next Day Air', + '02' => '2nd Day Air', + '03' => 'Ups Ground', + '07' => 'Ups Worldwide Express', + '08' => 'Ups Worldwide Expedited', + '11' => 'Standard', + '12' => '3 Day Select', + '13' => 'Next Day Air Saver', + '14' => 'Next Day Air Early A.M.', + '54' => 'Ups Worldwide Express Plus', + '59' => '2nd Day Air A.M.', + '65' => 'UPS World Wide Saver', + '82' => 'Today Standard', + '83' => 'Today Dedicated Courier', + '84' => 'Today Intercity', + '85' => 'Today Express', + '86' => 'Today Express Saver', + '03' => 'Ups Ground', + ]; + + foreach ($mapServices as $key => $service) { + if ($key == $serviceCode) { + return $service; + } + } + + return $serviceCode; + } } \ No newline at end of file diff --git a/packages/Webkul/UpsShipping/src/Repositories/UpsRepository.php b/packages/Webkul/UpsShipping/src/Repositories/UpsRepository.php index bcdfe3b..73b6cf7 100644 --- a/packages/Webkul/UpsShipping/src/Repositories/UpsRepository.php +++ b/packages/Webkul/UpsShipping/src/Repositories/UpsRepository.php @@ -7,6 +7,7 @@ class UpsRepository /** * Get the Admin Products * + * @param array $cartItems * @return array */ public function getSellerAdminData($cartItems) @@ -17,14 +18,14 @@ public function getSellerAdminData($cartItems) /** * Validate if a service is allowed * - * @param string $service + * @param string $serviceCode * @param array $allowedServices * @return bool */ - public function validateAllowedMethods($service, $allowedServices) + public function validateAllowedMethods($serviceCode, $allowedServices) { foreach ($allowedServices as $methods) { - if (in_array($service, $methods)) { + if (in_array($serviceCode, $methods)) { return true; } } @@ -40,16 +41,14 @@ public function validateAllowedMethods($service, $allowedServices) */ public function getAllowedMethods($allServices) { - $allowedServices = explode(",", core()->getConfigData('sales.carriers.ups.ups_services')); + $allowedServiceCodes = explode(",", core()->getConfigData('sales.carriers.ups.ups_services')); + $allowedMethods = []; foreach ($allServices as $services) { - $allowedMethod = []; - foreach ($services as $serviceType => $upsService) { - if (in_array($serviceType, $allowedServices)) { - $allowedMethod[] = [$serviceType => $upsService]; - } - } + $allowedMethod = array_filter($services, function ($serviceCode) use ($allowedServiceCodes) { + return in_array($serviceCode, $allowedServiceCodes); + }, ARRAY_FILTER_USE_KEY); if (! empty($allowedMethod)) { $allowedMethods[] = $allowedMethod; @@ -67,23 +66,23 @@ public function getAllowedMethods($allServices) */ public function getCommonMethods($methods) { - $availableServicesArray = []; + $availableServiceCodes = []; - foreach ($methods as $fedexMethods) { - foreach (array_keys($fedexMethods) as $serviceType) { - $availableServicesArray[] = $serviceType; - } + foreach ($methods as $upsMethods) { + $availableServiceCodes = array_merge($availableServiceCodes, array_keys($upsMethods)); } - $countMethods = count($methods); - $countServices = array_count_values($availableServicesArray); + $methodsCount = count($methods); + + $serviceCounts = array_count_values($availableServiceCodes); + $finalServices = []; - foreach ($countServices as $serviceType => $servicesCount) { - if ($servicesCount == $countMethods) { - foreach ($methods as $fedexMethods) { - if (isset($fedexMethods[$serviceType])) { - $finalServices[$serviceType][] = $fedexMethods[$serviceType]; + foreach ($serviceCounts as $serviceCode => $serviceCount) { + if ($serviceCount == $methodsCount) { + foreach ($methods as $upsMethods) { + if (isset($upsMethods[$serviceCode])) { + $finalServices[$serviceCode][] = $upsMethods[$serviceCode]; } } } diff --git a/packages/Webkul/UpsShipping/src/Resources/views/configurations/field-type.blade.php b/packages/Webkul/UpsShipping/src/Resources/views/configurations/field-type.blade.php index fefd168..e1a57ce 100644 --- a/packages/Webkul/UpsShipping/src/Resources/views/configurations/field-type.blade.php +++ b/packages/Webkul/UpsShipping/src/Resources/views/configurations/field-type.blade.php @@ -108,7 +108,6 @@ class="text-gray-600 dark:text-gray-300" @elseif ($field['type'] == 'editor') -