Add enitities for customers and orders

This commit is contained in:
Akolzin Dmitry 2018-08-29 17:45:35 +03:00
parent 57c2ca99c9
commit a6abd523bb
26 changed files with 796 additions and 3838 deletions

View File

@ -10,10 +10,10 @@
}
],
"require-dev": {
"opencart/opencart" : "2.3.0.2",
"opencart/opencart" : "3.0.2.0",
"vlucas/phpdotenv": "~1.1.0",
"phpunit/phpunit" : "~4.0",
"beyondit/opencart-test-suite": "~2.3.0",
"phpunit/phpunit" : "^6",
"beyondit/opencart-test-suite": "~3.0",
"consolidation/robo": "~1",
"henrikbjorn/lurker": "^1.2"
},

View File

@ -9,19 +9,7 @@
* @license https://opensource.org/licenses/MIT MIT License
* @link http://www.retailcrm.ru/docs/Developers/ApiVersion5
*/
class ControllerExtensionModuleRetailcrm extends Controller
{
private $_error = array();
protected $log, $statuses, $payments, $deliveryTypes, $retailcrmApiClient, $moduleTitle, $tokenTitle;
public $children, $template;
public function __construct($registry)
{
parent::__construct($registry);
$this->load->library('retailcrm/retailcrm');
$this->moduleTitle = $this->retailcrm->getModuleTitle();
$this->tokenTitle = $this->retailcrm->getTokenTitle();
}
class ControllerExtensionModuleRetailcrm extends Controller {
/**
* Install method
@ -33,10 +21,10 @@ class ControllerExtensionModuleRetailcrm extends Controller
$this->load->model('setting/setting');
$this->model_setting_setting->editSetting(
$this->moduleTitle,
\Retailcrm\Retailcrm::MODULE,
array(
$this->moduleTitle . '_status' => 1,
$this->moduleTitle . '_country' => array($this->config->get('config_country_id'))
\Retailcrm\Retailcrm::MODULE . '_status' => 1,
\Retailcrm\Retailcrm::MODULE . '_country' => array($this->config->get('config_country_id'))
)
);
@ -53,8 +41,8 @@ class ControllerExtensionModuleRetailcrm extends Controller
$this->uninstall_collector();
$this->load->model('setting/setting');
$this->model_setting_setting->editSetting(
$this->moduleTitle,
array($this->moduleTitle . '_status' => 0)
\Retailcrm\Retailcrm::MODULE,
array(\Retailcrm\Retailcrm::MODULE . '_status' => 0)
);
$this->model_setting_setting->deleteSetting('retailcrm_history');
$this->deleteEvents();
@ -66,12 +54,14 @@ class ControllerExtensionModuleRetailcrm extends Controller
* @return void
*/
public function install_collector()
{
$collector = $this->getCollectorTitle();
$this->loadModels();
{
$this->load->model('setting/setting');
$this->{'model_' . $this->modelExtension}->install('analytics', 'daemon_collector');
$this->model_setting_setting->editSetting($collector, array($collector . '_status' => 1));
$this->load->model('setting/extension');
$this->model_setting_extension->install('analytics', 'daemon_collector');
$this->model_setting_setting->editSetting(
'analytics_daemon_collector',
array('analytics_daemon_collector_status' => 1)
);
}
/**
@ -80,12 +70,14 @@ class ControllerExtensionModuleRetailcrm extends Controller
* @return void
*/
public function uninstall_collector()
{
$collector = $this->getCollectorTitle();
$this->loadModels();
{
$this->load->model('setting/setting');
$this->model_setting_setting->editSetting($collector, array($collector . '_status' => 0));
$this->{'model_' . $this->modelExtension}->uninstall('analytics', 'daemon_collector');
$this->load->model('setting/extension');
$this->model_setting_setting->editSetting(
'analytics_daemon_collector',
array('analytics_daemon_collector_status' => 0)
);
$this->model_setting_extension->uninstall('analytics', 'daemon_collector');
}
/**
@ -95,7 +87,9 @@ class ControllerExtensionModuleRetailcrm extends Controller
*/
public function index()
{
$this->loadModels();
$this->load->library('retailcrm/retailcrm');
$this->load->model('setting/extension');
$this->load->model('setting/event');
$this->load->model('localisation/country');
$this->load->model('setting/setting');
$this->load->model('extension/retailcrm/references');
@ -103,8 +97,9 @@ class ControllerExtensionModuleRetailcrm extends Controller
$this->document->setTitle($this->language->get('heading_title'));
$this->document->addStyle('/admin/view/stylesheet/retailcrm.css');
$collector = $this->getCollectorTitle();
$history_setting = $this->model_setting_setting->getSetting('retailcrm_history');
$retailcrm_api_client = $this->retailcrm->getApiClient();
$opencart_api_client = $this->retailcrm->getOcApiClient($this->registry);
if ($this->request->server['REQUEST_METHOD'] == 'POST' && $this->validate()) {
if ($this->checkEvents() === false) {
@ -112,81 +107,49 @@ class ControllerExtensionModuleRetailcrm extends Controller
$this->addEvents();
}
$analytics = $this->{'model_' . $this->modelExtension}->getInstalled('analytics');
$analytics = $this->model_setting_extension->getInstalled('analytics');
if ($this->request->post[$this->moduleTitle . '_collector_active'] == 1
&& !in_array($collector, $analytics)
if ($this->request->post[\Retailcrm\Retailcrm::MODULE . '_collector_active'] == 1
&& !in_array('analytics_daemon_collector', $analytics)
) {
$this->install_collector();
} elseif ($this->request->post[$this->moduleTitle . '_collector_active'] == 0
&& in_array($collector, $analytics)
} elseif ($this->request->post[\Retailcrm\Retailcrm::MODULE . '_collector_active'] == 0
&& in_array('analytics_daemon_collector', $analytics)
) {
$this->uninstall_collector();
}
if (parse_url($this->request->post[$this->moduleTitle . '_url'])) {
$crm_url = parse_url($this->request->post[$this->moduleTitle . '_url'], PHP_URL_HOST);
$this->request->post[$this->moduleTitle . '_url'] = 'https://' . $crm_url;
if (parse_url($this->request->post[\Retailcrm\Retailcrm::MODULE . '_url'])) {
$crm_url = parse_url($this->request->post[\Retailcrm\Retailcrm::MODULE . '_url'], PHP_URL_HOST);
$this->request->post[\Retailcrm\Retailcrm::MODULE . '_url'] = 'https://' . $crm_url;
}
if (isset($this->request->post[$this->moduleTitle . '_custom_field_active'])
&& $this->request->post[$this->moduleTitle . '_custom_field_active'] == 0
if (isset($this->request->post[\Retailcrm\Retailcrm::MODULE . '_custom_field_active'])
&& $this->request->post[\Retailcrm\Retailcrm::MODULE . '_custom_field_active'] == 0
) {
unset($this->request->post[$this->moduleTitle . '_custom_field']);
unset($this->request->post[\Retailcrm\Retailcrm::MODULE . '_custom_field']);
}
$this->model_setting_setting->editSetting(
$this->moduleTitle,
\Retailcrm\Retailcrm::MODULE,
$this->request->post
);
if ($this->request->post[$this->moduleTitle . '_apiversion'] != 'v3') {
if (!isset($history_setting['retailcrm_history_orders']) && !isset($history_setting['retailcrm_history_customers'])) {
$api = $this->retailcrm->getApiClient(
$this->request->post[$this->moduleTitle . '_url'],
$this->request->post[$this->moduleTitle . '_apikey'],
$this->request->post[$this->moduleTitle . '_apiversion']
);
if (!isset($history_setting['retailcrm_history_orders'])
&& !isset($history_setting['retailcrm_history_customers'])
) {
$api = $this->retailcrm->getApiClient(
$this->request->post[\Retailcrm\Retailcrm::MODULE . '_url'],
$this->request->post[\Retailcrm\Retailcrm::MODULE . '_apikey'],
$this->request->post[\Retailcrm\Retailcrm::MODULE . '_apiversion']
);
$ordersHistory = $api->ordersHistory();
if ($ordersHistory->isSuccessful() && !empty($ordersHistory['history'])) {
$ordersHistory = $api->ordersHistory(array(), $ordersHistory['pagination']['totalPageCount']);
if ($ordersHistory->isSuccessful()) {
$ordersHistoryArr = $ordersHistory['history'];
$lastChangeOrders = end($ordersHistoryArr);
$sinceIdOrders = $lastChangeOrders['id'];
$generatedAt = $ordersHistory['generatedAt'];
}
}
$customersHistory = $api->customersHistory();
if ($customersHistory->isSuccessful() && !empty($customersHistory['history'])) {
$customersHistory = $api->customersHistory(array(), $customersHistory['pagination']['totalPageCount']);
if ($customersHistory->isSuccessful()) {
$customersHistoryArr = $customersHistory['history'];
$lastChangeCustomers = end($customersHistoryArr);
$sinceIdCustomers = $lastChangeCustomers['id'];
}
}
$this->model_setting_setting->editSetting(
'retailcrm_history',
array(
'retailcrm_history_orders' => isset($sinceIdOrders) ? $sinceIdOrders : 1,
'retailcrm_history_customers' => isset($sinceIdCustomers) ? $sinceIdCustomers : 1,
'retailcrm_history_datetime' => isset($generatedAt) ? $generatedAt : date('Y-m-d H:i:s')
)
);
}
$this->getHistory($api);
}
$this->session->data['success'] = $this->language->get('text_success');
$redirect = $this->url->link(
'extension/module/retailcrm', $this->tokenTitle . '=' . $this->session->data[$this->tokenTitle],
'extension/module/retailcrm', 'user_token=' . $this->session->data['user_token'],
'SSL'
);
@ -254,48 +217,34 @@ class ControllerExtensionModuleRetailcrm extends Controller
'text_order_number'
);
$_data = &$data;
foreach ($text_strings as $text) {
$_data[$text] = $this->language->get($text);
}
$_data['retailcrm_errors'] = array();
$_data['saved_settings'] = $this->model_setting_setting
->getSetting($this->moduleTitle);
->getSetting(\Retailcrm\Retailcrm::MODULE);
$url = isset($_data['saved_settings'][$this->moduleTitle . '_url'])
? $_data['saved_settings'][$this->moduleTitle . '_url']
$url = isset($_data['saved_settings'][\Retailcrm\Retailcrm::MODULE . '_url'])
? $_data['saved_settings'][\Retailcrm\Retailcrm::MODULE . '_url']
: null;
$key = isset($_data['saved_settings'][$this->moduleTitle . '_apikey'])
? $_data['saved_settings'][$this->moduleTitle . '_apikey']
: null;
$apiVersion = isset($_data['saved_settings'][$this->moduleTitle . '_apiversion'])
? $_data['saved_settings'][$this->moduleTitle . '_apiversion']
$key = isset($_data['saved_settings'][\Retailcrm\Retailcrm::MODULE . '_apikey'])
? $_data['saved_settings'][\Retailcrm\Retailcrm::MODULE . '_apikey']
: null;
if (!empty($url) && !empty($key)) {
$_data['delivery'] = $this->model_extension_retailcrm_references
->getDeliveryTypes();
->getDeliveryTypes($opencart_api_client ,$retailcrm_api_client);
$_data['statuses'] = $this->model_extension_retailcrm_references
->getOrderStatuses();
->getOrderStatuses($retailcrm_api_client);
$_data['payments'] = $this->model_extension_retailcrm_references
->getPaymentTypes();
if ($apiVersion == 'v5') {
$_data['customFields'] = $this->model_extension_retailcrm_references
->getCustomFields();
}
if ($apiVersion != 'v3') {
$_data['priceTypes'] = $this->model_extension_retailcrm_references
->getPriceTypes();
}
->getPaymentTypes($retailcrm_api_client);
$_data['customFields'] = $this->model_extension_retailcrm_references
->getCustomFields($retailcrm_api_client);
}
$config_data = array(
$this->moduleTitle . '_status'
\Retailcrm\Retailcrm::MODULE . '_status'
);
foreach ($config_data as $conf) {
@ -318,7 +267,7 @@ class ControllerExtensionModuleRetailcrm extends Controller
'text' => $this->language->get('text_home'),
'href' => $this->url->link(
'common/dashboard',
$this->tokenTitle . '=' . $this->session->data[$this->tokenTitle], 'SSL'
'user_token' . '=' . $this->session->data['user_token'], 'SSL'
),
'separator' => false
);
@ -327,7 +276,7 @@ class ControllerExtensionModuleRetailcrm extends Controller
'text' => $this->language->get('text_module'),
'href' => $this->url->link(
'extension/extension',
$this->tokenTitle . '=' . $this->session->data[$this->tokenTitle], 'SSL'
'user_token' . '=' . $this->session->data['user_token'], 'SSL'
),
'separator' => ' :: '
);
@ -336,19 +285,19 @@ class ControllerExtensionModuleRetailcrm extends Controller
'text' => $this->language->get('retailcrm_title'),
'href' => $this->url->link(
'extension/module/retailcrm',
$this->tokenTitle . '=' . $this->session->data[$this->tokenTitle], 'SSL'
'user_token' . '=' . $this->session->data['user_token'], 'SSL'
),
'separator' => ' :: '
);
$_data['action'] = $this->url->link(
'extension/module/retailcrm',
$this->tokenTitle . '=' . $this->session->data[$this->tokenTitle], 'SSL'
'user_token' . '=' . $this->session->data['user_token'], 'SSL'
);
$_data['cancel'] = $this->url->link(
version_compare(VERSION, '3.0', '<') ? 'extension/extension' : 'marketplace/extension',
$this->tokenTitle . '=' . $this->session->data[$this->tokenTitle], 'SSL'
'marketplace/extension',
'user_token' . '=' . $this->session->data['user_token'], 'SSL'
);
$_data['modules'] = array();
@ -361,13 +310,12 @@ class ControllerExtensionModuleRetailcrm extends Controller
$this->load->model('design/layout');
$_data['layouts'] = $this->model_design_layout->getLayouts();
$_data['header'] = $this->load->controller('common/header');
$_data['column_left'] = $this->load->controller('common/column_left');
$_data['footer'] = $this->load->controller('common/footer');
$_data['countries'] = $this->model_localisation_country->getCountries();
$_data['catalog'] = $this->request->server['HTTPS'] ? HTTPS_CATALOG : HTTP_CATALOG;
$_data[$this->tokenTitle] = $this->request->get[$this->tokenTitle];
$_data['user_token'] = $this->request->get['user_token'];
if(file_exists(DIR_SYSTEM . '/cron/export_done')) {
$_data['export_file'] = false;
@ -382,11 +330,15 @@ class ControllerExtensionModuleRetailcrm extends Controller
);
$_data['collectorFields'] = $collectorFields;
$_data['api_versions'] = array('v3', 'v4', 'v5');
$_data['default_apiversion'] = 'v4';
$_data['api_versions'] = array('v5');
$_data['default_apiversion'] = 'v5';
$retailcrmLog = file_exists(DIR_SYSTEM . 'storage/logs/retailcrm.log') ? DIR_SYSTEM . 'storage/logs/retailcrm.log' : false;
$ocApiLog = file_exists(DIR_SYSTEM . 'storage/logs/opencartapi.log') ? DIR_SYSTEM . 'storage/logs/opencartapi.log' : false;
$retailcrmLog = file_exists(DIR_SYSTEM . 'storage/logs/retailcrm.log')
? DIR_SYSTEM . 'storage/logs/retailcrm.log'
: false;
$ocApiLog = file_exists(DIR_SYSTEM . 'storage/logs/opencartapi.log')
? DIR_SYSTEM . 'storage/logs/opencartapi.log'
: false;
if ($this->checkLogFile($retailcrmLog) !== false) {
$_data['logs']['retailcrm_log'] = $this->checkLogFile($retailcrmLog);
@ -400,8 +352,8 @@ class ControllerExtensionModuleRetailcrm extends Controller
$_data['logs']['oc_error'] = $this->language->get('text_error_log');
}
$_data['clear_retailcrm'] = $this->url->link('extension/module/retailcrm/clear_retailcrm', $this->tokenTitle . '=' . $this->session->data[$this->tokenTitle], true);
$_data['clear_opencart'] = $this->url->link('extension/module/retailcrm/clear_opencart', $this->tokenTitle . '=' . $this->session->data[$this->tokenTitle], true);
$_data['clear_retailcrm'] = $this->url->link('extension/module/retailcrm/clear_retailcrm', 'user_token' . '=' . $this->session->data['user_token'], true);
$_data['clear_opencart'] = $this->url->link('extension/module/retailcrm/clear_opencart', 'user_token' . '=' . $this->session->data['user_token'], true);
$_data['button_clear'] = $this->language->get('button_clear');
$this->response->setOutput(
@ -417,25 +369,12 @@ class ControllerExtensionModuleRetailcrm extends Controller
*/
public function history()
{
$this->load->model('setting/setting');
$settings = $this->model_setting_setting->getSetting($this->moduleTitle);
if ($settings[$this->moduleTitle . '_apiversion'] == 'v3') {
if (file_exists(DIR_APPLICATION . 'model/extension/retailcrm/custom/history/v3.php')) {
$this->load->model('extension/retailcrm/custom/history/v3');
$this->model_extension_retailcrm_custom_history_v3->request($this->retailcrm->getApiClient());
} else {
$this->load->model('extension/retailcrm/history/v3');
$this->model_extension_retailcrm_history_v3->request($this->retailcrm->getApiClient());
}
if (file_exists(DIR_APPLICATION . 'model/extension/retailcrm/custom/history/v4-5.php')) {
$this->load->model('extension/retailcrm/custom/history/v4-5');
$this->model_extension_retailcrm_custom_history_v4_5->request($this->retailcrm->getApiClient());
} else {
if (file_exists(DIR_APPLICATION . 'model/extension/retailcrm/custom/history/v4-5.php')) {
$this->load->model('extension/retailcrm/custom/history/v4-5');
$this->model_extension_retailcrm_custom_history_v4_5->request($this->retailcrm->getApiClient());
} else {
$this->load->model('extension/retailcrm/history/v4_5');
$this->model_extension_retailcrm_history_v4_5->request($this->retailcrm->getApiClient());
}
$this->load->model('extension/retailcrm/history/v4_5');
$this->model_extension_retailcrm_history_v4_5->request($this->retailcrm->getApiClient());
}
}
@ -464,7 +403,7 @@ class ControllerExtensionModuleRetailcrm extends Controller
* @return void
*/
public function customer_edit($route, $customer)
{
{
$this->load->model('localisation/country');
$this->load->model('localisation/zone');
$this->load->model('customer/customer');
@ -487,7 +426,7 @@ class ControllerExtensionModuleRetailcrm extends Controller
'postcode' => $address['postcode'],
'iso_code_2' => $country['iso_code_2'],
'zone' => $zone['name']
);
);
}
$this->load->model('extension/retailcrm/customer');
@ -514,8 +453,8 @@ class ControllerExtensionModuleRetailcrm extends Controller
if (!isset($data['fromApi'])) {
$this->load->model('setting/setting');
$status = $this->model_setting_setting->getSetting($this->moduleTitle);
$data['order_status'] = $status[$this->moduleTitle . '_status'][$data['order_status_id']];
$status = $this->model_setting_setting->getSetting(\Retailcrm\Retailcrm::MODULE);
$data['order_status'] = $status[\Retailcrm\Retailcrm::MODULE . '_status'][$data['order_status_id']];
$this->load->model('extension/retailcrm/order');
$this->model_extension_retailcrm_order->uploadOrder($data, $this->retailcrm->getApiClient());
@ -610,22 +549,20 @@ class ControllerExtensionModuleRetailcrm extends Controller
private function validate()
{
$versionsMap = array(
'v3' => '3.0',
'v4' => '4.0',
'v5' => '5.0'
);
if (!empty($this->request->post[$this->moduleTitle . '_url']) && !empty($this->request->post[$this->moduleTitle . '_apikey'])) {
if (!empty($this->request->post[\Retailcrm\Retailcrm::MODULE . '_url']) && !empty($this->request->post[\Retailcrm\Retailcrm::MODULE . '_apikey'])) {
$apiClient = $this->retailcrm->getApiClient(
$this->request->post[$this->moduleTitle . '_url'],
$this->request->post[$this->moduleTitle . '_apikey']
$this->request->post[\Retailcrm\Retailcrm::MODULE . '_url'],
$this->request->post[\Retailcrm\Retailcrm::MODULE . '_apikey']
);
}
$response = $apiClient->apiVersions();
$response = isset($apiClient) ? $apiClient->apiVersions() : false;
if ($response && $response->isSuccessful()) {
if (!in_array($versionsMap[$this->request->post[$this->moduleTitle . '_apiversion']], $response['versions'])) {
if (!in_array($versionsMap[$this->request->post[\Retailcrm\Retailcrm::MODULE . '_apiversion']], $response['versions'])) {
$this->_error['warning'] = $this->language->get('text_error_api');
}
} else {
@ -636,9 +573,9 @@ class ControllerExtensionModuleRetailcrm extends Controller
$this->_error['warning'] = $this->language->get('error_permission');
}
if (isset($this->request->post[$this->moduleTitle . '_collector']['custom']) &&
$this->request->post[$this->moduleTitle . '_collector']['custom_form'] == 1) {
$customField = $this->request->post[$this->moduleTitle . '_collector']['custom'];
if (isset($this->request->post[\Retailcrm\Retailcrm::MODULE . '_collector']['custom']) &&
$this->request->post[\Retailcrm\Retailcrm::MODULE . '_collector']['custom_form'] == 1) {
$customField = $this->request->post[\Retailcrm\Retailcrm::MODULE . '_collector']['custom'];
if (empty($customField['name']) && empty($customField['email']) && empty($customField['phone'])) {
$this->_error['fields'] = $this->language->get('text_error_collector_fields');
@ -654,7 +591,7 @@ class ControllerExtensionModuleRetailcrm extends Controller
/**
* Clear retailcrm log file
*
*
* @return void
*/
public function clear_retailcrm()
@ -667,12 +604,18 @@ class ControllerExtensionModuleRetailcrm extends Controller
fclose($handle);
}
$this->response->redirect($this->url->link('extension/module/retailcrm', $this->tokenTitle . '=' . $this->session->data[$this->tokenTitle], true));
$this->response->redirect(
$this->url->link(
'extension/module/retailcrm',
'user_token' . '=' . $this->session->data['user_token'],
true
)
);
}
/**
* Clear opencart API log file
*
*
* @return void
*/
public function clear_opencart()
@ -685,54 +628,18 @@ class ControllerExtensionModuleRetailcrm extends Controller
fclose($handle);
}
$this->response->redirect($this->url->link('extension/module/retailcrm', $this->tokenTitle . '=' . $this->session->data[$this->tokenTitle], true));
}
/**
* Method for load models
*
* @return void
*/
private function loadModels()
{
if (version_compare(VERSION, '3.0', '<')) {
$this->load->model('extension/event');
$this->load->model('extension/extension');
// $this->load->model('extension/module');
$this->modelEvent = 'extension_event';
$this->modelExtension = 'extension_extension';
// $this->modelModule = 'extension_module';
} else {
$this->load->model('setting/event');
$this->load->model('setting/extension');
// $this->load->model('setting/module');
$this->modelEvent = 'setting_event';
$this->modelExtension = 'setting_extension';
// $this->modelModule = 'setting_module';
}
}
/**
* Get collector module name
*
* @return string
*/
private function getCollectorTitle()
{
if (version_compare(VERSION, '3.0', '<')) {
$title = 'daemon_collector';
} else {
$title = 'analytics_daemon_collector';
}
return $title;
$this->response->redirect(
$this->url->link(
'extension/module/retailcrm',
'user_token' . '=' . $this->session->data['user_token'],
true
)
);
}
/**
* Check file size
*
*
* @return string
*/
private function checkLogFile($file)
@ -754,51 +661,49 @@ class ControllerExtensionModuleRetailcrm extends Controller
/**
* Add events to db
*
*
* @return void
*/
private function addEvents()
{
$this->loadModels();
$this->{'model_' . $this->modelEvent}
$this->model_setting_event
->addEvent(
$this->moduleTitle,
\Retailcrm\Retailcrm::MODULE,
'catalog/model/checkout/order/addOrder/after',
'extension/module/retailcrm/order_create'
);
$this->{'model_' . $this->modelEvent}
$this->model_setting_event
->addEvent(
$this->moduleTitle,
\Retailcrm\Retailcrm::MODULE,
'catalog/model/checkout/order/addOrderHistory/after',
'extension/module/retailcrm/order_edit'
);
$this->{'model_' . $this->modelEvent}
$this->model_setting_event
->addEvent(
$this->moduleTitle,
\Retailcrm\Retailcrm::MODULE,
'catalog/model/account/customer/addCustomer/after',
'extension/module/retailcrm/customer_create'
);
$this->{'model_' . $this->modelEvent}
$this->model_setting_event
->addEvent(
$this->moduleTitle,
\Retailcrm\Retailcrm::MODULE,
'catalog/model/account/customer/editCustomer/after',
'extension/module/retailcrm/customer_edit'
);
$this->{'model_' . $this->modelEvent}
$this->model_setting_event
->addEvent(
$this->moduleTitle,
\Retailcrm\Retailcrm::MODULE,
'catalog/model/account/address/editAddress/after',
'extension/module/retailcrm/customer_edit'
);
$this->{'model_' . $this->modelEvent}
$this->model_setting_event
->addEvent(
$this->moduleTitle,
\Retailcrm\Retailcrm::MODULE,
'admin/model/customer/customer/editCustomer/after',
'extension/module/retailcrm/customer_edit'
);
@ -806,13 +711,13 @@ class ControllerExtensionModuleRetailcrm extends Controller
/**
* Check events in db
*
*
* @return boolean
*/
private function checkEvents()
{
$events = $this->{'model_' . $this->modelEvent}->getEvent(
$this->moduleTitle,
$events = $this->model_setting_event->getEvent(
\Retailcrm\Retailcrm::MODULE,
'catalog/model/checkout/order/addOrder/after',
'extension/module/retailcrm/order_create'
);
@ -826,17 +731,60 @@ class ControllerExtensionModuleRetailcrm extends Controller
/**
* Delete events from db
*
*
* @return void
*/
private function deleteEvents()
{
$this->loadModels();
$this->model_setting_event->deleteEventByCode(\Retailcrm\Retailcrm::MODULE);
}
if (version_compare(VERSION, '3.0', '<')) {
$this->{'model_' . $this->modelEvent}->deleteEvent($this->moduleTitle);
} else {
$this->{'model_' . $this->modelEvent}->deleteEventByCode($this->moduleTitle);
/**
* Getting history for first setting save
*
* @param $apiClient
*
* @return void
*/
private function getHistory($apiClient)
{
$ordersHistoryBegin = $apiClient->ordersHistory();
if ($ordersHistoryBegin->isSuccessful() && !empty($ordersHistoryBegin['history'])) {
$ordersHistoryEnd = $apiClient->ordersHistory(array(),
$ordersHistoryBegin['pagination']['totalPageCount']
);
if ($ordersHistoryEnd->isSuccessful()) {
$ordersHistoryArr = $ordersHistoryEnd['history'];
$lastChangeOrders = end($ordersHistoryArr);
$sinceIdOrders = $lastChangeOrders['id'];
$generatedAt = $ordersHistoryEnd['generatedAt'];
}
}
$customersHistoryBegin = $apiClient->customersHistory();
if ($customersHistoryBegin->isSuccessful() && !empty($customersHistoryBegin['history'])) {
$customersHistoryEnd = $apiClient->customersHistory(
array(),
$customersHistoryBegin['pagination']['totalPageCount']
);
if ($customersHistoryEnd->isSuccessful()) {
$customersHistoryArr = $customersHistoryEnd['history'];
$lastChangeCustomers = end($customersHistoryArr);
$sinceIdCustomers = $lastChangeCustomers['id'];
}
}
$this->model_setting_setting->editSetting(
'retailcrm_history',
array(
'retailcrm_history_orders' => isset($sinceIdOrders) ? $sinceIdOrders : 1,
'retailcrm_history_customers' => isset($sinceIdCustomers) ? $sinceIdCustomers : 1,
'retailcrm_history_datetime' => isset($generatedAt) ? $generatedAt : date('Y-m-d H:i:s')
)
);
}
}

View File

@ -1,117 +0,0 @@
<?php
require_once 'v4_5.php';
class ModelExtensionRetailcrmHistoryV3 extends ModelExtensionRetailcrmHistoryV45
{
protected $createResult;
/**
* Getting changes from RetailCRM
*
* @param \RetailcrmProxy $retailcrmApiClient
*
* @return boolean
*/
public function request($retailcrmApiClient)
{
$moduleTitle = $this->retailcrm->getModuleTitle();
$this->load->model('setting/setting');
$this->load->model('setting/store');
$this->load->model('user/api');
$this->load->model('sale/order');
$this->load->model('customer/customer');
$this->load->model('extension/retailcrm/references');
$this->load->model('catalog/product');
$this->load->model('catalog/option');
$this->load->model('localisation/zone');
$this->load->language('extension/module/retailcrm');
$settings = $this->model_setting_setting->getSetting($moduleTitle);
$history = $this->model_setting_setting->getSetting('retailcrm_history');
$settings['domain'] = parse_url(HTTP_SERVER, PHP_URL_HOST);
$url = isset($settings[$moduleTitle . '_url']) ? $settings[$moduleTitle . '_url'] : null;
$key = isset($settings[$moduleTitle . '_apikey']) ? $settings[$moduleTitle . '_apikey'] : null;
if (empty($url) || empty($key)) {
$this->log->addNotice('You need to configure retailcrm module first.');
return false;
}
$lastRun = !empty($history['retailcrm_history_datetime'])
? new DateTime($history['retailcrm_history_datetime'])
: new DateTime(date('Y-m-d H:i:s', strtotime('-1 days', strtotime(date('Y-m-d H:i:s')))));
$packsOrders = $retailcrmApiClient->ordersHistory($lastRun);
if(!$packsOrders->isSuccessful() && count($packsOrders['orders']) <= 0) {
return false;
}
$generatedAt = $packsOrders['generatedAt'];
$this->totalTitle = $this->totalTitles();
$this->subtotalSettings = $this->model_setting_setting->getSetting($this->totalTitle . 'sub_total');
$this->totalSettings = $this->model_setting_setting->getSetting($this->totalTitle . 'total');
$this->shippingSettings = $this->model_setting_setting->getSetting($this->totalTitle . 'shipping');
$this->delivery = array_flip($settings[$moduleTitle . '_delivery']);
$this->payment = array_flip($settings[$moduleTitle . '_payment']);
$this->status = array_flip($settings[$moduleTitle . '_status']);
$this->payment_default = $settings[$moduleTitle . '_default_payment'];
$this->delivery_default = $settings[$moduleTitle . '_default_shipping'];
$this->ocPayment = $this->model_extension_retailcrm_references
->getOpercartPaymentTypes();
$this->ocDelivery = $this->model_extension_retailcrm_references
->getOpercartDeliveryTypes();
$this->zones = $this->model_localisation_zone->getZones();
$updatedOrders = array();
$newOrders = array();
$orders = $packsOrders['orders'];
foreach ($orders as $order) {
if (isset($order['deleted'])) {
continue;
}
if (isset($order['externalId'])) {
$updatedOrders[] = $order['id'];
} else {
$newOrders[] = $order['id'];
}
}
unset($orders);
if (!empty($newOrders)) {
$orders = $retailcrmApiClient->ordersList($filter = array('ids' => $newOrders));
if ($orders) {
$this->createResult = $this->createOrders($orders['orders']);
}
}
if (!empty($updatedOrders)) {
$orders = $retailcrmApiClient->ordersList($filter = array('ids' => $updatedOrders));
if ($orders) {
$this->updateOrders($orders['orders']);
}
}
$this->model_setting_setting->editSetting('retailcrm_history', array('retailcrm_history_datetime' => $generatedAt));
if (!empty($this->createResult['customers'])) {
$retailcrmApiClient->customersFixExternalIds($this->createResult['customers']);
}
if (!empty($this->createResult['orders'])) {
$retailcrmApiClient->ordersFixExternalIds($this->createResult['orders']);
}
return true;
}
}

View File

@ -4,44 +4,32 @@ class ModelExtensionRetailcrmPrices extends Model
{
protected $settings;
protected $moduleTitle;
private $options;
private $optionValues;
/**
* Constructor
*
* @param Registry $registry
* Upload prices to CRM
*
* @param array $products
* @param \RetailcrmProxy $retailcrm_api_client
* @return mixed bool | array
*/
public function __construct($registry)
public function uploadPrices($products, $retailcrm_api_client)
{
parent::__construct($registry);
$this->load->library('retailcrm/retailcrm');
$this->load->model('catalog/option');
$this->load->model('setting/setting');
$this->moduleTitle = $this->retailcrm->getModuleTitle();
$this->settings = $this->model_setting_setting->getSetting($this->moduleTitle);
}
$prices = $this->getPrices($products, $retailcrm_api_client);
/**
* Upload prices to CRM
*
* @param array $products
* @param \RetailcrmProxy $retailcrmApiClient
* @return mixed bool | array
*/
public function uploadPrices($products, $retailcrmApiClient)
{
$prices = $this->getPrices($products, $retailcrmApiClient);
if ($retailcrmApiClient === false || !$prices) {
if ($retailcrm_api_client === false || !$prices) {
return false;
}
$pricesUpload = array_chunk($prices, 250);
foreach ($pricesUpload as $priceUpload) {
$retailcrmApiClient->storePricesUpload($priceUpload);
$retailcrm_api_client->storePricesUpload($priceUpload);
}
return $pricesUpload;
@ -49,18 +37,20 @@ class ModelExtensionRetailcrmPrices extends Model
/**
* Get prices
*
*
* @param array $products
*
*
* @return mixed
*/
protected function getPrices($products, $retailcrmApiClient)
protected function getPrices($products, $retailcrm_api_client)
{
$prices = array();
$site = $this->getSite($retailcrmApiClient);
$settings = $this->model_setting_setting->getSetting(\retailcrm\Retailcrm::MODULE);
if (!isset($this->settings[$this->moduleTitle . '_special'])
|| $this->settings[$this->moduleTitle . '_apiversion'] == 'v3'
$prices = array();
$site = $this->getSite($retailcrm_api_client);
if (!isset($settings[$this->moduleTitle . '_special'])
|| $settings[$this->moduleTitle . '_apiversion'] == 'v3'
) {
return false;
}
@ -115,7 +105,7 @@ class ModelExtensionRetailcrmPrices extends Model
'site' => $site,
'prices' => array(
array(
'code' => $this->settings[$this->moduleTitle . '_special'],
'code' => $settings[$this->moduleTitle . '_special'],
'price' => $productPrice + $optionsValues['price']
)
)
@ -128,9 +118,9 @@ class ModelExtensionRetailcrmPrices extends Model
/**
* Get actual special
*
*
* @param array $specials
*
*
* @return float $productPrice
*/
private function getSpecialPrice($specials)
@ -157,10 +147,10 @@ class ModelExtensionRetailcrmPrices extends Model
/**
* Get data option
*
*
* @param int $optionId
* @param int $optionValueId
*
*
* @return array
*/
private function getOptionData($optionId, $optionValueId) {
@ -191,9 +181,9 @@ class ModelExtensionRetailcrmPrices extends Model
*
* @return mixed boolean | string
*/
private function getSite($retailcrmApiClient)
private function getSite($retailcrm_api_client)
{
$response = $retailcrmApiClient->sitesList();
$response = $retailcrm_api_client->sitesList();
if ($response && $response->isSuccessful()) {
$sites = $response->sites;

View File

@ -1,93 +1,72 @@
<?php
class ModelExtensionRetailcrmReferences extends Model
{
protected $settings;
protected $moduleTitle;
protected $retailcrmApiClient;
private $opencartApiClient;
public function __construct($registry)
{
parent::__construct($registry);
$this->load->model('setting/setting');
$this->load->library('retailcrm/retailcrm');
$this->moduleTitle = $this->retailcrm->getModuleTitle();
$this->settings = $this->model_setting_setting->getSetting($this->moduleTitle);
$this->retailcrmApiClient = $this->retailcrm->getApiClient();
}
class ModelExtensionRetailcrmReferences extends Model {
/**
* Get opencart delivery methods
*
*
* @return array
*/
public function getOpercartDeliveryTypes()
public function getOpercartDeliveryTypes($opencart_api_client)
{
$this->opencartApiClient = $this->retailcrm->getOcApiClient($this->registry);
return $this->opencartApiClient->getDeliveryTypes();
return $opencart_api_client->getDeliveryTypes();
}
/**
* Get all delivery types
*
*
* @return array
*/
public function getDeliveryTypes()
public function getDeliveryTypes($opencart_api_client, $retailcrm_api_client)
{
$this->load->model('setting/store');
return array(
'opencart' => $this->getOpercartDeliveryTypes(),
'retailcrm' => $this->getApiDeliveryTypes()
'opencart' => $this->getOpercartDeliveryTypes($opencart_api_client),
'retailcrm' => $this->getApiDeliveryTypes($retailcrm_api_client)
);
}
/**
* Get all statuses
*
*
* @return array
*/
public function getOrderStatuses()
public function getOrderStatuses($retailcrm_api_client)
{
return array(
'opencart' => $this->getOpercartOrderStatuses(),
'retailcrm' => $this->getApiOrderStatuses()
'retailcrm' => $this->getApiOrderStatuses($retailcrm_api_client)
);
}
/**
* Get all payment types
*
*
* @return array
*/
public function getPaymentTypes()
public function getPaymentTypes($retailcrm_api_client)
{
return array(
'opencart' => $this->getOpercartPaymentTypes(),
'retailcrm' => $this->getApiPaymentTypes()
'retailcrm' => $this->getApiPaymentTypes($retailcrm_api_client)
);
}
/**
* Get all custom fields
*
*
* @return array
*/
public function getCustomFields()
public function getCustomFields($retailcrm_api_client)
{
return array(
'opencart' => $this->getOpencartCustomFields(),
'retailcrm' => $this->getApiCustomFields()
'retailcrm' => $this->getApiCustomFields($retailcrm_api_client)
);
}
/**
* Get opencart order statuses
*
*
* @return array
*/
public function getOpercartOrderStatuses()
@ -100,7 +79,7 @@ class ModelExtensionRetailcrmReferences extends Model
/**
* Get opencart payment types
*
*
* @return array
*/
public function getOpercartPaymentTypes()
@ -113,7 +92,7 @@ class ModelExtensionRetailcrmReferences extends Model
$extension = basename($file, '.php');
$this->load->language('extension/payment/' . $extension);
if (version_compare(VERSION, '3.0', '<')) {
$configStatus = $extension . '_status';
} else {
@ -133,80 +112,80 @@ class ModelExtensionRetailcrmReferences extends Model
/**
* Get opencart custom fields
*
*
* @return array
*/
public function getOpencartCustomFields()
{
$this->load->model('customer/custom_field');
return $this->model_customer_custom_field->getCustomFields();
}
/**
* Get RetailCRM delivery types
*
*
* @return array
*/
public function getApiDeliveryTypes()
public function getApiDeliveryTypes($retailcrm_api_client)
{
$response = $this->retailcrmApiClient->deliveryTypesList();
$response = $retailcrm_api_client->deliveryTypesList();
return (!$response->isSuccessful()) ? array() : $response->deliveryTypes;
}
/**
* Get RetailCRM order statuses
*
*
* @return array
*/
public function getApiOrderStatuses()
public function getApiOrderStatuses($retailcrm_api_client)
{
$response = $this->retailcrmApiClient->statusesList();
$response = $retailcrm_api_client->statusesList();
return (!$response->isSuccessful()) ? array() : $response->statuses;
}
/**
* Get RetailCRM payment types
*
*
* @return array
*/
public function getApiPaymentTypes()
public function getApiPaymentTypes($retailcrm_api_client)
{
$response = $this->retailcrmApiClient->paymentTypesList();
$response = $retailcrm_api_client->paymentTypesList();
return (!$response->isSuccessful()) ? array() : $response->paymentTypes;
}
/**
* Get RetailCRM custom fields
*
*
* @return array
*/
public function getApiCustomFields()
public function getApiCustomFields($retailcrm_api_client)
{
$customers = $this->retailcrmApiClient->customFieldsList(array('entity' => 'customer'));
$orders = $this->retailcrmApiClient->customFieldsList(array('entity' => 'order'));
$customers = $retailcrm_api_client->customFieldsList(array('entity' => 'customer'));
$orders = $retailcrm_api_client->customFieldsList(array('entity' => 'order'));
$customFieldsCustomers = (!$customers->isSuccessful()) ? array() : $customers->customFields;
$customFieldsOrders = (!$orders->isSuccessful()) ? array() : $orders->customFields;
$custom_fields_customers = (!$customers->isSuccessful()) ? array() : $customers->customFields;
$custom_fields_orders = (!$orders->isSuccessful()) ? array() : $orders->customFields;
if (!$customFieldsCustomers && !$customFieldsOrders) {
if (!$custom_fields_customers && !$custom_fields_orders) {
return array();
}
return array('customers' => $customFieldsCustomers, 'orders' => $customFieldsOrders);
return array('customers' => $custom_fields_customers, 'orders' => $custom_fields_orders);
}
/**
* Get RetailCRM price types
*
*
* @return array
*/
public function getPriceTypes()
public function getPriceTypes($retailcrm_api_client)
{
$response = $this->retailcrmApiClient->priceTypesList();
$response = $retailcrm_api_client->priceTypesList();
return (!$response->isSuccessful()) ? array() : $response->priceTypes;
}

View File

@ -1,600 +0,0 @@
<?php echo $header; ?><?php echo $column_left;?>
<div id="content">
<div class="page-header">
<div class="container-fluid">
<div class="pull-right">
<?php if ($export_file) : ?>
<button type="button" id="export" data-toggle="tooltip" title="<?php echo $text_button_export; ?>" class="btn btn-success"><i class="fa fa-download"></i></button>
<?php endif; ?>
<button type="button" id="icml" data-toggle="tooltip" title="<?php echo $text_button_catalog; ?>" class="btn btn-success"><i class="fa fa-file-text-o"></i></button>
<button type="submit" form="form-retailcrm" data-toggle="tooltip" title="<?php echo $button_save; ?>" class="btn btn-primary"><i class="fa fa-save"></i></button>
<a href="<?php echo $cancel; ?>" data-toggle="tooltip" title="<?php echo $button_cancel; ?>" class="btn btn-default"><i class="fa fa-reply"></i></a>
</div>
<h1><?php echo $heading_title; ?></h1>
<ul class="breadcrumb">
<?php foreach ($breadcrumbs as $breadcrumb) { ?>
<li><a href="<?php echo $breadcrumb['href']; ?>"><?php echo $breadcrumb['text']; ?></a></li>
<?php } ?>
</ul>
</div>
</div>
<div class="container-fluid">
<?php if ($error_warning) : ?>
<div class="alert alert-danger">
<button type="button" class="close" data-dismiss="alert">&times;</button>
<i class="fa fa-exclamation-circle"></i> <?php echo $error_warning; ?>
</div>
<?php endif; ?>
<?php if (isset($saved_settings['retailcrm_url'])): ?>
<div class="alert alert-info"><i class="fa fa-exclamation-circle"></i>
<button type="button" class="close" data-dismiss="alert">&times;</button>
<?php echo $text_notice; ?>
<a href="<?php echo $saved_settings['retailcrm_url']; ?>/admin/settings#t-main"><?php echo $saved_settings['retailcrm_url']; ?>/admin/settings#t-main</a>
</div>
<?php endif; ?>
<div class="panel panel-default">
<div class="panel-body">
<form action="<?php echo $action; ?>" method="post" enctype="multipart/form-data" id="form-retailcrm" class="form-horizontal">
<ul class="nav nav-tabs">
<li class="active"><a href="#tab-general" data-toggle="tab"><?php echo $general_tab_text; ?></a></li>
<?php if (isset($saved_settings['retailcrm_apikey']) && $saved_settings['retailcrm_apikey'] != '' && isset($saved_settings['retailcrm_url']) && $saved_settings['retailcrm_url'] != ''): ?>
<li><a href="#tab-references" data-toggle="tab"><?php echo $references_tab_text; ?></a></li>
<li><a href="#tab-collector" data-toggle="tab"><?php echo $collector_tab_text; ?></a></li>
<?php if ($saved_settings['retailcrm_apiversion'] == 'v5') : ?>
<li><a href="#tab-custom_fields" data-toggle="tab"><?php echo $custom_fields_tab_text; ?></a></li>
<?php endif; ?>
<li><a href="#tab-logs" data-toggle="tab"><?php echo $logs_tab_text; ?></a></li>
<?php endif; ?>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="tab-general">
<input type="hidden" name="retailcrm_status" value="1">
<fieldset>
<legend><?php echo $retailcrm_base_settings; ?></legend>
<div class="form-group retailcrm_unit">
<label class="col-sm-2 control-label" for="retailcrm_url"><?php echo $retailcrm_apiversion; ?></label>
<div class="col-lg-1 col-md-2 col-sm-2">
<select name="retailcrm_apiversion" class="form-control">
<?php foreach($api_versions as $version) : ?>
<option value="<?php echo $version; ?>" <?php if (isset($saved_settings['retailcrm_apiversion']) && $saved_settings['retailcrm_apiversion'] == $version) echo "selected='selected'"; elseif (!isset($saved_settings['retailcrm_apiversion']) && $default_apiversion == $version) echo "selected='selected'"; ?>><?php echo $version; ?></option>
<?php endforeach ?>
</select>
</div>
</div>
<div class="form-group retailcrm_unit">
<label class="col-sm-2 control-label" for="retailcrm_url"><?php echo $retailcrm_url; ?></label>
<div class="col-lg-4 col-md-6 col-sm-10">
<input id="retailcrm_url" type="text" name="retailcrm_url" value="<?php if (isset($saved_settings['retailcrm_url'])): echo $saved_settings['retailcrm_url']; endif; ?>" class="form-control" />
</div>
</div>
<div class="form-group retailcrm_unit">
<label class="col-sm-2 control-label" for="retailcrm_apikey"><?php echo $retailcrm_apikey; ?></label>
<div class="col-lg-4 col-md-6 col-sm-10">
<input id="retailcrm_apikey" type="text" name="retailcrm_apikey" value="<?php if (isset($saved_settings['retailcrm_apikey'])): echo $saved_settings['retailcrm_apikey']; endif;?>" class="form-control" />
</div>
</div>
</fieldset>
<fieldset>
<legend><?php echo $retailcrm_countries_settings; ?></legend>
<div class="form-group retailcrm_unit">
<label class="col-sm-2 control-label">Страны</label>
<div class="col-lg-4 col-md-6 col-sm-10">
<div class="well well-sm" style="height: 150px; overflow: auto;">
<?php foreach($countries as $country) : ?>
<div class="checkbox">
<label>
<input type="checkbox" name="<?php echo 'retailcrm_country[]'; ?>" value="<?php echo $country['country_id']; ?>" <?php if(isset($saved_settings['retailcrm_country']) && in_array($country['country_id'], $saved_settings['retailcrm_country'])): echo 'checked'; endif;?>>
<?php echo $country['name']; ?>
</label>
</div>
<?php endforeach; ?>
</div>
</div>
</div>
</fieldset>
<?php if (isset($saved_settings['retailcrm_apikey']) && $saved_settings['retailcrm_apikey'] != '' && isset($saved_settings['retailcrm_url']) && $saved_settings['retailcrm_url'] != ''): ?>
<?php if (!empty($retailcrm_errors)) : ?>
<?php foreach($retailcrm_errors as $retailcrm_error): ?>
<div class="warning"><?php echo $retailcrm_error ?></div>
<?php endforeach; ?>
<?php else: ?>
<fieldset>
<legend><?php echo $retailcrm_upload_order; ?></legend>
<div class="form-group retailcrm_unit">
<label class="col-sm-2 control-label"><?php echo $text_button_export_order; ?> №</label>
<div class="col-sm-10">
<div class="row">
<div class="col-lg-3 col-md-6 col-sm-6">
<input type="text" name="order_id" class="form-control" />
</div>
<div class="col-lg-3 col-md-4 col-sm-6">
<button type="button" id="export_order" class="btn btn-success"><i class="fa fa-download"></i> <?php echo $text_button_export_order; ?></button>
</div>
</div>
</div>
</div>
</fieldset>
<?php if (isset($saved_settings['retailcrm_apiversion']) && $saved_settings['retailcrm_apiversion'] != 'v3') : ?>
<fieldset>
<legend><?php echo $special_price_settings; ?></legend>
<div class="form-group retailcrm_unit">
<label class="col-sm-2 control-label"><?php echo $special_price_settings; ?></label>
<div class="col-md-4 col-sm-10">
<select id="retailcrm_special" name="retailcrm_special" class="form-control">
<?php foreach ($priceTypes as $priceType) :?>
<?php if ($priceType['active'] == true) :?>
<option value="<?php echo $priceType['code']; ?>" <?php if(isset($saved_settings['retailcrm_special']) && $saved_settings['retailcrm_special'] == $priceType['code']):?>selected="selected"<?php endif;?>>
<?php echo $priceType['name']; ?>
</option>
<?php endif; ?>
<?php endforeach; ?>
</select>
</div>
</div>
</fieldset>
<?php endif; ?>
<fieldset>
<legend><?php echo $order_number; ?></legend>
<div class="form-group">
<label class="col-sm-2 control-label" for="retailcrm_order_number"><?php echo $text_order_number; ?></label>
<div class="col-sm-10">
<label class="radio-inline">
<input type="radio" name="retailcrm_order_number" value="1" <?php if (isset($saved_settings['retailcrm_order_number']) &&
$saved_settings['retailcrm_order_number'] == 1) :
echo 'checked'; endif; ?> />
<?php echo $text_yes; ?>
</label>
<label class="radio-inline">
<input type="radio" name="retailcrm_order_number" value="0" <?php if (!isset($saved_settings['retailcrm_order_number']) ||
$saved_settings['retailcrm_order_number'] == 0) :
echo 'checked'; endif; ?> />
<?php echo $text_no; ?>
</label>
</div>
</div>
</fieldset>
</div>
<div class="tab-pane" id="tab-references">
<fieldset>
<legend><?php echo $retailcrm_dict_settings; ?></legend>
<div class="form-group">
<label class="col-sm-2 control-label"><?php echo $retailcrm_dict_delivery; ?></label>
<div class="col-sm-10">
<div class="row">
<?php if ($delivery['opencart']) :?>
<?php foreach($delivery['opencart'] as $value): ?>
<div class="col-sm-12" style="margin-bottom:10px;">
<div class="pm" style="margin-bottom:5px;"><?php echo $value['title'].':'; ?></div>
<?php unset($value['title']); ?>
<?php foreach ($value as $key => $val): ?>
<div class="row retailcrm_unit">
<div class="col-lg-4 col-md-6 col-sm-6">
<select id="retailcrm_delivery_<?php echo $val['code']; ?>" name="retailcrm_delivery[<?php echo $val['code']; ?>]" class="form-control">
<?php foreach ($delivery['retailcrm'] as $k => $v): ?>
<option value="<?php echo $v['code'];?>" <?php if(isset($saved_settings['retailcrm_delivery'][$key]) && $v['code'] == $saved_settings['retailcrm_delivery'][$key]):?>selected="selected"<?php endif;?>>
<?php echo $v['name'];?>
</option>
<?php endforeach; ?>
</select>
</div>
<div class="col-lg-4 col-md-6 col-sm-6">
<label class="control-label" style="text-align:left!important;" for="retailcrm_pm_<?php echo $val['code']; ?>"><?php echo $val['title']; ?></label>
</div>
</div>
<?php endforeach; ?>
</div>
<?php endforeach; ?>
<?php else :?>
<div class="alert alert-info"><i class="fa fa-exclamation-circle"></i>
<button type="button" class="close" data-dismiss="alert">&times;</button>
<?php echo $text_error_delivery; ?>
</div>
<?php endif; ?>
</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label"><?php echo $retailcrm_dict_status; ?></label>
<div class="col-sm-10">
<?php foreach ($statuses['opencart'] as $status): ?>
<?php $uid = $status['order_status_id']?>
<div class="row retailcrm_unit">
<div class="col-lg-4 col-md-6 col-sm-6">
<select id="retailcrm_status_<?php echo $uid; ?>" name="retailcrm_status[<?php echo $uid; ?>]" class="form-control">
<?php foreach ($statuses['retailcrm'] as $k => $v): ?>
<option value="<?php echo $v['code'];?>" <?php if(isset($saved_settings['retailcrm_status'][$uid]) && $v['code'] == $saved_settings['retailcrm_status'][$uid]):?>selected="selected"<?php endif;?>>
<?php echo $v['name'];?>
</option>
<?php endforeach; ?>
</select>
</div>
<div class="col-lg-4 col-md-6 col-sm-6">
<label class="control-label" style="text-align:left!important;" for="retailcrm_status_<?php echo $status['order_status_id']; ?>"><?php echo $status['name']; ?></label>
</div>
</div>
<?php endforeach; ?>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label"><?php echo $retailcrm_dict_payment; ?></label>
<div class="col-sm-10">
<?php foreach ($payments['opencart'] as $key => $value): ?>
<div class="row retailcrm_unit">
<div class="col-lg-4 col-md-6 col-sm-6">
<select id="retailcrm_payment_<?php echo $key; ?>" name="retailcrm_payment[<?php echo $key; ?>]" class="form-control">
<?php foreach ($payments['retailcrm'] as $k => $v): ?>
<option value="<?php echo $v['code'];?>" <?php if(isset($saved_settings['retailcrm_payment'][$key]) && $v['code'] == $saved_settings['retailcrm_payment'][$key]):?>selected="selected"<?php endif;?>>
<?php echo $v['name'];?>
</option>
<?php endforeach; ?>
</select>
</div>
<div class="col-lg-4 col-md-6 col-sm-6">
<label class="control-label" for="retailcrm_payment_<?php echo $key; ?>"><?php echo $value; ?></label>
</div>
</div>
<?php endforeach; ?>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label"><?php echo $retailcrm_dict_default; ?></label>
<div class="col-sm-10">
<div class="row">
<div class="retailcrm_unit col-sm-12">
<div class="row">
<div class="col-lg-4 col-md-6 col-sm-6">
<select id="retailcrm_default_payment" name="retailcrm_default_payment" class="form-control">
<?php foreach ($payments['opencart'] as $k => $v): ?>
<option value="<?php echo $k;?>" <?php if(isset($saved_settings['retailcrm_default_payment']) && $k == $saved_settings['retailcrm_default_payment']):?>selected="selected"<?php endif;?>>
<?php echo $v;?>
</option>
<?php endforeach; ?>
</select>
</div>
<div class="col-lg-4 col-md-6 col-sm-6">
<label class="control-label" for="retailcrm_default_payment"><?php echo $text_payment; ?></label>
</div>
</div>
</div>
<div class="retailcrm_unit col-sm-12">
<div class="row">
<div class="col-lg-4 col-md-6 col-sm-6">
<select id="retailcrm_default_shipping" name="retailcrm_default_shipping" class="form-control">
<?php foreach ($delivery['opencart'] as $key => $value): ?>
<optgroup label="<?php echo $value['title']; ?>">
<?php unset($value['title']); ?>
<?php foreach ($value as $v): ?>
<option value="<?php echo $v['code'];?>" <?php if(isset($saved_settings['retailcrm_default_shipping']) && $v['code'] == $saved_settings['retailcrm_default_shipping']):?>selected="selected"<?php endif;?>>
<?php echo $v['title'];?>
</option>
<?php endforeach; ?>
</optgroup>
<?php endforeach; ?>
</select>
</div>
<div class="col-lg-4 col-md-6 col-sm-6">
<label class="control-label" for="retailcrm_default_payment"><?php echo $text_shipping; ?></label>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label"><?php echo $retailcrm_missing_status; ?></label>
<div class="col-sm-10">
<div class="row">
<div class="col-lg-4 col-md-6 col-sm-6">
<select id="retailcrm_missing_status" name="retailcrm_missing_status" class="form-control">
<option>-- Выберите --</option>
<?php foreach ($statuses['retailcrm'] as $k => $v): ?>
<option value="<?php echo $k;?>" <?php if(isset($saved_settings['retailcrm_missing_status']) && $k == $saved_settings['retailcrm_missing_status']):?>selected="selected"<?php endif;?>>
<?php echo $v['name'];?>
</option>
<?php endforeach; ?>
</select>
</div>
</div>
</div>
</div>
</fieldset>
<?php endif; ?>
<?php endif; ?>
</div>
<div class="tab-pane" id="tab-collector">
<fieldset>
<legend><?php echo $daemon_collector; ?></legend>
<div class="form-group">
<label class="col-sm-2 control-label" for="retailcrm_collector_active"><?php echo $text_collector_activity; ?></label>
<div class="col-sm-10">
<label class="radio-inline">
<input type="radio" name="retailcrm_collector_active" value="1" <?php if (isset($saved_settings['retailcrm_collector_active']) &&
$saved_settings['retailcrm_collector_active'] == 1) :
echo 'checked'; endif; ?> />
<?php echo $text_yes; ?>
</label>
<label class="radio-inline">
<input type="radio" name="retailcrm_collector_active" value="0" <?php if (!isset($saved_settings['retailcrm_collector_active']) ||
$saved_settings['retailcrm_collector_active'] == 0) :
echo 'checked'; endif; ?> />
<?php echo $text_no; ?>
</label>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label" for="retailcrm_collector" class="col-md-4"><?php echo $collector_site_key; ?></label>
<div class="col-sm-10">
<input id="retailcrm_collector_site_key" type="text" name="retailcrm_collector[site_key]" value="<?php if (isset($saved_settings['retailcrm_collector']['site_key'])): echo $saved_settings['retailcrm_collector']['site_key']; endif; ?>" class="form-control" />
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label" for="retailcrm_collector"><?php echo $text_collector_form_capture; ?></label>
<div class="col-sm-10">
<label class="radio-inline">
<input type="radio" name="retailcrm_collector[form_capture]" value="1" <?php if (isset($saved_settings['retailcrm_collector']['form_capture']) &&
$saved_settings['retailcrm_collector']['form_capture'] == 1) :
echo 'checked'; endif; ?>>
<?php echo $text_yes; ?>
</label>
<label class="radio-inline">
<input type="radio" name="retailcrm_collector[form_capture]" value="0" <?php if (!isset($saved_settings['retailcrm_collector']['form_capture']) ||
$saved_settings['retailcrm_collector']['form_capture'] == 0) :
echo 'checked'; endif; ?>>
<?php echo $text_no; ?>
</label>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label" for="retailcrm_collector_period" class="col-md-4"><?php echo $text_collector_period; ?></label>
<div class="col-sm-4">
<input id="retailcrm_collector_period" type="text" name="retailcrm_collector[period]" value="<?php if (isset($saved_settings['retailcrm_collector']['period'])): echo $saved_settings['retailcrm_collector']['period']; endif; ?>" class="form-control" />
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label" for="retailcrm_collector[]"><?php echo $text_label_promo; ?></label>
<div class="col-sm-10">
<input id="retailcrm_collector[]" type="text" name="retailcrm_collector[label_promo]" value="<?php if (isset($saved_settings['retailcrm_collector']['label_promo'])): echo $saved_settings['retailcrm_collector']['label_promo']; endif; ?>" class="form-control" />
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label" for="retailcrm_collector_label_send"><?php echo $text_label_send; ?></label>
<div class="col-sm-10">
<input id="retailcrm_collector_label_send" type="text" name="retailcrm_collector[label_send]" value="<?php if (isset($saved_settings['retailcrm_collector']['label_send'])): echo $saved_settings['retailcrm_collector']['label_send']; endif; ?>" class="form-control" />
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label" for="retailcrm_collector"><?php echo $collector_custom_text; ?></label>
<div class="col-sm-10">
<label class="radio-inline">
<input type="radio" name="retailcrm_collector[custom_form]" value="1" <?php if (isset($saved_settings['retailcrm_collector']['custom_form']) &&
$saved_settings['retailcrm_collector']['custom_form'] == 1) :
echo 'checked'; endif; ?>>
<?php echo $text_yes; ?>
</label>
<label class="radio-inline">
<input type="radio" name="retailcrm_collector[custom_form]" value="0" <?php if (!isset($saved_settings['retailcrm_collector']['custom_form']) ||
$saved_settings['retailcrm_collector']['custom_form'] == 0) :
echo 'checked'; endif; ?>>
<?php echo $text_no; ?>
</label>
</div>
</div>
<?php foreach ($collectorFields as $field => $label) : ?>
<div class="form-group">
<label class="col-sm-2 control-label" for="retailcrm_collector"><?php echo $label; ?></label>
<div class="col-sm-10">
<div class="row">
<div class="col-md-4 col-sm-6">
<input id="retailcrm_collector" type="text" name="retailcrm_collector[custom][<?php echo $field; ?>]" value="<?php if (isset($saved_settings['retailcrm_collector']['custom'][$field])) : echo $saved_settings['retailcrm_collector']['custom'][$field]; endif; ?>" class="form-control" />
</div>
<div class="col-md-8 col-sm-6" style="margin-top: 8px;">
<input style="margin-top: 0; vertical-align: middle;" type="checkbox" name="retailcrm_collector[require][<?php echo $field; ?>_require]" value="1" <?php if (isset($saved_settings['retailcrm_collector']['require'][$field.'_require'])) : echo 'checked'; endif;?> />
<label style="margin-bottom: 0; vertical-align: middle; margin-left: 5px;" for="retailcrm_collector"><?php echo $text_require; ?></label>
</div>
</div>
</div>
</div>
<?php endforeach; ?>
</fieldset>
</div>
<?php if (isset($saved_settings['retailcrm_apiversion']) && $saved_settings['retailcrm_apiversion'] == 'v5' && isset($customFields)) : ?>
<div class="tab-pane" id="tab-custom_fields">
<fieldset>
<legend><?php echo $retailcrm_dict_custom_fields; ?></legend>
<?php if ($customFields['retailcrm'] && $customFields['opencart']) : ?>
<div class="form-group">
<label class="col-sm-2 control-label" for="retailcrm_custom_field_active"><?php echo $text_custom_field_activity; ?></label>
<div class="col-sm-10">
<label class="radio-inline">
<input type="radio" name="retailcrm_custom_field_active" value="1" <?php if (isset($saved_settings['retailcrm_custom_field_active']) &&
$saved_settings['retailcrm_custom_field_active'] == 1) :
echo 'checked'; endif; ?> />
<?php echo $text_yes; ?>
</label>
<label class="radio-inline">
<input type="radio" name="retailcrm_custom_field_active" value="0" <?php if (!isset($saved_settings['retailcrm_custom_field_active']) ||
$saved_settings['retailcrm_custom_field_active'] == 0) :
echo 'checked'; endif; ?> />
<?php echo $text_no; ?>
</label>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label"><?php echo $text_customers_custom_fields; ?></label>
<div class="col-sm-10">
<div class="row">
<?php foreach ($customFields['opencart'] as $customField) : ?>
<div class="col-sm-12" style="margin-bottom:5px;">
<div class="row">
<?php $fid = 'c_' . $customField['custom_field_id'] ?>
<div class="col-sm-4">
<select id="retailcrm_custom_field_<?php echo $fid; ?>" name="retailcrm_custom_field[<?php echo $fid; ?>]" class="form-control">
<?php foreach ($customFields['retailcrm']['customers'] as $v): ?>
<option value="<?php echo $v['code'];?>" <?php if(isset($saved_settings['retailcrm_custom_field'][$fid]) && $v['code'] == $saved_settings['retailcrm_custom_field'][$fid]):?>selected="selected"<?php endif;?>>
<?php echo $v['name'];?>
</option>
<?php endforeach; ?>
</select>
</div>
<label style="padding-top: 9px;" for="retailcrm_custom_field_<?php echo $fid; ?>"><?php echo $customField['name']; ?></label>
</div>
</div>
<?php endforeach; ?>
</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label"><?php echo $text_orders_custom_fields; ?></label>
<div class="col-sm-10">
<div class="row">
<?php foreach ($customFields['opencart'] as $customField) : ?>
<div class="col-sm-12" style="margin-bottom:5px;">
<div class="row">
<?php $fid = 'o_' . $customField['custom_field_id'] ?>
<div class="col-sm-4">
<select id="retailcrm_custom_field_<?php echo $fid; ?>" name="retailcrm_custom_field[<?php echo $fid; ?>]" class="form-control">
<?php foreach ($customFields['retailcrm']['orders'] as $v): ?>
<option value="<?php echo $v['code'];?>" <?php if(isset($saved_settings['retailcrm_custom_field'][$fid]) && $v['code'] == $saved_settings['retailcrm_custom_field'][$fid]):?>selected="selected"<?php endif;?>>
<?php echo $v['name'];?>
</option>
<?php endforeach; ?>
</select>
</div>
<label style="padding-top: 9px;" for="retailcrm_custom_field_<?php echo $fid; ?>"><?php echo $customField['name']; ?></label>
</div>
</div>
<?php endforeach; ?>
</div>
</div>
</div>
<?php elseif (!$customFields['retailcrm'] && !$customFields['opencart']) : ?>
<div class="alert alert-info"><i class="fa fa-exclamation-circle"></i>
<button type="button" class="close" data-dismiss="alert">&times;</button>
<?php echo $text_error_custom_field; ?>
</div>
<?php elseif (!$customFields['retailcrm']) : ?>
<div class="alert alert-info"><i class="fa fa-exclamation-circle"></i>
<button type="button" class="close" data-dismiss="alert">&times;</button>
<?php echo $text_error_cf_retailcrm; ?>
</div>
<?php elseif (!$customFields['opencart']) : ?>
<div class="alert alert-info"><i class="fa fa-exclamation-circle"></i>
<button type="button" class="close" data-dismiss="alert">&times;</button>
<?php echo $text_error_cf_opencart; ?>
</div>
<?php endif; ?>
</fieldset>
</div>
<?php endif; ?>
<div class="tab-pane" id="tab-logs">
<fieldset style="margin-bottom: 30px;">
<legend>Retailcrm API error log</legend>
<div class="retailcrm_unit">
<a onclick="confirm('<?php echo $text_confirm_log; ?>') ? location.href='<?php echo $clear_retailcrm; ?>' : false;" data-toggle="tooltip" title="<?php echo $button_clear; ?>" class="btn btn-danger"><i class="fa fa-eraser"></i> <span class="hidden-xs"><?php echo $button_clear; ?></span></a>
</div>
<?php if (isset($logs['retailcrm_log'])) : ?>
<div class="row">
<div class="col-sm-12">
<textarea wrap="off" rows="15" readonly class="form-control"><?php echo $logs['retailcrm_log']; ?></textarea>
</div>
</div>
<?php elseif (isset($logs['retailcrm_error'])) : ?>
<div class="alert alert-danger alert-dismissible"><i class="fa fa-exclamation-circle"></i> <?php echo $logs['retailcrm_error']; ?>
<button type="button" class="close" data-dismiss="alert">&times;</button>
</div>
<?php endif; ?>
</fieldset>
<fieldset>
<legend>Opencart API error log</legend>
<div class="retailcrm_unit">
<a onclick="confirm('<?php echo $text_confirm_log; ?>') ? location.href='<?php echo $clear_opencart; ?>' : false;" data-toggle="tooltip" title="<?php echo $button_clear; ?>" class="btn btn-danger"><i class="fa fa-eraser"></i> <span class="hidden-xs"><?php echo $button_clear; ?></span></a>
</div>
<?php if (isset($logs['oc_api_log'])) : ?>
<div class="row">
<div class="col-sm-12">
<textarea wrap="off" rows="15" readonly class="form-control"><?php echo $logs['oc_api_log']; ?></textarea>
</div>
</div>
<?php elseif (isset($logs['oc_error'])) : ?>
<div class="alert alert-danger alert-dismissible"><i class="fa fa-exclamation-circle"></i> <?php echo $logs['oc_error']; ?>
<button type="button" class="close" data-dismiss="alert">&times;</button>
</div>
<?php endif; ?>
</fieldset>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<?php echo $footer; ?>
<script type="text/javascript">
var token = '<?php echo $token; ?>';
$('#icml').on('click', function() {
$.ajax({
url: '<?php echo $catalog; ?>' + 'admin/index.php?route=extension/module/retailcrm/icml&token=' + token,
beforeSend: function() {
$('#icml').button('loading');
},
complete: function() {
$('.alert-success').remove();
$('#content > .container-fluid').prepend('<div class="alert alert-success"><i class="fa fa-exclamation-circle"></i> <?php echo $text_success_catalog; ?></div>');
$('#icml').button('reset');
},
error: function(){
alert('error');
}
});
});
$('#export').on('click', function() {
$.ajax({
url: '<?php echo $catalog; ?>' + 'admin/index.php?route=extension/module/retailcrm/export&token=' + token,
beforeSend: function() {
$('#export').button('loading');
},
complete: function() {
$('.alert-success').remove();
$('#content > .container-fluid').prepend('<div class="alert alert-success"><i class="fa fa-exclamation-circle"></i> <?php echo $text_success_export; ?></div>');
$('#export').button('reset');
},
error: function(){
alert('error');
}
});
});
$('#export_order').on('click', function() {
var order_id = $('input[name=\'order_id\']').val();
if (order_id && order_id > 0) {
$.ajax({
url: '<?php echo $catalog; ?>' + 'admin/index.php?route=extension/module/retailcrm/exportOrder&token=' + token + '&order_id=' + order_id,
beforeSend: function() {
$('#export_order').button('loading');
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
},
success: function(data, textStatus, jqXHR) {
response = JSON.parse(jqXHR['responseText']);
if (response['status_code'] == '400') {
$('.alert-danger').remove();
$('#content > .container-fluid').prepend('<div class="alert alert-danger"><i class="fa fa-exclamation-circle"></i><?php echo $text_error_order; ?>' + response['error_msg'] + '</div>');
$('#export_order').button('reset');
} else {
$('.alert-success').remove();
$('#content > .container-fluid').prepend('<div class="alert alert-success"><i class="fa fa-exclamation-circle"></i><?php echo $text_success_export_order; ?></div>');
$('#export_order').button('reset');
$('input[name=\'order_id\']').val('');
}
}
});
} else {
$('.alert-danger').remove();
$('#content > .container-fluid').prepend('<div class="alert alert-danger"><i class="fa fa-exclamation-circle"></i> <?php echo $text_error_order_id; ?></div>');
$('#export_order').button('reset');
}
});
</script>

View File

@ -11,73 +11,44 @@
*/
class ControllerExtensionModuleRetailcrm extends Controller {
private $retailcrmApiClient;
public function __construct($registry)
{
parent::__construct($registry);
$this->load->library('retailcrm/retailcrm');
$this->retailcrmApiClient = $this->retailcrm->getApiClient();
}
/**
* Create order on event
*
* @param string $trigger
* @param array $data
* @param int $order_id order identificator
* @param string $route
* @param array $args
* @param int $output
*
* @return void
* @return boolean
*/
public function order_create($trigger, $data, $order_id = null) {
$this->load->model('checkout/order');
$this->load->model('account/order');
public function orderCreate($route, $args, $output) {
if ($route != 'checkout/order/addOrder') {
return false;
}
$this->load->library('retailcrm/retailcrm');
$data = $this->model_checkout_order->getOrder($order_id);;
$data['products'] = $this->model_account_order->getOrderProducts($order_id);
$data['totals'] = $this->model_account_order->getOrderTotals($order_id);
$moduleTitle = $this->retailcrm->getModuleTitle();
$retailcrm_order = $this->retailcrm->getObject('Order');
$retailcrm_order->prepare($args[0]);
$retailcrm_order->setField('externalId', $output);
$retailcrm_order->create($this->retailcrm->getApiClient());
foreach ($data['products'] as $key => $product) {
$productOptions = $this->model_account_order->getOrderOptions($order_id, $product['order_product_id']);
if (!empty($productOptions)) {
$data['products'][$key]['option'] = $productOptions;
}
}
if (!isset($data['fromApi'])) {
$this->load->model('setting/setting');
$status = $this->model_setting_setting->getSetting($moduleTitle);
if (isset($data['order_status_id']) && $data['order_status_id'] > 0) {
$data['order_status'] = $status[$moduleTitle . '_status'][$data['order_status_id']];
}
if (file_exists(DIR_APPLICATION . 'model/extension/retailcrm/custom/order.php')) {
$this->load->model('extension/retailcrm/custom/order');
$order = $this->model_extension_retailcrm_custom_order->processOrder($data);
$this->model_extension_retailcrm_custom_order->sendToCrm($order, $this->retailcrmApiClient);
} else {
$this->load->model('extension/retailcrm/order');
$order = $this->model_extension_retailcrm_order->processOrder($data);
$this->model_extension_retailcrm_order->sendToCrm($order, $this->retailcrmApiClient);
}
}
return true;
}
/**
* Update order on event
*
* @param string $trigger
* @param array $parameter2
* @param string $route
* @param array $args
*
* @return void
* @return boolean
*/
public function order_edit($trigger, $parameter2 = null) {
$order_id = $parameter2[0];
public function orderEdit($route, $args) {
if ($route != 'checkout/order/editOrder') {
return false;
}
$order_id = $args[0];
$this->load->model('checkout/order');
$this->load->model('account/order');
@ -124,63 +95,46 @@ class ControllerExtensionModuleRetailcrm extends Controller {
/**
* Create customer on event
*
* @param int $customerId customer identificator
* @param string $route
* @param array $args
* @param int $output
*
* @return void
* @return boolean
*/
public function customer_create($parameter1, $parameter2 = null, $parameter3 = null) {
$this->load->model('account/customer');
$this->load->model('localisation/country');
$this->load->model('localisation/zone');
$customerId = $parameter3;
$customer = $this->model_account_customer->getCustomer($customerId);
if ($this->request->post) {
$country = $this->model_localisation_country->getCountry($this->request->post['country_id']);
$zone = $this->model_localisation_zone->getZone($this->request->post['zone_id']);
$customer['address'] = array(
'address_1' => $this->request->post['address_1'],
'address_2' => $this->request->post['address_2'],
'city' => $this->request->post['city'],
'postcode' => $this->request->post['postcode'],
'iso_code_2' => $country['iso_code_2'],
'zone' => $zone['name']
);
public function customerCreate($route, $args, $output) {
if ($route != 'account/customer/addCustomer') {
return false;
}
if (file_exists(DIR_APPLICATION . 'model/extension/retailcrm/custom/customer.php')) {
$this->load->model('extension/retailcrm/custom/customer');
$this->model_extension_retailcrm_custom_customer->sendToCrm($customer, $this->retailcrmApiClient);
} else {
$this->load->model('extension/retailcrm/customer');
$this->model_extension_retailcrm_customer->sendToCrm($customer, $this->retailcrmApiClient);
}
$this->load->library('retailcrm/retailcrm');
$retailcrm_customer = $this->retailcrm->createObject('Customer');
$retailcrm_customer->prepare($args[0]);
$retailcrm_customer->setField('externalId', $output);
$retailcrm_customer->create();
return true;
}
/**
* Update customer on event
*
* @param int $customerId customer identificator
*
* @return void
* @param string $route
* @param array $args
* @return boolean
*/
public function customer_edit($parameter1, $parameter2, $parameter3) {
$customerId = $this->customer->getId();
$this->load->model('account/customer');
$customer = $this->model_account_customer->getCustomer($customerId);
$this->load->model('account/address');
$customer['address'] = $this->model_account_address->getAddress($customer['address_id']);
if (file_exists(DIR_APPLICATION . 'model/extension/retailcrm/custom/customer.php')) {
$this->load->model('extension/retailcrm/custom/customer');
$this->model_extension_retailcrm_custom_customer->changeInCrm($customer, $this->retailcrmApiClient);
} else {
$this->load->model('extension/retailcrm/customer');
$this->model_extension_retailcrm_customer->changeInCrm($customer, $this->retailcrmApiClient);
public function customerEdit($route, $args) {
if ($route != 'account/customer/editCustomer') {
return false;
}
$customer_id = $args[0];
$data = $args[1];
$this->load->library('retailcrm/customer');
$this->retailcrm->process($data);
$this->retailcrm->setField('externalId', $customer_id);
$this->retailcrm->edit();
return true;
}
}

View File

@ -47,22 +47,19 @@ class OpencartApiClient {
}
private function request($method, $getParams, $postParams) {
$this->load->model('setting/store');
$opencartStoreInfo = $this->model_setting_store->getStore($this->opencartStoreId);
if ($this->apiToken !== false) {
if (version_compare(VERSION, '3.0', '<')) {
$getParams['key'] = $this->apiToken['key'];
} else {
$getParams['key'] = $this->apiToken['key'];
$getParams['username'] = $this->apiToken['username'];
$getParams['key'] = $this->apiToken['key'];
$getParams['username'] = $this->apiToken['username'];
if (isset($this->session->data['user_token'])) {
$getParams['api_token'] = $this->session->data['user_token'];
} else {
$session = $this->registry->get('session');
$session->start();
$getParams['api_token'] = $session->getId();
}
if (isset($this->session->data['user_token'])) {
$getParams['api_token'] = $this->session->data['user_token'];
} else {
$session = $this->registry->get('session');
$session->start();
$getParams['api_token'] = $session->getId();
}
}
@ -143,7 +140,7 @@ class OpencartApiClient {
/**
* Get delivery types
*
*
* @return array
*/
public function getDeliveryTypes()
@ -153,10 +150,10 @@ class OpencartApiClient {
/**
* Add history order
*
*
* @param int $order_id
* @param int $order_status_id
*
*
* @return void
*/
public function addHistory($order_id, $order_status_id)
@ -166,7 +163,7 @@ class OpencartApiClient {
/**
* Get module name
*
*
* @return string
*/
private function getModuleTitle()

View File

@ -1,831 +0,0 @@
<?php
/**
* PHP version 5.3
*
* API client class
*
* @category RetailCrm
* @package RetailCrm
* @author RetailCrm <integration@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
* @link http://www.retailcrm.ru/docs/Developers/ApiVersion3
*/
class RetailcrmApiClient3
{
protected $client;
/**
* Site code
*/
protected $siteCode;
/**
* Client creating
*
* @param string $url
* @param string $apiKey
* @param string $site
* @return mixed
*/
public function __construct($url, $apiKey, $version = null, $site = null)
{
if ('/' != substr($url, strlen($url) - 1, 1)) {
$url .= '/';
}
$url = $version == null ? $url . 'api' : $url . 'api/' . $version;
$this->client = new RetailcrmHttpClient($url, array('apiKey' => $apiKey));
$this->siteCode = $site;
}
/**
* Returns api versions list
*
* @throws \RetailCrm\Exception\InvalidJsonException
* @throws \RetailCrm\Exception\CurlException
* @throws \InvalidArgumentException
*
* @return ApiResponse
*/
public function apiVersions()
{
return $this->client->makeRequest('/api-versions', RetailcrmHttpClient::METHOD_GET);
}
/**
* Create a order
*
* @param array $order
* @param string $site (default: null)
* @return ApiResponse
*/
public function ordersCreate(array $order, $site = null)
{
if (!sizeof($order)) {
throw new InvalidArgumentException('Parameter `order` must contains a data');
}
return $this->client->makeRequest("/orders/create", RetailcrmHttpClient::METHOD_POST, $this->fillSite($site, array(
'order' => json_encode($order)
)));
}
/**
* Edit a order
*
* @param array $order
* @param string $by
* @param string $site (default: null)
* @return ApiResponse
*/
public function ordersEdit(array $order, $by = 'externalId', $site = null)
{
if (!sizeof($order)) {
throw new InvalidArgumentException('Parameter `order` must contains a data');
}
$this->checkIdParameter($by);
if (!isset($order[$by])) {
throw new InvalidArgumentException(sprintf('Order array must contain the "%s" parameter.', $by));
}
return $this->client->makeRequest(
"/orders/" . $order[$by] . "/edit",
RetailcrmHttpClient::METHOD_POST,
$this->fillSite($site, array(
'order' => json_encode($order),
'by' => $by,
))
);
}
/**
* Upload array of the orders
*
* @param array $orders
* @param string $site (default: null)
* @return ApiResponse
*/
public function ordersUpload(array $orders, $site = null)
{
if (!sizeof($orders)) {
throw new InvalidArgumentException('Parameter `orders` must contains array of the orders');
}
return $this->client->makeRequest("/orders/upload", RetailcrmHttpClient::METHOD_POST, $this->fillSite($site, array(
'orders' => json_encode($orders),
)));
}
/**
* Get order by id or externalId
*
* @param string $id
* @param string $by (default: 'externalId')
* @param string $site (default: null)
* @return ApiResponse
*/
public function ordersGet($id, $by = 'externalId', $site = null)
{
$this->checkIdParameter($by);
return $this->client->makeRequest("/orders/$id", RetailcrmHttpClient::METHOD_GET, $this->fillSite($site, array(
'by' => $by
)));
}
/**
* Returns a orders history
*
* @param DateTime $startDate (default: null)
* @param DateTime $endDate (default: null)
* @param int $limit (default: 100)
* @param int $offset (default: 0)
* @param bool $skipMyChanges (default: true)
* @return ApiResponse
*/
public function ordersHistory(
DateTime $startDate = null,
DateTime $endDate = null,
$limit = 100,
$offset = 0,
$skipMyChanges = true
) {
$parameters = array();
if ($startDate) {
$parameters['startDate'] = $startDate->format('Y-m-d H:i:s');
}
if ($endDate) {
$parameters['endDate'] = $endDate->format('Y-m-d H:i:s');
}
if ($limit) {
$parameters['limit'] = (int) $limit;
}
if ($offset) {
$parameters['offset'] = (int) $offset;
}
if ($skipMyChanges) {
$parameters['skipMyChanges'] = (bool) $skipMyChanges;
}
return $this->client->makeRequest('/orders/history', RetailcrmHttpClient::METHOD_GET, $parameters);
}
/**
* Returns filtered orders list
*
* @param array $filter (default: array())
* @param int $page (default: null)
* @param int $limit (default: null)
* @return ApiResponse
*/
public function ordersList(array $filter = array(), $page = null, $limit = null)
{
$parameters = array();
if (sizeof($filter)) {
$parameters['filter'] = $filter;
}
if (null !== $page) {
$parameters['page'] = (int) $page;
}
if (null !== $limit) {
$parameters['limit'] = (int) $limit;
}
return $this->client->makeRequest('/orders', RetailcrmHttpClient::METHOD_GET, $parameters);
}
/**
* Returns statuses of the orders
*
* @param array $ids (default: array())
* @param array $externalIds (default: array())
* @return ApiResponse
*/
public function ordersStatuses(array $ids = array(), array $externalIds = array())
{
$parameters = array();
if (sizeof($ids)) {
$parameters['ids'] = $ids;
}
if (sizeof($externalIds)) {
$parameters['externalIds'] = $externalIds;
}
return $this->client->makeRequest('/orders/statuses', RetailcrmHttpClient::METHOD_GET, $parameters);
}
/**
* Save order IDs' (id and externalId) association in the CRM
*
* @param array $ids
* @return ApiResponse
*/
public function ordersFixExternalIds(array $ids)
{
if (!sizeof($ids)) {
throw new InvalidArgumentException('Method parameter must contains at least one IDs pair');
}
return $this->client->makeRequest("/orders/fix-external-ids", RetailcrmHttpClient::METHOD_POST, array(
'orders' => json_encode($ids),
));
}
/**
* Get orders assembly history
*
* @param array $filter (default: array())
* @param int $page (default: null)
* @param int $limit (default: null)
* @return ApiResponse
*/
public function ordersPacksHistory(array $filter = array(), $page = null, $limit = null)
{
$parameters = array();
if (sizeof($filter)) {
$parameters['filter'] = $filter;
}
if (null !== $page) {
$parameters['page'] = (int) $page;
}
if (null !== $limit) {
$parameters['limit'] = (int) $limit;
}
return $this->client->makeRequest('/orders/packs/history', RetailcrmHttpClient::METHOD_GET, $parameters);
}
/**
* Create a customer
*
* @param array $customer
* @param string $site (default: null)
* @return ApiResponse
*/
public function customersCreate(array $customer, $site = null)
{
if (!sizeof($customer)) {
throw new InvalidArgumentException('Parameter `customer` must contains a data');
}
return $this->client->makeRequest("/customers/create", RetailcrmHttpClient::METHOD_POST, $this->fillSite($site, array(
'customer' => json_encode($customer)
)));
}
/**
* Edit a customer
*
* @param array $customer
* @param string $by (default: 'externalId')
* @param string $site (default: null)
* @return ApiResponse
*/
public function customersEdit(array $customer, $by = 'externalId', $site = null)
{
if (!sizeof($customer)) {
throw new InvalidArgumentException('Parameter `customer` must contains a data');
}
$this->checkIdParameter($by);
if (!isset($customer[$by])) {
throw new InvalidArgumentException(sprintf('Customer array must contain the "%s" parameter.', $by));
}
return $this->client->makeRequest(
"/customers/" . $customer[$by] . "/edit",
RetailcrmHttpClient::METHOD_POST,
$this->fillSite(
$site,
array(
'customer' => json_encode($customer),
'by' => $by
)
)
);
}
/**
* Upload array of the customers
*
* @param array $customers
* @param string $site (default: null)
* @return ApiResponse
*/
public function customersUpload(array $customers, $site = null)
{
if (!sizeof($customers)) {
throw new InvalidArgumentException('Parameter `customers` must contains array of the customers');
}
return $this->client->makeRequest("/customers/upload", RetailcrmHttpClient::METHOD_POST, $this->fillSite($site, array(
'customers' => json_encode($customers),
)));
}
/**
* Get customer by id or externalId
*
* @param string $id
* @param string $by (default: 'externalId')
* @param string $site (default: null)
* @return ApiResponse
*/
public function customersGet($id, $by = 'externalId', $site = null)
{
$this->checkIdParameter($by);
return $this->client->makeRequest("/customers/$id", RetailcrmHttpClient::METHOD_GET, $this->fillSite($site, array(
'by' => $by
)));
}
/**
* Returns filtered customers list
*
* @param array $filter (default: array())
* @param int $page (default: null)
* @param int $limit (default: null)
* @return ApiResponse
*/
public function customersList(array $filter = array(), $page = null, $limit = null)
{
$parameters = array();
if (sizeof($filter)) {
$parameters['filter'] = $filter;
}
if (null !== $page) {
$parameters['page'] = (int) $page;
}
if (null !== $limit) {
$parameters['limit'] = (int) $limit;
}
return $this->client->makeRequest('/customers', RetailcrmHttpClient::METHOD_GET, $parameters);
}
/**
* Save customer IDs' (id and externalId) association in the CRM
*
* @param array $ids
* @return ApiResponse
*/
public function customersFixExternalIds(array $ids)
{
if (!sizeof($ids)) {
throw new InvalidArgumentException('Method parameter must contains at least one IDs pair');
}
return $this->client->makeRequest("/customers/fix-external-ids", RetailcrmHttpClient::METHOD_POST, array(
'customers' => json_encode($ids),
));
}
/**
* Get purchace prices & stock balance
*
* @param array $filter (default: array())
* @param int $page (default: null)
* @param int $limit (default: null)
* @param string $site (default: null)
* @return ApiResponse
*/
public function storeInventories(array $filter = array(), $page = null, $limit = null, $site = null)
{
$parameters = array();
if (sizeof($filter)) {
$parameters['filter'] = $filter;
}
if (null !== $page) {
$parameters['page'] = (int) $page;
}
if (null !== $limit) {
$parameters['limit'] = (int) $limit;
}
return $this->client->makeRequest('/store/inventories', RetailcrmHttpClient::METHOD_GET, $this->fillSite($site, $parameters));
}
/**
* Upload store inventories
*
* @param array $offers
* @param string $site (default: null)
* @return ApiResponse
*/
public function storeInventoriesUpload(array $offers, $site = null)
{
if (!sizeof($offers)) {
throw new InvalidArgumentException('Parameter `offers` must contains array of the customers');
}
return $this->client->makeRequest(
"/store/inventories/upload",
RetailcrmHttpClient::METHOD_POST,
$this->fillSite($site, array('offers' => json_encode($offers)))
);
}
/**
* Returns deliveryServices list
*
* @return ApiResponse
*/
public function deliveryServicesList()
{
return $this->client->makeRequest('/reference/delivery-services', RetailcrmHttpClient::METHOD_GET);
}
/**
* Returns deliveryTypes list
*
* @return ApiResponse
*/
public function deliveryTypesList()
{
return $this->client->makeRequest('/reference/delivery-types', RetailcrmHttpClient::METHOD_GET);
}
/**
* Returns orderMethods list
*
* @return ApiResponse
*/
public function orderMethodsList()
{
return $this->client->makeRequest('/reference/order-methods', RetailcrmHttpClient::METHOD_GET);
}
/**
* Returns orderTypes list
*
* @return ApiResponse
*/
public function orderTypesList()
{
return $this->client->makeRequest('/reference/order-types', RetailcrmHttpClient::METHOD_GET);
}
/**
* Returns paymentStatuses list
*
* @return ApiResponse
*/
public function paymentStatusesList()
{
return $this->client->makeRequest('/reference/payment-statuses', RetailcrmHttpClient::METHOD_GET);
}
/**
* Returns paymentTypes list
*
* @return ApiResponse
*/
public function paymentTypesList()
{
return $this->client->makeRequest('/reference/payment-types', RetailcrmHttpClient::METHOD_GET);
}
/**
* Returns productStatuses list
*
* @return ApiResponse
*/
public function productStatusesList()
{
return $this->client->makeRequest('/reference/product-statuses', RetailcrmHttpClient::METHOD_GET);
}
/**
* Returns statusGroups list
*
* @return ApiResponse
*/
public function statusGroupsList()
{
return $this->client->makeRequest('/reference/status-groups', RetailcrmHttpClient::METHOD_GET);
}
/**
* Returns statuses list
*
* @return ApiResponse
*/
public function statusesList()
{
return $this->client->makeRequest('/reference/statuses', RetailcrmHttpClient::METHOD_GET);
}
/**
* Returns sites list
*
* @return ApiResponse
*/
public function sitesList()
{
return $this->client->makeRequest('/reference/sites', RetailcrmHttpClient::METHOD_GET);
}
/**
* Returns stores list
*
* @return ApiResponse
*/
public function storesList()
{
return $this->client->makeRequest('/reference/stores', RetailcrmHttpClient::METHOD_GET);
}
/**
* Edit deliveryService
*
* @param array $data delivery service data
* @return ApiResponse
*/
public function deliveryServicesEdit(array $data)
{
if (!isset($data['code'])) {
throw new InvalidArgumentException('Data must contain "code" parameter.');
}
return $this->client->makeRequest(
'/reference/delivery-services/' . $data['code'] . '/edit',
RetailcrmHttpClient::METHOD_POST,
array(
'deliveryService' => json_encode($data)
)
);
}
/**
* Edit deliveryType
*
* @param array $data delivery type data
* @return ApiResponse
*/
public function deliveryTypesEdit(array $data)
{
if (!isset($data['code'])) {
throw new InvalidArgumentException('Data must contain "code" parameter.');
}
return $this->client->makeRequest(
'/reference/delivery-types/' . $data['code'] . '/edit',
RetailcrmHttpClient::METHOD_POST,
array(
'deliveryType' => json_encode($data)
)
);
}
/**
* Edit orderMethod
*
* @param array $data order method data
* @return ApiResponse
*/
public function orderMethodsEdit(array $data)
{
if (!isset($data['code'])) {
throw new InvalidArgumentException('Data must contain "code" parameter.');
}
return $this->client->makeRequest(
'/reference/order-methods/' . $data['code'] . '/edit',
RetailcrmHttpClient::METHOD_POST,
array(
'orderMethod' => json_encode($data)
)
);
}
/**
* Edit orderType
*
* @param array $data order type data
* @return ApiResponse
*/
public function orderTypesEdit(array $data)
{
if (!isset($data['code'])) {
throw new InvalidArgumentException('Data must contain "code" parameter.');
}
return $this->client->makeRequest(
'/reference/order-types/' . $data['code'] . '/edit',
RetailcrmHttpClient::METHOD_POST,
array(
'orderType' => json_encode($data)
)
);
}
/**
* Edit paymentStatus
*
* @param array $data payment status data
* @return ApiResponse
*/
public function paymentStatusesEdit(array $data)
{
if (!isset($data['code'])) {
throw new InvalidArgumentException('Data must contain "code" parameter.');
}
return $this->client->makeRequest(
'/reference/payment-statuses/' . $data['code'] . '/edit',
RetailcrmHttpClient::METHOD_POST,
array(
'paymentStatus' => json_encode($data)
)
);
}
/**
* Edit paymentType
*
* @param array $data payment type data
* @return ApiResponse
*/
public function paymentTypesEdit(array $data)
{
if (!isset($data['code'])) {
throw new InvalidArgumentException('Data must contain "code" parameter.');
}
return $this->client->makeRequest(
'/reference/payment-types/' . $data['code'] . '/edit',
RetailcrmHttpClient::METHOD_POST,
array(
'paymentType' => json_encode($data)
)
);
}
/**
* Edit productStatus
*
* @param array $data product status data
* @return ApiResponse
*/
public function productStatusesEdit(array $data)
{
if (!isset($data['code'])) {
throw new InvalidArgumentException('Data must contain "code" parameter.');
}
return $this->client->makeRequest(
'/reference/product-statuses/' . $data['code'] . '/edit',
RetailcrmHttpClient::METHOD_POST,
array(
'productStatus' => json_encode($data)
)
);
}
/**
* Edit order status
*
* @param array $data status data
* @return ApiResponse
*/
public function statusesEdit(array $data)
{
if (!isset($data['code'])) {
throw new InvalidArgumentException('Data must contain "code" parameter.');
}
return $this->client->makeRequest(
'/reference/statuses/' . $data['code'] . '/edit',
RetailcrmHttpClient::METHOD_POST,
array(
'status' => json_encode($data)
)
);
}
/**
* Edit site
*
* @param array $data site data
* @return ApiResponse
*/
public function sitesEdit(array $data)
{
if (!isset($data['code'])) {
throw new InvalidArgumentException('Data must contain "code" parameter.');
}
return $this->client->makeRequest(
'/reference/sites/' . $data['code'] . '/edit',
RetailcrmHttpClient::METHOD_POST,
array(
'site' => json_encode($data)
)
);
}
/**
* Edit store
*
* @param array $data site data
* @return ApiResponse
*/
public function storesEdit(array $data)
{
if (!isset($data['code'])) {
throw new InvalidArgumentException('Data must contain "code" parameter.');
}
if (!isset($data['name'])) {
throw new InvalidArgumentException('Data must contain "name" parameter.');
}
return $this->client->makeRequest(
'/reference/stores/' . $data['code'] . '/edit',
RetailcrmHttpClient::METHOD_POST,
array(
'store' => json_encode($data)
)
);
}
/**
* Update CRM basic statistic
*
* @return ApiResponse
*/
public function statisticUpdate()
{
return $this->client->makeRequest('/statistic/update', RetailcrmHttpClient::METHOD_GET);
}
/**
* Return current site
*
* @return string
*/
public function getSite()
{
return $this->siteCode;
}
/**
* Set site
*
* @param string $site
* @return void
*/
public function setSite($site)
{
$this->siteCode = $site;
}
/**
* Check ID parameter
*
* @param string $by
* @return bool
*/
protected function checkIdParameter($by)
{
$allowedForBy = array('externalId', 'id');
if (!in_array($by, $allowedForBy)) {
throw new InvalidArgumentException(sprintf(
'Value "%s" for parameter "by" is not valid. Allowed values are %s.',
$by,
implode(', ', $allowedForBy)
));
}
return true;
}
/**
* Fill params by site value
*
* @param string $site
* @param array $params
* @return array
*/
protected function fillSite($site, array $params)
{
if ($site) {
$params['site'] = $site;
} elseif ($this->siteCode) {
$params['site'] = $this->siteCode;
}
return $params;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -6,34 +6,24 @@
*/
class RetailcrmProxy
{
private $api;
private $log;
public function __construct($url, $key, $log, $version = null)
{
{
switch ($version) {
case 'v5':
$this->api = new RetailcrmApiClient5($url, $key, $version);
break;
case 'v4':
$this->api = new RetailcrmApiClient4($url, $key, $version);
break;
case 'v3':
$this->api = new RetailcrmApiClient3($url, $key, $version);
break;
case null:
$this->api = new RetailcrmApiClient3($url, $key, $version);
break;
}
$this->log = $log;
}
public function __call($method, $arguments)
{
{
$date = date('[Y-m-d H:i:s]');
try {
$response = call_user_func_array(array($this->api, $method), $arguments);

View File

@ -0,0 +1,140 @@
<?php
namespace Retailcrm;
abstract class Base
{
protected $registry;
protected $data = array();
/**
* Base constructor.
*
* @param $registry
*/
public function __construct($registry)
{
$this->registry = $registry;
}
/**
* @param $name
*
* @return mixed
*/
public function __get($name) {
return $this->registry->get($name);
}
/**
* @param $field
* @param $value
*
* @return bool
*/
public function setField($field, $value) {
if (!isset($this->data[$field])) {
return false;
}
$this->data[$field] = $value;
return true;
}
/**
* @param $fields
*/
public function setFields($fields) {
foreach ($fields as $field) {
$this->setField($field['field'], $field['value']);
}
}
/**
* @param $data
* @param $element
*/
public function setDataArray($data, $element) {
if (is_array($data)) {
$this->setField($element, $data);
}
}
/**
* @param array $custom_fields
* @param array $setting
* @param string $prefix
*
* @return array
*/
protected function prepareCustomFields($custom_fields, $setting, $prefix) {
$result = array();
if (!$custom_fields || empty($custom_fields)) {
return $result;
}
foreach ($custom_fields as $loc => $custom_field) {
if (\is_int($loc)) {
$result = $this->getCustomFields($custom_field, $setting, $prefix);
} elseif (\is_string($loc)) {
foreach ($custom_field as $field) {
if (!$field) {
continue;
}
$result = $this->getCustomFields($field, $setting, $prefix);
}
}
}
return $result;
}
/**
* @param array $custom_fields
* @param array $setting
* @param string $prefix
*
* @return array $result
*/
private function getCustomFields($custom_fields, $setting, $prefix) {
$result = array();
foreach ($custom_fields as $key => $field) {
if (isset($setting[\Retailcrm\Retailcrm::MODULE. '_custom_field'][$prefix . $key])) {
$result[$setting[\Retailcrm\Retailcrm::MODULE. '_custom_field'][$prefix . $key]] = $field;
}
}
return $result;
}
/**
* Prepare data array
*
* @param $data
*
* @return void
*/
abstract function prepare($data);
/**
* Send to crm
*
* @param $retailcrm_api_client
*
* @return void
*/
abstract function create($retailcrm_api_client);
/**
* Edit in crm
*
* @param $retailcrm_api_client
*
* @return void
*/
abstract function edit($retailcrm_api_client);
}

View File

@ -0,0 +1,65 @@
<?php
namespace Retailcrm;
class Customer extends Base
{
protected $registry;
protected $data = array(
'externalId' => 0,
'createdAt' => null,
'firstName' => null,
'lastName' => null,
'patronymic' => null,
'email' => null,
'phones' => array(),
'address' => array(),
'customFields' => array()
);
public function prepare($customer) {
if (file_exists(DIR_SYSTEM . 'library/retailcrm/custom.php')) {
$custom = new \Retailcrm\Custom($this->registry);
$this->data = $custom->processCustomer($customer);
} else {
$this->load->model('setting/setting');
$setting = $this->model_setting_setting->getSetting(\Retailcrm\Retailcrm::MODULE);
if (isset($customer['firstname']) && $customer['firstname']) {
$this->setField('firstName', $customer['firstname']);
}
if (isset($customer['lastname']) && $customer['lastname']) {
$this->setField('lastName', $customer['lastname']);
}
if (isset($customer['telephone']) && $customer['telephone']) {
$phones = array(
array(
'number' => $customer['telephone']
)
);
$this->setDataArray($phones, 'phones');
}
$this->setField('email', $customer['email']);
$this->setField('createdAt', date('Y-m-d H:i:s'));
if (isset($settings[\Retailcrm\Retailcrm::MODULE . '_custom_field']) && $customer['custom_field']) {
$custom_fields = $this->prepareCustomFields($customer['custom_field'], $setting, 'c_');
if ($custom_fields) {
$this->setDataArray($custom_fields, 'customFields');
}
}
}
}
public function create($retailctm_api_client) {
$retailctm_api_client->customersCreate($this->data);
}
public function edit($retailctm_api_client) {
$retailctm_api_client->customersEdit($this->data);
}
}

View File

@ -0,0 +1,241 @@
<?php
namespace Retailcrm;
class Order extends Base
{
protected $registry;
protected $data = array(
'number' => 0,
'countryIso' => null,
'externalId' => 0,
'customer' => array(),
'status' => null,
'firstName' => null,
'lastName' => null,
'patronymic' => null,
'email' => null,
'phone' => null,
'discountManualAmount' => 0,
'items' => array(),
'delivery' => array(),
'customFields' => array(),
'payments' => array()
);
public function prepare($order) {
if (file_exists(DIR_SYSTEM . 'library/retailcrm/custom.php')) {
$custom = new \Retailcrm\Custom($this->registry);
$this->data = $custom->processOrder($order);
} else {
$this->load->model('setting/setting');
$this->load->model('catalog/product');
$settings = $this->model_setting_setting->getSetting(\Retailcrm\Retailcrm::MODULE);
$delivery_settings = $settings[\Retailcrm\Retailcrm::MODULE . '_delivery'];
$payments_settings = $settings[\Retailcrm\Retailcrm::MODULE . '_payment'];
$status_settings = $settings[\Retailcrm\Retailcrm::MODULE . '_status'];
$totals = $this->explodeTotals($order['totals']);
$coupon_total = 0;
$delivery_cost = 0;
if (isset($totals['shipping'])) {
$delivery_cost = $totals['shipping'];
}
if (isset($totals['coupon'])) {
$coupon_total += abs($totals['coupon']);
}
if (isset($totals['reward'])) {
$coupon_total += abs($totals['reward']);
}
if (isset($order['order_status_id']) && $order['order_status_id'] > 0) {
$status = $status_settings[$order['order_status_id']];
} elseif (isset($order['order_status_id']) && $order['order_status_id'] == 0) {
$status = $settings[\Retailcrm\Retailcrm::MODULE . '_missing_status'];
}
$fields = array(
'firstName' => $order['firstname'],
'lastName' => $order['lastname'],
'email' => $order['email'],
'phone' => $order['telephone'],
'customerComment' => $order['comment'],
'createdAt' => $order['date_added'],
'discountManualAmount' => $coupon_total,
'status' => $status
);
$this->setFields($fields);
if (isset($order['shipping_code'])) {
$delivery_code = $this->getDeliveryMethod($order['shipping_code'], $delivery_settings);
}
$delivery = array(
'address' => array(
'index' => isset($order['shipping_postcode']) ? $order['shipping_postcode'] : '',
'city' => isset($order['shipping_city']) ? $order['shipping_city'] : '',
'region' => isset($order['shipping_zone']) ? $order['shipping_zone'] : '',
'text' => implode(', ', array(
isset($order['shipping_postcode']) ? $order['shipping_postcode'] : '',
isset($order['shipping_country']) ? $order['shipping_country'] : '',
isset($order['shipping_city']) ? $order['shipping_city'] : '',
isset($order['shipping_address_1']) ? $order['shipping_address_1'] : '',
isset($order['shipping_address_2']) ? $order['shipping_address_2'] : ''
))
)
);
if (isset($delivery_code)) {
$delivery['code'] = $delivery_code;
}
if ($delivery_cost) {
$delivery['cost'] = $delivery_cost;
}
$this->setDataArray($delivery, 'delivery');
$this->setOrderProducts($order['products']);
$payments = array();
if (isset($payments_settings[$order['payment_code']])) {
$payment = array(
'order' => array(
'externalId' => $order['order_id']
),
'externalId' => $order['order_id'],
'type' => $payments_settings[$order['payment_code']],
'amount' => $order['total']
);
$payments[] = $payment;
}
$this->setDataArray($payments, 'payments');
if (isset($settings[\Retailcrm\Retailcrm::MODULE . '_custom_field']) && $order['custom_field']) {
$custom_fields = $this->prepareCustomFields($order['custom_field'], $settings, 'o_');
if ($custom_fields) {
$this->setDataArray($custom_fields, 'customFields');
}
}
}
}
public function create($retailcrm_api_client) {
$retailcrm_api_client->ordersCreate($this->data);
}
public function edit($retailcrm_api_client) {
$retailcrm_api_client->ordersEdit($this->data);
}
/**
* @param string $shipping_code
* @param array $deliveries
*
* @return mixed
*/
private function getDeliveryMethod($shipping_code, $deliveries) {
if (!empty($shipping_code)) {
$shipping_code_array = explode('.', $shipping_code);
$shipping_module = $shipping_code_array[0];
if (isset($deliveries[$shipping_code])) {
$delivery_code = $deliveries[$shipping_code];
} elseif (isset($deliveries[$shipping_module])) {
$delivery_code = $deliveries[$shipping_module];
}
}
if (!isset($delivery_code) && isset($shipping_module) && $deliveries) {
$delivery = '';
array_walk($deliveries, function ($item, $key) use ($shipping_module, &$delivery) {
if (strripos($item, $shipping_module) !== false) {
$delivery = $item;
}
});
$delivery_code = $deliveries[$delivery];
}
return $delivery_code;
}
/**
* @param array $products
*
* @return void
*/
private function setOrderProducts($products) {
$offer_options = array('select', 'radio');
$items = array();
foreach ($products as $product) {
if (!empty($product['option'])) {
$offer_id = '';
$options = array();
$properties = array();
foreach ($product['option'] as $option) {
if ($option['type'] == 'checkbox') {
$properties[] = array(
'code' => $option['product_option_value_id'],
'name' => $option['name'],
'value' => $option['value']
);
}
if (!in_array($option['type'], $offer_options)) {
continue;
}
$options[$option['product_option_id']] = $option['option_value_id'];
}
ksort($options);
foreach ($options as $optionKey => $optionValue) {
$offer_id .= $optionKey . '-' . $optionValue;
}
}
$item = array(
'offer' => array(
'externalId' => !empty($offer_id) ? $product['product_id'] . '#' . $offer_id : $product['product_id']
),
'productName' => $product['name'],
'initialPrice' => $product['price'],
'quantity' => $product['quantity'],
);
if (!empty($properties)) {
$item['properties'] = $properties;
}
$items[] = $item;
}
$this->setDataArray($items, 'items');
}
/**
* @param $totals
*
* @return array
*/
private function explodeTotals($totals)
{
$resultTotals = array();
foreach ($totals as $total) {
$resultTotals[$total['code']] = $total['value'];
}
return $resultTotals;
}
}

View File

@ -1,13 +1,14 @@
<?php
namespace retailcrm;
namespace Retailcrm;
require_once 'bootstrap.php';
require_once 'api/bootstrap.php';
class Retailcrm {
protected $apiClient;
protected $registry;
const MODULE = 'module_retailcrm';
public function __construct($registry)
{
$this->registry = $registry;
@ -17,6 +18,10 @@ class Retailcrm {
return $this->registry->get($name);
}
public function createObject($object) {
return new $object($this->registry);
}
/**
* Get api client object
*
@ -24,21 +29,21 @@ class Retailcrm {
* @param string $apiKey (default = null)
* @param string $apiVersion (default = null)
*
* @return mixed object | boolean
* @return mixed object | boolean
*/
public function getApiClient($apiUrl = null, $apiKey = null, $apiVersion = null)
{
$this->load->model('setting/setting');
$setting = $this->model_setting_setting->getSetting($this->getModuleTitle());
$setting = $this->model_setting_setting->getSetting(self::MODULE);
if ($apiUrl === null && $apiKey === null) {
$apiUrl = isset($setting[$this->getModuleTitle() . '_url'])
? $setting[$this->getModuleTitle() . '_url'] : '';
$apiKey = isset($setting[$this->getModuleTitle() . '_apikey'])
? $setting[$this->getModuleTitle() . '_apikey'] : '';
$apiVersion = isset($setting[$this->getModuleTitle() . '_apiversion'])
? $setting[$this->getModuleTitle() . '_apiversion'] : '';
$apiUrl = isset($setting[self::MODULE . '_url'])
? $setting[self::MODULE . '_url'] : '';
$apiKey = isset($setting[self::MODULE . '_apikey'])
? $setting[self::MODULE . '_apikey'] : '';
$apiVersion = isset($setting[self::MODULE . '_apiversion'])
? $setting[self::MODULE . '_apiversion'] : '';
}
if ($apiUrl && $apiKey) {
@ -60,38 +65,6 @@ class Retailcrm {
return new \OpencartApiClient($registry);
}
/**
* Get module title for this version
*
* @return string $title
*/
public function getModuleTitle()
{
if (version_compare(VERSION, '3.0', '<')) {
$title = 'retailcrm';
} else {
$title = 'module_retailcrm';
}
return $title;
}
/**
* Get token param name
*
* @return string $token
*/
public function getTokenTitle()
{
if (version_compare(VERSION, '3.0', '<')) {
$token = 'token';
} else {
$token = 'user_token';
}
return $token;
}
public function getOffers($product)
{
// Формируем офферы отнсительно доступных опций
@ -100,8 +73,8 @@ class Retailcrm {
$requiredOptions = array();
$notRequiredOptions = array();
// Оставляем опции связанные с вариациями товаров, сортируем по параметру обязательный или нет
foreach($options as $option) {
if(in_array($option['type'], $offerOptions)) {
foreach ($options as $option) {
if (in_array($option['type'], $offerOptions)) {
if($option['required']) {
$requiredOptions[] = $option;
} else {
@ -112,19 +85,19 @@ class Retailcrm {
$offers = array();
// Сначала совмещаем все обязательные опции
foreach($requiredOptions as $requiredOption) {
foreach ($requiredOptions as $requiredOption) {
// Если первая итерация
if(empty($offers)) {
foreach($requiredOption['product_option_value'] as $optionValue) {
if (empty($offers)) {
foreach ($requiredOption['product_option_value'] as $optionValue) {
$offers[$requiredOption['product_option_id'].':'.$requiredOption['option_id'].'-'.$optionValue['option_value_id']] = array(
'price' => (float)$optionValue['price'],
'qty' => $optionValue['quantity']
);
}
} else {
foreach($offers as $optionKey => $optionAttr) {
foreach ($offers as $optionKey => $optionAttr) {
unset($offers[$optionKey]); // Работая в контексте обязательных опций не забываем удалять прошлые обязательные опции, т.к. они должны быть скомбинированы с другими обязательными опциями
foreach($requiredOption['product_option_value'] as $optionValue) {
foreach ($requiredOption['product_option_value'] as $optionValue) {
$offers[$optionKey.'_'.$requiredOption['product_option_id'].':'.$requiredOption['option_id'].'-'.$optionValue['option_value_id']] = array(
'price' => $optionAttr['price'] + (float)$optionValue['price'],
'qty' => ($optionAttr['qty'] > $optionValue['quantity']) ?
@ -134,21 +107,21 @@ class Retailcrm {
}
}
}
// Совмещаем или добавляем необязательные опции, учитывая тот факт что обязательных опций может и не быть.
foreach($notRequiredOptions as $notRequiredOption) {
foreach ($notRequiredOptions as $notRequiredOption) {
// Если обязательных опцией не оказалось и первая итерация
if(empty($offers)) {
if (empty($offers)) {
$offers['0:0-0'] = 0; // В случае работы с необязательными опциями мы должны учитывать товарное предложение без опций, поэтому создадим "пустую" опцию
foreach($notRequiredOption['product_option_value'] as $optionValue) {
foreach ($notRequiredOption['product_option_value'] as $optionValue) {
$offers[$notRequiredOption['product_option_id'].':'.$notRequiredOption['option_id'].'-'.$optionValue['option_value_id']] = array(
'price' => (float)$optionValue['price'],
'qty' => $optionValue['quantity']
);
}
} else {
foreach($offers as $optionKey => $optionAttr) {
foreach($notRequiredOption['product_option_value'] as $optionValue) {
foreach ($offers as $optionKey => $optionAttr) {
foreach ($notRequiredOption['product_option_value'] as $optionValue) {
$offers[$optionKey.'_'.$notRequiredOption['product_option_id'].':'.$notRequiredOption['option_id'].'-'.$optionValue['option_value_id']] = array(
'price' => $optionAttr['price'] + (float)$optionValue['price'],
'qty' => ($optionAttr['qty'] > $optionValue['quantity']) ?
@ -159,7 +132,7 @@ class Retailcrm {
}
}
if(empty($offers)) {
if (empty($offers)) {
$offers = array('0:0-0' => array('price' => '0', 'qty' => '0'));
}

View File

@ -14,7 +14,7 @@ class ControllerRetailcrmAdminTest extends OpenCartTest
$this->db->query("UPDATE ".DB_PREFIX."user_group SET permission='".$this->db->escape(json_encode($permissions))."' WHERE name = 'Administrator'");
}
$this->retailcrm = $this->getMockBuilder('\retailcrm\Retailcrm')
$this->retailcrm = $this->getMockBuilder('\retailcrm\retailcrm')
->disableOriginalConstructor()
->getMock();
}

View File

@ -29,7 +29,7 @@ class ModelRetailcrmOrderAdminTest extends OpenCartTest
->getMock();
$this->settingModel = $this->loadModel('setting/setting');
$this->retailcrm = new \retailcrm\Retailcrm(self::$registry);
$this->retailcrm = new \retailcrm\retailcrm(self::$registry);
$this->settingModel->editSetting(
$this->retailcrm->getModuleTitle(),

View File

@ -22,7 +22,7 @@ class ModelRetailcrmPricesAdminTest extends OpenCartTest
->getMock();
$this->settingModel = $this->loadModel('setting/setting');
$this->retailcrm = new \retailcrm\Retailcrm(self::$registry);
$this->retailcrm = new \retailcrm\retailcrm(self::$registry);
$this->settingModel->editSetting(
$this->retailcrm->getModuleTitle(),

View File

@ -14,7 +14,7 @@ class ControllerRetailcrmApiCatalogTest extends OpenCartTest
$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "api` WHERE api_id = 1");
$api = $query->row;
$this->apiKey = $api['key'];
$this->retailcrm = new \retailcrm\Retailcrm(self::$registry);
$this->retailcrm = new \retailcrm\retailcrm(self::$registry);
$this->setSetting(
$this->retailcrm->getModuleTitle(),

View File

@ -27,7 +27,7 @@ class ModelRetailcrmOrderCatalogTest extends OpenCartTest
))
->getMock();
$this->retailcrm = new \retailcrm\Retailcrm(self::$registry);
$this->retailcrm = new \retailcrm\retailcrm(self::$registry);
$this->setSetting(
$this->retailcrm->getModuleTitle(),