From d9bbff7bbf4416ee9aca9d64ec57195aef7a3767 Mon Sep 17 00:00:00 2001
From: "@ChristelLoftus" <christel@bob.co.za>
Date: Tue, 13 Aug 2024 10:51:18 +0200
Subject: [PATCH] Add rates test on extension activation

---
 Model/Carrier/BobGo.php           | 91 ++++++++++++++++++++++++++++++-
 Observer/ConfigChangeObserver.php | 54 ++++++++++++++++++
 etc/acl.xml                       | 12 ++++
 etc/adminhtml/events.xml          |  7 +++
 etc/frontend/di.xml               |  7 +++
 etc/module.xml                    |  2 +
 6 files changed, 171 insertions(+), 2 deletions(-)
 create mode 100644 Observer/ConfigChangeObserver.php
 create mode 100644 etc/acl.xml
 create mode 100644 etc/adminhtml/events.xml

diff --git a/Model/Carrier/BobGo.php b/Model/Carrier/BobGo.php
index ee0dd13..7cf58db 100644
--- a/Model/Carrier/BobGo.php
+++ b/Model/Carrier/BobGo.php
@@ -101,6 +101,11 @@ class BobGo extends AbstractCarrierOnline implements \Magento\Shipping\Model\Car
      */
     protected \Magento\Framework\HTTP\Client\Curl $curl;
 
