Parcourir la source

Ticket #4711 - Providers for Automations.

AntonLV il y a 2 ans
Parent
commit
c2390c4f7f

+ 38 - 0
agents.php

@@ -0,0 +1,38 @@
+<?php
+/**
+ * Copyright (c) UNA, Inc - https://una.io
+ * MIT License - https://opensource.org/licenses/MIT
+ *
+ * @defgroup    UnaCore UNA Core
+ * @{
+ */
+
+require_once('./inc/header.inc.php');
+require_once(BX_DIRECTORY_PATH_INC . "utils.inc.php");
+
+bx_import('BxDolLanguages');
+
+/**
+ * Work with Providers
+ */
+if(($iProviderId = bx_get('p')) !== false) {
+    $iProviderId = bx_process_input($iProviderId, BX_DATA_INT);
+    if(!$iProviderId)
+        exit;
+
+    $oProvider = BxDolAIProvider::getObjectInstance($iProviderId);
+    if(!$oProvider)
+        exit;
+
+    if(($sAction = bx_get('a')) !== false) {
+        $sAction = 'processAction' . bx_gen_method_name(bx_process_input($sAction));
+        if(method_exists($oProvider, $sAction))
+            $oProvider->$sAction();
+    }
+    else {
+        $mixedResponce = $oProvider->call('products/7433953116300.json', ['fields' => 'id,title,handle,body_html,tags,variants'], 'get');
+        print_r($mixedResponce);
+    }
+}
+
+/** @} */

+ 21 - 13
inc/classes/BxDolAIProvider.php

