get('\Magento\Framework\App\ResourceConnection')->getConnection('core_write'); if(!$request) {return false;} $rfrCount = 0;$isRfr = 0; $nonRfrCount = 0; $totalReman = 0; $rowTotalReman = 0; $totalNew = 0; $specialOrder = 0; $vendors = array(); $overSizedParts = array(); $partnumber = array(); foreach($request->getAllItems() as $item) { if($item->getProductType() != "simple") continue; if($item->getIsRfr() == 1){ $rfrCount = $rfrCount + $item->getQty(); } else{ $nonRfrCount++; } $isRfr = $item->getIsRfr(); if($item->getIsRfr() != 1 && ($item->getVendorId() == '12' || $item->getVendorId() == '85') ) { $totalReman += $item->getQty(); $rowTotalReman += $item->getRowTotal(); } elseif($item->getVendorId() != '12' && $item->getVendorId() != '85'){ $totalNew += $item->getQty(); } if($specialOrder == 0 && $item->getStoreId() != 13) { $currentQty = $connection->fetchOne("SELECT qty FROM ps_vendor_item_info WHERE item_id = '". $item->getVendorProductId() ."'"); $oversize = $item->getProduct()->getResource()->getAttributeRawValue($item->getProduct()->getId(),'oversizelevel1',0); $itemQty = $item->getQty(); if(!$isRfr && $currentQty - $itemQty < 0) $specialOrder = 1; if($oversize) { $specialOrder = 1; } } $i = $item->getVendorId(); if($isRfr == 1){ //For RFR shipping calculation assign vendor = 0 $i = 0; } else if($item->getVendorProductId() == ""){ $i = 1; } if(!isset($vendors[$i]['weight'])) { $vendors[$i]['weight'] = 0; } if(!isset($vendors[$i]['value'])) { $vendors[$i]['value'] = 0; } if(!isset($vendors[$i]['partCnt'])) { $vendors[$i]['partCnt'] = 0; } if(!isset($vendors[$i]['zip'])) { if($i == 0 && $isRfr == 1){ $userid = 12; } else if($i == 1 && $item->getVendorProductId() == ""){ $userid = 12; } else{ $userid = $i; } $user = $objectManager->create('Magento\User\Model\User')->load($userid); $zip = ""; $region = ""; if($user->getId()) { $zip = $user->getZipCode(); $region = $user->getRegion(); } $vendors[$i]['zip'] = $zip; $vendors[$i]['region'] = $region; } $weight = $item->getRowWeight(); if($weight <= 0) { $weight = $item->getProduct()->getResource()->getAttributeRawValue($item->getProduct()->getId(),'weight',0) * $item->getQty(); } /*PartSimple Shipping Logic Changes START - Ticket 33954 product weight 8lbs*/ if(!in_array($i, array(0,12,85))) { if($item->getProduct()->getResource()->getAttributeRawValue($item->getProduct()->getId(),'weight',0) < 8){ $weight = intval(8 * $item->getQty()); }else{ $weight = $item->getProduct()->getResource()->getAttributeRawValue($item->getProduct()->getId(),'weight',0) * $item->getQty(); } } /*PartSimple Shipping Logic Changes START - Ticket 33954*/ $vendors[$i]['weight'] = $weight + $vendors[$i]['weight']; $vendors[$i]['partCnt'] += $item->getQty(); // For 17836 } return array( 'rfr' => $rfrCount, 'non' => $nonRfrCount, 'special' => $specialOrder, 'vendors' => $vendors, 'oversize' => $overSizedParts, 'totalReman' => $totalReman, 'totalNew' => $totalNew, 'rowTotalReman' => $rowTotalReman ); } protected function _getXmlQuotes(){ $url = $this->getConfigData('gateway_xml_url'); $this->setXMLAccessRequest(); $xmlRequest = $this->_xmlAccessRequest; $debugData['accessRequest'] = $this->filterDebugData($xmlRequest); $rowRequest = $this->_rawRequest; /*Custom*/ $request = $this->_request; $allowedMethods = explode(',', $this->getConfigData('allowed_methods')); $this->_currentStore = $request->getStoreId(); // Change for ccsrfr reman pricing $this->_currentRegion = $request->getDestRegionId(); //For CCSRFR pickup option reman $quoteDetails = $this->getQuoteDetails($request); $this->_overSizedParts = $quoteDetails['oversize']; $this->_totalReman = $quoteDetails['totalReman']; $this->_totalRFR = $quoteDetails['rfr']; $this->_totalNew = $quoteDetails['totalNew']; $this->_rowTotalReman = $quoteDetails['rowTotalReman']; //for ccdirect // Calculate Additional Cost for oversized parts if any $additionalCost = 0; $oversizeCharges = array(); $apiCall = 1; // Should UPS API be called or if failed $tempOverSizeParts = $this->_overSizedParts; if(TRUE || !empty($tempOverSizeParts)) { for($k = 1;$k<=4;$k++) { switch($k) { case 1: $cnt = 'one'; break; case 2: $cnt = 'two'; break; case 3: $cnt = 'three'; break; case 4: $cnt = 'four'; break; } $oversizeCharges[$k] = $this->_scopeConfig->getValue('carriers/tier/tier_oversize_'.$cnt.'_charge', \Magento\Store\Model\ScopeInterface::SCOPE_STORE); } foreach($tempOverSizeParts as $level => $partCount) { $additionalCost += $oversizeCharges[$level] * $partCount; } } if($quoteDetails && array($quoteDetails)) { // Set Ground in Allowed methods if Order is Special/Oversize/Vendor does not support express delivery $specialOrder = $quoteDetails['special']; $quoteVendors = array_keys($quoteDetails['vendors']); $expAvail = $this->checkExpressAvailable($quoteVendors); if(empty($quoteVendors)) { $apiCall = 0; // Either there are only RFR or only Oversize parts in cart } if($specialOrder || !$expAvail) { $allowedMethods = array('03'); } $this->_newAllowedMethods = $allowedMethods; } else{ $apiCall = 0; // Quote Details Failed } $freeGroundVendors = array(12,85); if($this->_currentStore == 6){ $freeGroundVendors = array(12,85,0); } // $freeGroundVendors = array(); $preparedGeneral = ''; $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // For 17836 $newShipRuleApply = 0; $customerSession = $objectManager->get('Magento\Customer\Model\Session'); if($customerSession->isLoggedIn()) { $customer = $customerSession->getCustomer(); //if($customer->getShipOnAccount() != "" && $customer->getShipOnAccount() != false && $customer->getShipOnAccount() != 0) { if($customer->getShipOnAccount() == 3) { $newShipRuleApply = 1; $this->_newShipRule = 1; } else { $customerGroups = array(8,6); // Reseller = 8 , ISP = 6 /*if($this->_currentStore == 6) { // Change for ccsrfr reman pricing $customerGroups = array(8,6,5); }*/ if(in_array($customer->getGroupId(),$customerGroups)) { $newShipRuleApply = 2; $this->_newShipRule = 2; } } if($newShipRuleApply != 0) $freeGroundVendors = array(); } // END - 17836 if($apiCall) { foreach($quoteVendors as $ven) { if(isset($quoteDetails['vendors'][$ven])) { $vendor = $quoteDetails['vendors'][$ven]; // $this->_logger->Debug(">> >Weight >>>> ccsDsssssssssssssssiscount--".$ven); if(!in_array($ven, array(0,12,85))){ // $this->_logger->Debug("Venodr Weight >>> " . $vendor['weight']); if($vendor['weight'] < 8 ){ $vendor['weight'] = 8; $quoteDetails['vendors'][$ven]['weight'] = 8; } // $this->_logger->Debug("Venodr Weight after >>> " . $vendor['weight']); } if(in_array($ven,$freeGroundVendors)) { $this->_freeGround = true; } else { $this->_freeGround = false; } // Remove $12 for CCS Parts on 2 Day and Express $this->_ccsDiscount = FALSE; if($ven == 12 || $ven == 0) { $this->_ccsDiscount = TRUE; } // $this->_logger->addDebug("ccsDsssssssssssssssiscount--".$this->_ccsDiscount.$ven); if($customerSession->isLoggedIn() && $customerSession->getCustomer()->getData('preferredaccountnumber') != "") { $this->_ccsDiscount = FALSE; } // $this->_logger->addDebug("ccsDsssssssssssssssiscount--".$this->_ccsDiscount."--".$newShipRuleApply); if($newShipRuleApply != 0) // For 17836 $this->_ccsDiscount = FALSE; // For 17836 $this->_currentVendor = $ven; // 17836 $this->_currentVendorPartCnt = $vendor['partCnt']; // 17836 if($vendor['weight'] > 150){ $vendor['weight'] = 150; } $rowRequest->setOrigPostal($vendor['zip']); $rowRequest->setOrigRegionCode($vendor['region']); $rowRequest->setWeight($vendor['weight']); } /*end - custom*/ if (self::USA_COUNTRY_ID == $rowRequest->getDestCountry()) { $destPostal = substr($rowRequest->getDestPostal(), 0, 5); } else { $destPostal = $rowRequest->getDestPostal(); } $params = [ 'accept_UPS_license_agreement' => 'yes', '10_action' => $rowRequest->getAction(), '13_product' => $rowRequest->getProduct(), '14_origCountry' => $rowRequest->getOrigCountry(), '15_origPostal' => $rowRequest->getOrigPostal(), 'origCity' => $rowRequest->getOrigCity(), 'origRegionCode' => $rowRequest->getOrigRegionCode(), '19_destPostal' => $destPostal, '22_destCountry' => $rowRequest->getDestCountry(), 'destRegionCode' => $rowRequest->getDestRegionCode(), '23_weight' => $rowRequest->getWeight(), '47_rate_chart' => $rowRequest->getPickup(), '48_container' => $rowRequest->getContainer(), '49_residential' => $rowRequest->getDestType(), ]; if ($params['10_action'] == '4') { $params['10_action'] = 'Shop'; $serviceCode = null; } else { $params['10_action'] = 'Rate'; $serviceCode = $rowRequest->getProduct() ? $rowRequest->getProduct() : ''; } $serviceDescription = $serviceCode ? $this->getShipmentByCode($serviceCode) : ''; $xmlParams = << Rating and Service 1.0 Rate {$params['10_action']} {$params['47_rate_chart']['code']} {$params['47_rate_chart']['label']} XMLRequest; if ($serviceCode !== null) { $xmlParams .= "" . "{$serviceCode}" . "{$serviceDescription}" . ""; } $xmlParams .= << XMLRequest; if ($this->getConfigFlag('negotiated_active') && ($shipper = $this->getConfigData('shipper_number'))) { $xmlParams .= "{$shipper}"; } if ($rowRequest->getIsReturn()) { $shipperCity = ''; $shipperPostalCode = $params['19_destPostal']; $shipperCountryCode = $params['22_destCountry']; $shipperStateProvince = $params['destRegionCode']; } else { $shipperCity = $params['origCity']; $shipperPostalCode = $params['15_origPostal']; $shipperCountryCode = $params['14_origCountry']; $shipperStateProvince = $params['origRegionCode']; } $xmlParams .= << {$shipperCity} {$shipperPostalCode} {$shipperCountryCode} {$shipperStateProvince}
{$params['19_destPostal']} {$params['22_destCountry']} {$params['49_residential']} {$params['destRegionCode']} XMLRequest; if ($params['49_residential'] === '01') { $xmlParams .= "{$params['49_residential']}"; } $xmlParams .= <<
{$params['15_origPostal']} {$params['14_origCountry']} {$params['origRegionCode']}
{$params['48_container']} {$rowRequest->getUnitMeasure()} {$params['23_weight']} XMLRequest; if ($this->getConfigFlag('negotiated_active')) { $xmlParams .= ""; } $xmlParams .= << XMLRequest; $xmlRequest .= $xmlParams; $xmlResponse = $this->_getCachedQuotes($xmlRequest); if ($xmlResponse === null) { $debugData['request'] = $xmlParams; try { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $xmlRequest); curl_setopt($ch, CURLOPT_TIMEOUT, 30); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (bool)$this->getConfigFlag('mode_xml')); $xmlResponse = curl_exec($ch); if ($xmlResponse !== false) { $debugData['result'] = $xmlResponse; $this->_setCachedQuotes($xmlRequest, $xmlResponse); } else { $debugData['result'] = ['error' => curl_error($ch)]; } curl_close($ch); } catch (\Exception $e) { $debugData['result'] = ['error' => $e->getMessage(), 'code' => $e->getCode()]; $xmlResponse = ''; } $this->_debug($debugData); } $parseXmlResponse = $this->_parseXmlResponse($xmlResponse); // $this->_logger->debug("RateShopPriceS XML Response >> : " . print_r($parseXmlResponse,true)); if(($this->_totalReman > 0 || $this->_totalRFR > 0) && $this->_totalNew == 0){ $shippingRegionId = ''; $pickupRegions = array(23,24,64); //Need to add regions for which we provide pickup option (23 -Illinois 24 - Indiana 64 - Wisconsin ) $shippingRegionId = $this->_currentRegion; if(is_array($pickupRegions) && in_array($shippingRegionId,$pickupRegions)) { $parseXmlResponse->append($this->_getPickupShippingRate()); } } if(!empty($this->_rateShopPrice)) { foreach($this->_rateShopPrice as $method => $data) { $rate = $this->_rateMethodFactory->create(); $rate->setCarrier('ups'); $rate->setCarrierTitle($this->getConfigData('title')); $rate->setMethod($method); $methodArr = $this->getShipmentByCode($method); $rate->setMethodTitle($methodArr); $rate->setCost($data['cost']); $rate->setPrice($data['price']); $parseXmlResponse->append($rate); } } } } return $parseXmlResponse; } protected function _parseXmlResponse($xmlResponse) { $costArr = []; $priceArr = []; $customerSession = \Magento\Framework\App\ObjectManager::getInstance()->get('Magento\Customer\Model\Session'); if (strlen(trim($xmlResponse)) > 0) { $xml = new \Magento\Framework\Simplexml\Config(); $xml->loadString($xmlResponse); $arr = $xml->getXpath("//RatingServiceSelectionResponse/Response/ResponseStatusCode/text()"); $success = (int)$arr[0]; if ($success === 1) { $arr = $xml->getXpath("//RatingServiceSelectionResponse/RatedShipment"); $allowedMethods = explode(",", $this->getConfigData('allowed_methods')); /*Start - Custom Code*/ if(!empty($this->_newAllowedMethods)) $allowedMethods = $this->_newAllowedMethods; /*End - Custom Code*/ // Negotiated rates $negotiatedArr = $xml->getXpath("//RatingServiceSelectionResponse/RatedShipment/NegotiatedRates"); $negotiatedActive = $this->getConfigFlag( 'negotiated_active' ) && $this->getConfigData( 'shipper_number' ) && !empty($negotiatedArr); $allowedCurrencies = $this->_currencyFactory->create()->getConfigAllowCurrencies(); foreach ($arr as $shipElement) { $code = (string)$shipElement->Service->Code; if (in_array($code, $allowedMethods)) { if ($negotiatedActive) { $cost = $shipElement->NegotiatedRates->NetSummaryCharges->GrandTotal->MonetaryValue; } else { $cost = $shipElement->TotalCharges->MonetaryValue; } //convert price with Origin country currency code to base currency code $successConversion = true; $responseCurrencyCode = $this->mapCurrencyCode( (string)$shipElement->TotalCharges->CurrencyCode ); if ($responseCurrencyCode) { if (in_array($responseCurrencyCode, $allowedCurrencies)) { $cost = (double)$cost * $this->_getBaseCurrencyRate($responseCurrencyCode); } else { $errorTitle = __( 'We can\'t convert a rate from "%1-%2".', $responseCurrencyCode, $this->_request->getPackageCurrency()->getCode() ); $error = $this->_rateErrorFactory->create(); $error->setCarrier('ups'); $error->setCarrierTitle($this->getConfigData('title')); $error->setErrorMessage($errorTitle); $successConversion = false; } } if ($successConversion) { $costArr[$code] = $cost; $priceArr[$code] = $this->getMethodPrice(floatval($cost), $code); } } } } else { $arr = $xml->getXpath("//RatingServiceSelectionResponse/Response/Error/ErrorDescription/text()"); $errorTitle = (string)$arr[0][0]; $error = $this->_rateErrorFactory->create(); $error->setCarrier('ups'); $error->setCarrierTitle($this->getConfigData('title')); $error->setErrorMessage($this->getConfigData('specificerrmsg')); } } $this->_result = $this->_rateFactory->create(); if (empty($priceArr)) { $error = $this->_rateErrorFactory->create(); $error->setCarrier('ups'); $error->setCarrierTitle($this->getConfigData('title')); if (!isset($errorTitle)) { $errorTitle = __('Cannot retrieve shipping rates'); } $error->setErrorMessage($this->getConfigData('specificerrmsg')); $this->_result->append($error); } else { foreach ($priceArr as $method => $price) { /*Start - Custom Code*/ if(!isset($this->_rateShopPrice[$method]['cost'])) { $this->_rateShopPrice[$method]['cost'] = 0; $this->_rateShopPrice[$method]['price'] = 0; } /*Start - 10% surcharge added*/ // $costArr[$method] += (10/100)*$costArr[$method]; // $price += (10/100)*$price; /*End - 10% surcharge added*/ /*PartSimple Shipping Margin Logic Changes START - Ticket 33954*/ if(in_array($this->_currentVendor, array(0,12,85))){ if($method == 13){ $costArr[$method] += (15/100)*$costArr[$method]; $price += (15/100)*$price; }else{ $costArr[$method] += (10/100)*$costArr[$method]; $price += (10/100)*$price; } // $costArr[$method] += (10/100)*$costArr[$method]; // $price += (10/100)*$price; }else { /*Start - 10% surcharge added*/ $costArr[$method] += ((20/100)*$costArr[$method])+3; $price += ((20/100)*$price)+3; /*End - 10% surcharge added*/ } /*PartSimple Shipping Margin Logic Changes ENDS - Ticket 33954*/ $this->_rateShopPrice[$method]['cost'] += $costArr[$method]; $this->_rateShopPrice[$method]['price'] += $price; $this->_logger->debug(">>>>> UPS Response check2: Price: ".$price." Method: ".$method." Cost: ".$costArr[$method]." : ".date("m-d-Y H:i:s.u")); /*Store Level Logic for Custom Shipping Changes Start */ if($this->_currentStore == 13){ if($this->_currentVendor == 0){ if($method == "03"){ $nCost = 7.99; if($this->_totalRFR >= 3){ $nCost = 0; } } if($method == "02"){ $nCost = 15; if($this->_totalRFR >= 3){ $nCost = 23; } } if($method == "01" || $method == "13"){ $nCost = 30; if($this->_totalRFR >= 3){ $nCost = 40; } } $nPrice = $nCost; $this->_rateShopPrice[$method]['cost'] -= $costArr[$method]; $this->_rateShopPrice[$method]['price'] -= $price; $this->_rateShopPrice[$method]['cost'] += $nCost; $this->_rateShopPrice[$method]['price'] += $nPrice; } elseif($method == "03" && ($this->_currentVendor == 85 || $this->_currentVendor == 12)){ if($this->_rowTotalReman >= 1000){ $nCost = 0; } else{ $nCost = 7.99; } $nPrice = $nCost; $this->_rateShopPrice[$method]['cost'] -= $costArr[$method]; $this->_rateShopPrice[$method]['price'] -= $price; $this->_rateShopPrice[$method]['cost'] += $nCost; $this->_rateShopPrice[$method]['price'] += $nPrice; } } else { if($this->_currentVendor == 12 || $this->_currentVendor == 0 || $this->_currentVendor == 85) { if($this->_freeGround) { if($method == "03") { $nCost = 0; $nPrice = 0; $this->_rateShopPrice[$method]['cost'] -= $costArr[$method]; $this->_rateShopPrice[$method]['price'] -= $price; $this->_rateShopPrice[$method]['cost'] += $nCost; $this->_rateShopPrice[$method]['price'] += $nPrice; } }else if($this->_newShipRule == 1) { $nCost = 0; $nPrice = 0; $this->_rateShopPrice[$method]['cost'] -= $costArr[$method]; $this->_rateShopPrice[$method]['price'] -= $price; $this->_rateShopPrice[$method]['cost'] += $nCost; $this->_rateShopPrice[$method]['price'] += $nPrice; }else if($this->_newShipRule == 2) { }else if($this->_newShipRule == 3) { }else if($this->_currentVendor == 0){ } } } /*Store Level Logic for Custom Shipping Changes Ends */ $cost = $this->_rateShopPrice[$method]['cost']; $price = $this->_rateShopPrice[$method]['price']; } } return $this->_result; } private function mapCurrencyCode($code) { $currencyMapping = [ 'RMB' => 'CNY', 'CNH' => 'CNY' ]; return isset($currencyMapping[$code]) ? $currencyMapping[$code] : $code; } protected function checkExpressAvailable($vendors) { for($i=0;$i_logger->addDebug(" Vendor List: ".print_r($vendors,true)); $exp = $this->_scopeConfig->getValue('carriers/fedex/vendors_exp_ship', \Magento\Store\Model\ScopeInterface::SCOPE_STORE); $expressVendors = explode(",", $exp); if(!array($expressVendors) && $exp != '') { $expressVendors = array($exp); } if(!is_array($expressVendors) || !count($expressVendors)) { return false; } $currentVendors = $vendors; if(count(array_intersect($currentVendors, $expressVendors)) == count($currentVendors)) return true; else return false; } protected function _getPickupShippingRate() { $rate = $this->_rateMethodFactory->create(); $rate->setCarrier("ups"); $rate->setCarrierTitle("Pickup"); $rate->setMethod('pickup'); $rate->setMethodTitle('Pickup Order'); $price = 0; $rate->setPrice(0); $rate->setCost(0); return $rate; } // Function to obtain an access token from UPS public function getUpsAccessToken($clientId, $secretId) { $tokenUrl = "https://wwwcie.ups.com/security/v1/oauth/token"; $ch = curl_init(); // Encode the client ID and secret as Basic {id}:{secret} $credentials = base64_encode($clientId. ':'. $secretId); curl_setopt($ch, CURLOPT_URL, $tokenUrl); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, "grant_type=client_credentials"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Authorization: Basic $credentials", "accept: application/json", "Content-Type: application/x-www-form-urlencoded" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Disable SSL verification (not recommended for production) $response = curl_exec($ch); curl_close($ch); $responseData = json_decode($response, true); if(isset($responseData['access_token'])) { return $responseData['access_token']; } } /** * Do remote request for and handle errors * * @return Result|null */ public function _getQuotes() { switch ($this->getConfigData('type')) { case 'UPS': return $this->_getCgiQuotes(); case 'UPS_XML': return $this->_getXmlQuotes(); case 'UPS_REST': // return $this->_getXmlQuotes(); return $this->_getRestQuotes(); default: break; } return null; } /** * Get REST rates * * @return Result * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ protected function _getRestQuotes() { $clientId = $this->getClientId(); $secretId = $this->getSecretId(); $url = $this->getConfigData('gateway_rest_url'); $accessToken = $this->getUpsAccessToken($clientId, $secretId); $rowRequest = $this->_rawRequest; /*====================================================== Custom Code Starts =============================================================================================*/ $request = $this->_request; $allowedMethods = explode(',', $this->getConfigData('allowed_methods')); $this->_currentStore = $request->getStoreId(); // Change for ccsrfr reman pricing $this->_currentRegion = $request->getDestRegionId(); //For CCSRFR pickup option reman $quoteDetails = $this->getQuoteDetails($request); $this->_overSizedParts = $quoteDetails['oversize']; $this->_totalReman = $quoteDetails['totalReman']; $this->_totalRFR = $quoteDetails['rfr']; $this->_totalNew = $quoteDetails['totalNew']; $this->_rowTotalReman = $quoteDetails['rowTotalReman']; //for ccdirect // Calculate Additional Cost for oversized parts if any $additionalCost = 0; $oversizeCharges = array(); $apiCall = 1; // Should UPS API be called or if failed $tempOverSizeParts = $this->_overSizedParts; if(TRUE || !empty($tempOverSizeParts)) { for($k = 1;$k<=4;$k++) { switch($k) { case 1: $cnt = 'one'; break; case 2: $cnt = 'two'; break; case 3: $cnt = 'three'; break; case 4: $cnt = 'four'; break; } $oversizeCharges[$k] = $this->_scopeConfig->getValue('carriers/tier/tier_oversize_'.$cnt.'_charge', \Magento\Store\Model\ScopeInterface::SCOPE_STORE); } foreach($tempOverSizeParts as $level => $partCount) { $additionalCost += $oversizeCharges[$level] * $partCount; } } if($quoteDetails && array($quoteDetails)) { // Set Ground in Allowed methods if Order is Special/Oversize/Vendor does not support express delivery $specialOrder = $quoteDetails['special']; $quoteVendors = array_keys($quoteDetails['vendors']); $expAvail = $this->checkExpressAvailable($quoteVendors); if(empty($quoteVendors)) { $apiCall = 0; // Either there are only RFR or only Oversize parts in cart } if($specialOrder || !$expAvail) { $allowedMethods = array('03'); } $this->_newAllowedMethods = $allowedMethods; } else{ $apiCall = 0; // Quote Details Failed } $freeGroundVendors = array(12,85); if($this->_currentStore == 6){ $freeGroundVendors = array(12,85,0); } // $freeGroundVendors = array(); $preparedGeneral = ''; $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // For 17836 $newShipRuleApply = 0; $customerSession = $objectManager->get('Magento\Customer\Model\Session'); if($customerSession->isLoggedIn()) { $customer = $customerSession->getCustomer(); if($customer->getShipOnAccount() == 3) { $newShipRuleApply = 1; $this->_newShipRule = 1; } else { $customerGroups = array(8,6); // Reseller = 8 , ISP = 6 if(in_array($customer->getGroupId(),$customerGroups)) { $newShipRuleApply = 2; $this->_newShipRule = 2; } } if($newShipRuleApply != 0) $freeGroundVendors = array(); } // END - 17836 if($apiCall) { foreach($quoteVendors as $ven) { if(isset($quoteDetails['vendors'][$ven])) { $vendor = $quoteDetails['vendors'][$ven]; if(!in_array($ven, array(0,12,85))){ if($vendor['weight'] < 8 ){ $vendor['weight'] = 8; $quoteDetails['vendors'][$ven]['weight'] = 8; } } if(in_array($ven,$freeGroundVendors)) { $this->_freeGround = true; } else { $this->_freeGround = false; } // Remove $12 for CCS Parts on 2 Day and Express $this->_ccsDiscount = FALSE; if($ven == 12 || $ven == 0) { $this->_ccsDiscount = TRUE; } if($customerSession->isLoggedIn() && $customerSession->getCustomer()->getData('preferredaccountnumber') != "") { $this->_ccsDiscount = FALSE; } if($newShipRuleApply != 0) // For 17836 $this->_ccsDiscount = FALSE; // For 17836 $this->_currentVendor = $ven; // 17836 $this->_currentVendorPartCnt = $vendor['partCnt']; // 17836 if($vendor['weight'] > 150){ $vendor['weight'] = 150; } $rowRequest->setOrigPostal($vendor['zip']); $rowRequest->setOrigRegionCode($vendor['region']); $rowRequest->setWeight($vendor['weight']); } // \Magento\Framework\App\ObjectManager::getInstance()->get('Psr\Log\LoggerInterface')->debug('Quote _parseRestResponse Check1 _currentVendor ==>>>> : ' . print_r($this->_currentVendor,true)); // $params = $this->setQuoteRequestData($rowRequest); if (self::USA_COUNTRY_ID == $rowRequest->getDestCountry()) { $destPostal = substr((string)$rowRequest->getDestPostal(), 0, 5); } else { $destPostal = $rowRequest->getDestPostal(); } $params = [ '10_action' => $rowRequest->getAction(), '13_product' => $rowRequest->getProduct(), '14_origCountry' => $rowRequest->getOrigCountry(), '15_origPostal' => $rowRequest->getOrigPostal(), 'origCity' => $rowRequest->getOrigCity(), 'origRegionCode' => $rowRequest->getOrigRegionCode(), '19_destPostal' => $destPostal, '22_destCountry' => $rowRequest->getDestCountry(), 'destRegionCode' => $rowRequest->getDestRegionCode(), '23_weight' => $rowRequest->getWeight(), '47_rate_chart' => $rowRequest->getPickup(), '48_container' => $rowRequest->getContainer(), '49_residential' => $rowRequest->getDestType(), ]; if ($params['10_action'] == '4') { $params['10_action'] = 'Shop'; $params['serviceCode'] = null; } else { $params['10_action'] = 'Rate'; $params['serviceCode'] = $rowRequest->getProduct() ? $rowRequest->getProduct() : null; } $params['serviceDescription'] = $params['serviceCode'] ? $this->getShipmentByCode($params['serviceCode']) : ''; /*================================================================ Custom Code ENDS =============================================================================================*/ $serviceCode = $params['serviceCode']; $serviceDescription = $params['serviceDescription']; $shipperNumber = ''; if ($this->getConfigFlag('negotiated_active') && ($shipperNumber = $this->getConfigData('shipper_number'))) { $shipperNumber = $this->getConfigData('shipper_number'); } if ($rowRequest->getIsReturn()) { $shipperCity = ''; $shipperPostalCode = $params['19_destPostal']; $shipperCountryCode = $params['22_destCountry']; $shipperStateProvince = $params['destRegionCode']; } else { $shipperCity = $params['origCity']; $shipperPostalCode = $params['15_origPostal']; $shipperCountryCode = $params['14_origCountry']; $shipperStateProvince = $params['origRegionCode']; } $residentialAddressIndicator = ''; if ($params['49_residential'] === '01') { $residentialAddressIndicator = $params['49_residential']; } $rateParams = [ "RateRequest" => [ "Request" => [ "TransactionReference" => [ "CustomerContext" => "Rating and Service" ] ], "Shipment" => [ "Shipper" => [ "Name" => "UPS", "ShipperNumber" => "{$shipperNumber}", "Address" => [ "AddressLine" => [ "{$residentialAddressIndicator}", ], "City" => "{$shipperCity}", "StateProvinceCode" => "{$shipperStateProvince}", "PostalCode" => "{$shipperPostalCode}", "CountryCode" => "{$shipperCountryCode}" ] ], "ShipTo" => [ "Address" => [ "AddressLine" => ["{$params['49_residential']}"], "StateProvinceCode" => "{$params['destRegionCode']}", "PostalCode" => "{$params['19_destPostal']}", "CountryCode" => "{$params['22_destCountry']}", "ResidentialAddressIndicator" => "{$residentialAddressIndicator}" ] ], "ShipFrom" => [ "Address" => [ "AddressLine" => [], "StateProvinceCode" => "{$params['origRegionCode']}", "PostalCode" => "{$params['15_origPostal']}", "CountryCode" => "{$params['14_origCountry']}" ] ], ] ] ]; if ($this->getConfigFlag('negotiated_active')) { $rateParams['RateRequest']['Shipment']['ShipmentRatingOptions']['TPFCNegotiatedRatesIndicator'] = "Y"; $rateParams['RateRequest']['Shipment']['ShipmentRatingOptions']['NegotiatedRatesIndicator'] = "Y"; } if ($this->getConfigFlag('include_taxes')) { $rateParams['RateRequest']['Shipment']['TaxInformationIndicator'] = "Y"; } if ($serviceCode !== null) { $rateParams['RateRequest']['Shipment']['Service']['code'] = $serviceCode; $rateParams['RateRequest']['Shipment']['Service']['Description'] = $serviceDescription; } foreach ($rowRequest->getPackages() as $package) { $rateParams['RateRequest']['Shipment']['Package'][] = [ "PackagingType" => [ "Code" => "{$params['48_container']}", "Description" => "Packaging" ], "Dimensions" => [ "UnitOfMeasurement" => [ "Code" => "IN", "Description" => "Inches" ], "Length" => "5", "Width" => "5", "Height" => "5" ], "PackageWeight" => [ "UnitOfMeasurement" => [ "Code" => "{$rowRequest->getUnitMeasure()}" ], "Weight" => "{$this->_getCorrectWeight($package['weight'])}" ] ]; } $ratePayload = json_encode($rateParams, JSON_PRETTY_PRINT); /** Rest API Payload */ $version = "v1"; $requestOption = $params['10_action']; $headers = [ "Authorization" => "Bearer " . $accessToken, "Content-Type" => "application/json" ]; $query = array( "additionalinfo" => "" ); // Initialize cURL session $curl = curl_init(); // Set options curl_setopt_array($curl, [ CURLOPT_HTTPHEADER => [ "Authorization: Bearer $accessToken", // Replace YOUR_BEARER_TOKEN_HERE with your actual token "Content-Type: application/json", // Remove or correct invalid headers ], CURLOPT_POSTFIELDS => $ratePayload, // Ensure $payload is a valid JSON object CURLOPT_URL => "https://onlinetools.ups.com/api/rating/". $version. "/". $requestOption. "?". http_build_query($query), CURLOPT_RETURNTRANSFER => true, CURLOPT_CUSTOMREQUEST => "POST", ]); $response = curl_exec($curl); $error = curl_error($curl); curl_close($curl); // Handle response or error if ($error) { // echo "cURL Error #: ". $error; } else { $parseRestResponse = $response; $parseRestResponse = $this->_parseRestResponse($response); } // $this->_logger->debug(">>>>>>>>>>>> RateShopPriceS111: ".print_r($parseRestResponse,true)); \Magento\Framework\App\ObjectManager::getInstance()->get('Psr\Log\LoggerInterface')->debug('Quote _getRestQuotes Check6ratePayload _rateShopPrice ==>>>> : ' . print_r($this->_rateShopPrice,true)); // \Magento\Framework\App\ObjectManager::getInstance()->get('Psr\Log\LoggerInterface')->debug('Quote _getRestQuotes Check6ratePayload _rateShopPrice ==>>>> : ' . print_r($parseRestResponse,true)); if(($this->_totalReman > 0 || $this->_totalRFR > 0) && $this->_totalNew == 0){ $shippingRegionId = ''; $pickupRegions = array(23,24,64); //Need to add regions for which we provide pickup option (23 -Illinois 24 - Indiana 64 - Wisconsin ) $shippingRegionId = $this->_currentRegion; if(is_array($pickupRegions) && in_array($shippingRegionId,$pickupRegions)) { $parseRestResponse->append($this->_getPickupShippingRate()); } } if(!empty($this->_rateShopPrice)) { foreach($this->_rateShopPrice as $method => $data) { $rate = $this->_rateMethodFactory->create(); $rate->setCarrier('ups'); $rate->setCarrierTitle($this->getConfigData('title')); $rate->setMethod($method); $methodArr = $this->getShipmentByCode($method); $rate->setMethodTitle($methodArr); $rate->setCost($data['cost']); $rate->setPrice($data['price']); $parseRestResponse->append($rate); } } } } return $parseRestResponse; } /** * Prepare shipping rate result based on response * * @param mixed $rateResponse * @return Result * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) * @SuppressWarnings(PHPMD.ElseExpression) */ protected function _parseRestResponse($rateResponse) { $costArr = []; $priceArr = []; $errorTitle = ''; if ($rateResponse !== null && strlen($rateResponse) > 0) { $rateResponseData = json_decode($rateResponse, true); if (isset($rateResponseData['RateResponse']['Response']['ResponseStatus']['Description']) && $rateResponseData['RateResponse']['Response']['ResponseStatus']['Description'] === 'Success') { $arr = $rateResponseData['RateResponse']['RatedShipment'] ?? []; $allowedMethods = explode(",", $this->getConfigData('allowed_methods') ?? ''); /*Start - Custom Code*/ if(!empty($this->_newAllowedMethods)) $allowedMethods = $this->_newAllowedMethods; /*End - Custom Code*/ $allowedCurrencies = $this->_currencyFactory->create()->getConfigAllowCurrencies(); foreach ($arr as $shipElement) { // Negotiated rates $negotiatedArr = $shipElement['NegotiatedRateCharges'] ?? [] ; $negotiatedActive = $this->getConfigFlag('negotiated_active') && $this->getConfigData('shipper_number') && !empty($negotiatedArr); $code = $shipElement['Service']['Code'] ?? ''; if (in_array($code, $allowedMethods)) { // \Magento\Framework\App\ObjectManager::getInstance()->get('Psr\Log\LoggerInterface')->debug('Quote _parseRestResponse Check1 allowedMethods shipElement ==>>>> : ' . print_r( $shipElement, true)); if ($negotiatedActive) { $includeTaxesArr = $shipElement['NegotiatedRateCharges']['TotalChargesWithTaxes'] ?? []; $includeTaxesActive = $this->getConfigFlag('include_taxes') && !empty($includeTaxesArr); if ($includeTaxesActive) { $cost = $shipElement['NegotiatedRateCharges']['TotalChargesWithTaxes']['MonetaryValue']; $responseCurrencyCode = $this->mapCurrencyCode((string)$shipElement['NegotiatedRateCharges']['TotalChargesWithTaxes']['CurrencyCode']); } else { $cost = $shipElement['NegotiatedRateCharges']['TotalCharge']['MonetaryValue']; $responseCurrencyCode = $this->mapCurrencyCode((string)$shipElement['NegotiatedRateCharges']['TotalCharge']['CurrencyCode']); } } else { $includeTaxesArr = $shipElement['TotalChargesWithTaxes'] ?? []; $includeTaxesActive = $this->getConfigFlag('include_taxes') && !empty($includeTaxesArr); if ($includeTaxesActive) { $cost = $shipElement['TotalChargesWithTaxes']['MonetaryValue']; $responseCurrencyCode = $this->mapCurrencyCode((string)$shipElement['TotalChargesWithTaxes']['CurrencyCode']); } else { $cost = $shipElement['TotalCharges']['MonetaryValue']; $responseCurrencyCode = $this->mapCurrencyCode((string)$shipElement['TotalCharges']['CurrencyCode']); } } //convert price with Origin country currency code to base currency code $successConversion = true; if ($responseCurrencyCode) { if (in_array($responseCurrencyCode, $allowedCurrencies)) { $cost = (double)$cost * $this->_getBaseCurrencyRate($responseCurrencyCode); } else { $errorTitle = __( 'We can\'t convert a rate from "%1-%2".', $responseCurrencyCode, $this->_request->getPackageCurrency()->getCode() ); $error = $this->_rateErrorFactory->create(); $error->setCarrier('ups'); $error->setCarrierTitle($this->getConfigData('title')); $error->setErrorMessage($errorTitle); $successConversion = false; } } if ($successConversion) { $costArr[$code] = $cost; $priceArr[$code] = $this->getMethodPrice((float)$cost, $code); } } // $this->processShippingRestRateForItem($shipElement,$allowedMethods,$allowedCurrencies,$costArr,$priceArr,$negotiatedActive); } } else { if(isset($rateResponseData['RateResponse']['Response']['ResponseStatus']['Description'])){ $errorTitle = $rateResponseData['RateResponse']['Response']['ResponseStatus']['Description']; } $error = $this->_rateErrorFactory->create(); $error->setCarrier('ups'); $error->setCarrierTitle($this->getConfigData('title')); $error->setErrorMessage($this->getConfigData('specificerrmsg')); } } \Magento\Framework\App\ObjectManager::getInstance()->get('Psr\Log\LoggerInterface')->debug('Quote _parseRestResponse Check1 allowedMethods costArr ==>>>> : ' . print_r( $costArr, true)); \Magento\Framework\App\ObjectManager::getInstance()->get('Psr\Log\LoggerInterface')->debug('Quote _parseRestResponse Check1 allowedMethods priceArr ==>>>> : ' . print_r( $priceArr, true)); $this->_result = $this->_rateFactory->create(); if (empty($priceArr)) { $error = $this->_rateErrorFactory->create(); $error->setCarrier('ups'); $error->setCarrierTitle($this->getConfigData('title')); if (!isset($errorTitle)) { $errorTitle = __('Cannot retrieve shipping rates'); } $error->setErrorMessage($this->getConfigData('specificerrmsg')); $this->_result->append($error); }else { foreach ($priceArr as $method => $price) { if(!isset($this->_rateShopPrice[$method]['cost'])) { $this->_rateShopPrice[$method]['cost'] = 0; $this->_rateShopPrice[$method]['price'] = 0; } /*PartSimple Shipping Margin surcharge Logic Changes START - Ticket 33954*/ if(in_array($this->_currentVendor, array(0,12,85))){ if($method == 13){ $costArr[$method] += (15/100)*$costArr[$method]; $price += (15/100)*$price; }else{ $costArr[$method] += (10/100)*$costArr[$method]; $price += (10/100)*$price; } }else { /*Start - 10% surcharge added*/ $costArr[$method] += ((20/100)*$costArr[$method])+3; $price += ((20/100)*$price)+3; /*End - 10% surcharge added*/ } /*PartSimple Shipping Margin surcharge Logic Changes ENDS - Ticket 33954*/ $this->_rateShopPrice[$method]['cost'] += $costArr[$method]; $this->_rateShopPrice[$method]['price'] += $price; /*Store Level Logic for Custom Shipping Changes Start */ if($this->_currentStore == 13){ if($this->_currentVendor == 0){ if($method == "03"){ $nCost = 7.99; if($this->_totalRFR >= 3){ $nCost = 0; } } if($method == "02"){ $nCost = 15; if($this->_totalRFR >= 3){ $nCost = 23; } } if($method == "01" || $method == "13"){ $nCost = 30; if($this->_totalRFR >= 3){ $nCost = 40; } } $nPrice = $nCost; $this->_rateShopPrice[$method]['cost'] -= $costArr[$method]; $this->_rateShopPrice[$method]['price'] -= $price; $this->_rateShopPrice[$method]['cost'] += $nCost; $this->_rateShopPrice[$method]['price'] += $nPrice; } elseif($method == "03" && ($this->_currentVendor == 85 || $this->_currentVendor == 12)){ if($this->_rowTotalReman >= 1000){ $nCost = 0; } else{ $nCost = 7.99; } $nPrice = $nCost; $this->_rateShopPrice[$method]['cost'] -= $costArr[$method]; $this->_rateShopPrice[$method]['price'] -= $price; $this->_rateShopPrice[$method]['cost'] += $nCost; $this->_rateShopPrice[$method]['price'] += $nPrice; } }else { if($this->_currentVendor == 12 || $this->_currentVendor == 0 || $this->_currentVendor == 85) { if($this->_freeGround) { if($method == "03") { $nCost = 0; $nPrice = 0; $this->_rateShopPrice[$method]['cost'] -= $costArr[$method]; $this->_rateShopPrice[$method]['price'] -= $price; $this->_rateShopPrice[$method]['cost'] += $nCost; $this->_rateShopPrice[$method]['price'] += $nPrice; } }else if($this->_newShipRule == 1) { $nCost = 0; $nPrice = 0; $this->_rateShopPrice[$method]['cost'] -= $costArr[$method]; $this->_rateShopPrice[$method]['price'] -= $price; $this->_rateShopPrice[$method]['cost'] += $nCost; $this->_rateShopPrice[$method]['price'] += $nPrice; }else if($this->_newShipRule == 2) { }else if($this->_newShipRule == 3) { }else if($this->_currentVendor == 0){ } } } /*Store Level Logic for Custom Shipping Changes Ends */ $cost = $this->_rateShopPrice[$method]['cost']; $price = $this->_rateShopPrice[$method]['price']; } } return $this->setRatePriceData($priceArr, $costArr, $errorTitle); } /** * Set Rate Response Price Data * * @param array $priceArr * @param array $costArr * @param string $errorTitle * @return Result */ private function setRatePriceData($priceArr, $costArr, $errorTitle) { $result = $this->_rateFactory->create(); if (empty($priceArr)) { $error = $this->_rateErrorFactory->create(); $error->setCarrier('ups'); $error->setCarrierTitle($this->getConfigData('title')); if ($this->getConfigData('specificerrmsg') !== '') { $errorTitle = $this->getConfigData('specificerrmsg'); } $error->setErrorMessage($errorTitle); $result->append($error); } else { foreach ($priceArr as $method => $price) { $rate = $this->_rateMethodFactory->create(); $rate->setCarrier('ups'); $rate->setCarrierTitle($this->getConfigData('title')); $rate->setMethod($method); $methodArr = $this->getShipmentByCode($method); $rate->setMethodTitle($methodArr); $rate->setCost($costArr[$method]); $rate->setPrice($price); // $result->append($rate); } } return $result; } // Function to make a request to the UPS API public function makeUpsApiRequest($accessToken, $query, $request, $endpointurl) { $curl = curl_init(); $payload = $request; $endpointurl = $endpointurl; \Magento\Framework\App\ObjectManager::getInstance()->get(\Psr\Log\LoggerInterface::class)->debug('\n\n@@@@@ GET UPS ENDPOint url >>>> >>> ' . print_r($endpointurl,true)); curl_setopt_array($curl, [ CURLOPT_HTTPHEADER => [ "Authorization: Bearer $accessToken", "Content-Type: application/json", "transId: string", "transactionSrc: testing" ], CURLOPT_POSTFIELDS => json_encode($payload), //CURLOPT_URL => "https://wwwcie.ups.com/api/shipments/". $version. "/ship?". http_build_query($query), CURLOPT_URL => $endpointurl, CURLOPT_RETURNTRANSFER => true, CURLOPT_CUSTOMREQUEST => "POST", ]); $response = curl_exec($curl); $error = curl_error($curl); curl_close($curl); if ($error) { echo "cURL Error #:". $error; } else { return $response; } } /** * @return string */ public function getClientId(){ $configPath = 'carriers/ups/client_id'; $clientId = $this->_scopeConfig->getValue($configPath, \Magento\Store\Model\ScopeInterface::SCOPE_STORE); if (!$clientId) { throw new \Magento\Framework\Exception\LocalizedException(__('Client ID is not set in the Magento configuration.')); } return $clientId; } /** * @return string */ public function getSecretId(){ $configPath = 'carriers/ups/secret_id'; $secretId = $this->_scopeConfig->getValue($configPath, \Magento\Store\Model\ScopeInterface::SCOPE_STORE); if (!$secretId) { throw new \Magento\Framework\Exception\LocalizedException(__('Client ID is not set in the Magento configuration.')); } return $secretId; } }