+    /**
+     * @var ScopeConfigInterface
+     */
+    protected $scopeConfig;  // Declare the scopeConfig property
+
 
     /**
      * @param \Magento\Framework\Controller\Result\JsonFactory $jsonFactory
@@ -161,6 +166,7 @@ class BobGo extends AbstractCarrierOnline implements \Magento\Shipping\Model\Car
 
         $this->_storeManager = $storeManager;
         $this->_productCollectionFactory = $productCollectionFactory;
+        $this->scopeConfig = $scopeConfig;
         parent::__construct(
             $scopeConfig,
             $rateErrorFactory,
@@ -293,6 +299,7 @@ class BobGo extends AbstractCarrierOnline implements \Magento\Shipping\Model\Car
         if (!$this->isActive()) {
             return false;
         }
+
         /**
          * Gets the destination company name from Company Name field in the checkout page
          * This method is used is the last resort to get the company name since the company name is not available in _rateFactory
@@ -834,8 +841,6 @@ class BobGo extends AbstractCarrierOnline implements \Magento\Shipping\Model\Car
 
                         $this->deliveryDays($min_delivery_date, $max_delivery_date, $method);
 
-                    } else {
-                        $method->setCarrierTitle($this->getConfigData('title'));
                     }
 
                 }
@@ -1048,4 +1053,86 @@ class BobGo extends AbstractCarrierOnline implements \Magento\Shipping\Model\Car
         }
         return true;
     }
+
+    public function triggerRatesTest()
+    {
+        // Check if the 'Show rates for checkout' setting is enabled
+        $isEnabled = $this->scopeConfig->getValue('carriers/bobgo/active', \Magento\Store\Model\ScopeInterface::SCOPE_STORE);
+
+        if ($isEnabled) {
+            // Sample test payload, replace with actual structure
+            $payload = [
+                'identifier' => $this->getBaseUrl(),
+                'rate' => [
+                    'origin' => [
+                        'company' => 'Test Store',
+                        'address1' => '123 Test St',
+                        'address2' => '',
+                        'city' => 'Test City',
+                        'suburb' => 'Test Suburb',
+                        'province' => 'Test Province',
+                        'country_code' => 'ZA',
+                        'postal_code' => '2000',
+                    ],
+                    'destination' => [
+                        'company' => 'Test Company',
+                        'address1' => '456 Test Ave',
+                        'address2' => '',
+                        'suburb' => 'Test Suburb',
+                        'city' => 'Test City',
+                        'province' => 'Test Province',
+                        'country_code' => 'ZA',
+                        'postal_code' => '3000',
+                    ],
+                    'items' => [
+                        [
+                            'sku' => 'test-sku-1',
+                            'quantity' => 1,
+                            'price' => 100.00,
+                            'weight' => 500, // in grams
+                        ]
+                    ],
+                ]
+            ];
+
+            try {
+                // Perform the API request
+                $this->curl->addHeader('Content-Type', 'application/json');
+                $this->curl->post($this->getApiUrl(), json_encode($payload));
+                $statusCode = $this->curl->getStatus();
+                $responseBody = $this->curl->getBody();
+
+                // Log the response for debugging purposes
+                $this->_logger->info('BobGo Rates API Test Response: ' . $responseBody);
+
+                // Decode the response
+                $response = json_decode($responseBody, true);
+
+                // Check if the response contains a 'message' (indicating an error)
+                if (isset($response['message'])) {
+                    throw new \Exception('Error from BobGo: ' . $response['message']);
+                }
+
+                // Check if the response contains rates with a valid id field
+                if (isset($response['rates']) && is_array($response['rates']) && !empty($response['rates'])) {
+                    foreach ($response['rates'] as $rate) {
+                        if (isset($rate['id']) && $rate['id'] !== null) {
+                            $this->_logger->info('Rates received successfully with a valid id.');
+                            return $response; // Successful response with a valid id
+                        }
+                    }
+                    throw new \Exception('Rates received but id field is empty or invalid.');
+                } else {
+                    throw new \Exception('Received response but no valid rates were found.');
+                }
+            } catch (\Exception $e) {
+                $this->_logger->error('Error in triggerRatesTest: ' . $e->getMessage());
+                return false;
+            }
+        }
+
+        return false;
+    }
+
+
 }
diff --git a/Observer/ConfigChangeObserver.php b/Observer/ConfigChangeObserver.php
new file mode 100644
index 0000000..42a0fe6
--- /dev/null
+++ b/Observer/ConfigChangeObserver.php
@@ -0,0 +1,54 @@
+<?php
+
+namespace BobGroup\BobGo\Observer;
+
+use Magento\Framework\Event\Observer;
+use Magento\Framework\Event\ObserverInterface;
+use Magento\Framework\Message\ManagerInterface;
+use Psr\Log\LoggerInterface;
+use BobGroup\BobGo\Model\Carrier\BobGo;
+
+class ConfigChangeObserver implements ObserverInterface
+{
+    protected $bobGo;
+    protected $logger;
+    protected $messageManager;
+
+    public function __construct(
+        BobGo $bobGo,
+        LoggerInterface $logger,
+        ManagerInterface $messageManager
+    ) {
+        $this->bobGo = $bobGo;
+        $this->logger = $logger;
+        $this->messageManager = $messageManager;
+    }
+
+    public function execute(Observer $observer)
+    {
+        $this->logger->info('ConfigChangeObserver triggered.');
+
+        $changedPaths = $observer->getEvent()->getData('changed_paths');
+
+        if (is_array($changedPaths) && in_array('carriers/bobgo/active', $changedPaths)) {
+            $this->logger->info('BobGo configuration change detected.');
+
+            if ($this->bobGo->isActive()) {
+                $result = $this->bobGo->triggerRatesTest();
+
+                if ($result !== false) {
+                    $this->logger->info('Rates test triggered successfully with a valid response.');
+                    $this->messageManager->addSuccessMessage(__('BobGo rates test triggered successfully.'));
+                } else {
+                    $this->logger->error('Error in BobGo rates test.');
+                    $this->messageManager->addErrorMessage(__('BobGo rates test failed. Please check visit https://www.bobgo.co.za/ and enable this channel for rates at checkout.'));
+                }
+            } else {
+                $this->logger->info('BobGo is not active.');
+            }
+        } else {
+            $this->logger->info('No relevant configuration changes detected.');
+        }
+    }
+
+}
diff --git a/etc/acl.xml b/etc/acl.xml
new file mode 100644
index 0000000..4abc946
--- /dev/null
+++ b/etc/acl.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0"?>
+<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+        xsi:noNamespaceSchemaLocation="urn:magento:framework:Acl/etc/acl.xsd">
+    <acl>
+        <resources>
+            <!-- Define at least one minimal resource -->
+            <resource id="Magento_Backend::admin">
+                <!-- You can leave this empty if you don't want to define specific permissions -->
+            </resource>
+        </resources>
+    </acl>
+</config>
diff --git a/etc/adminhtml/events.xml b/etc/adminhtml/events.xml
new file mode 100644
index 0000000..1fac000
--- /dev/null
+++ b/etc/adminhtml/events.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0"?>
+<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
+    <event name="admin_system_config_changed_section_carriers">
+        <observer name="bobgo_config_change_observer" instance="BobGroup\BobGo\Observer\ConfigChangeObserver" />
+    </event>
+
+</config>
diff --git a/etc/frontend/di.xml b/etc/frontend/di.xml
index 2ee6f54..f424156 100644
--- a/etc/frontend/di.xml
+++ b/etc/frontend/di.xml
@@ -7,4 +7,11 @@
             </argument>
         </arguments>
     </type>
+    <type name="BobGroup\BobGo\Observer\ConfigChangeObserver">
+        <arguments>
+            <argument name="scopeConfig" xsi:type="object">Magento\Framework\App\Config\ScopeConfigInterface</argument>
+            <argument name="logger" xsi:type="object">Psr\Log\LoggerInterface</argument>
+        </arguments>
+    </type>
+
 </config>
diff --git a/etc/module.xml b/etc/module.xml
index d736136..5e262c8 100644
--- a/etc/module.xml
+++ b/etc/module.xml
@@ -15,6 +15,8 @@
             <module name="Magento_Sales"/>
             <module name="Magento_Quote"/>
             <module name="Magento_SalesRule"/>
+            <module name="Magento_Config"/>
+            <module name="Magento_Shipping"/>
         </sequence>
     </module>
 </config>
-- 
GitLab