diff --git a/admin/controller/extension/module/retailcrm.php b/admin/controller/extension/module/retailcrm.php index 2af82fb..13533e7 100644 --- a/admin/controller/extension/module/retailcrm.php +++ b/admin/controller/extension/module/retailcrm.php @@ -9,7 +9,7 @@ require_once DIR_SYSTEM . 'library/retailcrm/bootstrap.php'; * @package RetailCrm * @author RetailCrm * @license https://opensource.org/licenses/MIT MIT License - * @link http://www.retailcrm.ru/docs/Developers/ApiVersion3 + * @link http://www.retailcrm.ru/docs/Developers/ApiVersion5 */ class ControllerExtensionModuleRetailcrm extends Controller { @@ -24,54 +24,56 @@ class ControllerExtensionModuleRetailcrm extends Controller */ public function install() { + $moduleTitle = $this->getModuleTitle(); $this->load->model('setting/setting'); + $this->model_setting_setting - ->editSetting('retailcrm', array( - 'retailcrm_status' => 1, - 'retailcrm_country' => array($this->config->get('config_country_id')) + ->editSetting($moduleTitle, array( + $moduleTitle . '_status' => 1, + $moduleTitle . '_country' => array($this->config->get('config_country_id')) ) ); + + $this->loadModels(); - $this->load->model('extension/event'); - - $this->model_extension_event + $this->{'model_' . $this->modelEvent} ->addEvent( - 'retailcrm', + $moduleTitle, 'catalog/model/checkout/order/addOrder/after', 'extension/module/retailcrm/order_create' ); - $this->model_extension_event + $this->{'model_' . $this->modelEvent} ->addEvent( - 'retailcrm', + $moduleTitle, 'catalog/model/checkout/order/addOrderHistory/after', 'extension/module/retailcrm/order_edit' ); - $this->model_extension_event + $this->{'model_' . $this->modelEvent} ->addEvent( - 'retailcrm', + $moduleTitle, 'catalog/model/account/customer/addCustomer/after', 'extension/module/retailcrm/customer_create' ); - $this->model_extension_event + $this->{'model_' . $this->modelEvent} ->addEvent( - 'retailcrm', + $moduleTitle, 'catalog/model/account/customer/editCustomer/after', 'extension/module/retailcrm/customer_edit' ); - $this->model_extension_event + $this->{'model_' . $this->modelEvent} ->addEvent( - 'retailcrm', + $moduleTitle, 'catalog/model/account/address/editAddress/after', 'extension/module/retailcrm/customer_edit' ); - $this->model_extension_event + $this->{'model_' . $this->modelEvent} ->addEvent( - 'retailcrm', + $moduleTitle, 'admin/model/customer/customer/editCustomer/after', 'extension/module/retailcrm/customer_edit' ); @@ -84,13 +86,15 @@ class ControllerExtensionModuleRetailcrm extends Controller */ public function uninstall() { + $moduleTitle = $this->getModuleTitle(); $this->uninstall_collector(); $this->load->model('setting/setting'); $this->model_setting_setting - ->editSetting('retailcrm', array('retailcrm_status' => 0)); + ->editSetting($moduleTitle, array($moduleTitle . '_status' => 0)); - $this->load->model('extension/event'); - $this->model_extension_event->deleteEvent('retailcrm'); + $this->loadModels(); + + $this->{'model_' . $this->modelEvent}->deleteEvent($moduleTitle); } /** @@ -99,11 +103,13 @@ class ControllerExtensionModuleRetailcrm extends Controller * @return void */ public function install_collector() - { - $this->load->model('extension/extension'); + { + $collector = $this->getCollectorTitle(); + $moduleTitle = $this->getModuleTitle(); + $this->loadModels(); $this->load->model('setting/setting'); - $this->model_extension_extension->install('analytics', 'daemon_collector'); - $this->model_setting_setting->editSetting('daemon_collector', array('daemon_collector_status' => 1)); + $this->{'model_' . $this->modelExtension}->install('analytics', $collector); + $this->model_setting_setting->editSetting($collector, array($collector . '_status' => 1)); } /** @@ -112,11 +118,12 @@ class ControllerExtensionModuleRetailcrm extends Controller * @return void */ public function uninstall_collector() - { - $this->load->model('extension/extension'); + { + $collector = $this->getCollectorTitle(); + $this->loadModels(); $this->load->model('setting/setting'); - $this->model_setting_setting->editSetting('daemon_collector', array('daemon_collector_status' => 0)); - $this->model_extension_extension->uninstall('analytics', 'daemon_collector'); + $this->model_setting_setting->editSetting($collector, array($collector . '_status' => 0)); + $this->{'model_' . $this->modelExtension}->uninstall('analytics', $collector); } /** @@ -126,38 +133,41 @@ class ControllerExtensionModuleRetailcrm extends Controller */ public function index() { - $this->load->model('extension/extension'); + $this->loadModels(); $this->load->model('localisation/country'); $this->load->model('setting/setting'); - $this->load->model('extension/module'); $this->load->model('extension/retailcrm/references'); $this->load->language('extension/module/retailcrm'); $this->document->setTitle($this->language->get('heading_title')); $this->document->addStyle('/admin/view/stylesheet/retailcrm.css'); + $tokenTitle = $this->getTokenTitle(); + $moduleTitle = $this->getModuleTitle(); + $collector = $this->getCollectorTitle(); + if ($this->request->server['REQUEST_METHOD'] == 'POST' && $this->validate()) { - $analytics = $this->model_extension_extension->getInstalled('analytics'); - - if ($this->request->post['retailcrm_collector_active'] == 1 && - !in_array('daemon_collector', $analytics)) { + $analytics = $this->{'model_' . $this->modelExtension}->getInstalled('analytics'); + + if ($this->request->post[$moduleTitle . '_collector_active'] == 1 && + !in_array($collector, $analytics)) { $this->install_collector(); - } elseif ($this->request->post['retailcrm_collector_active'] == 0 && - in_array('daemon_collector', $analytics)) { + } elseif ($this->request->post[$moduleTitle . '_collector_active'] == 0 && + in_array($collector, $analytics)) { $this->uninstall_collector(); } - if (parse_url($this->request->post['retailcrm_url'])){ - $crm_url = parse_url($this->request->post['retailcrm_url'], PHP_URL_HOST); - $this->request->post['retailcrm_url'] = 'https://'.$crm_url; + if (parse_url($this->request->post[$moduleTitle . '_url'])){ + $crm_url = parse_url($this->request->post[$moduleTitle . '_url'], PHP_URL_HOST); + $this->request->post[$moduleTitle . '_url'] = 'https://'.$crm_url; } $this->model_setting_setting->editSetting( - 'retailcrm', + $moduleTitle, $this->request->post ); $this->session->data['success'] = $this->language->get('text_success'); $redirect = $this->url->link( - 'extension/module/retailcrm', 'token=' . $this->session->data['token'], + 'extension/module/retailcrm', $tokenTitle . '=' . $this->session->data[$tokenTitle], 'SSL' ); @@ -172,6 +182,7 @@ class ControllerExtensionModuleRetailcrm extends Controller 'button_cancel', 'text_notice', 'retailcrm_title', + 'retailcrm_apiversion', 'retailcrm_url', 'retailcrm_apikey', 'retailcrm_base_settings', @@ -205,7 +216,6 @@ class ControllerExtensionModuleRetailcrm extends Controller 'text_require' ); - $this->load->model('extension/extension'); $_data = &$data; foreach ($text_strings as $text) { @@ -214,13 +224,16 @@ class ControllerExtensionModuleRetailcrm extends Controller $_data['retailcrm_errors'] = array(); $_data['saved_settings'] = $this->model_setting_setting - ->getSetting('retailcrm'); + ->getSetting($moduleTitle); - $url = isset($_data['saved_settings']['retailcrm_url']) - ? $_data['saved_settings']['retailcrm_url'] + $url = isset($_data['saved_settings'][$moduleTitle . '_url']) + ? $_data['saved_settings'][$moduleTitle . '_url'] : null; - $key = isset($_data['saved_settings']['retailcrm_apikey']) - ? $_data['saved_settings']['retailcrm_apikey'] + $key = isset($_data['saved_settings'][$moduleTitle . '_apikey']) + ? $_data['saved_settings'][$moduleTitle . '_apikey'] + : null; + $apiVersion = isset($_data['saved_settings'][$moduleTitle . '_apiversion']) + ? $_data['saved_settings'][$moduleTitle . '_apiversion'] : null; if (!empty($url) && !empty($key)) { @@ -228,7 +241,8 @@ class ControllerExtensionModuleRetailcrm extends Controller $this->retailcrm = new RetailcrmProxy( $url, $key, - DIR_SYSTEM . 'storage/logs/retailcrm.log' + DIR_SYSTEM . 'storage/logs/retailcrm.log', + $apiVersion ); $_data['delivery'] = $this->model_extension_retailcrm_references @@ -241,7 +255,7 @@ class ControllerExtensionModuleRetailcrm extends Controller } $config_data = array( - 'retailcrm_status' + $moduleTitle . '_status' ); foreach ($config_data as $conf) { @@ -258,19 +272,13 @@ class ControllerExtensionModuleRetailcrm extends Controller $_data['error_warning'] = ''; } - if (isset($this->_error['fields'])) { - $_data['error_warning'] = $this->_error['fields']; - } else { - $_data['error_warning'] = ''; - } - $_data['breadcrumbs'] = array(); $_data['breadcrumbs'][] = array( 'text' => $this->language->get('text_home'), 'href' => $this->url->link( 'common/home', - 'token=' . $this->session->data['token'], 'SSL' + $tokenTitle . '=' . $this->session->data[$tokenTitle], 'SSL' ), 'separator' => false ); @@ -279,7 +287,7 @@ class ControllerExtensionModuleRetailcrm extends Controller 'text' => $this->language->get('text_module'), 'href' => $this->url->link( 'extension/extension/module', - 'token=' . $this->session->data['token'], 'SSL' + $tokenTitle . '=' . $this->session->data[$tokenTitle], 'SSL' ), 'separator' => ' :: ' ); @@ -288,19 +296,19 @@ class ControllerExtensionModuleRetailcrm extends Controller 'text' => $this->language->get('retailcrm_title'), 'href' => $this->url->link( 'extension/module/retailcrm', - 'token=' . $this->session->data['token'], 'SSL' + $tokenTitle . '=' . $this->session->data[$tokenTitle], 'SSL' ), 'separator' => ' :: ' ); $_data['action'] = $this->url->link( 'extension/module/retailcrm', - 'token=' . $this->session->data['token'], 'SSL' + $tokenTitle . '=' . $this->session->data[$tokenTitle], 'SSL' ); $_data['cancel'] = $this->url->link( - 'extension/extension', - 'token=' . $this->session->data['token'], 'SSL' + version_compare(VERSION, '3.0', '<') ? 'extension/extension' : 'marketplace/extension', + $tokenTitle . '=' . $this->session->data[$tokenTitle], 'SSL' ); $_data['modules'] = array(); @@ -319,7 +327,7 @@ class ControllerExtensionModuleRetailcrm extends Controller $_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['token'] = $this->request->get['token']; + $_data[$tokenTitle] = $this->request->get[$tokenTitle]; if(file_exists(DIR_SYSTEM . '/cron/export_done')) { $_data['export_file'] = false; @@ -334,10 +342,13 @@ class ControllerExtensionModuleRetailcrm extends Controller ); $_data['collectorFields'] = $collectorFields; + $_data['api_versions'] = array('v3', 'v4', 'v5'); + $_data['default_apiversion'] = 'v4'; $this->response->setOutput( - $this->load->view('extension/module/retailcrm.tpl', $_data) + $this->load->view('extension/module/retailcrm', $_data) ); + } /** @@ -346,13 +357,29 @@ class ControllerExtensionModuleRetailcrm extends Controller * @return void */ public function history() - { - if (file_exists(DIR_APPLICATION . 'model/extension/retailcrm/custom/history.php')) { - $this->load->model('extension/retailcrm/custom/history'); - $this->model_extension_retailcrm_custom_history->request(); + { + $moduleTitle = $this->getModuleTitle(); + $this->load->model('setting/setting'); + $settings = $this->model_setting_setting->getSetting($moduleTitle); + + if ($settings[$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(); + } else { + $this->load->model('extension/retailcrm/history/v3'); + $this->model_extension_retailcrm_history_v3->request(); + } } else { - $this->load->model('extension/retailcrm/history'); - $this->model_extension_retailcrm_history->request(); + + 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(); + } else { + $this->load->model('extension/retailcrm/history/v4_5'); + $this->model_extension_retailcrm_history_v4_5->request(); + } } } @@ -444,6 +471,7 @@ class ControllerExtensionModuleRetailcrm extends Controller { $order_id = isset($this->request->get['order_id']) ? $this->request->get['order_id'] : ''; $this->load->model('sale/order'); + $moduleTitle = $this->getModuleTitle(); $data = $this->model_sale_order->getOrder($order_id); $data['products'] = $this->model_sale_order->getOrderProducts($order_id); @@ -451,8 +479,8 @@ class ControllerExtensionModuleRetailcrm extends Controller if (!isset($data['fromApi'])) { $this->load->model('setting/setting'); - $status = $this->model_setting_setting->getSetting('retailcrm'); - $data['order_status'] = $status['retailcrm_status'][$data['order_status_id']]; + $status = $this->model_setting_setting->getSetting($moduleTitle); + $data['order_status'] = $status[$moduleTitle . '_status'][$data['order_status_id']]; $this->load->model('extension/retailcrm/order'); $result = $this->model_extension_retailcrm_order->uploadOrder($data); @@ -478,12 +506,13 @@ class ControllerExtensionModuleRetailcrm extends Controller $orders = $this->model_sale_order->getOrders(); $fullOrders = array(); + foreach($orders as $order) { $fullOrder = $this->model_sale_order->getOrder($order['order_id']); $fullOrder['order_total'] = $this->model_sale_order->getOrderTotals($order['order_id']); - $fullOrder['products'] = $this->model_sale_order->getOrderProducts($order['order_id']); + foreach($fullOrder['products'] as $key=>$product) { $fullOrder['products'][$key]['option'] = $this->model_sale_order->getOrderOptions($product['order_id'], $product['order_product_id']); } @@ -503,13 +532,31 @@ class ControllerExtensionModuleRetailcrm extends Controller */ private function validate() { + $moduleTitle = $this->getModuleTitle(); + + if (!empty($this->request->post[$moduleTitle . '_url']) && !empty($this->request->post[$moduleTitle . '_apikey'])) { + + $this->retailcrm = new RetailcrmProxy( + $this->request->post[$moduleTitle . '_url'], + $this->request->post[$moduleTitle . '_apikey'], + DIR_SYSTEM . 'storage/logs/retailcrm.log', + $this->request->post[$moduleTitle . '_apiversion'] + ); + } + + $response = $this->retailcrm->statisticUpdate(); + + if (!$response->isSuccessful()) { + $this->_error['warning'] = $this->language->get('text_error_api'); + } + if (!$this->user->hasPermission('modify', 'extension/module/retailcrm')) { $this->_error['warning'] = $this->language->get('error_permission'); } - if (isset($this->request->post['retailcrm_collector']['custom']) && - $this->request->post['retailcrm_collector']['custom_form'] == 1) { - $customField = $this->request->post['retailcrm_collector']['custom']; + if (isset($this->request->post[$moduleTitle . '_collector']['custom']) && + $this->request->post[$moduleTitle . '_collector']['custom_form'] == 1) { + $customField = $this->request->post[$moduleTitle . '_collector']['custom']; if (empty($customField['name']) && empty($customField['email']) && empty($customField['phone'])) { $this->_error['fields'] = $this->language->get('text_error_collector_fields'); @@ -522,4 +569,58 @@ class ControllerExtensionModuleRetailcrm extends Controller return false; } } + + 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'; + } + } + + private function getTokenTitle() + { + if (version_compare(VERSION, '3.0', '<')) { + $token = 'token'; + } else { + $token = 'user_token'; + } + + return $token; + } + + private function getModuleTitle() + { + if (version_compare(VERSION, '3.0', '<')) { + $title = 'retailcrm'; + } else { + $title = 'module_retailcrm'; + } + + return $title; + } + + private function getCollectorTitle() + { + if (version_compare(VERSION, '3.0', '<')) { + $title = 'daemon_collector'; + } else { + $title = 'analytics_daemon_collector'; + } + + return $title; + } } diff --git a/admin/language/en-gb/extension/module/retailcrm.php b/admin/language/en-gb/extension/module/retailcrm.php index 3e55368..1d59139 100644 --- a/admin/language/en-gb/extension/module/retailcrm.php +++ b/admin/language/en-gb/extension/module/retailcrm.php @@ -18,6 +18,7 @@ $_['references_tab_text'] = 'References'; $_['collector_tab_text'] = 'Collector'; $_['collector_custom_text'] = 'Custom form'; +$_['retailcrm_apiversion'] = 'API Version'; $_['retailcrm_url'] = 'RetailCRM URL'; $_['retailcrm_apikey'] = 'RetailCRM API Key'; $_['collector_site_key'] = 'Site key'; @@ -40,6 +41,7 @@ $_['field_email'] = 'Email'; $_['field_phone'] = 'Phone'; $_['text_require'] = 'Require'; $_['text_error_collector_fields']= 'Fill in the field names Daemon Collector'; +$_['text_error_api'] = 'The selected version of the API is unavailable'; $_['retailcrm_dict_delivery'] = 'Shipment methods'; $_['retailcrm_dict_status'] = 'Order statuses'; diff --git a/admin/language/ru-ru/extension/module/retailcrm.php b/admin/language/ru-ru/extension/module/retailcrm.php index 0c99f25..1e6c044 100644 --- a/admin/language/ru-ru/extension/module/retailcrm.php +++ b/admin/language/ru-ru/extension/module/retailcrm.php @@ -18,6 +18,7 @@ $_['references_tab_text'] = 'Справочники'; $_['collector_tab_text'] = 'Collector'; $_['collector_custom_text'] = 'Настройка полей формы'; +$_['retailcrm_apiversion'] = 'Версия API'; $_['retailcrm_url'] = 'Адрес RetailCRM'; $_['retailcrm_apikey'] = 'Api ключ RetailCRM'; $_['collector_site_key'] = 'Ключ сайта'; @@ -40,6 +41,7 @@ $_['field_email'] = 'Email'; $_['field_phone'] = 'Телефон'; $_['text_require'] = 'Обязательно для заполнения'; $_['text_error_collector_fields']= 'Заполните названия полей формы Демон Collector'; +$_['text_error_api'] = 'Недоступна выбранная версия API'; $_['retailcrm_dict_delivery'] = 'Способы доставки'; $_['retailcrm_dict_status'] = 'Статусы'; diff --git a/admin/model/extension/retailcrm/customer.php b/admin/model/extension/retailcrm/customer.php index b05975f..1448b0b 100644 --- a/admin/model/extension/retailcrm/customer.php +++ b/admin/model/extension/retailcrm/customer.php @@ -2,22 +2,12 @@ class ModelExtensionRetailcrmCustomer extends Model { - public function uploadToCrm($customers) { - $this->load->model('setting/setting'); - $settings = $this->model_setting_setting->getSetting('retailcrm'); + public function uploadToCrm($customers) + { + $this->initApi(); if(empty($customers)) return false; - if(empty($settings['retailcrm_url']) || empty($settings['retailcrm_apikey'])) - return false; - - require_once DIR_SYSTEM . 'library/retailcrm/bootstrap.php'; - - $this->retailcrmApi = new RetailcrmProxy( - $settings['retailcrm_url'], - $settings['retailcrm_apikey'], - DIR_SYSTEM . 'storage/logs/retailcrm.log' - ); $customersToCrm = array(); @@ -32,23 +22,13 @@ class ModelExtensionRetailcrmCustomer extends Model { } } - public function changeInCrm($customer) { - $this->load->model('setting/setting'); - $settings = $this->model_setting_setting->getSetting('retailcrm'); + public function changeInCrm($customer) + { + $this->initApi(); if(empty($customer)) return false; - if(empty($settings['retailcrm_url']) || empty($settings['retailcrm_apikey'])) - return false; - - require_once DIR_SYSTEM . 'library/retailcrm/bootstrap.php'; - - $this->retailcrmApi = new RetailcrmProxy( - $settings['retailcrm_url'], - $settings['retailcrm_apikey'], - DIR_SYSTEM . 'storage/logs/retailcrm.log' - ); - + $customerToCrm = $this->process($customer); $this->retailcrmApi->customersEdit($customerToCrm); @@ -80,4 +60,34 @@ class ModelExtensionRetailcrmCustomer extends Model { return $customerToCrm; } + + protected function initApi() + { + $moduleTitle = $this->getModuleTitle(); + $this->load->model('setting/setting'); + $settings = $this->model_setting_setting->getSetting($moduleTitle); + + if(empty($settings[$moduleTitle . '_url']) || empty($settings[$moduleTitle . '_apikey'])) + return false; + + require_once DIR_SYSTEM . 'library/retailcrm/bootstrap.php'; + + $this->retailcrmApi = new RetailcrmProxy( + $settings[$moduleTitle . '_url'], + $settings[$moduleTitle . '_apikey'], + DIR_SYSTEM . 'storage/logs/retailcrm.log', + $settings[$moduleTitle . '_apiversion'] + ); + } + + private function getModuleTitle() + { + if (version_compare(VERSION, '3.0', '<')) { + $title = 'retailcrm'; + } else { + $title = 'module_retailcrm'; + } + + return $title; + } } diff --git a/admin/model/extension/retailcrm/history.php b/admin/model/extension/retailcrm/history/v3.php similarity index 87% rename from admin/model/extension/retailcrm/history.php rename to admin/model/extension/retailcrm/history/v3.php index 35755e0..f486c26 100644 --- a/admin/model/extension/retailcrm/history.php +++ b/admin/model/extension/retailcrm/history/v3.php @@ -1,13 +1,14 @@ getModuleTitle(); $this->load->model('setting/setting'); $this->load->model('setting/store'); $this->load->model('user/api'); @@ -20,12 +21,12 @@ class ModelExtensionRetailcrmHistory extends Model $this->load->language('extension/module/retailcrm'); - $settings = $this->model_setting_setting->getSetting('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['retailcrm_url']) ? $settings['retailcrm_url'] : null; - $key = isset($settings['retailcrm_apikey']) ? $settings['retailcrm_apikey'] : null; + $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.'); @@ -35,26 +36,20 @@ class ModelExtensionRetailcrmHistory extends Model $this->opencartApiClient = new OpencartApiClient($this->registry); $crm = new RetailcrmProxy( - $settings['retailcrm_url'], - $settings['retailcrm_apikey'], - DIR_SYSTEM . 'storage/logs/retailcrm.log' + $settings[$moduleTitle . '_url'], + $settings[$moduleTitle . '_apikey'], + DIR_SYSTEM . 'storage/logs/retailcrm.log', + $settings[$moduleTitle . '_apiversion'] ); $lastRun = !empty($history['retailcrm_history']) ? new DateTime($history['retailcrm_history']) : new DateTime(date('Y-m-d H:i:s', strtotime('-1 days', strtotime(date('Y-m-d H:i:s'))))); - $packsOrders = $crm->ordersHistory(array( - 'startDate' => $lastRun->format('Y-m-d H:i:s'), - ), 1, 100); - $packsCustomers = $crm->customersHistory(array( - 'startDate' => $lastRun->format('Y-m-d H:i:s'), - ), 1, 100); - if(!$packsOrders->isSuccessful() && count($packsOrders->history) <= 0 && !$packsCustomers->isSuccessful() && count($Customers->history) <= 0) + $packsOrders = $crm->ordersHistory($lastRun); + + if(!$packsOrders->isSuccessful() && count($packsOrders['orders']) <= 0) return false; - - $orders = RetailcrmHistoryHelper::assemblyOrder($packsOrders->history); - $customers = RetailcrmHistoryHelper::assemblyCustomer($packsCustomers->history); $generatedAt = $packsOrders['generatedAt']; @@ -62,19 +57,20 @@ class ModelExtensionRetailcrmHistory extends Model $this->totalSettings = $this->model_setting_setting->getSetting('total'); $this->shippingSettings = $this->model_setting_setting->getSetting('shipping'); - $this->delivery = array_flip($settings['retailcrm_delivery']); - $this->payment = array_flip($settings['retailcrm_payment']); - $this->status = array_flip($settings['retailcrm_status']); + $this->delivery = array_flip($settings[$moduleTitle . '_delivery']); + $this->payment = array_flip($settings[$moduleTitle . '_payment']); + $this->status = array_flip($settings[$moduleTitle . '_status']); $this->ocPayment = $this->model_extension_retailcrm_references ->getOpercartPaymentTypes(); - $this->ocDelivery = $settings['retailcrm_delivery']; + $this->ocDelivery = $settings[$moduleTitle . '_delivery']; $this->zones = $this->model_localisation_zone->getZones(); $updatedOrders = array(); $newOrders = array(); + $orders = $packsOrders['orders']; foreach ($orders as $order) { @@ -89,19 +85,6 @@ class ModelExtensionRetailcrmHistory extends Model unset($orders); - $updateCustomers = array(); - - foreach ($customers as $customer) { - - if (isset($customer['deleted'])) continue; - - if (isset($customer['externalId'])) { - $updateCustomers[] = $customer['id']; - } - } - - unset($customers); - if (!empty($newOrders)) { $orders = $crm->ordersList($filter = array('ids' => $newOrders)); if ($orders) { @@ -115,13 +98,6 @@ class ModelExtensionRetailcrmHistory extends Model $this->updateOrders($orders['orders']); } } - - if (!empty($updateCustomers)) { - $customers = $crm->customersList($filter = array('ids' => $updateCustomers)); - if ($customers) { - $this->updateCustomers($customers['customers']); - } - } $this->model_setting_setting->editSetting('retailcrm_history', array('retailcrm_history' => $generatedAt)); @@ -135,7 +111,7 @@ class ModelExtensionRetailcrmHistory extends Model } protected function updateOrders($orders) - { + { foreach ($orders as $order) { $store = $this->config->get('config_store_id'); @@ -301,7 +277,7 @@ class ModelExtensionRetailcrmHistory extends Model } protected function createOrders($orders) - { + { $customersIdsFix = array(); $ordersIdsFix = array(); @@ -486,28 +462,14 @@ class ModelExtensionRetailcrmHistory extends Model return array('customers' => $customersIdsFix, 'orders' => $ordersIdsFix); } - protected function updateCustomers($customers) - { - foreach ($customers as $customer) { - - $customer_id = $customer['externalId']; - $customerData = $this->model_customer_customer->getCustomer($customer_id); - - $customerData['firstname'] = $customer['firstName']; - $customerData['lastname'] = $customer['lastName']; - $customerData['email'] = $customer['email']; - $customerData['telephone'] = $customer['phones'][0]['number']; - - $customerAddress = $this->model_customer_customer->getAddress($customerData['address_id']); - - $customerAddress['firstname'] = $customer['firstName']; - $customerAddress['lastname'] = $customer['lastName']; - $customerAddress['address_1'] = $customer['address']['text']; - $customerAddress['city'] = $customer['address']['city']; - $customerAddress['postcode'] = $customer['address']['index']; - $customerData['address'] = array($customerAddress); - - $this->model_customer_customer->editCustomer($customer_id, $customerData); + private function getModuleTitle() + { + if (version_compare(VERSION, '3.0', '<')) { + $title = 'retailcrm'; + } else { + $title = 'module_retailcrm'; } + + return $title; } } diff --git a/admin/model/extension/retailcrm/history/v4_5.php b/admin/model/extension/retailcrm/history/v4_5.php new file mode 100644 index 0000000..6c56b07 --- /dev/null +++ b/admin/model/extension/retailcrm/history/v4_5.php @@ -0,0 +1,568 @@ +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; + } + + $this->opencartApiClient = new OpencartApiClient($this->registry); + + $crm = new RetailcrmProxy( + $settings[$moduleTitle . '_url'], + $settings[$moduleTitle . '_apikey'], + DIR_SYSTEM . 'storage/logs/retailcrm.log', + $settings[$moduleTitle . '_apiversion'] + ); + + $lastRun = !empty($history['retailcrm_history']) + ? new DateTime($history['retailcrm_history']) + : new DateTime(date('Y-m-d H:i:s', strtotime('-1 days', strtotime(date('Y-m-d H:i:s'))))); + + $packsOrders = $crm->ordersHistory(array( + 'startDate' => $lastRun->format('Y-m-d H:i:s'), + ), 1, 100); + $packsCustomers = $crm->customersHistory(array( + 'startDate' => $lastRun->format('Y-m-d H:i:s'), + ), 1, 100); + if(!$packsOrders->isSuccessful() && count($packsOrders->history) <= 0 && !$packsCustomers->isSuccessful() && count($Customers->history) <= 0) + return false; + + $orders = RetailcrmHistoryHelper::assemblyOrder($packsOrders->history); + $customers = RetailcrmHistoryHelper::assemblyCustomer($packsCustomers->history); + + $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->ocPayment = $this->model_extension_retailcrm_references + ->getOpercartPaymentTypes(); + + $this->ocDelivery = $settings[$moduleTitle . '_delivery']; + + $this->zones = $this->model_localisation_zone->getZones(); + + $updatedOrders = array(); + $newOrders = array(); + + foreach ($orders as $order) { + + if (isset($order['deleted'])) continue; + + if (isset($order['externalId'])) { + $updatedOrders[] = $order['id']; + } else { + $newOrders[] = $order['id']; + } + } + + unset($orders); + + $updateCustomers = array(); + + foreach ($customers as $customer) { + + if (isset($customer['deleted'])) continue; + + if (isset($customer['externalId'])) { + $updateCustomers[] = $customer['id']; + } + } + + unset($customers); + + if (!empty($newOrders)) { + $orders = $crm->ordersList($filter = array('ids' => $newOrders)); + if ($orders) { + $this->createResult = $this->createOrders($orders['orders']); + } + } + + if (!empty($updatedOrders)) { + $orders = $crm->ordersList($filter = array('ids' => $updatedOrders)); + if ($orders) { + $this->updateOrders($orders['orders']); + } + } + + if (!empty($updateCustomers)) { + $customers = $crm->customersList($filter = array('ids' => $updateCustomers)); + if ($customers) { + $this->updateCustomers($customers['customers']); + } + } + + $this->model_setting_setting->editSetting('retailcrm_history', array('retailcrm_history' => $generatedAt)); + + if (!empty($this->createResult['customers'])) { + $crm->customersFixExternalIds($this->createResult['customers']); + } + + if (!empty($this->createResult['orders'])) { + $crm->ordersFixExternalIds($this->createResult['orders']); + } + } + + protected function updateOrders($orders) + { + foreach ($orders as $order) { + $store = $this->config->get('config_store_id'); + + if (isset($order['payments'])) { + foreach ($order['payments'] as $orderPayment) { + if (isset($orderPayment['externalId'])) { + $payment = $orderPayment; + } + } + + if (!isset($payment) && count($order['payments']) == 1) { + $payment = end($order['payments']); + } + } elseif (isset($order['paymentType'])) { + $payment = $order['paymentType']; + } + + $data = array(); + + $data['store_id'] = $store == null ? 0 : $store; + $data['customer'] = $order['firstName']; + $data['customer_id'] = (!empty($order['customer']['externalId'])) ? $order['customer']['externalId'] : 0; + $data['customer_group_id'] = 1; + $data['firstname'] = $order['firstName']; + $data['lastname'] = (!empty($order['lastName'])) ? $order['lastName'] : ' '; + $data['email'] = $order['email']; + $data['telephone'] = (!empty($order['phone'])) ? $order['phone'] : ''; + $data['comment'] = !empty($order['customerComment']) ? $order['customerComment'] : ''; + $data['fax'] = ''; + + $data['payment_address'] = '0'; + $data['payment_firstname'] = $order['firstName']; + $data['payment_lastname'] = (!empty($order['lastName'])) ? $order['lastName'] : ' '; + $data['payment_address_1'] = isset($order['customer']['address']) ? $order['customer']['address']['text'] : ''; + $data['payment_address_2'] = ''; + $data['payment_company'] = ''; + $data['payment_company_id'] = ''; + $data['payment_city'] = !empty($order['customer']['address']['city']) ? $order['customer']['address']['city'] : $order['delivery']['address']['city']; + $data['payment_postcode'] = !empty( $order['customer']['address']['index'] ) ? $order['customer']['address']['index'] : $order['delivery']['address']['index']; + + $region = ''; + + if (is_int($order['delivery']['address']['region'])) { + $region = $order['delivery']['address']['region']; + } else { + foreach ($this->zones as $zone) { + if ($order['delivery']['address']['region'] == $zone['name']) { + $region = $zone['zone_id']; + } + } + } + + $data['payment_country_id'] = !empty($order['delivery']['address']['country']) ? $order['delivery']['address']['country'] : 0; + $data['payment_zone_id'] = !empty($order['delivery']['address']['region']) ? $order['delivery']['address']['region'] : $region; + + $data['shipping_country_id'] = !empty($order['delivery']['address']['country']) ? $order['delivery']['address']['country'] : 0; + $data['shipping_zone_id'] = $region; + + $data['shipping_address'] = '0'; + $data['shipping_firstname'] = $order['firstName']; + $data['shipping_lastname'] = (!empty($order['lastName'])) ? $order['lastName'] : ' '; + $data['shipping_address_1'] = $order['delivery']['address']['text']; + $data['shipping_address_2'] = ''; + $data['shipping_company'] = ''; + $data['shipping_company_id'] = ''; + $data['shipping_city'] = $order['delivery']['address']['city']; + $data['shipping_postcode'] = $order['delivery']['address']['index']; + + $data['shipping'] = $this->delivery[$order['delivery']['code']]; + $data['shipping_method'] = $this->ocDelivery[$data['shipping']]; + $data['shipping_code'] = $this->delivery[$order['delivery']['code']]; + + if (isset($payment)) { + $data['payment'] = $this->payment[$payment['type']]; + $data['payment_method'] = $this->ocPayment[$data['payment']]; + $data['payment_code'] = $this->payment[$payment['type']]; + } else { + $this->load->model('sale/order'); + $order_data = $this->model_sale_order->getOrder($order['externalId']); + $data['payment_method'] = $order_data['payment_method']; + $data['payment_code'] = $order_data['payment_code']; + } + + // this data will not retrive from crm for now + $data['tax'] = ''; + $data['tax_id'] = ''; + $data['product'] = ''; + $data['product_id'] = ''; + $data['reward'] = ''; + $data['affiliate'] = ''; + $data['affiliate_id'] = ''; + $data['payment_tax_id'] = ''; + $data['order_product_id'] = ''; + $data['payment_company'] = ''; + $data['payment_company_id'] = ''; + $data['company'] = ''; + $data['company_id'] = ''; + + $data['order_product'] = array(); + + foreach ($order['items'] as $item) { + //$product = $this->model_catalog_product->getProduct($item['offer']['externalId']); + $productId = $item['offer']['externalId']; + $options = array(); + if(mb_strpos($item['offer']['externalId'], '#') > 1) { + $offer = explode('#', $item['offer']['externalId']); + $productId = $offer[0]; + $optionsFromCRM = explode('_', $offer[1]); + + foreach($optionsFromCRM as $optionFromCRM) { + $optionData = explode('-', $optionFromCRM); + $productOptionId = $optionData[0]; + $optionValueId = $optionData[1]; + + $productOptions = $this->model_catalog_product->getProductOptions($productId); + + foreach($productOptions as $productOption) { + if($productOptionId == $productOption['product_option_id']) { + foreach($productOption['product_option_value'] as $productOptionValue) { + if($productOptionValue['option_value_id'] == $optionValueId) { + $options[$productOptionId] = $productOptionValue['product_option_value_id']; + } + } + } + } + } + } + $data['order_product'][] = array( + 'product_id' => $productId, + 'quantity' => $item['quantity'], + 'option' => $options + ); + } + + $deliveryCost = !empty($order['delivery']['cost']) ? $order['delivery']['cost'] : 0; + + if(isset($order['discount']) && $order['discount'] > 0) { + $orderTotals = $this->model_sale_order->getOrderTotals($order['externalId']); + foreach($orderTotals as $orderTotal) { + if($orderTotal['code'] == 'coupon') { + $data['order_total'][] = $orderTotal; + } + } + } + + $data['order_total'] = array( + array( + 'order_total_id' => '', + 'code' => 'sub_total', + 'title' => $this->language->get('product_summ'), + 'value' => $order['summ'], + 'text' => $order['summ'], + 'sort_order' => $this->subtotalSettings['sub_total_sort_order'] + ), + array( + 'order_total_id' => '', + 'code' => 'shipping', + 'title' => $this->ocDelivery[$data['shipping_code']], + 'value' => $deliveryCost, + 'text' => $deliveryCost, + 'sort_order' => $this->shippingSettings[$this->totalTitle . 'shipping_sort_order'] + ), + array( + 'order_total_id' => '', + 'code' => 'total', + 'title' => $this->language->get('column_total'), + 'value' => isset($order['totalSumm']) ? $order['totalSumm'] : $order['summ'] + $deliveryCost, + 'text' => isset($order['totalSumm']) ? $order['totalSumm'] : $order['summ'] + $deliveryCost, + 'sort_order' => $this->totalSettings[$this->totalTitle . 'total_sort_order'] + ) + ); + + $data['fromApi'] = true; + + if (array_key_exists($order['status'], $this->status)) { + $data['order_status_id'] = $this->status[$order['status']]; + } else { + $tmpOrder = $this->model_sale_order->getOrder($order['externalId']); + $data['order_status_id'] = $tmpOrder['order_status_id']; + } + + $this->opencartApiClient->editOrder($order['externalId'], $data); + } + } + + protected function createOrders($orders) + { + $customersIdsFix = array(); + $ordersIdsFix = array(); + + foreach ($orders as $order) { + $store = $this->config->get('config_store_id'); + + if (isset($order['payments'])) { + $payment = end($order['payments']); + } elseif (isset($order['paymentType'])) { + $payment = $order['paymentType']; + } + + $customer_id = (!empty($order['customer']['externalId'])) + ? $order['customer']['externalId'] + : 0; + + $data = array(); + + if ($customer_id == 0) { + $cData = array( + 'store_id' => 0, + 'customer_group_id' => '1', + 'firstname' => $order['firstName'], + 'lastname' => (!empty($order['lastName'])) ? $order['lastName'] : ' ', + 'email' => $order['email'], + 'telephone' => (!empty($order['customer']['phones'][0]['number']) ) ? $order['customer']['phones'][0]['number'] : ' ', + 'fax' => '', + 'newsletter' => 0, + 'password' => 'tmppass', + 'status' => 1, + 'address' => array( + array( + 'firstname' => $order['firstName'], + 'lastname' => (!empty($order['lastName'])) ? $order['lastName'] : ' ', + 'address_1' => $order['customer']['address']['text'], + 'address_2' => ' ', + 'city' => !empty($order['customer']['address']['city']) ? $order['customer']['address']['city'] : $order['delivery']['address']['city'], + 'postcode' => isset($order['customer']['address']['index']) ? $order['customer']['address']['index'] : $order['delivery']['address']['index'], + 'tax_id' => '1', + 'company' => '', + 'company_id' => '', + 'zone_id' => '0', + 'country_id' => 0 + ) + ), + ); + + + $this->model_customer_customer->addCustomer($cData); + + if (!empty($order['email'])) { + $tryToFind = $this->model_customer_customer->getCustomerByEmail($order['email']); + $customer_id = $tryToFind['customer_id']; + } else { + $last = $this->model_customer_customer->getCustomers($data = array('order' => 'DESC', 'limit' => 1)); + $customer_id = $last[0]['customer_id']; + } + + $customersIdsFix[] = array('id' => $order['customer']['id'], 'externalId' => (int)$customer_id); + } + + $data['store_id'] = $store == null ? 0 : $store; + $data['customer'] = $order['firstName']; + $data['customer_id'] = $customer_id; + $data['customer_group_id'] = 1; + $data['firstname'] = $order['firstName']; + $data['lastname'] = (!empty($order['lastName'])) ? $order['lastName'] : ' '; + $data['email'] = $order['email']; + $data['telephone'] = (!empty($order['customer']['phones'][0]['number'])) ? $order['customer']['phones'][0]['number'] : ' '; + $data['comment'] = !empty($order['customerComment']) ? $order['customerComment'] : ''; + $data['fax'] = ''; + $data['payment_address'] = '0'; + $data['payment_firstname'] = $order['firstName']; + $data['payment_lastname'] = (!empty($order['lastName'])) ? $order['lastName'] : ' '; + $data['payment_address_1'] = $order['customer']['address']['text']; + $data['payment_address_2'] = ''; + $data['payment_company'] = ''; + $data['payment_company_id'] = ''; + $data['payment_city'] = !empty($order['customer']['address']['city']) ? $order['customer']['address']['city'] : $order['delivery']['address']['city']; + $data['payment_postcode'] = !empty($order['customer']['address']['index']) ? $order['customer']['address']['index'] : $order['delivery']['address']['index']; + + $region = ''; + + if (!empty($order['delivery']['address']['region']) && is_int($order['delivery']['address']['region'])) { + $region = $order['delivery']['address']['region']; + } else { + foreach ($this->zones as $zone) { + if ($order['delivery']['address']['region'] == $zone['name']) { + $region = $zone['zone_id']; + } + } + } + + $data['payment_country_id'] = !empty($order['delivery']['address']['country']) ? $order['delivery']['address']['country'] : 0; + $data['payment_zone_id'] = !empty($order['delivery']['address']['region']) ? $order['delivery']['address']['region'] : $region; + $data['shipping_country_id'] = !empty($order['delivery']['address']['country']) ? $order['delivery']['address']['country'] : 0; + $data['shipping_zone_id'] = $region; + $data['shipping_address'] = '0'; + $data['shipping_firstname'] = $order['firstName']; + $data['shipping_lastname'] = (!empty($order['lastName'])) ? $order['lastName'] : ' '; + $data['shipping_address_1'] = $order['delivery']['address']['text']; + $data['shipping_address_2'] = ''; + $data['shipping_company'] = ''; + $data['shipping_company_id'] = ''; + $data['shipping_city'] = $order['delivery']['address']['city']; + $data['shipping_postcode'] = $order['delivery']['address']['index']; + + $data['shipping'] = $this->delivery[$order['delivery']['code']]; + $data['shipping_method'] = $this->ocDelivery[$data['shipping']]; + $data['shipping_code'] = $this->delivery[$order['delivery']['code']]; + + if (isset($payment)) { + $data['payment'] = $this->payment[$payment['type']]; + $data['payment_method'] = $this->ocPayment[$data['payment']]; + $data['payment_code'] = $this->payment[$payment['type']]; + } + + // this data will not retrive from crm for now + $data['tax'] = ''; + $data['tax_id'] = ''; + $data['product'] = ''; + $data['product_id'] = ''; + $data['reward'] = ''; + $data['affiliate'] = ''; + $data['affiliate_id'] = ''; + $data['payment_tax_id'] = ''; + $data['order_product_id'] = ''; + $data['payment_company'] = ''; + $data['payment_company_id'] = ''; + $data['company'] = ''; + $data['company_id'] = ''; + + $data['order_product'] = array(); + + foreach ($order['items'] as $item) { + $product = $this->model_catalog_product->getProduct($item['offer']['externalId']); + $data['order_product'][] = array( + 'product_id' => $item['offer']['externalId'], + 'name' => $item['offer']['name'], + 'quantity' => $item['quantity'], + 'price' => $item['initialPrice'], + 'total' => $item['initialPrice'] * $item['quantity'], + 'model' => $product['model'], + + // this data will not retrive from crm + 'order_product_id' => '', + 'tax' => 0, + 'reward' => 0 + ); + } + + $deliveryCost = !empty($order['delivery']['cost']) ? $order['delivery']['cost'] : 0; + + $data['order_total'] = array( + array( + 'order_total_id' => '', + 'code' => 'sub_total', + 'title' => $this->language->get('product_summ'), + 'value' => $order['summ'], + 'text' => $order['summ'], + 'sort_order' => $this->subtotalSettings['sub_total_sort_order'] + ), + array( + 'order_total_id' => '', + 'code' => 'shipping', + 'title' => $this->ocDelivery[$data['shipping_code']], + 'value' => $deliveryCost, + 'text' => $deliveryCost, + 'sort_order' => $this->shippingSettings[$this->totalTitle . 'shipping_sort_order'] + ), + array( + 'order_total_id' => '', + 'code' => 'total', + 'title' => $this->language->get('column_total'), + 'value' => !empty($order['totalSumm']) ? $order['totalSumm'] : $order['summ'] + $deliveryCost, + 'text' => isset($order['totalSumm']) ? $order['totalSumm'] : $order['summ'] + $deliveryCost, + 'sort_order' => $this->totalSettings[$this->totalTitle . 'total_sort_order'] + ) + ); + + $data['fromApi'] = true; + $data['order_status_id'] = 1; + + $this->opencartApiClient->addOrder($data); + + $last = $this->model_sale_order->getOrders($data = array('order' => 'DESC', 'limit' => 1, 'start' => 0)); + + $ordersIdsFix[] = array('id' => $order['id'], 'externalId' => (int) $last[0]['order_id']); + } + + return array('customers' => $customersIdsFix, 'orders' => $ordersIdsFix); + } + + protected function updateCustomers($customers) + { + foreach ($customers as $customer) { + + $customer_id = $customer['externalId']; + $customerData = $this->model_customer_customer->getCustomer($customer_id); + + $customerData['firstname'] = $customer['firstName']; + $customerData['lastname'] = $customer['lastName']; + $customerData['email'] = $customer['email']; + $customerData['telephone'] = $customer['phones'][0]['number']; + + $customerAddress = $this->model_customer_customer->getAddress($customerData['address_id']); + + $customerAddress['firstname'] = $customer['firstName']; + $customerAddress['lastname'] = $customer['lastName']; + $customerAddress['address_1'] = $customer['address']['text']; + $customerAddress['city'] = $customer['address']['city']; + $customerAddress['postcode'] = $customer['address']['index']; + $customerData['address'] = array($customerAddress); + + $this->model_customer_customer->editCustomer($customer_id, $customerData); + } + } + + private function getModuleTitle() + { + if (version_compare(VERSION, '3.0', '<')) { + $title = 'retailcrm'; + } else { + $title = 'module_retailcrm'; + } + + return $title; + } + + private function totalTitles() + { + if (version_compare(VERSION, '3.0', '<')) { + $title = ''; + } else { + $title = 'total_'; + } + + return $title; + } +} diff --git a/admin/model/extension/retailcrm/order.php b/admin/model/extension/retailcrm/order.php index f3d3963..a097a04 100644 --- a/admin/model/extension/retailcrm/order.php +++ b/admin/model/extension/retailcrm/order.php @@ -3,10 +3,8 @@ class ModelExtensionRetailcrmOrder extends Model { public function uploadToCrm($orders) { - $this->load->model('catalog/product'); - $this->load->model('setting/setting'); - $this->settings = $this->model_setting_setting->getSetting('retailcrm'); + $this->initApi(); $ordersToCrm = array(); @@ -17,48 +15,40 @@ class ModelExtensionRetailcrmOrder extends Model { $chunkedOrders = array_chunk($ordersToCrm, 50); foreach($chunkedOrders as $ordersPart) { - $this->retailcrmApi->ordersUpload($ordersPart); + $this->retailcrm->ordersUpload($ordersPart); } } - public function uploadOrder($order) + public function uploadOrder($order_data) { if(isset($this->request->post['fromApi'])) return; - $this->load->model('setting/setting'); - $settings = $this->model_setting_setting->getSetting('retailcrm'); - - if(!empty($settings['retailcrm_url']) && !empty($settings['retailcrm_apikey'])) { - $this->load->model('catalog/product'); - - require_once DIR_SYSTEM . 'library/retailcrm/bootstrap.php'; - - $this->retailcrm = new RetailcrmProxy( - $settings['retailcrm_url'], - $settings['retailcrm_apikey'], - DIR_SYSTEM . 'storage/logs/retailcrm.log' - ); - - $customers = $this->retailcrm->customersList( - array( - 'name' => $order['telephone'], - 'email' => $order['email'] - ), - 1, - 100 - ); - - $order = $this->process($order); + $moduleTitle = $this->getModuleTitle(); + $this->initApi(); - if($customers) { - foreach ($customers['customers'] as $customer) { - $order['customer']['id'] = $customer['id']; - } + $customers = $this->retailcrm->customersList( + array( + 'name' => $order_data['telephone'], + 'email' => $order_data['email'] + ), + 1, + 100 + ); + + $order = $this->process($order_data); + + if($customers) { + foreach ($customers['customers'] as $customer) { + $order['customer']['id'] = $customer['id']; } + } - unset($customers); + unset($customers); - $result = $this->retailcrm->ordersCreate($order); + $result = $this->retailcrm->ordersCreate($order); + + if ($this->settings[$this->moduleTitle . '_apiversion'] == 'v5' && $result->isSuccessful()) { + $this->createPayment($order_data, $order_data['order_id']); } return $result; @@ -67,6 +57,7 @@ class ModelExtensionRetailcrmOrder extends Model { private function process($order_data) { $order = array(); + $this->moduleTitle = $this->getModuleTitle(); $payment_code = $order_data['payment_code']; $delivery_code = $order_data['shipping_code']; @@ -92,12 +83,15 @@ class ModelExtensionRetailcrmOrder extends Model { } $order['createdAt'] = $order_data['date_added']; - $order['paymentType'] = $this->settings['retailcrm_payment'][$payment_code]; + + if ($this->settings[$this->moduleTitle . '_apiversion'] != 'v5') { + $order['paymentType'] = $this->settings[$this->moduleTitle . '_payment'][$payment_code]; + } $country = (isset($order_data['shipping_country'])) ? $order_data['shipping_country'] : '' ; $order['delivery'] = array( - 'code' => !empty($delivery_code) ? $this->settings['retailcrm_delivery'][$delivery_code] : '', + 'code' => !empty($delivery_code) ? $this->settings[$this->moduleTitle . '_delivery'][$delivery_code] : '', 'cost' => $deliveryCost, 'address' => array( 'index' => $order_data['shipping_postcode'], @@ -126,6 +120,14 @@ class ModelExtensionRetailcrmOrder extends Model { $productOptions = $this->model_catalog_product->getProductOptions($product['product_id']); 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'], $offerOptions)) continue; foreach($productOptions as $productOption) { if($productOption['product_option_id'] = $option['product_option_id']) { @@ -147,16 +149,97 @@ class ModelExtensionRetailcrmOrder extends Model { $offerId = implode('_', $offerId); } - $order['items'][] = array( - 'offer' => array( - 'externalId' => !empty($offerId) ? $product['product_id'].'#'.$offerId : $product['product_id'] - ), - 'productName' => $product['name'], - 'initialPrice' => $product['price'], - 'quantity' => $product['quantity'], - ); + if ($this->settings[$this->moduleTitle . '_apiversion'] != 'v3') { + $item = array( + 'offer' => array( + 'externalId' => !empty($offerId) ? $product['product_id'].'#'.$offerId : $product['product_id'] + ), + 'productName' => $product['name'], + 'initialPrice' => $product['price'], + 'quantity' => $product['quantity'], + ); + } else { + $item = array( + 'productName' => $product['name'], + 'initialPrice' => $product['price'], + 'quantity' => $product['quantity'], + 'productId' => !empty($offerId) ? $product['product_id'].'#'.$offerId : $product['product_id'] + ); + } + + if (isset($properties)) $item['properties'] = $properties; + $order['items'][] = $item; } return $order; } + + protected function createPayment($order, $order_id) + { + $this->moduleTitle = $this->getModuleTitle(); + + if (version_compare(VERSION, '3.0', '<')) { + $settingPaid = $this->model_setting_setting->getSetting($order['payment_code']); + } else { + $settingPaid = $this->model_setting_setting->getSetting('payment_' . $order['payment_code']); + } + + $payment_code = $order['payment_code']; + + foreach ($order['totals'] as $total) { + if ($total['code'] == 'total') $amount = $total['value']; + } + + $payment = array( + 'externalId' => $order_id, + 'type' => $this->settings[$this->moduleTitle . '_payment'][$payment_code], + 'amount' => $amount + ); + + if (version_compare(VERSION, '3.0', '<')) { + if ($order['order_status_id'] == $settingPaid[$order['payment_code'] . '_order_status_id']) { + $payment['status'] = 'paid'; + } + } else { + if ($order['order_status_id'] == $settingPaid['payment_' . $order['payment_code'] . '_order_status_id']) { + $payment['status'] = 'paid'; + } + } + + $payment['order'] = array( + 'externalId' => $order_id + ); + + $this->retailcrm->ordersPaymentCreate($payment); + } + + private function initApi() + { + $moduleTitle = $this->getModuleTitle(); + $this->load->model('setting/setting'); + $this->settings = $this->model_setting_setting->getSetting($moduleTitle); + + if(!empty($this->settings[$moduleTitle . '_url']) && !empty($this->settings[$moduleTitle . '_apikey'])) { + + require_once DIR_SYSTEM . 'library/retailcrm/bootstrap.php'; + + $this->retailcrm = new RetailcrmProxy( + $this->settings[$moduleTitle . '_url'], + $this->settings[$moduleTitle . '_apikey'], + DIR_SYSTEM . 'storage/logs/retailcrm.log', + $this->settings[$moduleTitle . '_apiversion'] + ); + } + } + + private function getModuleTitle() + { + if (version_compare(VERSION, '3.0', '<')) { + $title = 'retailcrm'; + } else { + $title = 'module_retailcrm'; + } + + return $title; + } } diff --git a/admin/model/extension/retailcrm/references.php b/admin/model/extension/retailcrm/references.php index 79d7564..54d7edc 100644 --- a/admin/model/extension/retailcrm/references.php +++ b/admin/model/extension/retailcrm/references.php @@ -59,8 +59,14 @@ class ModelExtensionRetailcrmReferences extends Model $extension = basename($file, '.php'); $this->load->language('extension/payment/' . $extension); + + if (version_compare(VERSION, '3.0', '<')) { + $configStatus = $extension . '_status'; + } else { + $configStatus = 'payment_' . $extension . '_status'; + } - if ($this->config->get($extension . '_status')) { + if ($this->config->get($configStatus)) { $paymentTypes[$extension] = strip_tags( $this->language->get('heading_title') ); @@ -72,56 +78,56 @@ class ModelExtensionRetailcrmReferences extends Model } public function getApiDeliveryTypes() - { - $this->load->model('setting/setting'); - $settings = $this->model_setting_setting->getSetting('retailcrm'); + { + $this->initApi(); + + $response = $this->retailcrm->deliveryTypesList(); - if(!empty($settings['retailcrm_url']) && !empty($settings['retailcrm_apikey'])) { - $this->retailcrm = new RetailcrmProxy( - $settings['retailcrm_url'], - $settings['retailcrm_apikey'], - DIR_SYSTEM . 'storage/logs/retailcrm.log' - ); - - $response = $this->retailcrm->deliveryTypesList(); - - return ($response === false) ? array() : $response->deliveryTypes; - } + return ($response === false) ? array() : $response->deliveryTypes; } public function getApiOrderStatuses() { - $this->load->model('setting/setting'); - $settings = $this->model_setting_setting->getSetting('retailcrm'); + $this->initApi(); - if(!empty($settings['retailcrm_url']) && !empty($settings['retailcrm_apikey'])) { - $this->retailcrm = new RetailcrmProxy( - $settings['retailcrm_url'], - $settings['retailcrm_apikey'], - DIR_SYSTEM . 'storage/logs/retailcrm.log' - ); + $response = $this->retailcrm->statusesList(); - $response = $this->retailcrm->statusesList(); - - return ($response === false) ? array() : $response->statuses; - } + return ($response === false) ? array() : $response->statuses; } public function getApiPaymentTypes() + { + $this->initApi(); + + $response = $this->retailcrm->paymentTypesList(); + + return ($response === false) ? array() : $response->paymentTypes; + } + + protected function initApi() { + $moduleTitle = $this->getModuleTitle(); $this->load->model('setting/setting'); - $settings = $this->model_setting_setting->getSetting('retailcrm'); + $settings = $this->model_setting_setting->getSetting($moduleTitle); - if(!empty($settings['retailcrm_url']) && !empty($settings['retailcrm_apikey'])) { + if(!empty($settings[$moduleTitle . '_url']) && !empty($settings[$moduleTitle . '_apikey'])) { $this->retailcrm = new RetailcrmProxy( - $settings['retailcrm_url'], - $settings['retailcrm_apikey'], - DIR_SYSTEM . 'storage/logs/retailcrm.log' + $settings[$moduleTitle . '_url'], + $settings[$moduleTitle . '_apikey'], + DIR_SYSTEM . 'storage/logs/retailcrm.log', + $settings[$moduleTitle . '_apiversion'] ); - - $response = $this->retailcrm->paymentTypesList(); - - return ($response === false) ? array() : $response->paymentTypes; } } + + private function getModuleTitle() + { + if (version_compare(VERSION, '3.0', '<')) { + $title = 'retailcrm'; + } else { + $title = 'module_retailcrm'; + } + + return $title; + } } diff --git a/admin/view/template/extension/module/retailcrm.tpl b/admin/view/template/extension/module/retailcrm.tpl index 6ee4124..cd3d8eb 100644 --- a/admin/view/template/extension/module/retailcrm.tpl +++ b/admin/view/template/extension/module/retailcrm.tpl @@ -51,6 +51,14 @@