@@ -9,6 +9,7 @@
 
 class BxDolAIProvider extends BxDol
 {
+    protected $_oDb;
     protected $_iId;
     protected $_sName;
     protected $_sCaption;
@@ -19,15 +20,15 @@ class BxDolAIProvider extends BxDol
     {
         parent::__construct();
 
-        if(empty($aProvider) || !is_array($aProvider) || strcmp($aProvider['name'], $this->_sName) != 0)
+        if(empty($aProvider) || !is_array($aProvider) || strcmp($aProvider['type']['name'], $this->_sName) != 0)
             $this->_log("Unexpected value provided for the credentials");
 
         $this->_oDb = new BxDolAIQuery();
 
         $this->_iId = (int)$aProvider['id'];
-        $this->_sName = $aProvider['name'];
-        $this->_sCaption = _t($aProvider['caption']);
-        $this->_sPrefix = $aProvider['option_prefix'];
+        $this->_sName = $aProvider['type']['name'];
+        $this->_sCaption = _t($aProvider['title']);
+        $this->_sPrefix = $aProvider['type']['option_prefix'];
 
         $this->_aOptions = [];
         if(!empty($aProvider['options']) && is_array($aProvider['options']))
@@ -47,18 +48,18 @@ class BxDolAIProvider extends BxDol
             return $GLOBALS['bxDolClasses'][$sPrefix . $iId];
 
         $aProvider = BxDolAIQuery::getProviderObject($iId);
-        if (!$aProvider || !is_array($aProvider))
+        if(!$aProvider || !is_array($aProvider))
             return false;
 
         $sClass = 'BxDolAIProvider';
-        if(!empty($aObject['class_name'])) {
-            $sClass = $aObject['class_name'];
-            if(!empty($aObject['class_file']))
-                require_once(BX_DIRECTORY_PATH_ROOT . $aObject['class_file']);
+        if(!empty($aProvider['type']['class_name'])) {
+            $sClass = $aProvider['type']['class_name'];
+            if(!empty($aProvider['type']['class_file']))
+                require_once(BX_DIRECTORY_PATH_ROOT . $aProvider['type']['class_file']);
         }
 
         $o = new $sClass($aProvider);
-        return ($GLOBALS['bxDolClasses'][$sPrefix . $sObject] = $o);
+        return ($GLOBALS['bxDolClasses'][$sPrefix . $iId] = $o);
     }
 
     public function initOptions($aOptions)
@@ -74,12 +75,19 @@ class BxDolAIProvider extends BxDol
         return isset($this->_aOptions[$sName]) ? $this->_aOptions[$sName]['value'] : '';
     }
 
+    public function processActionWebhook()
+    {
+        // Should be overwritten to process webhooks.
+    }
+
+    public function call($sRequest, $aParams, $sMethod = 'post-json', $aHeaders = [])
+    {
+        // Should be overwritten to process calls.
+    }
+
     /**
      * Internal methods.
      */
-    protected function _call($sRequest, $aParams, $sMethod = 'post-json', $aHeaders = [])
-    {}
-
     protected function _log($sMessage, $bUseLog = false)
     {
         if($bUseLog) {

+ 22 - 11
inc/classes/BxDolAIProviderShopifyAdmin.php

@@ -38,11 +38,11 @@ class BxDolAIProviderShopifyAdmin extends BxDolAIProvider
     protected $_sEndpoint;
     protected $_sStorefront;
 
-    public function __construct($iProfile, $aSource)
+    public function __construct($aProvider)
     {
         $this->_sName = self::$NAME;
 
-        parent::__construct($iProfile, $aSource);
+        parent::__construct($aProvider);
 
         $this->_sShopDomain = $this->getOption('shop_domain');
         $this->_sAccessToken = $this->getOption('access_token');
@@ -53,9 +53,7 @@ class BxDolAIProviderShopifyAdmin extends BxDolAIProvider
 
     public function getEntry($sId)
     {
-        $CNF = &$this->_oModule->_oConfig->CNF;
-
-        $sProduct = $this->_call('products/' . $sId . '.json', [
+        $sProduct = $this->call('products/' . $sId . '.json', [
             'fields' => 'id,title,handle,body_html,tags,variants',
         ], 'get');
         
@@ -69,10 +67,12 @@ class BxDolAIProviderShopifyAdmin extends BxDolAIProvider
         return $aProduct['product'];
     }
 
-    /**
-     * Internal methods.
-     */
-    protected function _call($sRequest, $aParams, $sMethod = 'post-json', $aHeaders = [])
+    public function processActionWebhook()
+    {
+        echo 'TODO: Webhook processing here';
+    }
+
+    public function call($sRequest, $aParams, $sMethod = 'post-json', $aHeaders = [])
     {
         $aHeaders[] = 'Content-Type: application/json';
         if(!empty($this->_sAccessToken))
@@ -80,9 +80,20 @@ class BxDolAIProviderShopifyAdmin extends BxDolAIProvider
         else
             $aHeaders[] = 'Authorization: Basic ' . base64_encode($this->_sApiKey . ':' . $this->_sApiSecretKey);
 
-        return bx_file_get_contents($this->_sEndpoint . $sRequest, $aParams, $sMethod, $aHeaders);
+        $sResponse = bx_file_get_contents($this->_sEndpoint . $sRequest, $aParams, $sMethod, $aHeaders);
+        if(empty($sResponse))
+            return false;
+        
+        $aResponse = json_decode($sResponse, true);
+        if(empty($aResponse) || !is_array($aResponse))
+            return false;
+
+        return $aResponse;
     }
-    
+
+    /**
+     * Internal methods.
+     */    
     protected function _dateI2S($iTimestamp)
     {
         return date("Y-m-d", $iTimestamp);

+ 1 - 1
inc/classes/BxDolAIQuery.php

@@ -37,7 +37,7 @@ class BxDolAIQuery extends BxDolDb
             LEFT JOIN `sys_agents_providers_values` AS `tpv` ON `tpo`.`id` = `tpv`.`option_id` AND `tpv`.`provider_id` = :provider_id
             WHERE 1 ORDER BY `tpo`.`order`";
 
-        $aProvider['options'] = $this->getAllWithKey($sQuery, 'name', [
+        $aProvider['options'] = $oDb->getAllWithKey($sQuery, 'name', [
             'provider_id' => $iId
         ]);
 

+ 1 - 1
install/sql/system.sql

@@ -6377,7 +6377,7 @@ INSERT INTO `sys_agents_provider_types`(`name`, `title`, `option_prefix`, `activ
 ('shopify_admin', '_sys_agents_pvd_cpt_shopify_admin', 'shf_adm_', 1, 1, 'BxDolAIProviderShopifyAdmin', '');
 SET @iProviderId = LAST_INSERT_ID();
 
-INSERT INTO `sys_agents_provider_options`(`provider_type_id`, `name`, `type`, `caption`, `description`, `extra`, `check_type`, `check_params`, `check_error`, `order`) VALUES
+INSERT INTO `sys_agents_provider_options`(`provider_type_id`, `name`, `type`, `title`, `description`, `extra`, `check_type`, `check_params`, `check_error`, `order`) VALUES
 (@iProviderId, 'shf_adm_shop_domain', 'text', '_sys_agents_pvd_opt_cpt_shop_domain', '_sys_agents_pvd_opt_dsc_shop_domain', '', '', '', '', 1),
 (@iProviderId, 'shf_adm_access_token', 'text', '_sys_agents_pvd_opt_cpt_access_token', '_sys_agents_pvd_opt_dsc_access_token', '', '', '', '', 2);
 

+ 9 - 6
studio/template/scripts/BxBaseStudioAgentsAutomators.php

@@ -180,19 +180,22 @@ class BxBaseStudioAgentsAutomators extends BxDolStudioAgentsAutomators
             $aValsToAdd = [];
 
             $aProvidersIds = $oForm->getCleanValue('providers_ids');
+            $bProvidersIds = !empty($aProvidersIds) && is_array($aProvidersIds);
             $aProvidersValues = $oForm->getCleanValue('providers');
+            $bProvidersValues = !empty($aProvidersValues) && is_array($aProvidersValues);
 
             //--- Remove deleted
-            $this->_oDb->deleteAutomatorProvidersById(array_diff(array_keys($aAutomator['providers']), $aProvidersIds));
+            if(!empty($aAutomator['providers']) && is_array($aAutomator['providers']))
+                $this->_oDb->deleteAutomatorProvidersById(array_diff(array_keys($aAutomator['providers']), $aProvidersIds));
 
             //--- Update existed
-            foreach($aProvidersIds as $iIndex => $iApId)
-                $this->_oDb->updateAutomatorProvider(['provider_id' => (int)$aProvidersValues[$iIndex]], ['id' => (int)$iApId]);
-
+            if($bProvidersIds)
+                foreach($aProvidersIds as $iIndex => $iApId)
+                    $this->_oDb->updateAutomatorProvider(['provider_id' => (int)$aProvidersValues[$iIndex]], ['id' => (int)$iApId]);
 
             //--- Add new
-            $iProvidersIds = count($aProvidersIds);
-            $iProvidersValues = count($aProvidersValues);
+            $iProvidersIds = $bProvidersIds ? count($aProvidersIds) : 0;
+            $iProvidersValues = $bProvidersValues ? count($aProvidersValues) : 0;
             if($iProvidersValues > $iProvidersIds) {
                 $aProvidersValues = array_slice($aProvidersValues, $iProvidersIds);
                 foreach($aProvidersValues as $iProvidersValue)