From a6abd523bbfb8c113488655f051574ccc2a68594 Mon Sep 17 00:00:00 2001 From: Akolzin Dmitry Date: Wed, 29 Aug 2018 17:45:35 +0300 Subject: [PATCH] Add enitities for customers and orders --- composer.json | 6 +- .../controller/extension/module/retailcrm.php | 400 ++-- .../model/extension/retailcrm/history/v3.php | 117 -- .../model/extension/retailcrm/prices.php | 62 +- .../model/extension/retailcrm/references.php | 107 +- .../template/extension/module/retailcrm.tpl | 600 ------ .../controller/extension/module/retailcrm.php | 152 +- .../library/retailcrm/OpencartApiClient.php | 29 +- .../library/retailcrm/RetailcrmApiClient3.php | 831 -------- .../library/retailcrm/RetailcrmApiClient4.php | 1771 ----------------- .../retailcrm/{ => api}/CurlException.php | 0 .../{ => api}/InvalidJsonException.php | 0 .../{ => api}/RetailcrmApiClient5.php | 0 .../{ => api}/RetailcrmApiResponse.php | 0 .../{ => api}/RetailcrmHttpClient.php | 0 .../retailcrm/{ => api}/RetailcrmProxy.php | 16 +- .../library/retailcrm/{ => api}/bootstrap.php | 0 src/upload/system/library/retailcrm/base.php | 140 ++ .../system/library/retailcrm/customer.php | 65 + src/upload/system/library/retailcrm/order.php | 241 +++ .../system/library/retailcrm/retailcrm.php | 87 +- tests/admin/ControllerRetailcrmAdminTest.php | 2 +- tests/admin/ModelRetailcrmOrderAdminTest.php | 2 +- tests/admin/ModelRetailcrmPricesAdminTest.php | 2 +- .../ControllerRetailcrmApiCatalogTest.php | 2 +- .../ModelRetailcrmOrderCatalogTest.php | 2 +- 26 files changed, 796 insertions(+), 3838 deletions(-) delete mode 100644 src/upload/admin/model/extension/retailcrm/history/v3.php delete mode 100644 src/upload/admin/view/template/extension/module/retailcrm.tpl delete mode 100644 src/upload/system/library/retailcrm/RetailcrmApiClient3.php delete mode 100644 src/upload/system/library/retailcrm/RetailcrmApiClient4.php rename src/upload/system/library/retailcrm/{ => api}/CurlException.php (100%) rename src/upload/system/library/retailcrm/{ => api}/InvalidJsonException.php (100%) rename src/upload/system/library/retailcrm/{ => api}/RetailcrmApiClient5.php (100%) rename src/upload/system/library/retailcrm/{ => api}/RetailcrmApiResponse.php (100%) rename src/upload/system/library/retailcrm/{ => api}/RetailcrmHttpClient.php (100%) rename src/upload/system/library/retailcrm/{ => api}/RetailcrmProxy.php (76%) rename src/upload/system/library/retailcrm/{ => api}/bootstrap.php (100%) create mode 100644 src/upload/system/library/retailcrm/base.php create mode 100644 src/upload/system/library/retailcrm/customer.php create mode 100644 src/upload/system/library/retailcrm/order.php diff --git a/composer.json b/composer.json index b541a38..e4499f4 100644 --- a/composer.json +++ b/composer.json @@ -10,10 +10,10 @@ } ], "require-dev": { - "opencart/opencart" : "2.3.0.2", + "opencart/opencart" : "3.0.2.0", "vlucas/phpdotenv": "~1.1.0", - "phpunit/phpunit" : "~4.0", - "beyondit/opencart-test-suite": "~2.3.0", + "phpunit/phpunit" : "^6", + "beyondit/opencart-test-suite": "~3.0", "consolidation/robo": "~1", "henrikbjorn/lurker": "^1.2" }, diff --git a/src/upload/admin/controller/extension/module/retailcrm.php b/src/upload/admin/controller/extension/module/retailcrm.php index 8a11213..7be03e2 100644 --- a/src/upload/admin/controller/extension/module/retailcrm.php +++ b/src/upload/admin/controller/extension/module/retailcrm.php @@ -9,19 +9,7 @@ * @license https://opensource.org/licenses/MIT MIT License * @link http://www.retailcrm.ru/docs/Developers/ApiVersion5 */ -class ControllerExtensionModuleRetailcrm extends Controller -{ - private $_error = array(); - protected $log, $statuses, $payments, $deliveryTypes, $retailcrmApiClient, $moduleTitle, $tokenTitle; - public $children, $template; - - public function __construct($registry) - { - parent::__construct($registry); - $this->load->library('retailcrm/retailcrm'); - $this->moduleTitle = $this->retailcrm->getModuleTitle(); - $this->tokenTitle = $this->retailcrm->getTokenTitle(); - } +class ControllerExtensionModuleRetailcrm extends Controller { /** * Install method @@ -33,10 +21,10 @@ class ControllerExtensionModuleRetailcrm extends Controller $this->load->model('setting/setting'); $this->model_setting_setting->editSetting( - $this->moduleTitle, + \Retailcrm\Retailcrm::MODULE, array( - $this->moduleTitle . '_status' => 1, - $this->moduleTitle . '_country' => array($this->config->get('config_country_id')) + \Retailcrm\Retailcrm::MODULE . '_status' => 1, + \Retailcrm\Retailcrm::MODULE . '_country' => array($this->config->get('config_country_id')) ) ); @@ -53,8 +41,8 @@ class ControllerExtensionModuleRetailcrm extends Controller $this->uninstall_collector(); $this->load->model('setting/setting'); $this->model_setting_setting->editSetting( - $this->moduleTitle, - array($this->moduleTitle . '_status' => 0) + \Retailcrm\Retailcrm::MODULE, + array(\Retailcrm\Retailcrm::MODULE . '_status' => 0) ); $this->model_setting_setting->deleteSetting('retailcrm_history'); $this->deleteEvents(); @@ -66,12 +54,14 @@ class ControllerExtensionModuleRetailcrm extends Controller * @return void */ public function install_collector() - { - $collector = $this->getCollectorTitle(); - $this->loadModels(); + { $this->load->model('setting/setting'); - $this->{'model_' . $this->modelExtension}->install('analytics', 'daemon_collector'); - $this->model_setting_setting->editSetting($collector, array($collector . '_status' => 1)); + $this->load->model('setting/extension'); + $this->model_setting_extension->install('analytics', 'daemon_collector'); + $this->model_setting_setting->editSetting( + 'analytics_daemon_collector', + array('analytics_daemon_collector_status' => 1) + ); } /** @@ -80,12 +70,14 @@ class ControllerExtensionModuleRetailcrm extends Controller * @return void */ public function uninstall_collector() - { - $collector = $this->getCollectorTitle(); - $this->loadModels(); + { $this->load->model('setting/setting'); - $this->model_setting_setting->editSetting($collector, array($collector . '_status' => 0)); - $this->{'model_' . $this->modelExtension}->uninstall('analytics', 'daemon_collector'); + $this->load->model('setting/extension'); + $this->model_setting_setting->editSetting( + 'analytics_daemon_collector', + array('analytics_daemon_collector_status' => 0) + ); + $this->model_setting_extension->uninstall('analytics', 'daemon_collector'); } /** @@ -95,7 +87,9 @@ class ControllerExtensionModuleRetailcrm extends Controller */ public function index() { - $this->loadModels(); + $this->load->library('retailcrm/retailcrm'); + $this->load->model('setting/extension'); + $this->load->model('setting/event'); $this->load->model('localisation/country'); $this->load->model('setting/setting'); $this->load->model('extension/retailcrm/references'); @@ -103,8 +97,9 @@ class ControllerExtensionModuleRetailcrm extends Controller $this->document->setTitle($this->language->get('heading_title')); $this->document->addStyle('/admin/view/stylesheet/retailcrm.css'); - $collector = $this->getCollectorTitle(); $history_setting = $this->model_setting_setting->getSetting('retailcrm_history'); + $retailcrm_api_client = $this->retailcrm->getApiClient(); + $opencart_api_client = $this->retailcrm->getOcApiClient($this->registry); if ($this->request->server['REQUEST_METHOD'] == 'POST' && $this->validate()) { if ($this->checkEvents() === false) { @@ -112,81 +107,49 @@ class ControllerExtensionModuleRetailcrm extends Controller $this->addEvents(); } - $analytics = $this->{'model_' . $this->modelExtension}->getInstalled('analytics'); + $analytics = $this->model_setting_extension->getInstalled('analytics'); - if ($this->request->post[$this->moduleTitle . '_collector_active'] == 1 - && !in_array($collector, $analytics) + if ($this->request->post[\Retailcrm\Retailcrm::MODULE . '_collector_active'] == 1 + && !in_array('analytics_daemon_collector', $analytics) ) { $this->install_collector(); - } elseif ($this->request->post[$this->moduleTitle . '_collector_active'] == 0 - && in_array($collector, $analytics) + } elseif ($this->request->post[\Retailcrm\Retailcrm::MODULE . '_collector_active'] == 0 + && in_array('analytics_daemon_collector', $analytics) ) { $this->uninstall_collector(); } - if (parse_url($this->request->post[$this->moduleTitle . '_url'])) { - $crm_url = parse_url($this->request->post[$this->moduleTitle . '_url'], PHP_URL_HOST); - $this->request->post[$this->moduleTitle . '_url'] = 'https://' . $crm_url; + if (parse_url($this->request->post[\Retailcrm\Retailcrm::MODULE . '_url'])) { + $crm_url = parse_url($this->request->post[\Retailcrm\Retailcrm::MODULE . '_url'], PHP_URL_HOST); + $this->request->post[\Retailcrm\Retailcrm::MODULE . '_url'] = 'https://' . $crm_url; } - if (isset($this->request->post[$this->moduleTitle . '_custom_field_active']) - && $this->request->post[$this->moduleTitle . '_custom_field_active'] == 0 + if (isset($this->request->post[\Retailcrm\Retailcrm::MODULE . '_custom_field_active']) + && $this->request->post[\Retailcrm\Retailcrm::MODULE . '_custom_field_active'] == 0 ) { - unset($this->request->post[$this->moduleTitle . '_custom_field']); + unset($this->request->post[\Retailcrm\Retailcrm::MODULE . '_custom_field']); } $this->model_setting_setting->editSetting( - $this->moduleTitle, + \Retailcrm\Retailcrm::MODULE, $this->request->post ); - if ($this->request->post[$this->moduleTitle . '_apiversion'] != 'v3') { - if (!isset($history_setting['retailcrm_history_orders']) && !isset($history_setting['retailcrm_history_customers'])) { - $api = $this->retailcrm->getApiClient( - $this->request->post[$this->moduleTitle . '_url'], - $this->request->post[$this->moduleTitle . '_apikey'], - $this->request->post[$this->moduleTitle . '_apiversion'] - ); + if (!isset($history_setting['retailcrm_history_orders']) + && !isset($history_setting['retailcrm_history_customers']) + ) { + $api = $this->retailcrm->getApiClient( + $this->request->post[\Retailcrm\Retailcrm::MODULE . '_url'], + $this->request->post[\Retailcrm\Retailcrm::MODULE . '_apikey'], + $this->request->post[\Retailcrm\Retailcrm::MODULE . '_apiversion'] + ); - $ordersHistory = $api->ordersHistory(); - - if ($ordersHistory->isSuccessful() && !empty($ordersHistory['history'])) { - $ordersHistory = $api->ordersHistory(array(), $ordersHistory['pagination']['totalPageCount']); - - if ($ordersHistory->isSuccessful()) { - $ordersHistoryArr = $ordersHistory['history']; - $lastChangeOrders = end($ordersHistoryArr); - $sinceIdOrders = $lastChangeOrders['id']; - $generatedAt = $ordersHistory['generatedAt']; - } - } - - $customersHistory = $api->customersHistory(); - - if ($customersHistory->isSuccessful() && !empty($customersHistory['history'])) { - $customersHistory = $api->customersHistory(array(), $customersHistory['pagination']['totalPageCount']); - - if ($customersHistory->isSuccessful()) { - $customersHistoryArr = $customersHistory['history']; - $lastChangeCustomers = end($customersHistoryArr); - $sinceIdCustomers = $lastChangeCustomers['id']; - } - } - - $this->model_setting_setting->editSetting( - 'retailcrm_history', - array( - 'retailcrm_history_orders' => isset($sinceIdOrders) ? $sinceIdOrders : 1, - 'retailcrm_history_customers' => isset($sinceIdCustomers) ? $sinceIdCustomers : 1, - 'retailcrm_history_datetime' => isset($generatedAt) ? $generatedAt : date('Y-m-d H:i:s') - ) - ); - } + $this->getHistory($api); } $this->session->data['success'] = $this->language->get('text_success'); $redirect = $this->url->link( - 'extension/module/retailcrm', $this->tokenTitle . '=' . $this->session->data[$this->tokenTitle], + 'extension/module/retailcrm', 'user_token=' . $this->session->data['user_token'], 'SSL' ); @@ -254,48 +217,34 @@ class ControllerExtensionModuleRetailcrm extends Controller 'text_order_number' ); - $_data = &$data; - foreach ($text_strings as $text) { $_data[$text] = $this->language->get($text); } $_data['retailcrm_errors'] = array(); $_data['saved_settings'] = $this->model_setting_setting - ->getSetting($this->moduleTitle); + ->getSetting(\Retailcrm\Retailcrm::MODULE); - $url = isset($_data['saved_settings'][$this->moduleTitle . '_url']) - ? $_data['saved_settings'][$this->moduleTitle . '_url'] + $url = isset($_data['saved_settings'][\Retailcrm\Retailcrm::MODULE . '_url']) + ? $_data['saved_settings'][\Retailcrm\Retailcrm::MODULE . '_url'] : null; - $key = isset($_data['saved_settings'][$this->moduleTitle . '_apikey']) - ? $_data['saved_settings'][$this->moduleTitle . '_apikey'] - : null; - $apiVersion = isset($_data['saved_settings'][$this->moduleTitle . '_apiversion']) - ? $_data['saved_settings'][$this->moduleTitle . '_apiversion'] + $key = isset($_data['saved_settings'][\Retailcrm\Retailcrm::MODULE . '_apikey']) + ? $_data['saved_settings'][\Retailcrm\Retailcrm::MODULE . '_apikey'] : null; if (!empty($url) && !empty($key)) { - $_data['delivery'] = $this->model_extension_retailcrm_references - ->getDeliveryTypes(); + ->getDeliveryTypes($opencart_api_client ,$retailcrm_api_client); $_data['statuses'] = $this->model_extension_retailcrm_references - ->getOrderStatuses(); + ->getOrderStatuses($retailcrm_api_client); $_data['payments'] = $this->model_extension_retailcrm_references - ->getPaymentTypes(); - - if ($apiVersion == 'v5') { - $_data['customFields'] = $this->model_extension_retailcrm_references - ->getCustomFields(); - } - - if ($apiVersion != 'v3') { - $_data['priceTypes'] = $this->model_extension_retailcrm_references - ->getPriceTypes(); - } + ->getPaymentTypes($retailcrm_api_client); + $_data['customFields'] = $this->model_extension_retailcrm_references + ->getCustomFields($retailcrm_api_client); } $config_data = array( - $this->moduleTitle . '_status' + \Retailcrm\Retailcrm::MODULE . '_status' ); foreach ($config_data as $conf) { @@ -318,7 +267,7 @@ class ControllerExtensionModuleRetailcrm extends Controller 'text' => $this->language->get('text_home'), 'href' => $this->url->link( 'common/dashboard', - $this->tokenTitle . '=' . $this->session->data[$this->tokenTitle], 'SSL' + 'user_token' . '=' . $this->session->data['user_token'], 'SSL' ), 'separator' => false ); @@ -327,7 +276,7 @@ class ControllerExtensionModuleRetailcrm extends Controller 'text' => $this->language->get('text_module'), 'href' => $this->url->link( 'extension/extension', - $this->tokenTitle . '=' . $this->session->data[$this->tokenTitle], 'SSL' + 'user_token' . '=' . $this->session->data['user_token'], 'SSL' ), 'separator' => ' :: ' ); @@ -336,19 +285,19 @@ class ControllerExtensionModuleRetailcrm extends Controller 'text' => $this->language->get('retailcrm_title'), 'href' => $this->url->link( 'extension/module/retailcrm', - $this->tokenTitle . '=' . $this->session->data[$this->tokenTitle], 'SSL' + 'user_token' . '=' . $this->session->data['user_token'], 'SSL' ), 'separator' => ' :: ' ); $_data['action'] = $this->url->link( 'extension/module/retailcrm', - $this->tokenTitle . '=' . $this->session->data[$this->tokenTitle], 'SSL' + 'user_token' . '=' . $this->session->data['user_token'], 'SSL' ); $_data['cancel'] = $this->url->link( - version_compare(VERSION, '3.0', '<') ? 'extension/extension' : 'marketplace/extension', - $this->tokenTitle . '=' . $this->session->data[$this->tokenTitle], 'SSL' + 'marketplace/extension', + 'user_token' . '=' . $this->session->data['user_token'], 'SSL' ); $_data['modules'] = array(); @@ -361,13 +310,12 @@ class ControllerExtensionModuleRetailcrm extends Controller $this->load->model('design/layout'); $_data['layouts'] = $this->model_design_layout->getLayouts(); - $_data['header'] = $this->load->controller('common/header'); $_data['column_left'] = $this->load->controller('common/column_left'); $_data['footer'] = $this->load->controller('common/footer'); $_data['countries'] = $this->model_localisation_country->getCountries(); $_data['catalog'] = $this->request->server['HTTPS'] ? HTTPS_CATALOG : HTTP_CATALOG; - $_data[$this->tokenTitle] = $this->request->get[$this->tokenTitle]; + $_data['user_token'] = $this->request->get['user_token']; if(file_exists(DIR_SYSTEM . '/cron/export_done')) { $_data['export_file'] = false; @@ -382,11 +330,15 @@ class ControllerExtensionModuleRetailcrm extends Controller ); $_data['collectorFields'] = $collectorFields; - $_data['api_versions'] = array('v3', 'v4', 'v5'); - $_data['default_apiversion'] = 'v4'; + $_data['api_versions'] = array('v5'); + $_data['default_apiversion'] = 'v5'; - $retailcrmLog = file_exists(DIR_SYSTEM . 'storage/logs/retailcrm.log') ? DIR_SYSTEM . 'storage/logs/retailcrm.log' : false; - $ocApiLog = file_exists(DIR_SYSTEM . 'storage/logs/opencartapi.log') ? DIR_SYSTEM . 'storage/logs/opencartapi.log' : false; + $retailcrmLog = file_exists(DIR_SYSTEM . 'storage/logs/retailcrm.log') + ? DIR_SYSTEM . 'storage/logs/retailcrm.log' + : false; + $ocApiLog = file_exists(DIR_SYSTEM . 'storage/logs/opencartapi.log') + ? DIR_SYSTEM . 'storage/logs/opencartapi.log' + : false; if ($this->checkLogFile($retailcrmLog) !== false) { $_data['logs']['retailcrm_log'] = $this->checkLogFile($retailcrmLog); @@ -400,8 +352,8 @@ class ControllerExtensionModuleRetailcrm extends Controller $_data['logs']['oc_error'] = $this->language->get('text_error_log'); } - $_data['clear_retailcrm'] = $this->url->link('extension/module/retailcrm/clear_retailcrm', $this->tokenTitle . '=' . $this->session->data[$this->tokenTitle], true); - $_data['clear_opencart'] = $this->url->link('extension/module/retailcrm/clear_opencart', $this->tokenTitle . '=' . $this->session->data[$this->tokenTitle], true); + $_data['clear_retailcrm'] = $this->url->link('extension/module/retailcrm/clear_retailcrm', 'user_token' . '=' . $this->session->data['user_token'], true); + $_data['clear_opencart'] = $this->url->link('extension/module/retailcrm/clear_opencart', 'user_token' . '=' . $this->session->data['user_token'], true); $_data['button_clear'] = $this->language->get('button_clear'); $this->response->setOutput( @@ -417,25 +369,12 @@ class ControllerExtensionModuleRetailcrm extends Controller */ public function history() { - $this->load->model('setting/setting'); - $settings = $this->model_setting_setting->getSetting($this->moduleTitle); - - if ($settings[$this->moduleTitle . '_apiversion'] == 'v3') { - if (file_exists(DIR_APPLICATION . 'model/extension/retailcrm/custom/history/v3.php')) { - $this->load->model('extension/retailcrm/custom/history/v3'); - $this->model_extension_retailcrm_custom_history_v3->request($this->retailcrm->getApiClient()); - } else { - $this->load->model('extension/retailcrm/history/v3'); - $this->model_extension_retailcrm_history_v3->request($this->retailcrm->getApiClient()); - } + if (file_exists(DIR_APPLICATION . 'model/extension/retailcrm/custom/history/v4-5.php')) { + $this->load->model('extension/retailcrm/custom/history/v4-5'); + $this->model_extension_retailcrm_custom_history_v4_5->request($this->retailcrm->getApiClient()); } else { - if (file_exists(DIR_APPLICATION . 'model/extension/retailcrm/custom/history/v4-5.php')) { - $this->load->model('extension/retailcrm/custom/history/v4-5'); - $this->model_extension_retailcrm_custom_history_v4_5->request($this->retailcrm->getApiClient()); - } else { - $this->load->model('extension/retailcrm/history/v4_5'); - $this->model_extension_retailcrm_history_v4_5->request($this->retailcrm->getApiClient()); - } + $this->load->model('extension/retailcrm/history/v4_5'); + $this->model_extension_retailcrm_history_v4_5->request($this->retailcrm->getApiClient()); } } @@ -464,7 +403,7 @@ class ControllerExtensionModuleRetailcrm extends Controller * @return void */ public function customer_edit($route, $customer) - { + { $this->load->model('localisation/country'); $this->load->model('localisation/zone'); $this->load->model('customer/customer'); @@ -487,7 +426,7 @@ class ControllerExtensionModuleRetailcrm extends Controller 'postcode' => $address['postcode'], 'iso_code_2' => $country['iso_code_2'], 'zone' => $zone['name'] - ); + ); } $this->load->model('extension/retailcrm/customer'); @@ -514,8 +453,8 @@ class ControllerExtensionModuleRetailcrm extends Controller if (!isset($data['fromApi'])) { $this->load->model('setting/setting'); - $status = $this->model_setting_setting->getSetting($this->moduleTitle); - $data['order_status'] = $status[$this->moduleTitle . '_status'][$data['order_status_id']]; + $status = $this->model_setting_setting->getSetting(\Retailcrm\Retailcrm::MODULE); + $data['order_status'] = $status[\Retailcrm\Retailcrm::MODULE . '_status'][$data['order_status_id']]; $this->load->model('extension/retailcrm/order'); $this->model_extension_retailcrm_order->uploadOrder($data, $this->retailcrm->getApiClient()); @@ -610,22 +549,20 @@ class ControllerExtensionModuleRetailcrm extends Controller private function validate() { $versionsMap = array( - 'v3' => '3.0', - 'v4' => '4.0', 'v5' => '5.0' ); - if (!empty($this->request->post[$this->moduleTitle . '_url']) && !empty($this->request->post[$this->moduleTitle . '_apikey'])) { + if (!empty($this->request->post[\Retailcrm\Retailcrm::MODULE . '_url']) && !empty($this->request->post[\Retailcrm\Retailcrm::MODULE . '_apikey'])) { $apiClient = $this->retailcrm->getApiClient( - $this->request->post[$this->moduleTitle . '_url'], - $this->request->post[$this->moduleTitle . '_apikey'] + $this->request->post[\Retailcrm\Retailcrm::MODULE . '_url'], + $this->request->post[\Retailcrm\Retailcrm::MODULE . '_apikey'] ); } - $response = $apiClient->apiVersions(); + $response = isset($apiClient) ? $apiClient->apiVersions() : false; if ($response && $response->isSuccessful()) { - if (!in_array($versionsMap[$this->request->post[$this->moduleTitle . '_apiversion']], $response['versions'])) { + if (!in_array($versionsMap[$this->request->post[\Retailcrm\Retailcrm::MODULE . '_apiversion']], $response['versions'])) { $this->_error['warning'] = $this->language->get('text_error_api'); } } else { @@ -636,9 +573,9 @@ class ControllerExtensionModuleRetailcrm extends Controller $this->_error['warning'] = $this->language->get('error_permission'); } - if (isset($this->request->post[$this->moduleTitle . '_collector']['custom']) && - $this->request->post[$this->moduleTitle . '_collector']['custom_form'] == 1) { - $customField = $this->request->post[$this->moduleTitle . '_collector']['custom']; + if (isset($this->request->post[\Retailcrm\Retailcrm::MODULE . '_collector']['custom']) && + $this->request->post[\Retailcrm\Retailcrm::MODULE . '_collector']['custom_form'] == 1) { + $customField = $this->request->post[\Retailcrm\Retailcrm::MODULE . '_collector']['custom']; if (empty($customField['name']) && empty($customField['email']) && empty($customField['phone'])) { $this->_error['fields'] = $this->language->get('text_error_collector_fields'); @@ -654,7 +591,7 @@ class ControllerExtensionModuleRetailcrm extends Controller /** * Clear retailcrm log file - * + * * @return void */ public function clear_retailcrm() @@ -667,12 +604,18 @@ class ControllerExtensionModuleRetailcrm extends Controller fclose($handle); } - $this->response->redirect($this->url->link('extension/module/retailcrm', $this->tokenTitle . '=' . $this->session->data[$this->tokenTitle], true)); + $this->response->redirect( + $this->url->link( + 'extension/module/retailcrm', + 'user_token' . '=' . $this->session->data['user_token'], + true + ) + ); } /** * Clear opencart API log file - * + * * @return void */ public function clear_opencart() @@ -685,54 +628,18 @@ class ControllerExtensionModuleRetailcrm extends Controller fclose($handle); } - $this->response->redirect($this->url->link('extension/module/retailcrm', $this->tokenTitle . '=' . $this->session->data[$this->tokenTitle], true)); - } - - /** - * Method for load models - * - * @return void - */ - private function loadModels() - { - if (version_compare(VERSION, '3.0', '<')) { - $this->load->model('extension/event'); - $this->load->model('extension/extension'); - // $this->load->model('extension/module'); - - $this->modelEvent = 'extension_event'; - $this->modelExtension = 'extension_extension'; - // $this->modelModule = 'extension_module'; - } else { - $this->load->model('setting/event'); - $this->load->model('setting/extension'); - // $this->load->model('setting/module'); - - $this->modelEvent = 'setting_event'; - $this->modelExtension = 'setting_extension'; - // $this->modelModule = 'setting_module'; - } - } - - /** - * Get collector module name - * - * @return string - */ - private function getCollectorTitle() - { - if (version_compare(VERSION, '3.0', '<')) { - $title = 'daemon_collector'; - } else { - $title = 'analytics_daemon_collector'; - } - - return $title; + $this->response->redirect( + $this->url->link( + 'extension/module/retailcrm', + 'user_token' . '=' . $this->session->data['user_token'], + true + ) + ); } /** * Check file size - * + * * @return string */ private function checkLogFile($file) @@ -754,51 +661,49 @@ class ControllerExtensionModuleRetailcrm extends Controller /** * Add events to db - * + * * @return void */ private function addEvents() { - $this->loadModels(); - - $this->{'model_' . $this->modelEvent} + $this->model_setting_event ->addEvent( - $this->moduleTitle, + \Retailcrm\Retailcrm::MODULE, 'catalog/model/checkout/order/addOrder/after', 'extension/module/retailcrm/order_create' ); - $this->{'model_' . $this->modelEvent} + $this->model_setting_event ->addEvent( - $this->moduleTitle, + \Retailcrm\Retailcrm::MODULE, 'catalog/model/checkout/order/addOrderHistory/after', 'extension/module/retailcrm/order_edit' ); - $this->{'model_' . $this->modelEvent} + $this->model_setting_event ->addEvent( - $this->moduleTitle, + \Retailcrm\Retailcrm::MODULE, 'catalog/model/account/customer/addCustomer/after', 'extension/module/retailcrm/customer_create' ); - $this->{'model_' . $this->modelEvent} + $this->model_setting_event ->addEvent( - $this->moduleTitle, + \Retailcrm\Retailcrm::MODULE, 'catalog/model/account/customer/editCustomer/after', 'extension/module/retailcrm/customer_edit' ); - $this->{'model_' . $this->modelEvent} + $this->model_setting_event ->addEvent( - $this->moduleTitle, + \Retailcrm\Retailcrm::MODULE, 'catalog/model/account/address/editAddress/after', 'extension/module/retailcrm/customer_edit' ); - $this->{'model_' . $this->modelEvent} + $this->model_setting_event ->addEvent( - $this->moduleTitle, + \Retailcrm\Retailcrm::MODULE, 'admin/model/customer/customer/editCustomer/after', 'extension/module/retailcrm/customer_edit' ); @@ -806,13 +711,13 @@ class ControllerExtensionModuleRetailcrm extends Controller /** * Check events in db - * + * * @return boolean */ private function checkEvents() { - $events = $this->{'model_' . $this->modelEvent}->getEvent( - $this->moduleTitle, + $events = $this->model_setting_event->getEvent( + \Retailcrm\Retailcrm::MODULE, 'catalog/model/checkout/order/addOrder/after', 'extension/module/retailcrm/order_create' ); @@ -826,17 +731,60 @@ class ControllerExtensionModuleRetailcrm extends Controller /** * Delete events from db - * + * * @return void */ private function deleteEvents() { - $this->loadModels(); + $this->model_setting_event->deleteEventByCode(\Retailcrm\Retailcrm::MODULE); + } - if (version_compare(VERSION, '3.0', '<')) { - $this->{'model_' . $this->modelEvent}->deleteEvent($this->moduleTitle); - } else { - $this->{'model_' . $this->modelEvent}->deleteEventByCode($this->moduleTitle); + /** + * Getting history for first setting save + * + * @param $apiClient + * + * @return void + */ + private function getHistory($apiClient) + { + $ordersHistoryBegin = $apiClient->ordersHistory(); + + if ($ordersHistoryBegin->isSuccessful() && !empty($ordersHistoryBegin['history'])) { + $ordersHistoryEnd = $apiClient->ordersHistory(array(), + $ordersHistoryBegin['pagination']['totalPageCount'] + ); + + if ($ordersHistoryEnd->isSuccessful()) { + $ordersHistoryArr = $ordersHistoryEnd['history']; + $lastChangeOrders = end($ordersHistoryArr); + $sinceIdOrders = $lastChangeOrders['id']; + $generatedAt = $ordersHistoryEnd['generatedAt']; + } } + + $customersHistoryBegin = $apiClient->customersHistory(); + + if ($customersHistoryBegin->isSuccessful() && !empty($customersHistoryBegin['history'])) { + $customersHistoryEnd = $apiClient->customersHistory( + array(), + $customersHistoryBegin['pagination']['totalPageCount'] + ); + + if ($customersHistoryEnd->isSuccessful()) { + $customersHistoryArr = $customersHistoryEnd['history']; + $lastChangeCustomers = end($customersHistoryArr); + $sinceIdCustomers = $lastChangeCustomers['id']; + } + } + + $this->model_setting_setting->editSetting( + 'retailcrm_history', + array( + 'retailcrm_history_orders' => isset($sinceIdOrders) ? $sinceIdOrders : 1, + 'retailcrm_history_customers' => isset($sinceIdCustomers) ? $sinceIdCustomers : 1, + 'retailcrm_history_datetime' => isset($generatedAt) ? $generatedAt : date('Y-m-d H:i:s') + ) + ); } } diff --git a/src/upload/admin/model/extension/retailcrm/history/v3.php b/src/upload/admin/model/extension/retailcrm/history/v3.php deleted file mode 100644 index 25fadb0..0000000 --- a/src/upload/admin/model/extension/retailcrm/history/v3.php +++ /dev/null @@ -1,117 +0,0 @@ -retailcrm->getModuleTitle(); - $this->load->model('setting/setting'); - $this->load->model('setting/store'); - $this->load->model('user/api'); - $this->load->model('sale/order'); - $this->load->model('customer/customer'); - $this->load->model('extension/retailcrm/references'); - $this->load->model('catalog/product'); - $this->load->model('catalog/option'); - $this->load->model('localisation/zone'); - - $this->load->language('extension/module/retailcrm'); - - $settings = $this->model_setting_setting->getSetting($moduleTitle); - $history = $this->model_setting_setting->getSetting('retailcrm_history'); - $settings['domain'] = parse_url(HTTP_SERVER, PHP_URL_HOST); - - $url = isset($settings[$moduleTitle . '_url']) ? $settings[$moduleTitle . '_url'] : null; - $key = isset($settings[$moduleTitle . '_apikey']) ? $settings[$moduleTitle . '_apikey'] : null; - - if (empty($url) || empty($key)) { - $this->log->addNotice('You need to configure retailcrm module first.'); - return false; - } - - $lastRun = !empty($history['retailcrm_history_datetime']) - ? new DateTime($history['retailcrm_history_datetime']) - : new DateTime(date('Y-m-d H:i:s', strtotime('-1 days', strtotime(date('Y-m-d H:i:s'))))); - - $packsOrders = $retailcrmApiClient->ordersHistory($lastRun); - - if(!$packsOrders->isSuccessful() && count($packsOrders['orders']) <= 0) { - return false; - } - - $generatedAt = $packsOrders['generatedAt']; - - $this->totalTitle = $this->totalTitles(); - $this->subtotalSettings = $this->model_setting_setting->getSetting($this->totalTitle . 'sub_total'); - $this->totalSettings = $this->model_setting_setting->getSetting($this->totalTitle . 'total'); - $this->shippingSettings = $this->model_setting_setting->getSetting($this->totalTitle . 'shipping'); - $this->delivery = array_flip($settings[$moduleTitle . '_delivery']); - $this->payment = array_flip($settings[$moduleTitle . '_payment']); - $this->status = array_flip($settings[$moduleTitle . '_status']); - $this->payment_default = $settings[$moduleTitle . '_default_payment']; - $this->delivery_default = $settings[$moduleTitle . '_default_shipping']; - $this->ocPayment = $this->model_extension_retailcrm_references - ->getOpercartPaymentTypes(); - - $this->ocDelivery = $this->model_extension_retailcrm_references - ->getOpercartDeliveryTypes(); - - $this->zones = $this->model_localisation_zone->getZones(); - - $updatedOrders = array(); - $newOrders = array(); - $orders = $packsOrders['orders']; - - foreach ($orders as $order) { - - if (isset($order['deleted'])) { - continue; - } - - if (isset($order['externalId'])) { - $updatedOrders[] = $order['id']; - } else { - $newOrders[] = $order['id']; - } - } - - unset($orders); - - if (!empty($newOrders)) { - $orders = $retailcrmApiClient->ordersList($filter = array('ids' => $newOrders)); - if ($orders) { - $this->createResult = $this->createOrders($orders['orders']); - } - } - - if (!empty($updatedOrders)) { - $orders = $retailcrmApiClient->ordersList($filter = array('ids' => $updatedOrders)); - if ($orders) { - $this->updateOrders($orders['orders']); - } - } - - $this->model_setting_setting->editSetting('retailcrm_history', array('retailcrm_history_datetime' => $generatedAt)); - - if (!empty($this->createResult['customers'])) { - $retailcrmApiClient->customersFixExternalIds($this->createResult['customers']); - } - - if (!empty($this->createResult['orders'])) { - $retailcrmApiClient->ordersFixExternalIds($this->createResult['orders']); - } - - return true; - } -} diff --git a/src/upload/admin/model/extension/retailcrm/prices.php b/src/upload/admin/model/extension/retailcrm/prices.php index 5c6c303..4d56a35 100644 --- a/src/upload/admin/model/extension/retailcrm/prices.php +++ b/src/upload/admin/model/extension/retailcrm/prices.php @@ -4,44 +4,32 @@ class ModelExtensionRetailcrmPrices extends Model { protected $settings; protected $moduleTitle; + private $options; private $optionValues; /** - * Constructor - * - * @param Registry $registry + * Upload prices to CRM + * + * @param array $products + * @param \RetailcrmProxy $retailcrm_api_client + * @return mixed bool | array */ - public function __construct($registry) + public function uploadPrices($products, $retailcrm_api_client) { - parent::__construct($registry); - $this->load->library('retailcrm/retailcrm'); $this->load->model('catalog/option'); $this->load->model('setting/setting'); - $this->moduleTitle = $this->retailcrm->getModuleTitle(); - $this->settings = $this->model_setting_setting->getSetting($this->moduleTitle); - } + $prices = $this->getPrices($products, $retailcrm_api_client); - /** - * Upload prices to CRM - * - * @param array $products - * @param \RetailcrmProxy $retailcrmApiClient - * @return mixed bool | array - */ - public function uploadPrices($products, $retailcrmApiClient) - { - $prices = $this->getPrices($products, $retailcrmApiClient); - - if ($retailcrmApiClient === false || !$prices) { + if ($retailcrm_api_client === false || !$prices) { return false; } $pricesUpload = array_chunk($prices, 250); foreach ($pricesUpload as $priceUpload) { - $retailcrmApiClient->storePricesUpload($priceUpload); + $retailcrm_api_client->storePricesUpload($priceUpload); } return $pricesUpload; @@ -49,18 +37,20 @@ class ModelExtensionRetailcrmPrices extends Model /** * Get prices - * + * * @param array $products - * + * * @return mixed */ - protected function getPrices($products, $retailcrmApiClient) + protected function getPrices($products, $retailcrm_api_client) { - $prices = array(); - $site = $this->getSite($retailcrmApiClient); + $settings = $this->model_setting_setting->getSetting(\retailcrm\Retailcrm::MODULE); - if (!isset($this->settings[$this->moduleTitle . '_special']) - || $this->settings[$this->moduleTitle . '_apiversion'] == 'v3' + $prices = array(); + $site = $this->getSite($retailcrm_api_client); + + if (!isset($settings[$this->moduleTitle . '_special']) + || $settings[$this->moduleTitle . '_apiversion'] == 'v3' ) { return false; } @@ -115,7 +105,7 @@ class ModelExtensionRetailcrmPrices extends Model 'site' => $site, 'prices' => array( array( - 'code' => $this->settings[$this->moduleTitle . '_special'], + 'code' => $settings[$this->moduleTitle . '_special'], 'price' => $productPrice + $optionsValues['price'] ) ) @@ -128,9 +118,9 @@ class ModelExtensionRetailcrmPrices extends Model /** * Get actual special - * + * * @param array $specials - * + * * @return float $productPrice */ private function getSpecialPrice($specials) @@ -157,10 +147,10 @@ class ModelExtensionRetailcrmPrices extends Model /** * Get data option - * + * * @param int $optionId * @param int $optionValueId - * + * * @return array */ private function getOptionData($optionId, $optionValueId) { @@ -191,9 +181,9 @@ class ModelExtensionRetailcrmPrices extends Model * * @return mixed boolean | string */ - private function getSite($retailcrmApiClient) + private function getSite($retailcrm_api_client) { - $response = $retailcrmApiClient->sitesList(); + $response = $retailcrm_api_client->sitesList(); if ($response && $response->isSuccessful()) { $sites = $response->sites; diff --git a/src/upload/admin/model/extension/retailcrm/references.php b/src/upload/admin/model/extension/retailcrm/references.php index 722c499..4aeef5a 100644 --- a/src/upload/admin/model/extension/retailcrm/references.php +++ b/src/upload/admin/model/extension/retailcrm/references.php @@ -1,93 +1,72 @@ load->model('setting/setting'); - $this->load->library('retailcrm/retailcrm'); - - $this->moduleTitle = $this->retailcrm->getModuleTitle(); - $this->settings = $this->model_setting_setting->getSetting($this->moduleTitle); - $this->retailcrmApiClient = $this->retailcrm->getApiClient(); - } +class ModelExtensionRetailcrmReferences extends Model { /** * Get opencart delivery methods - * + * * @return array */ - public function getOpercartDeliveryTypes() + public function getOpercartDeliveryTypes($opencart_api_client) { - $this->opencartApiClient = $this->retailcrm->getOcApiClient($this->registry); - - return $this->opencartApiClient->getDeliveryTypes(); + return $opencart_api_client->getDeliveryTypes(); } /** * Get all delivery types - * + * * @return array */ - public function getDeliveryTypes() + public function getDeliveryTypes($opencart_api_client, $retailcrm_api_client) { - $this->load->model('setting/store'); - return array( - 'opencart' => $this->getOpercartDeliveryTypes(), - 'retailcrm' => $this->getApiDeliveryTypes() + 'opencart' => $this->getOpercartDeliveryTypes($opencart_api_client), + 'retailcrm' => $this->getApiDeliveryTypes($retailcrm_api_client) ); } /** * Get all statuses - * + * * @return array */ - public function getOrderStatuses() + public function getOrderStatuses($retailcrm_api_client) { return array( 'opencart' => $this->getOpercartOrderStatuses(), - 'retailcrm' => $this->getApiOrderStatuses() + 'retailcrm' => $this->getApiOrderStatuses($retailcrm_api_client) ); } /** * Get all payment types - * + * * @return array */ - public function getPaymentTypes() + public function getPaymentTypes($retailcrm_api_client) { return array( 'opencart' => $this->getOpercartPaymentTypes(), - 'retailcrm' => $this->getApiPaymentTypes() + 'retailcrm' => $this->getApiPaymentTypes($retailcrm_api_client) ); } /** * Get all custom fields - * + * * @return array */ - public function getCustomFields() + public function getCustomFields($retailcrm_api_client) { return array( 'opencart' => $this->getOpencartCustomFields(), - 'retailcrm' => $this->getApiCustomFields() + 'retailcrm' => $this->getApiCustomFields($retailcrm_api_client) ); } /** * Get opencart order statuses - * + * * @return array */ public function getOpercartOrderStatuses() @@ -100,7 +79,7 @@ class ModelExtensionRetailcrmReferences extends Model /** * Get opencart payment types - * + * * @return array */ public function getOpercartPaymentTypes() @@ -113,7 +92,7 @@ class ModelExtensionRetailcrmReferences extends Model $extension = basename($file, '.php'); $this->load->language('extension/payment/' . $extension); - + if (version_compare(VERSION, '3.0', '<')) { $configStatus = $extension . '_status'; } else { @@ -133,80 +112,80 @@ class ModelExtensionRetailcrmReferences extends Model /** * Get opencart custom fields - * + * * @return array */ public function getOpencartCustomFields() { $this->load->model('customer/custom_field'); - + return $this->model_customer_custom_field->getCustomFields(); } /** * Get RetailCRM delivery types - * + * * @return array */ - public function getApiDeliveryTypes() + public function getApiDeliveryTypes($retailcrm_api_client) { - $response = $this->retailcrmApiClient->deliveryTypesList(); + $response = $retailcrm_api_client->deliveryTypesList(); return (!$response->isSuccessful()) ? array() : $response->deliveryTypes; } /** * Get RetailCRM order statuses - * + * * @return array */ - public function getApiOrderStatuses() + public function getApiOrderStatuses($retailcrm_api_client) { - $response = $this->retailcrmApiClient->statusesList(); + $response = $retailcrm_api_client->statusesList(); return (!$response->isSuccessful()) ? array() : $response->statuses; } /** * Get RetailCRM payment types - * + * * @return array */ - public function getApiPaymentTypes() + public function getApiPaymentTypes($retailcrm_api_client) { - $response = $this->retailcrmApiClient->paymentTypesList(); + $response = $retailcrm_api_client->paymentTypesList(); return (!$response->isSuccessful()) ? array() : $response->paymentTypes; } /** * Get RetailCRM custom fields - * + * * @return array */ - public function getApiCustomFields() + public function getApiCustomFields($retailcrm_api_client) { - $customers = $this->retailcrmApiClient->customFieldsList(array('entity' => 'customer')); - $orders = $this->retailcrmApiClient->customFieldsList(array('entity' => 'order')); + $customers = $retailcrm_api_client->customFieldsList(array('entity' => 'customer')); + $orders = $retailcrm_api_client->customFieldsList(array('entity' => 'order')); - $customFieldsCustomers = (!$customers->isSuccessful()) ? array() : $customers->customFields; - $customFieldsOrders = (!$orders->isSuccessful()) ? array() : $orders->customFields; + $custom_fields_customers = (!$customers->isSuccessful()) ? array() : $customers->customFields; + $custom_fields_orders = (!$orders->isSuccessful()) ? array() : $orders->customFields; - if (!$customFieldsCustomers && !$customFieldsOrders) { + if (!$custom_fields_customers && !$custom_fields_orders) { return array(); } - - return array('customers' => $customFieldsCustomers, 'orders' => $customFieldsOrders); + + return array('customers' => $custom_fields_customers, 'orders' => $custom_fields_orders); } /** * Get RetailCRM price types - * + * * @return array */ - public function getPriceTypes() + public function getPriceTypes($retailcrm_api_client) { - $response = $this->retailcrmApiClient->priceTypesList(); + $response = $retailcrm_api_client->priceTypesList(); return (!$response->isSuccessful()) ? array() : $response->priceTypes; } diff --git a/src/upload/admin/view/template/extension/module/retailcrm.tpl b/src/upload/admin/view/template/extension/module/retailcrm.tpl deleted file mode 100644 index 5adffdf..0000000 --- a/src/upload/admin/view/template/extension/module/retailcrm.tpl +++ /dev/null @@ -1,600 +0,0 @@ - -
- -
- -
- - -
- - - - -
-
-
- -
-
- -
- -
- -
- -
-
-
- -
- -
-
-
- -
- -
-
-
-
- -
- -
-
- -
- -
- -
-
-
-
- - - -
- - -
- -
- -
-
-
- -
-
- -
-
-
-
-
- -
- -
- -
- -
-
-
- -
- -
- -
- - -
-
-
-
-
-
- -
- -
-
- - -
-
- - $val): ?> -
-
- -
-
- -
-
- -
- - -
- - -
- -
-
-
-
- -
- - -
-
- -
-
- -
-
- -
-
-
- -
- $value): ?> -
-
- -
-
- -
-
- -
-
-
- -
-
-
-
-
- -
-
- -
-
-
-
-
-
- -
-
- -
-
-
-
-
-
-
- -
-
-
- -
-
-
-
-
- - -
-
-
- -
- -
- - -
-
-
- -
- -
-
-
- -
- - -
-
-
- -
- -
-
-
- -
- -
-
-
- -
- -
-
-
- -
- - -
-
- $label) : ?> -
- -
-
-
- -
-
- /> - -
-
-
-
- -
-
- -
-
- - -
- -
- - -
-
-
- -
-
- -
-
- -
- -
- -
-
- -
-
-
-
- -
-
- -
-
- -
- -
- -
-
- -
-
-
- -
- - -
- -
- - -
- -
- - -
- -
-
- -
-
- Retailcrm API error log -
- -
- -
-
- -
-
- -
- -
- -
-
- Opencart API error log -
- -
- -
-
- -
-
- -
- -
- -
-
-
-
-
-
-
-
- - - diff --git a/src/upload/catalog/controller/extension/module/retailcrm.php b/src/upload/catalog/controller/extension/module/retailcrm.php index faf73ae..794113b 100644 --- a/src/upload/catalog/controller/extension/module/retailcrm.php +++ b/src/upload/catalog/controller/extension/module/retailcrm.php @@ -11,73 +11,44 @@ */ class ControllerExtensionModuleRetailcrm extends Controller { - private $retailcrmApiClient; - - public function __construct($registry) - { - parent::__construct($registry); - - $this->load->library('retailcrm/retailcrm'); - $this->retailcrmApiClient = $this->retailcrm->getApiClient(); - } - /** * Create order on event * - * @param string $trigger - * @param array $data - * @param int $order_id order identificator + * @param string $route + * @param array $args + * @param int $output * - * @return void + * @return boolean */ - public function order_create($trigger, $data, $order_id = null) { - $this->load->model('checkout/order'); - $this->load->model('account/order'); + public function orderCreate($route, $args, $output) { + if ($route != 'checkout/order/addOrder') { + return false; + } + $this->load->library('retailcrm/retailcrm'); - $data = $this->model_checkout_order->getOrder($order_id);; - $data['products'] = $this->model_account_order->getOrderProducts($order_id); - $data['totals'] = $this->model_account_order->getOrderTotals($order_id); - $moduleTitle = $this->retailcrm->getModuleTitle(); + $retailcrm_order = $this->retailcrm->getObject('Order'); + $retailcrm_order->prepare($args[0]); + $retailcrm_order->setField('externalId', $output); + $retailcrm_order->create($this->retailcrm->getApiClient()); - foreach ($data['products'] as $key => $product) { - $productOptions = $this->model_account_order->getOrderOptions($order_id, $product['order_product_id']); - - if (!empty($productOptions)) { - $data['products'][$key]['option'] = $productOptions; - } - } - - if (!isset($data['fromApi'])) { - $this->load->model('setting/setting'); - $status = $this->model_setting_setting->getSetting($moduleTitle); - - if (isset($data['order_status_id']) && $data['order_status_id'] > 0) { - $data['order_status'] = $status[$moduleTitle . '_status'][$data['order_status_id']]; - } - - if (file_exists(DIR_APPLICATION . 'model/extension/retailcrm/custom/order.php')) { - $this->load->model('extension/retailcrm/custom/order'); - $order = $this->model_extension_retailcrm_custom_order->processOrder($data); - $this->model_extension_retailcrm_custom_order->sendToCrm($order, $this->retailcrmApiClient); - } else { - $this->load->model('extension/retailcrm/order'); - $order = $this->model_extension_retailcrm_order->processOrder($data); - $this->model_extension_retailcrm_order->sendToCrm($order, $this->retailcrmApiClient); - } - } + return true; } /** * Update order on event * - * @param string $trigger - * @param array $parameter2 + * @param string $route + * @param array $args * - * @return void + * @return boolean */ - public function order_edit($trigger, $parameter2 = null) { - $order_id = $parameter2[0]; + public function orderEdit($route, $args) { + if ($route != 'checkout/order/editOrder') { + return false; + } + + $order_id = $args[0]; $this->load->model('checkout/order'); $this->load->model('account/order'); @@ -124,63 +95,46 @@ class ControllerExtensionModuleRetailcrm extends Controller { /** * Create customer on event * - * @param int $customerId customer identificator + * @param string $route + * @param array $args + * @param int $output * - * @return void + * @return boolean */ - public function customer_create($parameter1, $parameter2 = null, $parameter3 = null) { - $this->load->model('account/customer'); - $this->load->model('localisation/country'); - $this->load->model('localisation/zone'); - - $customerId = $parameter3; - $customer = $this->model_account_customer->getCustomer($customerId); - - if ($this->request->post) { - $country = $this->model_localisation_country->getCountry($this->request->post['country_id']); - $zone = $this->model_localisation_zone->getZone($this->request->post['zone_id']); - - $customer['address'] = array( - 'address_1' => $this->request->post['address_1'], - 'address_2' => $this->request->post['address_2'], - 'city' => $this->request->post['city'], - 'postcode' => $this->request->post['postcode'], - 'iso_code_2' => $country['iso_code_2'], - 'zone' => $zone['name'] - ); + public function customerCreate($route, $args, $output) { + if ($route != 'account/customer/addCustomer') { + return false; } - if (file_exists(DIR_APPLICATION . 'model/extension/retailcrm/custom/customer.php')) { - $this->load->model('extension/retailcrm/custom/customer'); - $this->model_extension_retailcrm_custom_customer->sendToCrm($customer, $this->retailcrmApiClient); - } else { - $this->load->model('extension/retailcrm/customer'); - $this->model_extension_retailcrm_customer->sendToCrm($customer, $this->retailcrmApiClient); - } + $this->load->library('retailcrm/retailcrm'); + $retailcrm_customer = $this->retailcrm->createObject('Customer'); + $retailcrm_customer->prepare($args[0]); + $retailcrm_customer->setField('externalId', $output); + $retailcrm_customer->create(); + + return true; } /** * Update customer on event * - * @param int $customerId customer identificator - * - * @return void + * @param string $route + * @param array $args + * @return boolean */ - public function customer_edit($parameter1, $parameter2, $parameter3) { - $customerId = $this->customer->getId(); - - $this->load->model('account/customer'); - $customer = $this->model_account_customer->getCustomer($customerId); - - $this->load->model('account/address'); - $customer['address'] = $this->model_account_address->getAddress($customer['address_id']); - - if (file_exists(DIR_APPLICATION . 'model/extension/retailcrm/custom/customer.php')) { - $this->load->model('extension/retailcrm/custom/customer'); - $this->model_extension_retailcrm_custom_customer->changeInCrm($customer, $this->retailcrmApiClient); - } else { - $this->load->model('extension/retailcrm/customer'); - $this->model_extension_retailcrm_customer->changeInCrm($customer, $this->retailcrmApiClient); + public function customerEdit($route, $args) { + if ($route != 'account/customer/editCustomer') { + return false; } + + $customer_id = $args[0]; + $data = $args[1]; + + $this->load->library('retailcrm/customer'); + $this->retailcrm->process($data); + $this->retailcrm->setField('externalId', $customer_id); + $this->retailcrm->edit(); + + return true; } } diff --git a/src/upload/system/library/retailcrm/OpencartApiClient.php b/src/upload/system/library/retailcrm/OpencartApiClient.php index 8f92be2..072959b 100644 --- a/src/upload/system/library/retailcrm/OpencartApiClient.php +++ b/src/upload/system/library/retailcrm/OpencartApiClient.php @@ -47,22 +47,19 @@ class OpencartApiClient { } private function request($method, $getParams, $postParams) { + $this->load->model('setting/store'); $opencartStoreInfo = $this->model_setting_store->getStore($this->opencartStoreId); if ($this->apiToken !== false) { - if (version_compare(VERSION, '3.0', '<')) { - $getParams['key'] = $this->apiToken['key']; - } else { - $getParams['key'] = $this->apiToken['key']; - $getParams['username'] = $this->apiToken['username']; + $getParams['key'] = $this->apiToken['key']; + $getParams['username'] = $this->apiToken['username']; - if (isset($this->session->data['user_token'])) { - $getParams['api_token'] = $this->session->data['user_token']; - } else { - $session = $this->registry->get('session'); - $session->start(); - $getParams['api_token'] = $session->getId(); - } + if (isset($this->session->data['user_token'])) { + $getParams['api_token'] = $this->session->data['user_token']; + } else { + $session = $this->registry->get('session'); + $session->start(); + $getParams['api_token'] = $session->getId(); } } @@ -143,7 +140,7 @@ class OpencartApiClient { /** * Get delivery types - * + * * @return array */ public function getDeliveryTypes() @@ -153,10 +150,10 @@ class OpencartApiClient { /** * Add history order - * + * * @param int $order_id * @param int $order_status_id - * + * * @return void */ public function addHistory($order_id, $order_status_id) @@ -166,7 +163,7 @@ class OpencartApiClient { /** * Get module name - * + * * @return string */ private function getModuleTitle() diff --git a/src/upload/system/library/retailcrm/RetailcrmApiClient3.php b/src/upload/system/library/retailcrm/RetailcrmApiClient3.php deleted file mode 100644 index d61d3e3..0000000 --- a/src/upload/system/library/retailcrm/RetailcrmApiClient3.php +++ /dev/null @@ -1,831 +0,0 @@ - - * @license https://opensource.org/licenses/MIT MIT License - * @link http://www.retailcrm.ru/docs/Developers/ApiVersion3 - */ -class RetailcrmApiClient3 -{ - protected $client; - - /** - * Site code - */ - protected $siteCode; - - /** - * Client creating - * - * @param string $url - * @param string $apiKey - * @param string $site - * @return mixed - */ - public function __construct($url, $apiKey, $version = null, $site = null) - { - if ('/' != substr($url, strlen($url) - 1, 1)) { - $url .= '/'; - } - - $url = $version == null ? $url . 'api' : $url . 'api/' . $version; - - $this->client = new RetailcrmHttpClient($url, array('apiKey' => $apiKey)); - $this->siteCode = $site; - } - - /** - * Returns api versions list - * - * @throws \RetailCrm\Exception\InvalidJsonException - * @throws \RetailCrm\Exception\CurlException - * @throws \InvalidArgumentException - * - * @return ApiResponse - */ - public function apiVersions() - { - return $this->client->makeRequest('/api-versions', RetailcrmHttpClient::METHOD_GET); - } - - /** - * Create a order - * - * @param array $order - * @param string $site (default: null) - * @return ApiResponse - */ - public function ordersCreate(array $order, $site = null) - { - if (!sizeof($order)) { - throw new InvalidArgumentException('Parameter `order` must contains a data'); - } - - return $this->client->makeRequest("/orders/create", RetailcrmHttpClient::METHOD_POST, $this->fillSite($site, array( - 'order' => json_encode($order) - ))); - } - - /** - * Edit a order - * - * @param array $order - * @param string $by - * @param string $site (default: null) - * @return ApiResponse - */ - public function ordersEdit(array $order, $by = 'externalId', $site = null) - { - if (!sizeof($order)) { - throw new InvalidArgumentException('Parameter `order` must contains a data'); - } - - $this->checkIdParameter($by); - - if (!isset($order[$by])) { - throw new InvalidArgumentException(sprintf('Order array must contain the "%s" parameter.', $by)); - } - - return $this->client->makeRequest( - "/orders/" . $order[$by] . "/edit", - RetailcrmHttpClient::METHOD_POST, - $this->fillSite($site, array( - 'order' => json_encode($order), - 'by' => $by, - )) - ); - } - - /** - * Upload array of the orders - * - * @param array $orders - * @param string $site (default: null) - * @return ApiResponse - */ - public function ordersUpload(array $orders, $site = null) - { - if (!sizeof($orders)) { - throw new InvalidArgumentException('Parameter `orders` must contains array of the orders'); - } - - return $this->client->makeRequest("/orders/upload", RetailcrmHttpClient::METHOD_POST, $this->fillSite($site, array( - 'orders' => json_encode($orders), - ))); - } - - /** - * Get order by id or externalId - * - * @param string $id - * @param string $by (default: 'externalId') - * @param string $site (default: null) - * @return ApiResponse - */ - public function ordersGet($id, $by = 'externalId', $site = null) - { - $this->checkIdParameter($by); - - return $this->client->makeRequest("/orders/$id", RetailcrmHttpClient::METHOD_GET, $this->fillSite($site, array( - 'by' => $by - ))); - } - - /** - * Returns a orders history - * - * @param DateTime $startDate (default: null) - * @param DateTime $endDate (default: null) - * @param int $limit (default: 100) - * @param int $offset (default: 0) - * @param bool $skipMyChanges (default: true) - * @return ApiResponse - */ - public function ordersHistory( - DateTime $startDate = null, - DateTime $endDate = null, - $limit = 100, - $offset = 0, - $skipMyChanges = true - ) { - $parameters = array(); - - if ($startDate) { - $parameters['startDate'] = $startDate->format('Y-m-d H:i:s'); - } - if ($endDate) { - $parameters['endDate'] = $endDate->format('Y-m-d H:i:s'); - } - if ($limit) { - $parameters['limit'] = (int) $limit; - } - if ($offset) { - $parameters['offset'] = (int) $offset; - } - if ($skipMyChanges) { - $parameters['skipMyChanges'] = (bool) $skipMyChanges; - } - - return $this->client->makeRequest('/orders/history', RetailcrmHttpClient::METHOD_GET, $parameters); - } - - /** - * Returns filtered orders list - * - * @param array $filter (default: array()) - * @param int $page (default: null) - * @param int $limit (default: null) - * @return ApiResponse - */ - public function ordersList(array $filter = array(), $page = null, $limit = null) - { - $parameters = array(); - - if (sizeof($filter)) { - $parameters['filter'] = $filter; - } - if (null !== $page) { - $parameters['page'] = (int) $page; - } - if (null !== $limit) { - $parameters['limit'] = (int) $limit; - } - - return $this->client->makeRequest('/orders', RetailcrmHttpClient::METHOD_GET, $parameters); - } - - /** - * Returns statuses of the orders - * - * @param array $ids (default: array()) - * @param array $externalIds (default: array()) - * @return ApiResponse - */ - public function ordersStatuses(array $ids = array(), array $externalIds = array()) - { - $parameters = array(); - - if (sizeof($ids)) { - $parameters['ids'] = $ids; - } - if (sizeof($externalIds)) { - $parameters['externalIds'] = $externalIds; - } - - return $this->client->makeRequest('/orders/statuses', RetailcrmHttpClient::METHOD_GET, $parameters); - } - - /** - * Save order IDs' (id and externalId) association in the CRM - * - * @param array $ids - * @return ApiResponse - */ - public function ordersFixExternalIds(array $ids) - { - if (!sizeof($ids)) { - throw new InvalidArgumentException('Method parameter must contains at least one IDs pair'); - } - - return $this->client->makeRequest("/orders/fix-external-ids", RetailcrmHttpClient::METHOD_POST, array( - 'orders' => json_encode($ids), - )); - } - - /** - * Get orders assembly history - * - * @param array $filter (default: array()) - * @param int $page (default: null) - * @param int $limit (default: null) - * @return ApiResponse - */ - public function ordersPacksHistory(array $filter = array(), $page = null, $limit = null) - { - $parameters = array(); - - if (sizeof($filter)) { - $parameters['filter'] = $filter; - } - if (null !== $page) { - $parameters['page'] = (int) $page; - } - if (null !== $limit) { - $parameters['limit'] = (int) $limit; - } - - return $this->client->makeRequest('/orders/packs/history', RetailcrmHttpClient::METHOD_GET, $parameters); - } - - /** - * Create a customer - * - * @param array $customer - * @param string $site (default: null) - * @return ApiResponse - */ - public function customersCreate(array $customer, $site = null) - { - if (!sizeof($customer)) { - throw new InvalidArgumentException('Parameter `customer` must contains a data'); - } - - return $this->client->makeRequest("/customers/create", RetailcrmHttpClient::METHOD_POST, $this->fillSite($site, array( - 'customer' => json_encode($customer) - ))); - } - - /** - * Edit a customer - * - * @param array $customer - * @param string $by (default: 'externalId') - * @param string $site (default: null) - * @return ApiResponse - */ - public function customersEdit(array $customer, $by = 'externalId', $site = null) - { - if (!sizeof($customer)) { - throw new InvalidArgumentException('Parameter `customer` must contains a data'); - } - - $this->checkIdParameter($by); - - if (!isset($customer[$by])) { - throw new InvalidArgumentException(sprintf('Customer array must contain the "%s" parameter.', $by)); - } - - return $this->client->makeRequest( - "/customers/" . $customer[$by] . "/edit", - RetailcrmHttpClient::METHOD_POST, - $this->fillSite( - $site, - array( - 'customer' => json_encode($customer), - 'by' => $by - ) - ) - ); - } - - /** - * Upload array of the customers - * - * @param array $customers - * @param string $site (default: null) - * @return ApiResponse - */ - public function customersUpload(array $customers, $site = null) - { - if (!sizeof($customers)) { - throw new InvalidArgumentException('Parameter `customers` must contains array of the customers'); - } - - return $this->client->makeRequest("/customers/upload", RetailcrmHttpClient::METHOD_POST, $this->fillSite($site, array( - 'customers' => json_encode($customers), - ))); - } - - /** - * Get customer by id or externalId - * - * @param string $id - * @param string $by (default: 'externalId') - * @param string $site (default: null) - * @return ApiResponse - */ - public function customersGet($id, $by = 'externalId', $site = null) - { - $this->checkIdParameter($by); - - return $this->client->makeRequest("/customers/$id", RetailcrmHttpClient::METHOD_GET, $this->fillSite($site, array( - 'by' => $by - ))); - } - - /** - * Returns filtered customers list - * - * @param array $filter (default: array()) - * @param int $page (default: null) - * @param int $limit (default: null) - * @return ApiResponse - */ - public function customersList(array $filter = array(), $page = null, $limit = null) - { - $parameters = array(); - - if (sizeof($filter)) { - $parameters['filter'] = $filter; - } - if (null !== $page) { - $parameters['page'] = (int) $page; - } - if (null !== $limit) { - $parameters['limit'] = (int) $limit; - } - - return $this->client->makeRequest('/customers', RetailcrmHttpClient::METHOD_GET, $parameters); - } - - /** - * Save customer IDs' (id and externalId) association in the CRM - * - * @param array $ids - * @return ApiResponse - */ - public function customersFixExternalIds(array $ids) - { - if (!sizeof($ids)) { - throw new InvalidArgumentException('Method parameter must contains at least one IDs pair'); - } - - return $this->client->makeRequest("/customers/fix-external-ids", RetailcrmHttpClient::METHOD_POST, array( - 'customers' => json_encode($ids), - )); - } - - /** - * Get purchace prices & stock balance - * - * @param array $filter (default: array()) - * @param int $page (default: null) - * @param int $limit (default: null) - * @param string $site (default: null) - * @return ApiResponse - */ - public function storeInventories(array $filter = array(), $page = null, $limit = null, $site = null) - { - $parameters = array(); - - if (sizeof($filter)) { - $parameters['filter'] = $filter; - } - if (null !== $page) { - $parameters['page'] = (int) $page; - } - if (null !== $limit) { - $parameters['limit'] = (int) $limit; - } - - return $this->client->makeRequest('/store/inventories', RetailcrmHttpClient::METHOD_GET, $this->fillSite($site, $parameters)); - } - - /** - * Upload store inventories - * - * @param array $offers - * @param string $site (default: null) - * @return ApiResponse - */ - public function storeInventoriesUpload(array $offers, $site = null) - { - if (!sizeof($offers)) { - throw new InvalidArgumentException('Parameter `offers` must contains array of the customers'); - } - - return $this->client->makeRequest( - "/store/inventories/upload", - RetailcrmHttpClient::METHOD_POST, - $this->fillSite($site, array('offers' => json_encode($offers))) - ); - } - - /** - * Returns deliveryServices list - * - * @return ApiResponse - */ - public function deliveryServicesList() - { - return $this->client->makeRequest('/reference/delivery-services', RetailcrmHttpClient::METHOD_GET); - } - - /** - * Returns deliveryTypes list - * - * @return ApiResponse - */ - public function deliveryTypesList() - { - return $this->client->makeRequest('/reference/delivery-types', RetailcrmHttpClient::METHOD_GET); - } - - /** - * Returns orderMethods list - * - * @return ApiResponse - */ - public function orderMethodsList() - { - return $this->client->makeRequest('/reference/order-methods', RetailcrmHttpClient::METHOD_GET); - } - - /** - * Returns orderTypes list - * - * @return ApiResponse - */ - public function orderTypesList() - { - return $this->client->makeRequest('/reference/order-types', RetailcrmHttpClient::METHOD_GET); - } - - /** - * Returns paymentStatuses list - * - * @return ApiResponse - */ - public function paymentStatusesList() - { - return $this->client->makeRequest('/reference/payment-statuses', RetailcrmHttpClient::METHOD_GET); - } - - /** - * Returns paymentTypes list - * - * @return ApiResponse - */ - public function paymentTypesList() - { - return $this->client->makeRequest('/reference/payment-types', RetailcrmHttpClient::METHOD_GET); - } - - /** - * Returns productStatuses list - * - * @return ApiResponse - */ - public function productStatusesList() - { - return $this->client->makeRequest('/reference/product-statuses', RetailcrmHttpClient::METHOD_GET); - } - - /** - * Returns statusGroups list - * - * @return ApiResponse - */ - public function statusGroupsList() - { - return $this->client->makeRequest('/reference/status-groups', RetailcrmHttpClient::METHOD_GET); - } - - /** - * Returns statuses list - * - * @return ApiResponse - */ - public function statusesList() - { - return $this->client->makeRequest('/reference/statuses', RetailcrmHttpClient::METHOD_GET); - } - - /** - * Returns sites list - * - * @return ApiResponse - */ - public function sitesList() - { - return $this->client->makeRequest('/reference/sites', RetailcrmHttpClient::METHOD_GET); - } - - /** - * Returns stores list - * - * @return ApiResponse - */ - public function storesList() - { - return $this->client->makeRequest('/reference/stores', RetailcrmHttpClient::METHOD_GET); - } - - /** - * Edit deliveryService - * - * @param array $data delivery service data - * @return ApiResponse - */ - public function deliveryServicesEdit(array $data) - { - if (!isset($data['code'])) { - throw new InvalidArgumentException('Data must contain "code" parameter.'); - } - - return $this->client->makeRequest( - '/reference/delivery-services/' . $data['code'] . '/edit', - RetailcrmHttpClient::METHOD_POST, - array( - 'deliveryService' => json_encode($data) - ) - ); - } - - /** - * Edit deliveryType - * - * @param array $data delivery type data - * @return ApiResponse - */ - public function deliveryTypesEdit(array $data) - { - if (!isset($data['code'])) { - throw new InvalidArgumentException('Data must contain "code" parameter.'); - } - - return $this->client->makeRequest( - '/reference/delivery-types/' . $data['code'] . '/edit', - RetailcrmHttpClient::METHOD_POST, - array( - 'deliveryType' => json_encode($data) - ) - ); - } - - /** - * Edit orderMethod - * - * @param array $data order method data - * @return ApiResponse - */ - public function orderMethodsEdit(array $data) - { - if (!isset($data['code'])) { - throw new InvalidArgumentException('Data must contain "code" parameter.'); - } - - return $this->client->makeRequest( - '/reference/order-methods/' . $data['code'] . '/edit', - RetailcrmHttpClient::METHOD_POST, - array( - 'orderMethod' => json_encode($data) - ) - ); - } - - /** - * Edit orderType - * - * @param array $data order type data - * @return ApiResponse - */ - public function orderTypesEdit(array $data) - { - if (!isset($data['code'])) { - throw new InvalidArgumentException('Data must contain "code" parameter.'); - } - - return $this->client->makeRequest( - '/reference/order-types/' . $data['code'] . '/edit', - RetailcrmHttpClient::METHOD_POST, - array( - 'orderType' => json_encode($data) - ) - ); - } - - /** - * Edit paymentStatus - * - * @param array $data payment status data - * @return ApiResponse - */ - public function paymentStatusesEdit(array $data) - { - if (!isset($data['code'])) { - throw new InvalidArgumentException('Data must contain "code" parameter.'); - } - - return $this->client->makeRequest( - '/reference/payment-statuses/' . $data['code'] . '/edit', - RetailcrmHttpClient::METHOD_POST, - array( - 'paymentStatus' => json_encode($data) - ) - ); - } - - /** - * Edit paymentType - * - * @param array $data payment type data - * @return ApiResponse - */ - public function paymentTypesEdit(array $data) - { - if (!isset($data['code'])) { - throw new InvalidArgumentException('Data must contain "code" parameter.'); - } - - return $this->client->makeRequest( - '/reference/payment-types/' . $data['code'] . '/edit', - RetailcrmHttpClient::METHOD_POST, - array( - 'paymentType' => json_encode($data) - ) - ); - } - - /** - * Edit productStatus - * - * @param array $data product status data - * @return ApiResponse - */ - public function productStatusesEdit(array $data) - { - if (!isset($data['code'])) { - throw new InvalidArgumentException('Data must contain "code" parameter.'); - } - - return $this->client->makeRequest( - '/reference/product-statuses/' . $data['code'] . '/edit', - RetailcrmHttpClient::METHOD_POST, - array( - 'productStatus' => json_encode($data) - ) - ); - } - - /** - * Edit order status - * - * @param array $data status data - * @return ApiResponse - */ - public function statusesEdit(array $data) - { - if (!isset($data['code'])) { - throw new InvalidArgumentException('Data must contain "code" parameter.'); - } - - return $this->client->makeRequest( - '/reference/statuses/' . $data['code'] . '/edit', - RetailcrmHttpClient::METHOD_POST, - array( - 'status' => json_encode($data) - ) - ); - } - - /** - * Edit site - * - * @param array $data site data - * @return ApiResponse - */ - public function sitesEdit(array $data) - { - if (!isset($data['code'])) { - throw new InvalidArgumentException('Data must contain "code" parameter.'); - } - - return $this->client->makeRequest( - '/reference/sites/' . $data['code'] . '/edit', - RetailcrmHttpClient::METHOD_POST, - array( - 'site' => json_encode($data) - ) - ); - } - - /** - * Edit store - * - * @param array $data site data - * @return ApiResponse - */ - public function storesEdit(array $data) - { - if (!isset($data['code'])) { - throw new InvalidArgumentException('Data must contain "code" parameter.'); - } - - if (!isset($data['name'])) { - throw new InvalidArgumentException('Data must contain "name" parameter.'); - } - - return $this->client->makeRequest( - '/reference/stores/' . $data['code'] . '/edit', - RetailcrmHttpClient::METHOD_POST, - array( - 'store' => json_encode($data) - ) - ); - } - - /** - * Update CRM basic statistic - * - * @return ApiResponse - */ - public function statisticUpdate() - { - return $this->client->makeRequest('/statistic/update', RetailcrmHttpClient::METHOD_GET); - } - - /** - * Return current site - * - * @return string - */ - public function getSite() - { - return $this->siteCode; - } - - /** - * Set site - * - * @param string $site - * @return void - */ - public function setSite($site) - { - $this->siteCode = $site; - } - - /** - * Check ID parameter - * - * @param string $by - * @return bool - */ - protected function checkIdParameter($by) - { - $allowedForBy = array('externalId', 'id'); - if (!in_array($by, $allowedForBy)) { - throw new InvalidArgumentException(sprintf( - 'Value "%s" for parameter "by" is not valid. Allowed values are %s.', - $by, - implode(', ', $allowedForBy) - )); - } - - return true; - } - - /** - * Fill params by site value - * - * @param string $site - * @param array $params - * @return array - */ - protected function fillSite($site, array $params) - { - if ($site) { - $params['site'] = $site; - } elseif ($this->siteCode) { - $params['site'] = $this->siteCode; - } - - return $params; - } -} diff --git a/src/upload/system/library/retailcrm/RetailcrmApiClient4.php b/src/upload/system/library/retailcrm/RetailcrmApiClient4.php deleted file mode 100644 index 1436175..0000000 --- a/src/upload/system/library/retailcrm/RetailcrmApiClient4.php +++ /dev/null @@ -1,1771 +0,0 @@ - - * @license https://opensource.org/licenses/MIT MIT License - * @link http://www.retailcrm.ru/docs/Developers/ApiVersion4 - */ -class RetailcrmApiClient4 -{ - protected $client; - - /** - * Site code - */ - protected $siteCode; - - /** - * Client creating - * - * @param string $url api url - * @param string $apiKey api key - * @param string $site site code - * - * @throws \InvalidArgumentException - * - * @return mixed - */ - public function __construct($url, $apiKey, $version = null, $site = null) - { - if ('/' !== $url[strlen($url) - 1]) { - $url .= '/'; - } - - $url = $version == null ? $url . 'api' : $url . 'api/' . $version; - - $this->client = new RetailcrmHttpClient($url, array('apiKey' => $apiKey)); - $this->siteCode = $site; - } - - /** - * Returns api versions list - * - * @throws \RetailCrm\Exception\InvalidJsonException - * @throws \RetailCrm\Exception\CurlException - * @throws \InvalidArgumentException - * - * @return ApiResponse - */ - public function apiVersions() - { - return $this->client->makeRequest('/api-versions', RetailcrmHttpClient::METHOD_GET); - } - - /** - * Returns users list - * - * @param array $filter - * @param null $page - * @param null $limit - * - * @throws \RetailCrm\Exception\InvalidJsonException - * @throws \RetailCrm\Exception\CurlException - * @throws \InvalidArgumentException - * - * @return ApiResponse - */ - public function usersList(array $filter = array(), $page = null, $limit = null) - { - $parameters = array(); - - if (count($filter)) { - $parameters['filter'] = $filter; - } - if (null !== $page) { - $parameters['page'] = (int) $page; - } - if (null !== $limit) { - $parameters['limit'] = (int) $limit; - } - - return $this->client->makeRequest( - '/users', - RetailcrmHttpClient::METHOD_GET, - $parameters - ); - } - - /** - * Returns user data - * - * @param integer $id user ID - * - * @throws \RetailCrm\Exception\InvalidJsonException - * @throws \RetailCrm\Exception\CurlException - * @throws \InvalidArgumentException - * - * @return ApiResponse - */ - public function usersGet($id) - { - return $this->client->makeRequest("/users/$id", RetailcrmHttpClient::METHOD_GET); - } - - /** - * Returns filtered orders list - * - * @param array $filter (default: array()) - * @param int $page (default: null) - * @param int $limit (default: null) - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function ordersList(array $filter = array(), $page = null, $limit = null) - { - $parameters = array(); - - if (count($filter)) { - $parameters['filter'] = $filter; - } - if (null !== $page) { - $parameters['page'] = (int) $page; - } - if (null !== $limit) { - $parameters['limit'] = (int) $limit; - } - - return $this->client->makeRequest( - '/orders', - RetailcrmHttpClient::METHOD_GET, - $parameters - ); - } - - /** - * Create a order - * - * @param array $order order data - * @param string $site (default: null) - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function ordersCreate(array $order, $site = null) - { - if (!count($order)) { - throw new \InvalidArgumentException( - 'Parameter `order` must contains a data' - ); - } - - return $this->client->makeRequest( - '/orders/create', - RetailcrmHttpClient::METHOD_POST, - $this->fillSite($site, array('order' => json_encode($order))) - ); - } - - /** - * Save order IDs' (id and externalId) association in the CRM - * - * @param array $ids order identificators - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function ordersFixExternalIds(array $ids) - { - if (! count($ids)) { - throw new \InvalidArgumentException( - 'Method parameter must contains at least one IDs pair' - ); - } - - return $this->client->makeRequest( - '/orders/fix-external-ids', - RetailcrmHttpClient::METHOD_POST, - array('orders' => json_encode($ids) - ) - ); - } - - /** - * Returns statuses of the orders - * - * @param array $ids (default: array()) - * @param array $externalIds (default: array()) - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function ordersStatuses(array $ids = array(), array $externalIds = array()) - { - $parameters = array(); - - if (count($ids)) { - $parameters['ids'] = $ids; - } - if (count($externalIds)) { - $parameters['externalIds'] = $externalIds; - } - - return $this->client->makeRequest( - '/orders/statuses', - RetailcrmHttpClient::METHOD_GET, - $parameters - ); - } - - /** - * Upload array of the orders - * - * @param array $orders array of orders - * @param string $site (default: null) - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function ordersUpload(array $orders, $site = null) - { - if (!count($orders)) { - throw new \InvalidArgumentException( - 'Parameter `orders` must contains array of the orders' - ); - } - - return $this->client->makeRequest( - '/orders/upload', - RetailcrmHttpClient::METHOD_POST, - $this->fillSite($site, array('orders' => json_encode($orders))) - ); - } - - /** - * Get order by id or externalId - * - * @param string $id order identificator - * @param string $by (default: 'externalId') - * @param string $site (default: null) - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function ordersGet($id, $by = 'externalId', $site = null) - { - $this->checkIdParameter($by); - - return $this->client->makeRequest( - "/orders/$id", - RetailcrmHttpClient::METHOD_GET, - $this->fillSite($site, array('by' => $by)) - ); - } - - /** - * Edit a order - * - * @param array $order order data - * @param string $by (default: 'externalId') - * @param string $site (default: null) - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function ordersEdit(array $order, $by = 'externalId', $site = null) - { - if (!count($order)) { - throw new \InvalidArgumentException( - 'Parameter `order` must contains a data' - ); - } - - $this->checkIdParameter($by); - - if (!array_key_exists($by, $order)) { - throw new \InvalidArgumentException( - sprintf('Order array must contain the "%s" parameter.', $by) - ); - } - - return $this->client->makeRequest( - sprintf('/orders/%s/edit', $order[$by]), - RetailcrmHttpClient::METHOD_POST, - $this->fillSite( - $site, - array('order' => json_encode($order), 'by' => $by) - ) - ); - } - - /** - * Get orders history - * @param array $filter - * @param null $page - * @param null $limit - * - * @return ApiResponse - */ - public function ordersHistory(array $filter = array(), $page = null, $limit = null) - { - $parameters = array(); - - if (count($filter)) { - $parameters['filter'] = $filter; - } - if (null !== $page) { - $parameters['page'] = (int) $page; - } - if (null !== $limit) { - $parameters['limit'] = (int) $limit; - } - - return $this->client->makeRequest( - '/orders/history', - RetailcrmHttpClient::METHOD_GET, - $parameters - ); - } - - /** - * Returns filtered customers list - * - * @param array $filter (default: array()) - * @param int $page (default: null) - * @param int $limit (default: null) - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function customersList(array $filter = array(), $page = null, $limit = null) - { - $parameters = array(); - - if (count($filter)) { - $parameters['filter'] = $filter; - } - if (null !== $page) { - $parameters['page'] = (int) $page; - } - if (null !== $limit) { - $parameters['limit'] = (int) $limit; - } - - return $this->client->makeRequest( - '/customers', - RetailcrmHttpClient::METHOD_GET, - $parameters - ); - } - - /** - * Create a customer - * - * @param array $customer customer data - * @param string $site (default: null) - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function customersCreate(array $customer, $site = null) - { - if (! count($customer)) { - throw new \InvalidArgumentException( - 'Parameter `customer` must contains a data' - ); - } - - return $this->client->makeRequest( - '/customers/create', - RetailcrmHttpClient::METHOD_POST, - $this->fillSite($site, array('customer' => json_encode($customer))) - ); - } - - /** - * Save customer IDs' (id and externalId) association in the CRM - * - * @param array $ids ids mapping - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function customersFixExternalIds(array $ids) - { - if (! count($ids)) { - throw new \InvalidArgumentException( - 'Method parameter must contains at least one IDs pair' - ); - } - - return $this->client->makeRequest( - '/customers/fix-external-ids', - RetailcrmHttpClient::METHOD_POST, - array('customers' => json_encode($ids)) - ); - } - - /** - * Upload array of the customers - * - * @param array $customers array of customers - * @param string $site (default: null) - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function customersUpload(array $customers, $site = null) - { - if (! count($customers)) { - throw new \InvalidArgumentException( - 'Parameter `customers` must contains array of the customers' - ); - } - - return $this->client->makeRequest( - '/customers/upload', - RetailcrmHttpClient::METHOD_POST, - $this->fillSite($site, array('customers' => json_encode($customers))) - ); - } - - /** - * Get customer by id or externalId - * - * @param string $id customer identificator - * @param string $by (default: 'externalId') - * @param string $site (default: null) - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function customersGet($id, $by = 'externalId', $site = null) - { - $this->checkIdParameter($by); - - return $this->client->makeRequest( - "/customers/$id", - RetailcrmHttpClient::METHOD_GET, - $this->fillSite($site, array('by' => $by)) - ); - } - - /** - * Edit a customer - * - * @param array $customer customer data - * @param string $by (default: 'externalId') - * @param string $site (default: null) - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function customersEdit(array $customer, $by = 'externalId', $site = null) - { - if (!count($customer)) { - throw new \InvalidArgumentException( - 'Parameter `customer` must contains a data' - ); - } - - $this->checkIdParameter($by); - - if (!array_key_exists($by, $customer)) { - throw new \InvalidArgumentException( - sprintf('Customer array must contain the "%s" parameter.', $by) - ); - } - - return $this->client->makeRequest( - sprintf('/customers/%s/edit', $customer[$by]), - RetailcrmHttpClient::METHOD_POST, - $this->fillSite( - $site, - array('customer' => json_encode($customer), 'by' => $by) - ) - ); - } - - /** - * Get customers history - * @param array $filter - * @param null $page - * @param null $limit - * - * @return ApiResponse - */ - public function customersHistory(array $filter = array(), $page = null, $limit = null) - { - $parameters = array(); - - if (count($filter)) { - $parameters['filter'] = $filter; - } - if (null !== $page) { - $parameters['page'] = (int) $page; - } - if (null !== $limit) { - $parameters['limit'] = (int) $limit; - } - - return $this->client->makeRequest( - '/customers/history', - RetailcrmHttpClient::METHOD_GET, - $parameters - ); - } - - /** - * Get orders assembly list - * - * @param array $filter (default: array()) - * @param int $page (default: null) - * @param int $limit (default: null) - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function ordersPacksList(array $filter = array(), $page = null, $limit = null) - { - $parameters = array(); - - if (count($filter)) { - $parameters['filter'] = $filter; - } - if (null !== $page) { - $parameters['page'] = (int) $page; - } - if (null !== $limit) { - $parameters['limit'] = (int) $limit; - } - - return $this->client->makeRequest( - '/orders/packs', - RetailcrmHttpClient::METHOD_GET, - $parameters - ); - } - - /** - * Create orders assembly - * - * @param array $pack pack data - * @param string $site (default: null) - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function ordersPacksCreate(array $pack, $site = null) - { - if (!count($pack)) { - throw new \InvalidArgumentException( - 'Parameter `pack` must contains a data' - ); - } - - return $this->client->makeRequest( - '/orders/packs/create', - RetailcrmHttpClient::METHOD_POST, - $this->fillSite($site, array('pack' => json_encode($pack))) - ); - } - - /** - * Get orders assembly history - * - * @param array $filter (default: array()) - * @param int $page (default: null) - * @param int $limit (default: null) - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function ordersPacksHistory(array $filter = array(), $page = null, $limit = null) - { - $parameters = array(); - - if (count($filter)) { - $parameters['filter'] = $filter; - } - if (null !== $page) { - $parameters['page'] = (int) $page; - } - if (null !== $limit) { - $parameters['limit'] = (int) $limit; - } - - return $this->client->makeRequest( - '/orders/packs/history', - RetailcrmHttpClient::METHOD_GET, - $parameters - ); - } - - /** - * Get orders assembly by id - * - * @param string $id pack identificator - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function ordersPacksGet($id) - { - if (empty($id)) { - throw new \InvalidArgumentException('Parameter `id` must be set'); - } - - return $this->client->makeRequest( - "/orders/packs/$id", - RetailcrmHttpClient::METHOD_GET - ); - } - - /** - * Delete orders assembly by id - * - * @param string $id pack identificator - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function ordersPacksDelete($id) - { - if (empty($id)) { - throw new \InvalidArgumentException('Parameter `id` must be set'); - } - - return $this->client->makeRequest( - sprintf('/orders/packs/%s/delete', $id), - RetailcrmHttpClient::METHOD_POST - ); - } - - /** - * Edit orders assembly - * - * @param array $pack pack data - * @param string $site (default: null) - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function ordersPacksEdit(array $pack, $site = null) - { - if (!count($pack) || empty($pack['id'])) { - throw new \InvalidArgumentException( - 'Parameter `pack` must contains a data & pack `id` must be set' - ); - } - - return $this->client->makeRequest( - sprintf('/orders/packs/%s/edit', $pack['id']), - RetailcrmHttpClient::METHOD_POST, - $this->fillSite($site, array('pack' => json_encode($pack))) - ); - } - - /** - * Get purchace prices & stock balance - * - * @param array $filter (default: array()) - * @param int $page (default: null) - * @param int $limit (default: null) - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function storeInventories(array $filter = array(), $page = null, $limit = null) - { - $parameters = array(); - - if (count($filter)) { - $parameters['filter'] = $filter; - } - if (null !== $page) { - $parameters['page'] = (int) $page; - } - if (null !== $limit) { - $parameters['limit'] = (int) $limit; - } - - return $this->client->makeRequest( - '/store/inventories', - RetailcrmHttpClient::METHOD_GET, - $parameters - ); - } - - /** - * Get store settings - * - * @param string $code get settings code - * - * @return ApiResponse - * @throws \RetailCrm\Exception\InvalidJsonException - * @throws \RetailCrm\Exception\CurlException - * @throws \InvalidArgumentException - * - * @return ApiResponse - */ - public function storeSettingsGet($code) - { - if (empty($code)) { - throw new \InvalidArgumentException('Parameter `code` must be set'); - } - - return $this->client->makeRequest( - "/store/setting/$code", - RetailcrmHttpClient::METHOD_GET - ); - } - - /** - * Edit store configuration - * - * @param array $configuration - * - * @throws \RetailCrm\Exception\InvalidJsonException - * @throws \RetailCrm\Exception\CurlException - * @throws \InvalidArgumentException - * - * @return ApiResponse - */ - public function storeSettingsEdit(array $configuration) - { - if (!count($configuration) || empty($configuration['code'])) { - throw new \InvalidArgumentException( - 'Parameter `configuration` must contains a data & configuration `code` must be set' - ); - } - - return $this->client->makeRequest( - sprintf('/store/setting/%s/edit', $configuration['code']), - RetailcrmHttpClient::METHOD_POST, - $configuration - ); - } - - /** - * Upload store inventories - * - * @param array $offers offers data - * @param string $site (default: null) - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function storeInventoriesUpload(array $offers, $site = null) - { - if (!count($offers)) { - throw new \InvalidArgumentException( - 'Parameter `offers` must contains array of the offers' - ); - } - - return $this->client->makeRequest( - '/store/inventories/upload', - RetailcrmHttpClient::METHOD_POST, - $this->fillSite($site, array('offers' => json_encode($offers))) - ); - } - - /** - * Get products - * - * @param array $filter (default: array()) - * @param int $page (default: null) - * @param int $limit (default: null) - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function storeProducts(array $filter = array(), $page = null, $limit = null) - { - $parameters = array(); - - if (count($filter)) { - $parameters['filter'] = $filter; - } - if (null !== $page) { - $parameters['page'] = (int) $page; - } - if (null !== $limit) { - $parameters['limit'] = (int) $limit; - } - - return $this->client->makeRequest( - '/store/products', - RetailcrmHttpClient::METHOD_GET, - $parameters - ); - } - - /** - * Upload prices - * - * @param array $prices (default: array()) - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function storePricesUpload(array $prices = array()) - { - return $this->client->makeRequest( - '/store/prices/upload', - RetailcrmHttpClient::METHOD_POST, - array('prices' => json_encode($prices)) - ); - } - - /** - * Get delivery settings - * - * @param string $code - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function deliverySettingsGet($code) - { - if (empty($code)) { - throw new \InvalidArgumentException('Parameter `code` must be set'); - } - - return $this->client->makeRequest( - "/delivery/generic/setting/$code", - RetailcrmHttpClient::METHOD_GET - ); - } - - /** - * Edit delivery configuration - * - * @param array $configuration - * - * @throws \RetailCrm\Exception\InvalidJsonException - * @throws \RetailCrm\Exception\CurlException - * @throws \InvalidArgumentException - * - * @return ApiResponse - */ - public function deliverySettingsEdit(array $configuration) - { - if (!count($configuration) || empty($configuration['code'])) { - throw new \InvalidArgumentException( - 'Parameter `configuration` must contains a data & configuration `code` must be set' - ); - } - - return $this->client->makeRequest( - sprintf('/delivery/generic/setting/%s/edit', $configuration['code']), - RetailcrmHttpClient::METHOD_POST, - array('configuration' => json_encode($configuration)) - ); - } - - /** - * Delivery tracking update - * - * @param string $code - * @param array $statusUpdate - * - * @throws \RetailCrm\Exception\InvalidJsonException - * @throws \RetailCrm\Exception\CurlException - * @throws \InvalidArgumentException - * - * @return ApiResponse - */ - public function deliveryTracking($code, array $statusUpdate) - { - if (empty($code)) { - throw new \InvalidArgumentException('Parameter `code` must be set'); - } - - if (!count($statusUpdate)) { - throw new \InvalidArgumentException( - 'Parameter `statusUpdate` must contains a data' - ); - } - - return $this->client->makeRequest( - sprintf('/delivery/generic/%s/tracking', $code), - RetailcrmHttpClient::METHOD_POST, - $statusUpdate - ); - } - - /** - * Returns available county list - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function countriesList() - { - return $this->client->makeRequest( - '/reference/countries', - RetailcrmHttpClient::METHOD_GET - ); - } - - /** - * Returns deliveryServices list - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function deliveryServicesList() - { - return $this->client->makeRequest( - '/reference/delivery-services', - RetailcrmHttpClient::METHOD_GET - ); - } - - /** - * Edit deliveryService - * - * @param array $data delivery service data - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function deliveryServicesEdit(array $data) - { - if (!array_key_exists('code', $data)) { - throw new \InvalidArgumentException( - 'Data must contain "code" parameter.' - ); - } - - return $this->client->makeRequest( - sprintf('/reference/delivery-services/%s/edit', $data['code']), - RetailcrmHttpClient::METHOD_POST, - array('deliveryService' => json_encode($data)) - ); - } - - /** - * Returns deliveryTypes list - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function deliveryTypesList() - { - return $this->client->makeRequest( - '/reference/delivery-types', - RetailcrmHttpClient::METHOD_GET - ); - } - - /** - * Edit deliveryType - * - * @param array $data delivery type data - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function deliveryTypesEdit(array $data) - { - if (!array_key_exists('code', $data)) { - throw new \InvalidArgumentException( - 'Data must contain "code" parameter.' - ); - } - - return $this->client->makeRequest( - sprintf('/reference/delivery-types/%s/edit', $data['code']), - RetailcrmHttpClient::METHOD_POST, - array('deliveryType' => json_encode($data)) - ); - } - - /** - * Returns orderMethods list - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function orderMethodsList() - { - return $this->client->makeRequest( - '/reference/order-methods', - RetailcrmHttpClient::METHOD_GET - ); - } - - /** - * Edit orderMethod - * - * @param array $data order method data - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function orderMethodsEdit(array $data) - { - if (!array_key_exists('code', $data)) { - throw new \InvalidArgumentException( - 'Data must contain "code" parameter.' - ); - } - - return $this->client->makeRequest( - sprintf('/reference/order-methods/%s/edit', $data['code']), - RetailcrmHttpClient::METHOD_POST, - array('orderMethod' => json_encode($data)) - ); - } - - /** - * Returns orderTypes list - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function orderTypesList() - { - return $this->client->makeRequest( - '/reference/order-types', - RetailcrmHttpClient::METHOD_GET - ); - } - - /** - * Edit orderType - * - * @param array $data order type data - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function orderTypesEdit(array $data) - { - if (!array_key_exists('code', $data)) { - throw new \InvalidArgumentException( - 'Data must contain "code" parameter.' - ); - } - - return $this->client->makeRequest( - sprintf('/reference/order-types/%s/edit', $data['code']), - RetailcrmHttpClient::METHOD_POST, - array('orderType' => json_encode($data)) - ); - } - - /** - * Returns paymentStatuses list - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function paymentStatusesList() - { - return $this->client->makeRequest( - '/reference/payment-statuses', - RetailcrmHttpClient::METHOD_GET - ); - } - - /** - * Edit paymentStatus - * - * @param array $data payment status data - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function paymentStatusesEdit(array $data) - { - if (!array_key_exists('code', $data)) { - throw new \InvalidArgumentException( - 'Data must contain "code" parameter.' - ); - } - - return $this->client->makeRequest( - sprintf('/reference/payment-statuses/%s/edit', $data['code']), - RetailcrmHttpClient::METHOD_POST, - array('paymentStatus' => json_encode($data)) - ); - } - - /** - * Returns paymentTypes list - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function paymentTypesList() - { - return $this->client->makeRequest( - '/reference/payment-types', - RetailcrmHttpClient::METHOD_GET - ); - } - - /** - * Edit paymentType - * - * @param array $data payment type data - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function paymentTypesEdit(array $data) - { - if (!array_key_exists('code', $data)) { - throw new \InvalidArgumentException( - 'Data must contain "code" parameter.' - ); - } - - return $this->client->makeRequest( - sprintf('/reference/payment-types/%s/edit', $data['code']), - RetailcrmHttpClient::METHOD_POST, - array('paymentType' => json_encode($data)) - ); - } - - /** - * Returns productStatuses list - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function productStatusesList() - { - return $this->client->makeRequest( - '/reference/product-statuses', - RetailcrmHttpClient::METHOD_GET - ); - } - - /** - * Edit productStatus - * - * @param array $data product status data - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function productStatusesEdit(array $data) - { - if (!array_key_exists('code', $data)) { - throw new \InvalidArgumentException( - 'Data must contain "code" parameter.' - ); - } - - return $this->client->makeRequest( - sprintf('/reference/product-statuses/%s/edit', $data['code']), - RetailcrmHttpClient::METHOD_POST, - array('productStatus' => json_encode($data)) - ); - } - - /** - * Returns sites list - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function sitesList() - { - return $this->client->makeRequest( - '/reference/sites', - RetailcrmHttpClient::METHOD_GET - ); - } - - /** - * Edit site - * - * @param array $data site data - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function sitesEdit(array $data) - { - if (!array_key_exists('code', $data)) { - throw new \InvalidArgumentException( - 'Data must contain "code" parameter.' - ); - } - - return $this->client->makeRequest( - sprintf('/reference/sites/%s/edit', $data['code']), - RetailcrmHttpClient::METHOD_POST, - array('site' => json_encode($data)) - ); - } - - /** - * Returns statusGroups list - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function statusGroupsList() - { - return $this->client->makeRequest( - '/reference/status-groups', - RetailcrmHttpClient::METHOD_GET - ); - } - - /** - * Returns statuses list - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function statusesList() - { - return $this->client->makeRequest( - '/reference/statuses', - RetailcrmHttpClient::METHOD_GET - ); - } - - /** - * Edit order status - * - * @param array $data status data - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function statusesEdit(array $data) - { - if (!array_key_exists('code', $data)) { - throw new \InvalidArgumentException( - 'Data must contain "code" parameter.' - ); - } - - return $this->client->makeRequest( - sprintf('/reference/statuses/%s/edit', $data['code']), - RetailcrmHttpClient::METHOD_POST, - array('status' => json_encode($data)) - ); - } - - /** - * Returns stores list - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function storesList() - { - return $this->client->makeRequest( - '/reference/stores', - RetailcrmHttpClient::METHOD_GET - ); - } - - /** - * Edit store - * - * @param array $data site data - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function storesEdit(array $data) - { - if (!array_key_exists('code', $data)) { - throw new \InvalidArgumentException( - 'Data must contain "code" parameter.' - ); - } - - if (!array_key_exists('name', $data)) { - throw new \InvalidArgumentException( - 'Data must contain "name" parameter.' - ); - } - - return $this->client->makeRequest( - sprintf('/reference/stores/%s/edit', $data['code']), - RetailcrmHttpClient::METHOD_POST, - array('store' => json_encode($data)) - ); - } - - /** - * Returns price types list - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function priceTypesList() - { - return $this->client->makeRequest( - '/reference/price-types', - RetailcrmHttpClient::METHOD_GET - ); - } - - /** - * Get telephony settings - * - * @param string $code - * - * @throws \RetailCrm\Exception\InvalidJsonException - * @throws \RetailCrm\Exception\CurlException - * @throws \InvalidArgumentException - * - * @return ApiResponse - */ - public function telephonySettingsGet($code) - { - if (empty($code)) { - throw new \InvalidArgumentException('Parameter `code` must be set'); - } - - return $this->client->makeRequest( - "/telephony/setting/$code", - RetailcrmHttpClient::METHOD_GET - ); - } - - /** - * Edit telephony settings - * - * @param string $code symbolic code - * @param string $clientId client id - * @param boolean $active telephony activity - * @param mixed $name service name - * @param mixed $makeCallUrl service init url - * @param mixed $image service logo url(svg file) - * - * @param array $additionalCodes - * @param array $externalPhones - * @param bool $allowEdit - * @param bool $inputEventSupported - * @param bool $outputEventSupported - * @param bool $hangupEventSupported - * @param bool $changeUserStatusUrl - * - * @return ApiResponse - */ - public function telephonySettingsEdit( - $code, - $clientId, - $active = false, - $name = false, - $makeCallUrl = false, - $image = false, - $additionalCodes = array(), - $externalPhones = array(), - $allowEdit = false, - $inputEventSupported = false, - $outputEventSupported = false, - $hangupEventSupported = false, - $changeUserStatusUrl = false - ) - { - if (!isset($code)) { - throw new \InvalidArgumentException('Code must be set'); - } - - $parameters['code'] = $code; - - if (!isset($clientId)) { - throw new \InvalidArgumentException('client id must be set'); - } - - $parameters['clientId'] = $clientId; - - if (!isset($active)) { - $parameters['active'] = false; - } else { - $parameters['active'] = $active; - } - - if (!isset($name)) { - throw new \InvalidArgumentException('name must be set'); - } - - if (isset($name)) { - $parameters['name'] = $name; - } - - if (isset($makeCallUrl)) { - $parameters['makeCallUrl'] = $makeCallUrl; - } - - if (isset($image)) { - $parameters['image'] = $image; - } - - if (isset($additionalCodes)) { - $parameters['additionalCodes'] = $additionalCodes; - } - - if (isset($externalPhones)) { - $parameters['externalPhones'] = $externalPhones; - } - - if (isset($allowEdit)) { - $parameters['allowEdit'] = $allowEdit; - } - - if (isset($inputEventSupported)) { - $parameters['inputEventSupported'] = $inputEventSupported; - } - - if (isset($outputEventSupported)) { - $parameters['outputEventSupported'] = $outputEventSupported; - } - - if (isset($hangupEventSupported)) { - $parameters['hangupEventSupported'] = $hangupEventSupported; - } - - if (isset($changeUserStatusUrl)) { - $parameters['changeUserStatusUrl'] = $changeUserStatusUrl; - } - - return $this->client->makeRequest( - "/telephony/setting/$code/edit", - RetailcrmHttpClient::METHOD_POST, - array('configuration' => json_encode($parameters)) - ); - } - - /** - * Call event - * - * @param string $phone phone number - * @param string $type call type - * @param array $codes - * @param string $hangupStatus - * @param string $externalPhone - * @param array $webAnalyticsData - * - * @return ApiResponse - * @internal param string $code additional phone code - * @internal param string $status call status - * - */ - public function telephonyCallEvent( - $phone, - $type, - $codes, - $hangupStatus, - $externalPhone = null, - $webAnalyticsData = array() - ) - { - if (!isset($phone)) { - throw new \InvalidArgumentException('Phone number must be set'); - } - - if (!isset($type)) { - throw new \InvalidArgumentException('Type must be set (in|out|hangup)'); - } - - if (empty($codes)) { - throw new \InvalidArgumentException('Codes array must be set'); - } - - $parameters['phone'] = $phone; - $parameters['type'] = $type; - $parameters['codes'] = $codes; - $parameters['hangupStatus'] = $hangupStatus; - $parameters['callExternalId'] = $externalPhone; - $parameters['webAnalyticsData'] = $webAnalyticsData; - - - return $this->client->makeRequest( - '/telephony/call/event', - RetailcrmHttpClient::METHOD_POST, - array('event' => json_encode($parameters)) - ); - } - - /** - * Upload calls - * - * @param array $calls calls data - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function telephonyCallsUpload(array $calls) - { - if (!count($calls)) { - throw new \InvalidArgumentException( - 'Parameter `calls` must contains array of the calls' - ); - } - - return $this->client->makeRequest( - '/telephony/calls/upload', - RetailcrmHttpClient::METHOD_POST, - array('calls' => json_encode($calls)) - ); - } - - /** - * Get call manager - * - * @param string $phone phone number - * @param bool $details detailed information - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function telephonyCallManager($phone, $details) - { - if (!isset($phone)) { - throw new \InvalidArgumentException('Phone number must be set'); - } - - $parameters['phone'] = $phone; - $parameters['details'] = isset($details) ? $details : 0; - - return $this->client->makeRequest( - '/telephony/manager', - RetailcrmHttpClient::METHOD_GET, - $parameters - ); - } - - /** - * Update CRM basic statistic - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function statisticUpdate() - { - return $this->client->makeRequest( - '/statistic/update', - RetailcrmHttpClient::METHOD_GET - ); - } - - /** - * Return current site - * - * @return string - */ - public function getSite() - { - return $this->siteCode; - } - - /** - * Set site - * - * @param string $site site code - * - * @return void - */ - public function setSite($site) - { - $this->siteCode = $site; - } - - /** - * Check ID parameter - * - * @param string $by identify by - * - * @throws \InvalidArgumentException - * - * @return bool - */ - protected function checkIdParameter($by) - { - $allowedForBy = array( - 'externalId', - 'id' - ); - - if (!in_array($by, $allowedForBy, false)) { - throw new \InvalidArgumentException( - sprintf( - 'Value "%s" for "by" param is not valid. Allowed values are %s.', - $by, - implode(', ', $allowedForBy) - ) - ); - } - - return true; - } - - /** - * Fill params by site value - * - * @param string $site site code - * @param array $params input parameters - * - * @return array - */ - protected function fillSite($site, array $params) - { - if ($site) { - $params['site'] = $site; - } elseif ($this->siteCode) { - $params['site'] = $this->siteCode; - } - - return $params; - } -} diff --git a/src/upload/system/library/retailcrm/CurlException.php b/src/upload/system/library/retailcrm/api/CurlException.php similarity index 100% rename from src/upload/system/library/retailcrm/CurlException.php rename to src/upload/system/library/retailcrm/api/CurlException.php diff --git a/src/upload/system/library/retailcrm/InvalidJsonException.php b/src/upload/system/library/retailcrm/api/InvalidJsonException.php similarity index 100% rename from src/upload/system/library/retailcrm/InvalidJsonException.php rename to src/upload/system/library/retailcrm/api/InvalidJsonException.php diff --git a/src/upload/system/library/retailcrm/RetailcrmApiClient5.php b/src/upload/system/library/retailcrm/api/RetailcrmApiClient5.php similarity index 100% rename from src/upload/system/library/retailcrm/RetailcrmApiClient5.php rename to src/upload/system/library/retailcrm/api/RetailcrmApiClient5.php diff --git a/src/upload/system/library/retailcrm/RetailcrmApiResponse.php b/src/upload/system/library/retailcrm/api/RetailcrmApiResponse.php similarity index 100% rename from src/upload/system/library/retailcrm/RetailcrmApiResponse.php rename to src/upload/system/library/retailcrm/api/RetailcrmApiResponse.php diff --git a/src/upload/system/library/retailcrm/RetailcrmHttpClient.php b/src/upload/system/library/retailcrm/api/RetailcrmHttpClient.php similarity index 100% rename from src/upload/system/library/retailcrm/RetailcrmHttpClient.php rename to src/upload/system/library/retailcrm/api/RetailcrmHttpClient.php diff --git a/src/upload/system/library/retailcrm/RetailcrmProxy.php b/src/upload/system/library/retailcrm/api/RetailcrmProxy.php similarity index 76% rename from src/upload/system/library/retailcrm/RetailcrmProxy.php rename to src/upload/system/library/retailcrm/api/RetailcrmProxy.php index bbf687f..f0e9001 100644 --- a/src/upload/system/library/retailcrm/RetailcrmProxy.php +++ b/src/upload/system/library/retailcrm/api/RetailcrmProxy.php @@ -6,34 +6,24 @@ */ class RetailcrmProxy { - private $api; private $log; public function __construct($url, $key, $log, $version = null) - { + { switch ($version) { case 'v5': $this->api = new RetailcrmApiClient5($url, $key, $version); break; - case 'v4': - $this->api = new RetailcrmApiClient4($url, $key, $version); - break; - case 'v3': - $this->api = new RetailcrmApiClient3($url, $key, $version); - break; - case null: - $this->api = new RetailcrmApiClient3($url, $key, $version); - break; } $this->log = $log; } public function __call($method, $arguments) - { + { $date = date('[Y-m-d H:i:s]'); - + try { $response = call_user_func_array(array($this->api, $method), $arguments); diff --git a/src/upload/system/library/retailcrm/bootstrap.php b/src/upload/system/library/retailcrm/api/bootstrap.php similarity index 100% rename from src/upload/system/library/retailcrm/bootstrap.php rename to src/upload/system/library/retailcrm/api/bootstrap.php diff --git a/src/upload/system/library/retailcrm/base.php b/src/upload/system/library/retailcrm/base.php new file mode 100644 index 0000000..a0a5e8c --- /dev/null +++ b/src/upload/system/library/retailcrm/base.php @@ -0,0 +1,140 @@ +registry = $registry; + } + + /** + * @param $name + * + * @return mixed + */ + public function __get($name) { + return $this->registry->get($name); + } + + /** + * @param $field + * @param $value + * + * @return bool + */ + public function setField($field, $value) { + if (!isset($this->data[$field])) { + return false; + } + + $this->data[$field] = $value; + + return true; + } + + /** + * @param $fields + */ + public function setFields($fields) { + foreach ($fields as $field) { + $this->setField($field['field'], $field['value']); + } + } + + /** + * @param $data + * @param $element + */ + public function setDataArray($data, $element) { + if (is_array($data)) { + $this->setField($element, $data); + } + } + + /** + * @param array $custom_fields + * @param array $setting + * @param string $prefix + * + * @return array + */ + protected function prepareCustomFields($custom_fields, $setting, $prefix) { + $result = array(); + + if (!$custom_fields || empty($custom_fields)) { + return $result; + } + + foreach ($custom_fields as $loc => $custom_field) { + if (\is_int($loc)) { + $result = $this->getCustomFields($custom_field, $setting, $prefix); + } elseif (\is_string($loc)) { + foreach ($custom_field as $field) { + if (!$field) { + continue; + } + + $result = $this->getCustomFields($field, $setting, $prefix); + } + } + } + + return $result; + } + + /** + * @param array $custom_fields + * @param array $setting + * @param string $prefix + * + * @return array $result + */ + private function getCustomFields($custom_fields, $setting, $prefix) { + $result = array(); + + foreach ($custom_fields as $key => $field) { + if (isset($setting[\Retailcrm\Retailcrm::MODULE. '_custom_field'][$prefix . $key])) { + $result[$setting[\Retailcrm\Retailcrm::MODULE. '_custom_field'][$prefix . $key]] = $field; + } + } + + return $result; + } + + /** + * Prepare data array + * + * @param $data + * + * @return void + */ + abstract function prepare($data); + + /** + * Send to crm + * + * @param $retailcrm_api_client + * + * @return void + */ + abstract function create($retailcrm_api_client); + + /** + * Edit in crm + * + * @param $retailcrm_api_client + * + * @return void + */ + abstract function edit($retailcrm_api_client); +} diff --git a/src/upload/system/library/retailcrm/customer.php b/src/upload/system/library/retailcrm/customer.php new file mode 100644 index 0000000..1b9eaca --- /dev/null +++ b/src/upload/system/library/retailcrm/customer.php @@ -0,0 +1,65 @@ + 0, + 'createdAt' => null, + 'firstName' => null, + 'lastName' => null, + 'patronymic' => null, + 'email' => null, + 'phones' => array(), + 'address' => array(), + 'customFields' => array() + ); + + public function prepare($customer) { + if (file_exists(DIR_SYSTEM . 'library/retailcrm/custom.php')) { + $custom = new \Retailcrm\Custom($this->registry); + $this->data = $custom->processCustomer($customer); + } else { + $this->load->model('setting/setting'); + $setting = $this->model_setting_setting->getSetting(\Retailcrm\Retailcrm::MODULE); + + if (isset($customer['firstname']) && $customer['firstname']) { + $this->setField('firstName', $customer['firstname']); + } + + if (isset($customer['lastname']) && $customer['lastname']) { + $this->setField('lastName', $customer['lastname']); + } + + if (isset($customer['telephone']) && $customer['telephone']) { + $phones = array( + array( + 'number' => $customer['telephone'] + ) + ); + $this->setDataArray($phones, 'phones'); + } + + $this->setField('email', $customer['email']); + $this->setField('createdAt', date('Y-m-d H:i:s')); + + if (isset($settings[\Retailcrm\Retailcrm::MODULE . '_custom_field']) && $customer['custom_field']) { + $custom_fields = $this->prepareCustomFields($customer['custom_field'], $setting, 'c_'); + + if ($custom_fields) { + $this->setDataArray($custom_fields, 'customFields'); + } + } + } + } + + public function create($retailctm_api_client) { + $retailctm_api_client->customersCreate($this->data); + } + + public function edit($retailctm_api_client) { + $retailctm_api_client->customersEdit($this->data); + } +} diff --git a/src/upload/system/library/retailcrm/order.php b/src/upload/system/library/retailcrm/order.php new file mode 100644 index 0000000..4013e88 --- /dev/null +++ b/src/upload/system/library/retailcrm/order.php @@ -0,0 +1,241 @@ + 0, + 'countryIso' => null, + 'externalId' => 0, + 'customer' => array(), + 'status' => null, + 'firstName' => null, + 'lastName' => null, + 'patronymic' => null, + 'email' => null, + 'phone' => null, + 'discountManualAmount' => 0, + 'items' => array(), + 'delivery' => array(), + 'customFields' => array(), + 'payments' => array() + ); + + public function prepare($order) { + if (file_exists(DIR_SYSTEM . 'library/retailcrm/custom.php')) { + $custom = new \Retailcrm\Custom($this->registry); + $this->data = $custom->processOrder($order); + } else { + $this->load->model('setting/setting'); + $this->load->model('catalog/product'); + $settings = $this->model_setting_setting->getSetting(\Retailcrm\Retailcrm::MODULE); + $delivery_settings = $settings[\Retailcrm\Retailcrm::MODULE . '_delivery']; + $payments_settings = $settings[\Retailcrm\Retailcrm::MODULE . '_payment']; + $status_settings = $settings[\Retailcrm\Retailcrm::MODULE . '_status']; + + $totals = $this->explodeTotals($order['totals']); + $coupon_total = 0; + $delivery_cost = 0; + + if (isset($totals['shipping'])) { + $delivery_cost = $totals['shipping']; + } + + if (isset($totals['coupon'])) { + $coupon_total += abs($totals['coupon']); + } + + if (isset($totals['reward'])) { + $coupon_total += abs($totals['reward']); + } + + if (isset($order['order_status_id']) && $order['order_status_id'] > 0) { + $status = $status_settings[$order['order_status_id']]; + } elseif (isset($order['order_status_id']) && $order['order_status_id'] == 0) { + $status = $settings[\Retailcrm\Retailcrm::MODULE . '_missing_status']; + } + + $fields = array( + 'firstName' => $order['firstname'], + 'lastName' => $order['lastname'], + 'email' => $order['email'], + 'phone' => $order['telephone'], + 'customerComment' => $order['comment'], + 'createdAt' => $order['date_added'], + 'discountManualAmount' => $coupon_total, + 'status' => $status + ); + + $this->setFields($fields); + if (isset($order['shipping_code'])) { + $delivery_code = $this->getDeliveryMethod($order['shipping_code'], $delivery_settings); + } + + $delivery = array( + 'address' => array( + 'index' => isset($order['shipping_postcode']) ? $order['shipping_postcode'] : '', + 'city' => isset($order['shipping_city']) ? $order['shipping_city'] : '', + 'region' => isset($order['shipping_zone']) ? $order['shipping_zone'] : '', + 'text' => implode(', ', array( + isset($order['shipping_postcode']) ? $order['shipping_postcode'] : '', + isset($order['shipping_country']) ? $order['shipping_country'] : '', + isset($order['shipping_city']) ? $order['shipping_city'] : '', + isset($order['shipping_address_1']) ? $order['shipping_address_1'] : '', + isset($order['shipping_address_2']) ? $order['shipping_address_2'] : '' + )) + ) + ); + + if (isset($delivery_code)) { + $delivery['code'] = $delivery_code; + } + + if ($delivery_cost) { + $delivery['cost'] = $delivery_cost; + } + + $this->setDataArray($delivery, 'delivery'); + $this->setOrderProducts($order['products']); + $payments = array(); + + if (isset($payments_settings[$order['payment_code']])) { + $payment = array( + 'order' => array( + 'externalId' => $order['order_id'] + ), + 'externalId' => $order['order_id'], + 'type' => $payments_settings[$order['payment_code']], + 'amount' => $order['total'] + ); + + $payments[] = $payment; + } + + $this->setDataArray($payments, 'payments'); + + if (isset($settings[\Retailcrm\Retailcrm::MODULE . '_custom_field']) && $order['custom_field']) { + $custom_fields = $this->prepareCustomFields($order['custom_field'], $settings, 'o_'); + + if ($custom_fields) { + $this->setDataArray($custom_fields, 'customFields'); + } + } + } + } + + public function create($retailcrm_api_client) { + $retailcrm_api_client->ordersCreate($this->data); + } + + public function edit($retailcrm_api_client) { + $retailcrm_api_client->ordersEdit($this->data); + } + + /** + * @param string $shipping_code + * @param array $deliveries + * + * @return mixed + */ + private function getDeliveryMethod($shipping_code, $deliveries) { + if (!empty($shipping_code)) { + $shipping_code_array = explode('.', $shipping_code); + $shipping_module = $shipping_code_array[0]; + + if (isset($deliveries[$shipping_code])) { + $delivery_code = $deliveries[$shipping_code]; + } elseif (isset($deliveries[$shipping_module])) { + $delivery_code = $deliveries[$shipping_module]; + } + } + + if (!isset($delivery_code) && isset($shipping_module) && $deliveries) { + $delivery = ''; + + array_walk($deliveries, function ($item, $key) use ($shipping_module, &$delivery) { + if (strripos($item, $shipping_module) !== false) { + $delivery = $item; + } + }); + + $delivery_code = $deliveries[$delivery]; + } + + return $delivery_code; + } + + /** + * @param array $products + * + * @return void + */ + private function setOrderProducts($products) { + $offer_options = array('select', 'radio'); + $items = array(); + + foreach ($products as $product) { + if (!empty($product['option'])) { + $offer_id = ''; + $options = array(); + $properties = array(); + + foreach ($product['option'] as $option) { + if ($option['type'] == 'checkbox') { + $properties[] = array( + 'code' => $option['product_option_value_id'], + 'name' => $option['name'], + 'value' => $option['value'] + ); + } + + if (!in_array($option['type'], $offer_options)) { + continue; + } + + $options[$option['product_option_id']] = $option['option_value_id']; + } + + ksort($options); + + foreach ($options as $optionKey => $optionValue) { + $offer_id .= $optionKey . '-' . $optionValue; + } + } + + $item = array( + 'offer' => array( + 'externalId' => !empty($offer_id) ? $product['product_id'] . '#' . $offer_id : $product['product_id'] + ), + 'productName' => $product['name'], + 'initialPrice' => $product['price'], + 'quantity' => $product['quantity'], + ); + + if (!empty($properties)) { + $item['properties'] = $properties; + } + + $items[] = $item; + } + + $this->setDataArray($items, 'items'); + } + + /** + * @param $totals + * + * @return array + */ + private function explodeTotals($totals) + { + $resultTotals = array(); + + foreach ($totals as $total) { + $resultTotals[$total['code']] = $total['value']; + } + + return $resultTotals; + } +} diff --git a/src/upload/system/library/retailcrm/retailcrm.php b/src/upload/system/library/retailcrm/retailcrm.php index 525a43b..6d7dffc 100644 --- a/src/upload/system/library/retailcrm/retailcrm.php +++ b/src/upload/system/library/retailcrm/retailcrm.php @@ -1,13 +1,14 @@ registry = $registry; @@ -17,6 +18,10 @@ class Retailcrm { return $this->registry->get($name); } + public function createObject($object) { + return new $object($this->registry); + } + /** * Get api client object * @@ -24,21 +29,21 @@ class Retailcrm { * @param string $apiKey (default = null) * @param string $apiVersion (default = null) * - * @return mixed object | boolean + * @return mixed object | boolean */ public function getApiClient($apiUrl = null, $apiKey = null, $apiVersion = null) { $this->load->model('setting/setting'); - $setting = $this->model_setting_setting->getSetting($this->getModuleTitle()); + $setting = $this->model_setting_setting->getSetting(self::MODULE); if ($apiUrl === null && $apiKey === null) { - $apiUrl = isset($setting[$this->getModuleTitle() . '_url']) - ? $setting[$this->getModuleTitle() . '_url'] : ''; - $apiKey = isset($setting[$this->getModuleTitle() . '_apikey']) - ? $setting[$this->getModuleTitle() . '_apikey'] : ''; - $apiVersion = isset($setting[$this->getModuleTitle() . '_apiversion']) - ? $setting[$this->getModuleTitle() . '_apiversion'] : ''; + $apiUrl = isset($setting[self::MODULE . '_url']) + ? $setting[self::MODULE . '_url'] : ''; + $apiKey = isset($setting[self::MODULE . '_apikey']) + ? $setting[self::MODULE . '_apikey'] : ''; + $apiVersion = isset($setting[self::MODULE . '_apiversion']) + ? $setting[self::MODULE . '_apiversion'] : ''; } if ($apiUrl && $apiKey) { @@ -60,38 +65,6 @@ class Retailcrm { return new \OpencartApiClient($registry); } - /** - * Get module title for this version - * - * @return string $title - */ - public function getModuleTitle() - { - if (version_compare(VERSION, '3.0', '<')) { - $title = 'retailcrm'; - } else { - $title = 'module_retailcrm'; - } - - return $title; - } - - /** - * Get token param name - * - * @return string $token - */ - public function getTokenTitle() - { - if (version_compare(VERSION, '3.0', '<')) { - $token = 'token'; - } else { - $token = 'user_token'; - } - - return $token; - } - public function getOffers($product) { // Формируем офферы отнсительно доступных опций @@ -100,8 +73,8 @@ class Retailcrm { $requiredOptions = array(); $notRequiredOptions = array(); // Оставляем опции связанные с вариациями товаров, сортируем по параметру обязательный или нет - foreach($options as $option) { - if(in_array($option['type'], $offerOptions)) { + foreach ($options as $option) { + if (in_array($option['type'], $offerOptions)) { if($option['required']) { $requiredOptions[] = $option; } else { @@ -112,19 +85,19 @@ class Retailcrm { $offers = array(); // Сначала совмещаем все обязательные опции - foreach($requiredOptions as $requiredOption) { + foreach ($requiredOptions as $requiredOption) { // Если первая итерация - if(empty($offers)) { - foreach($requiredOption['product_option_value'] as $optionValue) { + if (empty($offers)) { + foreach ($requiredOption['product_option_value'] as $optionValue) { $offers[$requiredOption['product_option_id'].':'.$requiredOption['option_id'].'-'.$optionValue['option_value_id']] = array( 'price' => (float)$optionValue['price'], 'qty' => $optionValue['quantity'] ); } } else { - foreach($offers as $optionKey => $optionAttr) { + foreach ($offers as $optionKey => $optionAttr) { unset($offers[$optionKey]); // Работая в контексте обязательных опций не забываем удалять прошлые обязательные опции, т.к. они должны быть скомбинированы с другими обязательными опциями - foreach($requiredOption['product_option_value'] as $optionValue) { + foreach ($requiredOption['product_option_value'] as $optionValue) { $offers[$optionKey.'_'.$requiredOption['product_option_id'].':'.$requiredOption['option_id'].'-'.$optionValue['option_value_id']] = array( 'price' => $optionAttr['price'] + (float)$optionValue['price'], 'qty' => ($optionAttr['qty'] > $optionValue['quantity']) ? @@ -134,21 +107,21 @@ class Retailcrm { } } } - + // Совмещаем или добавляем необязательные опции, учитывая тот факт что обязательных опций может и не быть. - foreach($notRequiredOptions as $notRequiredOption) { + foreach ($notRequiredOptions as $notRequiredOption) { // Если обязательных опцией не оказалось и первая итерация - if(empty($offers)) { + if (empty($offers)) { $offers['0:0-0'] = 0; // В случае работы с необязательными опциями мы должны учитывать товарное предложение без опций, поэтому создадим "пустую" опцию - foreach($notRequiredOption['product_option_value'] as $optionValue) { + foreach ($notRequiredOption['product_option_value'] as $optionValue) { $offers[$notRequiredOption['product_option_id'].':'.$notRequiredOption['option_id'].'-'.$optionValue['option_value_id']] = array( 'price' => (float)$optionValue['price'], 'qty' => $optionValue['quantity'] ); } } else { - foreach($offers as $optionKey => $optionAttr) { - foreach($notRequiredOption['product_option_value'] as $optionValue) { + foreach ($offers as $optionKey => $optionAttr) { + foreach ($notRequiredOption['product_option_value'] as $optionValue) { $offers[$optionKey.'_'.$notRequiredOption['product_option_id'].':'.$notRequiredOption['option_id'].'-'.$optionValue['option_value_id']] = array( 'price' => $optionAttr['price'] + (float)$optionValue['price'], 'qty' => ($optionAttr['qty'] > $optionValue['quantity']) ? @@ -159,7 +132,7 @@ class Retailcrm { } } - if(empty($offers)) { + if (empty($offers)) { $offers = array('0:0-0' => array('price' => '0', 'qty' => '0')); } diff --git a/tests/admin/ControllerRetailcrmAdminTest.php b/tests/admin/ControllerRetailcrmAdminTest.php index bc8dd01..6be635d 100644 --- a/tests/admin/ControllerRetailcrmAdminTest.php +++ b/tests/admin/ControllerRetailcrmAdminTest.php @@ -14,7 +14,7 @@ class ControllerRetailcrmAdminTest extends OpenCartTest $this->db->query("UPDATE ".DB_PREFIX."user_group SET permission='".$this->db->escape(json_encode($permissions))."' WHERE name = 'Administrator'"); } - $this->retailcrm = $this->getMockBuilder('\retailcrm\Retailcrm') + $this->retailcrm = $this->getMockBuilder('\retailcrm\retailcrm') ->disableOriginalConstructor() ->getMock(); } diff --git a/tests/admin/ModelRetailcrmOrderAdminTest.php b/tests/admin/ModelRetailcrmOrderAdminTest.php index 3ed8d70..fa2ffaf 100644 --- a/tests/admin/ModelRetailcrmOrderAdminTest.php +++ b/tests/admin/ModelRetailcrmOrderAdminTest.php @@ -29,7 +29,7 @@ class ModelRetailcrmOrderAdminTest extends OpenCartTest ->getMock(); $this->settingModel = $this->loadModel('setting/setting'); - $this->retailcrm = new \retailcrm\Retailcrm(self::$registry); + $this->retailcrm = new \retailcrm\retailcrm(self::$registry); $this->settingModel->editSetting( $this->retailcrm->getModuleTitle(), diff --git a/tests/admin/ModelRetailcrmPricesAdminTest.php b/tests/admin/ModelRetailcrmPricesAdminTest.php index 150cfee..a9b4b6d 100644 --- a/tests/admin/ModelRetailcrmPricesAdminTest.php +++ b/tests/admin/ModelRetailcrmPricesAdminTest.php @@ -22,7 +22,7 @@ class ModelRetailcrmPricesAdminTest extends OpenCartTest ->getMock(); $this->settingModel = $this->loadModel('setting/setting'); - $this->retailcrm = new \retailcrm\Retailcrm(self::$registry); + $this->retailcrm = new \retailcrm\retailcrm(self::$registry); $this->settingModel->editSetting( $this->retailcrm->getModuleTitle(), diff --git a/tests/catalog/ControllerRetailcrmApiCatalogTest.php b/tests/catalog/ControllerRetailcrmApiCatalogTest.php index 6afaff5..798e8af 100644 --- a/tests/catalog/ControllerRetailcrmApiCatalogTest.php +++ b/tests/catalog/ControllerRetailcrmApiCatalogTest.php @@ -14,7 +14,7 @@ class ControllerRetailcrmApiCatalogTest extends OpenCartTest $query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "api` WHERE api_id = 1"); $api = $query->row; $this->apiKey = $api['key']; - $this->retailcrm = new \retailcrm\Retailcrm(self::$registry); + $this->retailcrm = new \retailcrm\retailcrm(self::$registry); $this->setSetting( $this->retailcrm->getModuleTitle(), diff --git a/tests/catalog/ModelRetailcrmOrderCatalogTest.php b/tests/catalog/ModelRetailcrmOrderCatalogTest.php index 88ee084..4f199e3 100644 --- a/tests/catalog/ModelRetailcrmOrderCatalogTest.php +++ b/tests/catalog/ModelRetailcrmOrderCatalogTest.php @@ -27,7 +27,7 @@ class ModelRetailcrmOrderCatalogTest extends OpenCartTest )) ->getMock(); - $this->retailcrm = new \retailcrm\Retailcrm(self::$registry); + $this->retailcrm = new \retailcrm\retailcrm(self::$registry); $this->setSetting( $this->retailcrm->getModuleTitle(),