+
+
+ +

@@ -106,8 +114,8 @@ +
-

diff --git a/admin/view/template/extension/module/retailcrm.twig b/admin/view/template/extension/module/retailcrm.twig new file mode 100644 index 0000000..f76247b --- /dev/null +++ b/admin/view/template/extension/module/retailcrm.twig @@ -0,0 +1,314 @@ +{{ header }}{{ column_left }} + +
+ +
+ {% if error_warning %} +
+ + {{ error_warning }} +
+ {% endif %} + {% if saved_settings.module_retailcrm_url is defined %} + + + {% endif %} + +
+
+
+ + +
+
+ + +

{{ retailcrm_base_settings }}

+
+
+ +
+
+
+ +
+
+
+ +
+ +

{{ retailcrm_countries_settings }}

+
+
+ {% for country in countries %} +
+ +
+ {% endfor %} +
+
+ + {% if saved_settings.module_retailcrm_apikey is defined and saved_settings.module_retailcrm_apikey and saved_settings.module_retailcrm_url is defined and saved_settings.module_retailcrm_url %} + + {% if retailcrm_errors|length %} + {% for retailcrm_error in retailcrm_errors %} +
{{ retailcrm_error }}
+ {% endfor %} + {% else %} +

{{ retailcrm_upload_order }}

+
+ + +
+
+ +
+

{{ retailcrm_dict_settings }}

+ +

{{ retailcrm_dict_delivery }}

+ {% for value in delivery.opencart %} + +
{{ value.title ~ ':' }}
+ + {% for key, val in value %} + {% if key != 'title' %} +
+ + +
+ {% endif %} + {% endfor %} + {% endfor %} + +

{{ retailcrm_dict_status }}

+ {% for status in statuses.opencart %} + {% set uid = status.order_status_id %} +
+ + +
+ {% endfor %} + +

{{ retailcrm_dict_payment }}

+ {% for key, value in payments.opencart %} +
+ + +
+ {% endfor %} + + {% endif %} + + {% endif %} +
+ +
+

{{ daemon_collector }}

+
+ + + +
+
+ + +
+ {% if saved_settings.module_retailcrm_collector.site_key is not empty and + saved_settings.module_retailcrm_collector_active == 1 %} +
+ + + +
+ {% if saved_settings.module_retailcrm_collector.form_capture is defined and + saved_settings.module_retailcrm_collector.form_capture == 1 %} +
+ + +
+
+ + +
+
+ + +
+
+ + + +
+ {% if saved_settings.module_retailcrm_collector.custom_form is defined and + saved_settings.module_retailcrm_collector.custom_form == 1 %} + {% for field, label in collectorFields %} +
+ +
+ {# #} + + +
+
+ {% endfor %} + {% endif %} + {% endif %} + {% endif %} +
+
+
+
+
+
+
+ +{{ footer }} + + \ No newline at end of file diff --git a/catalog/controller/api/retailcrm.php b/catalog/controller/api/retailcrm.php index 823258c..b1441ce 100644 --- a/catalog/controller/api/retailcrm.php +++ b/catalog/controller/api/retailcrm.php @@ -26,11 +26,11 @@ class ControllerApiRetailcrm extends Controller protected function getDeliveryTypesByZones($country_id) { + $this->loadModels(); $this->load->model('localisation/zone'); $this->load->model('localisation/country'); - $this->load->model('extension/extension'); - $shippingModules = $this->model_extension_extension->getExtensions('shipping'); + $shippingModules = $this->{'model_' . $this->modelExtension}->getExtensions('shipping'); $zones = $this->model_localisation_zone->getZonesByCountryId($country_id); $country = $this->model_localisation_country->getCountry($country_id); $quote_data = array(); @@ -48,8 +48,13 @@ class ControllerApiRetailcrm extends Controller foreach ($shippingModules as $shippingModule) { $this->load->model('extension/shipping/' . $shippingModule['code']); - - if ($this->config->get($shippingModule['code'] . '_status')) { + if (version_compare(VERSION, '3.0', '<')) { + $shippingCode = $shippingModule['code']; + } else { + $shippingCode = 'shipping_' . $shippingModule['code']; + } + + if ($this->config->get($shippingCode . '_status')) { if($this->{'model_extension_shipping_' . $shippingModule['code']}->getQuote($address)) { $quote_data[] = $this->{'model_extension_shipping_' . $shippingModule['code']}->getQuote($address); } @@ -70,4 +75,28 @@ class ControllerApiRetailcrm extends Controller return $deliveryTypes; } + + private function loadModels() + { + if (version_compare(VERSION, '3.0', '<')) { + $this->load->model('extension/extension'); + + $this->modelExtension = 'extension_extension'; + } else { + $this->load->model('setting/extension'); + + $this->modelExtension = 'setting_extension'; + } + } + + private function getModuleTitle() + { + if (version_compare(VERSION, '3.0', '<')) { + $title = 'retailcrm'; + } else { + $title = 'module_retailcrm'; + } + + return $title; + } } diff --git a/catalog/controller/extension/analytics/daemon_collector.php b/catalog/controller/extension/analytics/daemon_collector.php index a8278d3..623a31a 100644 --- a/catalog/controller/extension/analytics/daemon_collector.php +++ b/catalog/controller/extension/analytics/daemon_collector.php @@ -2,9 +2,10 @@ class ControllerExtensionAnalyticsDaemonCollector extends Controller { public function index() { $this->load->model('setting/setting'); + $moduleTitle = $this->getModuleTitle(); - $settings = $this->model_setting_setting->getSetting('retailcrm'); - $setting = $settings['retailcrm_collector']; + $settings = $this->model_setting_setting->getSetting($moduleTitle); + $setting = $settings[$moduleTitle . '_collector']; $siteCode = isset($setting['site_key']) ? $setting['site_key'] : ''; if ($this->customer->isLogged()) $customerId = $this->customer->getID(); @@ -78,4 +79,15 @@ class ControllerExtensionAnalyticsDaemonCollector extends Controller { return html_entity_decode($js, ENT_QUOTES, 'UTF-8'); } + + private function getModuleTitle() + { + if (version_compare(VERSION, '3.0', '<')) { + $title = 'retailcrm'; + } else { + $title = 'module_retailcrm'; + } + + return $title; + } } diff --git a/catalog/controller/extension/module/retailcrm.php b/catalog/controller/extension/module/retailcrm.php index 20efee9..b056e93 100644 --- a/catalog/controller/extension/module/retailcrm.php +++ b/catalog/controller/extension/module/retailcrm.php @@ -19,7 +19,8 @@ class ControllerExtensionModuleRetailcrm extends Controller * @return void */ public function order_create($parameter1, $parameter2 = null, $parameter3 = null) - { + { + $moduleTitle = $this->getModuleTitle(); $this->load->model('checkout/order'); $this->load->model('account/order'); @@ -38,9 +39,9 @@ class ControllerExtensionModuleRetailcrm extends Controller if (!isset($data['fromApi'])) { $this->load->model('setting/setting'); - $status = $this->model_setting_setting->getSetting('retailcrm'); + $status = $this->model_setting_setting->getSetting($moduleTitle); if ($data['order_status_id'] > 0) { - $data['order_status'] = $status['retailcrm_status'][$data['order_status_id']]; + $data['order_status'] = $status[$moduleTitle . '_status'][$data['order_status_id']]; } $this->load->model('extension/retailcrm/order'); @@ -56,6 +57,7 @@ class ControllerExtensionModuleRetailcrm extends Controller * @return void */ public function order_edit($parameter1, $parameter2 = null) { + $moduleTitle = $this->getModuleTitle(); $order_id = $parameter2[0]; $this->load->model('checkout/order'); @@ -77,10 +79,10 @@ class ControllerExtensionModuleRetailcrm extends Controller if (!isset($data['fromApi'])) { $this->load->model('setting/setting'); - $status = $this->model_setting_setting->getSetting('retailcrm'); + $status = $this->model_setting_setting->getSetting($moduleTitle); if ($data['order_status_id'] > 0) { - $data['order_status'] = $status['retailcrm_status'][$data['order_status_id']]; + $data['order_status'] = $status[$moduleTitle . '_status'][$data['order_status_id']]; } $this->load->model('extension/retailcrm/order'); @@ -140,4 +142,15 @@ class ControllerExtensionModuleRetailcrm extends Controller $this->load->model('extension/retailcrm/customer'); $this->model_extension_retailcrm_customer->changeInCrm($customer); } + + private function getModuleTitle() + { + if (version_compare(VERSION, '3.0', '<')) { + $title = 'retailcrm'; + } else { + $title = 'module_retailcrm'; + } + + return $title; + } } diff --git a/catalog/model/extension/retailcrm/customer.php b/catalog/model/extension/retailcrm/customer.php index 251683b..c51f73a 100644 --- a/catalog/model/extension/retailcrm/customer.php +++ b/catalog/model/extension/retailcrm/customer.php @@ -1,44 +1,24 @@ load->model('setting/setting'); - $settings = $this->model_setting_setting->getSetting('retailcrm'); + public function sendToCrm($customer) + { + $this->initApi(); if(empty($customer)) return false; - if(empty($settings['retailcrm_url']) || empty($settings['retailcrm_apikey'])) - return false; - - require_once DIR_SYSTEM . 'library/retailcrm/bootstrap.php'; - - $this->retailcrmApi = new RetailcrmProxy( - $settings['retailcrm_url'], - $settings['retailcrm_apikey'], - DIR_SYSTEM . 'storage/logs/retailcrm.log' - ); - + $customerToCrm = $this->process($customer); $this->retailcrmApi->customersCreate($customerToCrm); } - public function changeInCrm($customer) { - $this->load->model('setting/setting'); - $settings = $this->model_setting_setting->getSetting('retailcrm'); + public function changeInCrm($customer) + { + $this->initApi(); if(empty($customer)) return false; - if(empty($settings['retailcrm_url']) || empty($settings['retailcrm_apikey'])) - return false; - - require_once DIR_SYSTEM . 'library/retailcrm/bootstrap.php'; - - $this->retailcrmApi = new RetailcrmProxy( - $settings['retailcrm_url'], - $settings['retailcrm_apikey'], - DIR_SYSTEM . 'storage/logs/retailcrm.log' - ); $customerToCrm = $this->process($customer); @@ -59,6 +39,46 @@ class ModelExtensionRetailcrmCustomer extends Model { 'createdAt' => $customer['date_added'] ); + if (isset($customer['address'])) { + $customerToCrm['address'] = array( + 'index' => $customer['address']['postcode'], + 'countryIso' => $customer['address']['iso_code_2'], + 'region' => $customer['address']['zone'], + 'city' => $customer['address']['city'], + 'text' => $customer['address']['address_1'] . ' ' . $customer['address']['address_2'] + ); + } + return $customerToCrm; } + + protected function initApi() + { + $this->load->model('setting/setting'); + $moduleTitle = $this->getModuleTitle(); + $settings = $this->model_setting_setting->getSetting($moduleTitle); + + if(empty($settings[$moduleTitle . '_url']) || empty($settings[$moduleTitle . '_apikey'])) + return false; + + require_once DIR_SYSTEM . 'library/retailcrm/bootstrap.php'; + + $this->retailcrmApi = new RetailcrmProxy( + $settings[$moduleTitle . '_url'], + $settings[$moduleTitle . '_apikey'], + DIR_SYSTEM . 'storage/logs/retailcrm.log', + $settings[$moduleTitle . '_apiversion'] + ); + } + + private function getModuleTitle() + { + if (version_compare(VERSION, '3.0', '<')) { + $title = 'retailcrm'; + } else { + $title = 'module_retailcrm'; + } + + return $title; + } } diff --git a/catalog/model/extension/retailcrm/order.php b/catalog/model/extension/retailcrm/order.php index 3a3a7a1..f722458 100644 --- a/catalog/model/extension/retailcrm/order.php +++ b/catalog/model/extension/retailcrm/order.php @@ -6,162 +6,31 @@ class ModelExtensionRetailcrmOrder extends Model { { if(isset($this->request->post['fromApi'])) return; - $this->load->model('setting/setting'); - $settings = $this->model_setting_setting->getSetting('retailcrm'); + $this->initApi(); - if(!empty($settings['retailcrm_url']) && !empty($settings['retailcrm_apikey'])) { - $this->load->model('catalog/product'); + $order = $this->processOrder($order_data, $order_id); - require_once DIR_SYSTEM . 'library/retailcrm/bootstrap.php'; + $customers = $this->retailcrm->customersList( + array( + 'name' => $order_data['telephone'], + 'email' => $order_data['email'] + ), + 1, + 100 + ); - $this->retailcrm = new RetailcrmProxy( - $settings['retailcrm_url'], - $settings['retailcrm_apikey'], - DIR_SYSTEM . 'storage/logs/retailcrm.log' - ); - - $order = array(); - - $customers = $this->retailcrm->customersList( - array( - 'name' => $order_data['telephone'], - 'email' => $order_data['email'] - ), - 1, - 100 - ); - - if($customers) { - foreach ($customers['customers'] as $customer) { - $order['customer']['id'] = $customer['id']; - } + if($customers) { + foreach ($customers['customers'] as $customer) { + $order['customer']['id'] = $customer['id']; } + } - unset($customers); + unset($customers); - $order['externalId'] = $order_id; - $order['firstName'] = $order_data['firstname']; - $order['lastName'] = $order_data['lastname']; - $order['phone'] = $order_data['telephone']; - $order['customerComment'] = $order_data['comment']; + $response = $this->retailcrm->ordersCreate($order); - if(!empty($order_data['email'])) { - $order['email'] = $order_data['email']; - } - - $deliveryCost = 0; - $altTotals = isset($order_data['order_total']) ? $order_data['order_total'] : ""; - $orderTotals = isset($order_data['totals']) ? $order_data['totals'] : $altTotals ; - $couponTotal = 0; - - if (!empty($orderTotals)) { - foreach ($orderTotals as $totals) { - if ($totals['code'] == 'shipping') { - $deliveryCost = $totals['value']; - } - - if ($totals['code'] == 'coupon') { - $couponTotal = abs($totals['value']); - } - } - } - - if(isset($couponTotal)) $order['discount'] = $couponTotal; - $order['createdAt'] = $order_data['date_added']; - - $payment_code = $order_data['payment_code']; - $order['paymentType'] = $settings['retailcrm_payment'][$payment_code]; - - if(!isset($order_data['shipping_iso_code_2']) && isset($order_data['shipping_country_id'])) { - $this->load->model('localisation/country'); - $shipping_country = $this->model_localisation_country->getCountry($order_data['shipping_country_id']); - $order_data['shipping_iso_code_2'] = $shipping_country['iso_code_2']; - } - - if(isset($settings['retailcrm_delivery'][$order_data['shipping_code']])) { - $delivery_code = $order_data['shipping_code']; - } else { - $delivery_code = stristr($order_data['shipping_code'], '.', TRUE); - } - - $order['delivery'] = array( - 'code' => !empty($delivery_code) ? $settings['retailcrm_delivery'][$delivery_code] : '', - 'cost' => $deliveryCost, - 'address' => array( - 'index' => $order_data['shipping_postcode'], - 'city' => $order_data['shipping_city'], - 'countryIso' => $order_data['shipping_iso_code_2'], - 'region' => $order_data['shipping_zone'], - 'text' => implode(', ', array( - $order_data['shipping_postcode'], - (isset($order_data['shipping_country'])) ? $order_data['shipping_country'] : '', - $order_data['shipping_city'], - $order_data['shipping_address_1'], - $order_data['shipping_address_2'] - )) - ) - ); - - $orderProducts = isset($order_data['products']) ? $order_data['products'] : $order_data['order_product']; - $offerOptions = array('select', 'radio'); - - foreach ($orderProducts as $product) { - $offerId = ''; - - if(!empty($product['option'])) { - $options = array(); - - $productOptions = $this->model_catalog_product->getProductOptions($product['product_id']); - - 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'], $offerOptions)) continue; - foreach($productOptions as $productOption) { - if($productOption['product_option_id'] = $option['product_option_id']) { - foreach($productOption['product_option_value'] as $productOptionValue) { - if($productOptionValue['product_option_value_id'] == $option['product_option_value_id']) { - $options[$option['product_option_id']] = $productOptionValue['option_value_id']; - } - } - } - } - } - - ksort($options); - - $offerId = array(); - foreach($options as $optionKey => $optionValue) { - $offerId[] = $optionKey.'-'.$optionValue; - } - $offerId = implode('_', $offerId); - } - - $item = array( - 'offer' => array( - 'externalId' => !empty($offerId) ? $product['product_id'].'#'.$offerId : $product['product_id'] - ), - 'productName' => $product['name'], - 'initialPrice' => $product['price'], - 'quantity' => $product['quantity'], - ); - - if (isset($properties)) $item['properties'] = $properties; - - $order['items'][] = $item; - } - - if (isset($order_data['order_status_id']) && $order_data['order_status_id'] > 0) { - $order['status'] = $settings['retailcrm_status'][$order_data['order_status_id']]; - } - - $this->retailcrm->ordersCreate($order); + if ($this->settings[$this->moduleTitle . '_apiversion'] == 'v5' && $response->isSuccessful()) { + $this->createPayment($order_data, $order_id); } } @@ -169,121 +38,166 @@ class ModelExtensionRetailcrmOrder extends Model { { if(isset($this->request->post['fromApi'])) return; + $this->initApi(); + + $order = $this->processOrder($order_data, $order_id); + + $customers = $this->retailcrm->customersList( + array( + 'name' => $order_data['telephone'], + 'email' => $order_data['email'] + ), + 1, + 100 + ); + + if($customers) { + foreach ($customers['customers'] as $customer) { + $order['customer']['id'] = $customer['id']; + } + } + + unset($customers); + + $response = $this->retailcrm->ordersEdit($order); + + if ($this->settings[$this->moduleTitle . '_apiversion'] == 'v5' && $response->isSuccessful()) { + $response_order = $this->retailcrm->ordersGet($order_id); + if ($response_order->isSuccessful()) $order_info = $response_order['order']; + + foreach ($order_info['payments'] as $payment_data) { + if ($payment_data['externalId'] == $order_id) { + $payment = $payment_data; + } + } + + if (isset($payment) && $payment['type'] != $this->settings[$this->moduleTitle . '_payment'][$order_data['payment_code']]) { + $response = $this->retailcrm->ordersPaymentDelete($payment['id']); + + if ($response->isSuccessful()) { + $this->createPayment($order_data, $order_id); + } + } + } + } + + protected function processOrder($order_data, $order_id) + { + $this->moduleTitle = $this->getModuleTitle(); $this->load->model('setting/setting'); - $settings = $this->model_setting_setting->getSetting('retailcrm'); - $settingPaid = $this->model_setting_setting->getSetting($order_data['payment_code']); + $this->load->model('catalog/product'); + $this->settings = $this->model_setting_setting->getSetting($this->moduleTitle); + + if (version_compare(VERSION, '3.0', '<')) { + $settingPaid = $this->model_setting_setting->getSetting($order_data['payment_code']); + } else { + $settingPaid = $this->model_setting_setting->getSetting('payment_' . $order_data['payment_code']); + } - if(!empty($settings['retailcrm_url']) && !empty($settings['retailcrm_apikey'])) { - $this->load->model('catalog/product'); + $payment_code = $order_data['payment_code']; + $order['externalId'] = $order_id; + $order['firstName'] = $order_data['firstname']; + $order['lastName'] = $order_data['lastname']; + $order['phone'] = $order_data['telephone']; + $order['customerComment'] = $order_data['comment']; - require_once DIR_SYSTEM . 'library/retailcrm/bootstrap.php'; + if(!empty($order_data['email'])) { + $order['email'] = $order_data['email']; + } + + $deliveryCost = 0; + $orderTotals = isset($order_data['totals']) ? $order_data['totals'] : $order_data['order_total'] ; - $this->retailcrm = new RetailcrmProxy( - $settings['retailcrm_url'], - $settings['retailcrm_apikey'], - DIR_SYSTEM . 'storage/logs/retailcrm.log' - ); - - $order = array(); - - $payment_code = $order_data['payment_code']; - $order['externalId'] = $order_id; - $order['firstName'] = $order_data['firstname']; - $order['lastName'] = $order_data['lastname']; - $order['phone'] = $order_data['telephone']; - $order['customerComment'] = $order_data['comment']; - - if(!empty($order_data['email'])) { - $order['email'] = $order_data['email']; + foreach ($orderTotals as $totals) { + if ($totals['code'] == 'shipping') { + $deliveryCost = $totals['value']; } - $deliveryCost = 0; - $orderTotals = isset($order_data['totals']) ? $order_data['totals'] : $order_data['order_total'] ; - - foreach ($orderTotals as $totals) { - if ($totals['code'] == 'shipping') { - $deliveryCost = $totals['value']; - } - - if ($totals['code'] == 'coupon') { - $couponTotal = abs($totals['value']); - } + if ($totals['code'] == 'coupon') { + $couponTotal = abs($totals['value']); } - - if(isset($couponTotal)) $order['discount'] = $couponTotal; - $order['createdAt'] = $order_data['date_added']; - $order['paymentType'] = $settings['retailcrm_payment'][$payment_code]; + } - $country = (isset($order_data['shipping_country'])) ? $order_data['shipping_country'] : '' ; + $order['createdAt'] = $order_data['date_added']; - if(isset($settings['retailcrm_delivery'][$order_data['shipping_code']])) { - $delivery_code = $order_data['shipping_code']; - } else { - $delivery_code = stristr($order_data['shipping_code'], '.', TRUE); - } + if ($this->settings[$this->moduleTitle . '_apiversion'] != 'v5') { + $order['paymentType'] = $this->settings[$this->moduleTitle . '_payment'][$payment_code]; + if (isset($couponTotal)) $order['discount'] = $couponTotal; + } else { + if (isset($couponTotal)) $order['discountManualAmount'] = $couponTotal; + } - $order['delivery'] = array( - 'code' => !empty($delivery_code) ? $settings['retailcrm_delivery'][$delivery_code] : '', - 'address' => array( - 'index' => $order_data['shipping_postcode'], - 'city' => $order_data['shipping_city'], - 'countryIso' => $order_data['shipping_iso_code_2'], - 'region' => $order_data['shipping_zone'], - 'text' => implode(', ', array( - $order_data['shipping_postcode'], - $country, - $order_data['shipping_city'], - $order_data['shipping_address_1'], - $order_data['shipping_address_2'] - )) - ) - ); + $country = (isset($order_data['shipping_country'])) ? $order_data['shipping_country'] : '' ; - if(!empty($deliveryCost)){ - $order['delivery']['cost'] = $deliveryCost; - } - - $orderProducts = isset($order_data['products']) ? $order_data['products'] : $order_data['order_product']; - $offerOptions = array('select', 'radio'); + if(isset($this->settings[$this->moduleTitle . '_delivery'][$order_data['shipping_code']])) { + $delivery_code = $order_data['shipping_code']; + } else { + $delivery_code = stristr($order_data['shipping_code'], '.', TRUE); + } - foreach ($orderProducts as $product) { - $offerId = ''; + $order['delivery'] = array( + 'code' => !empty($delivery_code) ? $this->settings[$this->moduleTitle . '_delivery'][$delivery_code] : '', + 'address' => array( + 'index' => $order_data['shipping_postcode'], + 'city' => $order_data['shipping_city'], + 'countryIso' => $order_data['shipping_iso_code_2'], + 'region' => $order_data['shipping_zone'], + 'text' => implode(', ', array( + $order_data['shipping_postcode'], + $country, + $order_data['shipping_city'], + $order_data['shipping_address_1'], + $order_data['shipping_address_2'] + )) + ) + ); - if (!empty($product['option'])) { - $options = array(); + if(!empty($deliveryCost)){ + $order['delivery']['cost'] = $deliveryCost; + } + + $orderProducts = isset($order_data['products']) ? $order_data['products'] : $order_data['order_product']; + $offerOptions = array('select', 'radio'); - $productOptions = $this->model_catalog_product->getProductOptions($product['product_id']); + foreach ($orderProducts as $product) { + $offerId = ''; - 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'], $offerOptions)) continue; - foreach($productOptions as $productOption) { - if($productOption['product_option_id'] = $option['product_option_id']) { - foreach($productOption['product_option_value'] as $productOptionValue) { - if($productOptionValue['product_option_value_id'] == $option['product_option_value_id']) { - $options[$option['product_option_id']] = $productOptionValue['option_value_id']; - } + if (!empty($product['option'])) { + $options = array(); + + $productOptions = $this->model_catalog_product->getProductOptions($product['product_id']); + + 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'], $offerOptions)) continue; + foreach($productOptions as $productOption) { + if($productOption['product_option_id'] = $option['product_option_id']) { + foreach($productOption['product_option_value'] as $productOptionValue) { + if($productOptionValue['product_option_value_id'] == $option['product_option_value_id']) { + $options[$option['product_option_id']] = $productOptionValue['option_value_id']; } } } } - - ksort($options); - - $offerId = array(); - foreach($options as $optionKey => $optionValue) { - $offerId[] = $optionKey.'-'.$optionValue; - } - $offerId = implode('_', $offerId); } + ksort($options); + + $offerId = array(); + foreach($options as $optionKey => $optionValue) { + $offerId[] = $optionKey.'-'.$optionValue; + } + $offerId = implode('_', $offerId); + } + + if ($this->settings[$this->moduleTitle . '_apiversion'] != 'v3') { $item = array( 'offer' => array( 'externalId' => !empty($offerId) ? $product['product_id'].'#'.$offerId : $product['product_id'] @@ -292,21 +206,137 @@ class ModelExtensionRetailcrmOrder extends Model { 'initialPrice' => $product['price'], 'quantity' => $product['quantity'], ); - - if (isset($properties)) $item['properties'] = $properties; - - $order['items'][] = $item; + } else { + $item = array( + 'productName' => $product['name'], + 'initialPrice' => $product['price'], + 'quantity' => $product['quantity'], + 'productId' => !empty($offerId) ? $product['product_id'].'#'.$offerId : $product['product_id'] + ); } + if (isset($properties)) $item['properties'] = $properties; + + $order['items'][] = $item; + if (isset($order_data['order_status_id']) && $order_data['order_status_id'] > 0) { - $order['status'] = $settings['retailcrm_status'][$order_data['order_status_id']]; + $order['status'] = $this->settings[$this->moduleTitle . '_status'][$order_data['order_status_id']]; } - if ($order_data['order_status_id'] == $settingPaid[$order_data['payment_code'] . '_order_status_id']) { - $order['paymentStatus'] = 'paid'; + if ($this->settings[$this->moduleTitle . '_apiversion'] != 'v5') { + if (version_compare(VERSION, '3.0', '<')) { + if ($order_data['order_status_id'] == $settingPaid[$order_data['payment_code'] . '_order_status_id']) { + $order['paymentStatus'] = 'paid'; + } + } else { + if ($order_data['order_status_id'] == $settingPaid['payment_' . $order_data['payment_code'] . '_order_status_id']) { + $order['paymentStatus'] = 'paid'; + } + } } - - $this->retailcrm->ordersEdit($order); + } + + return $order; + } + + protected function createPayment($order, $order_id) + { + if (version_compare(VERSION, '3.0', '<')) { + $settingPaid = $this->model_setting_setting->getSetting($order['payment_code']); + } else { + $settingPaid = $this->model_setting_setting->getSetting('payment_' . $order['payment_code']); + } + + $payment_code = $order['payment_code']; + + foreach ($order['totals'] as $total) { + if ($total['code'] == 'total') $amount = $total['value']; + } + + $payment = array( + 'externalId' => $order_id, + 'type' => $this->settings[$this->moduleTitle . '_payment'][$payment_code], + 'amount' => $amount + ); + + if (version_compare(VERSION, '3.0', '<')) { + if ($order['order_status_id'] == $settingPaid[$order['payment_code'] . '_order_status_id']) { + $payment['status'] = 'paid'; + } + } else { + if ($order['order_status_id'] == $settingPaid['payment_' . $order['payment_code'] . '_order_status_id']) { + $payment['status'] = 'paid'; + } + } + + $payment['order'] = array( + 'externalId' => $order_id + ); + + $this->retailcrm->ordersPaymentCreate($payment); + } + + protected function editPayment($order, $order_id) + { + if (version_compare(VERSION, '3.0', '<')) { + $settingPaid = $this->model_setting_setting->getSetting($order['payment_code']); + } else { + $settingPaid = $this->model_setting_setting->getSetting('payment_' . $order['payment_code']); + } + + $payment_code = $order['payment_code']; + + foreach ($order['totals'] as $total) { + if ($total['code'] == 'total') $amount = $total['value']; + } + + $payment = array( + 'externalId' => $order_id, + 'type' => $this->settings[$this->moduleTitle . '_payment'][$payment_code], + 'amount' => $amount + ); + + if (version_compare(VERSION, '3.0', '<')) { + if ($order['order_status_id'] == $settingPaid[$order['payment_code'] . '_order_status_id']) { + $payment['status'] = 'paid'; + } + } else { + if ($order['order_status_id'] == $settingPaid['payment_' . $order['payment_code'] . '_order_status_id']) { + $payment['status'] = 'paid'; + } + } + + $this->retailcrm->ordersPaymentEdit($payment); + } + + private function initApi() + { + $moduleTitle = $this->getModuleTitle(); + $this->load->model('setting/setting'); + $settings = $this->model_setting_setting->getSetting($moduleTitle); + + if(!empty($settings[$moduleTitle . '_url']) && !empty($settings[$moduleTitle . '_apikey'])) { + + require_once DIR_SYSTEM . 'library/retailcrm/bootstrap.php'; + + $this->retailcrm = new RetailcrmProxy( + $settings[$moduleTitle . '_url'], + $settings[$moduleTitle . '_apikey'], + DIR_SYSTEM . 'storage/logs/retailcrm.log', + $settings[$moduleTitle . '_apiversion'] + ); } } + + private function getModuleTitle() + { + if (version_compare(VERSION, '3.0', '<')) { + $title = 'retailcrm'; + } else { + $title = 'module_retailcrm'; + } + + return $title; + } + } diff --git a/system/cron/dispatch.php b/system/cron/dispatch.php index 69ee0ed..e1ababf 100644 --- a/system/cron/dispatch.php +++ b/system/cron/dispatch.php @@ -50,6 +50,12 @@ $registry->set('load', $loader); // Config $config = new Config(); + +if (version_compare(VERSION, '3.0', '>=')) { + $config->load('default'); + $config->load('catalog'); +} + $registry->set('config', $config); // Database @@ -122,7 +128,13 @@ $cache = new Cache('file'); $registry->set('cache', $cache); $registry->set('response', $response); -$session = new Session(); + +if (version_compare(VERSION, '3.0', '<')) { + $session = new Session(); +} else { + $session = new Session($config->get('session_engine'), $registry); +} + $registry->set('session', $session); $languages = array(); @@ -150,8 +162,12 @@ $registry->set('weight', new Cart\Weight($registry)); $registry->set('length', new Cart\Length($registry)); $registry->set('user', new Cart\User($registry)); +if (version_compare(VERSION, '3.0', '<')) { + $controller = new Front($registry); +} else { + $controller = new Router($registry); +} -$controller = new Front($registry); $action = new Action($cli_action); $controller->dispatch($action, new Action('error/not_found')); diff --git a/system/library/retailcrm/OpencartApiClient.php b/system/library/retailcrm/OpencartApiClient.php index c9e3569..47a8684 100644 --- a/system/library/retailcrm/OpencartApiClient.php +++ b/system/library/retailcrm/OpencartApiClient.php @@ -44,7 +44,12 @@ class OpencartApiClient { $opencartStoreInfo = $this->model_setting_store->getStore($this->opencartStoreId); if(!empty($this->apiToken)) { - $getParams['token'] = $this->apiToken; + if (version_compare(VERSION, '3.0', '<')) { + $getParams['token'] = $this->apiToken; + } else { + $getParams['api_token'] = $this->apiToken; + } + } $postParams['fromApi'] = true; @@ -89,10 +94,7 @@ class OpencartApiClient { $api = array(); foreach ($apiUsers as $apiUser) { if($apiUser['status'] == 1) { - $api = array( - 'api_id' => $apiUser['api_id'], - 'key' => $apiUser['key'] - ); + $api = $apiUser; break; } } @@ -114,12 +116,15 @@ class OpencartApiClient { $this->model_user_api->addApiIp($api['api_id'], $innerIp); } - - $apiAnswer = $this->request('login', array(), $apiUser); - - $this->apiToken = $apiAnswer['token']; - - return $apiAnswer; + if (version_compare(VERSION, '3.0', '<')){ + $apiAnswer = $this->request('login', array(), $api); + $this->apiToken = $apiAnswer['token']; + } else { + $this->apiToken = $this->apiLogin(); + } + + if (isset($apiAnswer)) + return $apiAnswer; } public function editOrder($order_id, $data) { @@ -303,4 +308,27 @@ class OpencartApiClient { return curl_exec($curl); } + + /** + * Login api user for opencart version > 3.0 + * + */ + private function apiLogin() { + $this->load->model('user/api'); + $registry = new Registry(); + $config = new Config(); + $config->load('default'); + + $api_info = $this->model_user_api->getApi($this->config->get('config_api_id')); + $session = new Session($this->config->get('session_engine'), $this->registry); + $session->start(); + + $this->model_user_api->deleteApiSessionBySessonId($session->getId()); + $this->model_user_api->addApiSession($api_info['api_id'], $session->getId(), $this->request->server['REMOTE_ADDR']); + + $session->data['api_id'] = $api_info['api_id']; + $api_token = $session->getId(); + + return $api_token; + } } diff --git a/system/library/retailcrm/RetailcrmApiClient3.php b/system/library/retailcrm/RetailcrmApiClient3.php new file mode 100644 index 0000000..7a6d7df --- /dev/null +++ b/system/library/retailcrm/RetailcrmApiClient3.php @@ -0,0 +1,819 @@ + + * @license https://opensource.org/licenses/MIT MIT License + * @link http://www.retailcrm.ru/docs/Developers/ApiVersion3 + */ +class RetailcrmApiClient3 +{ + const VERSION = 'v3'; + + protected $client; + + /** + * Site code + */ + protected $siteCode; + + /** + * Client creating + * + * @param string $url + * @param string $apiKey + * @param string $site + * @return mixed + */ + public function __construct($url, $apiKey, $site = null) + { + if ('/' != substr($url, strlen($url) - 1, 1)) { + $url .= '/'; + } + + $url = $url . 'api/' . self::VERSION; + + $this->client = new RetailcrmHttpClient($url, array('apiKey' => $apiKey)); + $this->siteCode = $site; + } + + /** + * 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/system/library/retailcrm/RetailcrmApiClient.php b/system/library/retailcrm/RetailcrmApiClient4.php similarity index 99% rename from system/library/retailcrm/RetailcrmApiClient.php rename to system/library/retailcrm/RetailcrmApiClient4.php index 4363e65..5a406f1 100644 --- a/system/library/retailcrm/RetailcrmApiClient.php +++ b/system/library/retailcrm/RetailcrmApiClient4.php @@ -10,9 +10,8 @@ * @license https://opensource.org/licenses/MIT MIT License * @link http://www.retailcrm.ru/docs/Developers/ApiVersion4 */ -class RetailcrmApiClient +class RetailcrmApiClient4 { - const VERSION = 'v4'; protected $client; diff --git a/system/library/retailcrm/RetailcrmApiClient5.php b/system/library/retailcrm/RetailcrmApiClient5.php new file mode 100644 index 0000000..bf80d53 --- /dev/null +++ b/system/library/retailcrm/RetailcrmApiClient5.php @@ -0,0 +1,2364 @@ + + * @license https://opensource.org/licenses/MIT MIT License + * @link http://www.retailcrm.ru/docs/Developers/ApiVersion5 + */ +class RetailcrmApiClient5 +{ + const VERSION = 'v5'; + + 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, $site = null) + { + if ('/' !== $url[strlen($url) - 1]) { + $url .= '/'; + } + + $url = $url . 'api/' . self::VERSION; + + $this->client = new RetailcrmHttpClient($url, array('apiKey' => $apiKey)); + $this->siteCode = $site; + } + + /** + * 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); + } + + /** + * Change user status + * + * @param integer $id user ID + * @param string $status user status + * + * @return ApiResponse + */ + public function usersStatus($id, $status) + { + $statuses = array("free", "busy", "dinner", "break"); + + if (empty($status) || !in_array($status, $statuses)) { + throw new \InvalidArgumentException( + 'Parameter `status` must be not empty & must be equal one of these values: free|busy|dinner|break' + ); + } + + return $this->client->makeRequest( + "/users/$id/status", + RetailcrmHttpClient::METHOD_POST, + array('status' => $status) + ); + } + + /** + * Get segments list + * + * @param array $filter + * @param null $limit + * @param null $page + * + * @return ApiResponse + */ + public function segmentsList(array $filter = array(), $limit = null, $page = 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( + '/segments', + RetailcrmHttpClient::METHOD_GET, + $parameters + ); + } + + /** + * Get custom fields list + * + * @param array $filter + * @param null $limit + * @param null $page + * + * @return ApiResponse + */ + public function customFieldsList(array $filter = array(), $limit = null, $page = 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( + '/custom-fields', + RetailcrmHttpClient::METHOD_GET, + $parameters + ); + } + + /** + * Create custom field + * + * @param $entity + * @param $customField + * + * @return ApiResponse + */ + public function customFieldsCreate($entity, $customField) + { + if (!count($customField) || + empty($customField['code']) || + empty($customField['name']) || + empty($customField['type']) + ) { + throw new \InvalidArgumentException( + 'Parameter `customField` must contain a data & fields `code`, `name` & `type` must be set' + ); + } + + if (empty($entity) || $entity != 'customer' || $entity != 'order') { + throw new \InvalidArgumentException( + 'Parameter `entity` must contain a data & value must be `order` or `customer`' + ); + } + + return $this->client->makeRequest( + "/custom-fields/$entity/create", + RetailcrmHttpClient::METHOD_POST, + array('customField' => json_encode($customField)) + ); + } + + /** + * Edit custom field + * + * @param $entity + * @param $customField + * + * @return ApiResponse + */ + public function customFieldsEdit($entity, $customField) + { + if (!count($customField) || empty($customField['code'])) { + throw new \InvalidArgumentException( + 'Parameter `customField` must contain a data & fields `code` must be set' + ); + } + + if (empty($entity) || $entity != 'customer' || $entity != 'order') { + throw new \InvalidArgumentException( + 'Parameter `entity` must contain a data & value must be `order` or `customer`' + ); + } + + return $this->client->makeRequest( + "/custom-fields/$entity/edit/{$customField['code']}", + $this->client::METHOD_POST, + array('customField' => json_encode($customField)) + ); + } + + /** + * Get custom field + * + * @param $entity + * @param $code + * + * @return ApiResponse + */ + public function customFieldsGet($entity, $code) + { + if (empty($code)) { + throw new \InvalidArgumentException( + 'Parameter `code` must be not empty' + ); + } + + if (empty($entity) || $entity != 'customer' || $entity != 'order') { + throw new \InvalidArgumentException( + 'Parameter `entity` must contain a data & value must be `order` or `customer`' + ); + } + + return $this->client->makeRequest( + "/custom-fields/$entity/$code", + RetailcrmHttpClient::METHOD_GET + ); + } + + /** + * Get custom dictionaries list + * + * @param array $filter + * @param null $limit + * @param null $page + * + * @return ApiResponse + */ + public function customDictionariesList(array $filter = [], $limit = null, $page = null) + { + $parameters = []; + + if (count($filter)) { + $parameters['filter'] = $filter; + } + if (null !== $page) { + $parameters['page'] = (int) $page; + } + if (null !== $limit) { + $parameters['limit'] = (int) $limit; + } + + return $this->client->makeRequest( + '/custom-fields/dictionaries', + RetailcrmHttpClient::METHOD_GET, + $parameters + ); + } + + /** + * Create custom dictionary + * + * @param $customDictionary + * + * @return ApiResponse + */ + public function customDictionariesCreate($customDictionary) + { + if (!count($customDictionary) || + empty($customDictionary['code']) || + empty($customDictionary['elements']) + ) { + throw new \InvalidArgumentException( + 'Parameter `dictionary` must contain a data & fields `code` & `elemets` must be set' + ); + } + + return $this->client->makeRequest( + "/custom-fields/dictionaries/{$customDictionary['code']}/create", + RetailcrmHttpClient::METHOD_POST, + array('customDictionary' => json_encode($customDictionary)) + ); + } + + /** + * Edit custom dictionary + * + * @param $customDictionary + * + * @return ApiResponse + */ + public function customDictionariesEdit($customDictionary) + { + if (!count($customDictionary) || + empty($customDictionary['code']) || + empty($customDictionary['elements']) + ) { + throw new \InvalidArgumentException( + 'Parameter `dictionary` must contain a data & fields `code` & `elemets` must be set' + ); + } + + return $this->client->makeRequest( + "/custom-fields/dictionaries/{$customDictionary['code']}/edit", + RetailcrmHttpClient::METHOD_POST, + array('customDictionary' => json_encode($customDictionary)) + ); + } + + /** + * Get custom dictionary + * + * @param $code + * + * @return ApiResponse + */ + public function customDictionariesGet($code) + { + if (empty($code)) { + throw new \InvalidArgumentException( + 'Parameter `code` must be not empty' + ); + } + + return $this->client->makeRequest( + "/custom-fields/dictionaries/$code", + 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 + ); + } + + /** + * Combine orders + * + * @param string $technique + * @param array $order + * @param array $resultOrder + * + * @return ApiResponse + */ + public function ordersCombine($order, $resultOrder, $technique = 'ours') + { + $techniques = array('ours', 'summ', 'theirs'); + + if (!count($order) || !count($resultOrder)) { + throw new \InvalidArgumentException( + 'Parameters `order` & `resultOrder` must contains a data' + ); + } + + if (!in_array($technique, $techniques)) { + throw new \InvalidArgumentException( + 'Parameter `technique` must be on of ours|summ|theirs' + ); + } + + return $this->client->makeRequest( + '/orders/combine', + RetailcrmHttpClient::METHOD_POST, + array( + 'technique' => $technique, + 'order' => json_encode($order), + 'resultOrder' => json_encode($resultOrder) + ) + ); + } + + /** + * Create an order payment + * + * @param array $payment order data + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function ordersPaymentCreate(array $payment) + { + if (!count($payment)) { + throw new \InvalidArgumentException( + 'Parameter `payment` must contains a data' + ); + } + + return $this->client->makeRequest( + '/orders/payments/create', + RetailcrmHttpClient::METHOD_POST, + array('payment' => json_encode($payment)) + ); + } + + /** + * Edit an order payment + * + * @param array $payment order data + * @param string $by by key + * @param null $site site code + * + * @return ApiResponse + */ + public function ordersPaymentEdit(array $payment, $by = 'externalId', $site = null) + { + if (!count($payment)) { + throw new \InvalidArgumentException( + 'Parameter `payment` must contains a data' + ); + } + + $this->checkIdParameter($by); + + if (!array_key_exists($by, $payment)) { + throw new \InvalidArgumentException( + sprintf('Order array must contain the "%s" parameter.', $by) + ); + } + + return $this->client->makeRequest( + sprintf('/orders/payments/%s/edit', $payment[$by]), + RetailcrmHttpClient::METHOD_POST, + $this->fillSite( + $site, + array('payment' => json_encode($payment), 'by' => $by) + ) + ); + } + + /** + * Edit an order payment + * + * @param string $id payment id + * + * @return ApiResponse + */ + public function ordersPaymentDelete($id) + { + if (!$id) { + throw new \InvalidArgumentException( + 'Parameter `id` must be set' + ); + } + + return $this->client->makeRequest( + sprintf('/orders/payments/%s/delete', $id), + RetailcrmHttpClient::METHOD_POST + ); + } + + /** + * 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 + ); + } + + /** + * Combine customers + * + * @param array $customers + * @param array $resultCustomer + * + * @return ApiResponse + */ + public function customersCombine(array $customers, $resultCustomer) + { + + if (!count($customers) || !count($resultCustomer)) { + throw new \InvalidArgumentException( + 'Parameters `customers` & `resultCustomer` must contains a data' + ); + } + + return $this->client->makeRequest( + '/customers/combine', + RetailcrmHttpClient::METHOD_POST, + array( + 'customers' => json_encode($customers), + 'resultCustomer' => json_encode($resultCustomer) + ) + ); + } + + /** + * Returns filtered customers notes 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 customersNotesList(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/notes', + RetailcrmHttpClient::METHOD_GET, + $parameters + ); + } + + /** + * Create customer note + * + * @param array $note (default: array()) + * @param string $site (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function customersNotesCreate($note, $site = null) + { + if (empty($note['customer']['id']) && empty($note['customer']['externalId'])) { + throw new \InvalidArgumentException( + 'Customer identifier must be set' + ); + } + return $this->client->makeRequest( + '/customers/notes/create', + RetailcrmHttpClient::METHOD_POST, + $this->fillSite($site, array('note' => json_encode($note))) + ); + } + + /** + * Delete customer note + * + * @param integer $id + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function customersNotesDelete($id) + { + if (empty($id)) { + throw new \InvalidArgumentException( + 'Note id must be set' + ); + } + return $this->client->makeRequest( + "/customers/notes/$id/delete", + RetailcrmHttpClient::METHOD_POST + ); + } + + /** + * 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 tasks list + * + * @param array $filter + * @param null $limit + * @param null $page + * + * @return ApiResponse + */ + public function tasksList(array $filter = array(), $limit = null, $page = 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( + '/tasks', + RetailcrmHttpClient::METHOD_GET, + $parameters + ); + } + + /** + * Create task + * + * @param array $task + * @param null $site + * + * @return ApiResponse + * + */ + public function tasksCreate($task, $site = null) + { + if (!count($task)) { + throw new \InvalidArgumentException( + 'Parameter `task` must contain a data' + ); + } + + return $this->client->makeRequest( + "/tasks/create", + RetailcrmHttpClient::METHOD_POST, + $this->fillSite( + $site, + array('task' => json_encode($task)) + ) + ); + } + + /** + * Edit task + * + * @param array $task + * @param null $site + * + * @return ApiResponse + * + */ + public function tasksEdit($task, $site = null) + { + if (!count($task)) { + throw new \InvalidArgumentException( + 'Parameter `task` must contain a data' + ); + } + + return $this->client->makeRequest( + "/tasks/{$task['id']}/edit", + RetailcrmHttpClient::METHOD_POST, + $this->fillSite( + $site, + array('task' => json_encode($task)) + ) + ); + } + + /** + * Get custom dictionary + * + * @param $id + * + * @return ApiResponse + */ + public function tasksGet($id) + { + if (empty($id)) { + throw new \InvalidArgumentException( + 'Parameter `id` must be not empty' + ); + } + + return $this->client->makeRequest( + "/tasks/$id", + RetailcrmHttpClient::METHOD_GET + ); + } + + /** + * Get products groups + * + * @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 storeProductsGroups(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/product-groups', + RetailcrmHttpClient::METHOD_GET, + $parameters + ); + } + + /** + * 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 + ); + } + + /** + * 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)) + ); + } + + /** + * 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/system/library/retailcrm/RetailcrmProxy.php b/system/library/retailcrm/RetailcrmProxy.php index 1f7442c..591245a 100644 --- a/system/library/retailcrm/RetailcrmProxy.php +++ b/system/library/retailcrm/RetailcrmProxy.php @@ -10,17 +10,31 @@ class RetailcrmProxy private $api; private $log; - public function __construct($url, $key, $log) - { - $this->api = new RetailcrmApiClient($url, $key); + public function __construct($url, $key, $log, $version = 'v4') + { + switch ($version) { + case 'v5': + $this->api = new RetailcrmApiClient5($url, $key); + break; + + case 'v4': + $this->api = new RetailcrmApiClient4($url, $key); + break; + + case 'v3': + $this->api = new RetailcrmApiClient3($url, $key); + 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); - $date = date('[Y-m-d H:i:s]'); if (!$response->isSuccessful()) { error_log($date . " [$method] " . $response->getErrorMsg() . "\n", 3, $this->log);