Transferring order number, added library retailcrm, check events in db, transferring order status for missing order (#65)

This commit is contained in:
Akolzin Dmitry 2018-01-23 16:34:20 +03:00 committed by GitHub
parent 68f11d3197
commit bf5a5b9e15
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
17 changed files with 630 additions and 468 deletions

View File

@ -1,7 +1,5 @@
<?php <?php
require_once DIR_SYSTEM . 'library/retailcrm/bootstrap.php';
/** /**
* Class ControllerModule * Class ControllerModule
* *
@ -14,9 +12,16 @@ require_once DIR_SYSTEM . 'library/retailcrm/bootstrap.php';
class ControllerExtensionModuleRetailcrm extends Controller class ControllerExtensionModuleRetailcrm extends Controller
{ {
private $_error = array(); private $_error = array();
protected $log, $statuses, $payments, $deliveryTypes, $retailcrm; protected $log, $statuses, $payments, $deliveryTypes, $retailcrmApiClient;
public $children, $template; public $children, $template;
public function __construct($registry)
{
parent::__construct($registry);
$this->load->library('retailcrm/retailcrm');
$this->moduleTitle = $this->retailcrm->getModuleTitle();
}
/** /**
* Install method * Install method
* *
@ -24,59 +29,16 @@ class ControllerExtensionModuleRetailcrm extends Controller
*/ */
public function install() public function install()
{ {
$moduleTitle = $this->getModuleTitle();
$this->load->model('setting/setting'); $this->load->model('setting/setting');
$this->model_setting_setting $this->model_setting_setting
->editSetting($moduleTitle, array( ->editSetting($this->moduleTitle, array(
$moduleTitle . '_status' => 1, $this->moduleTitle . '_status' => 1,
$moduleTitle . '_country' => array($this->config->get('config_country_id')) $this->moduleTitle . '_country' => array($this->config->get('config_country_id'))
) )
); );
$this->loadModels(); $this->addEvents();
$this->{'model_' . $this->modelEvent}
->addEvent(
$moduleTitle,
'catalog/model/checkout/order/addOrder/after',
'extension/module/retailcrm/order_create'
);
$this->{'model_' . $this->modelEvent}
->addEvent(
$moduleTitle,
'catalog/model/checkout/order/addOrderHistory/after',
'extension/module/retailcrm/order_edit'
);
$this->{'model_' . $this->modelEvent}
->addEvent(
$moduleTitle,
'catalog/model/account/customer/addCustomer/after',
'extension/module/retailcrm/customer_create'
);
$this->{'model_' . $this->modelEvent}
->addEvent(
$moduleTitle,
'catalog/model/account/customer/editCustomer/after',
'extension/module/retailcrm/customer_edit'
);
$this->{'model_' . $this->modelEvent}
->addEvent(
$moduleTitle,
'catalog/model/account/address/editAddress/after',
'extension/module/retailcrm/customer_edit'
);
$this->{'model_' . $this->modelEvent}
->addEvent(
$moduleTitle,
'admin/model/customer/customer/editCustomer/after',
'extension/module/retailcrm/customer_edit'
);
} }
/** /**
@ -86,19 +48,12 @@ class ControllerExtensionModuleRetailcrm extends Controller
*/ */
public function uninstall() public function uninstall()
{ {
$moduleTitle = $this->getModuleTitle();
$this->uninstall_collector(); $this->uninstall_collector();
$this->load->model('setting/setting'); $this->load->model('setting/setting');
$this->model_setting_setting $this->model_setting_setting
->editSetting($moduleTitle, array($moduleTitle . '_status' => 0)); ->editSetting($this->moduleTitle, array($this->moduleTitle . '_status' => 0));
$this->model_setting_setting->deleteSetting('retailcrm_history'); $this->model_setting_setting->deleteSetting('retailcrm_history');
$this->loadModels(); $this->deleteEvents();
if (version_compare(VERSION, '3.0', '<')) {
$this->{'model_' . $this->modelEvent}->deleteEvent($moduleTitle);
} else {
$this->{'model_' . $this->modelEvent}->deleteEventByCode($moduleTitle);
}
} }
/** /**
@ -109,7 +64,6 @@ class ControllerExtensionModuleRetailcrm extends Controller
public function install_collector() public function install_collector()
{ {
$collector = $this->getCollectorTitle(); $collector = $this->getCollectorTitle();
$moduleTitle = $this->getModuleTitle();
$this->loadModels(); $this->loadModels();
$this->load->model('setting/setting'); $this->load->model('setting/setting');
$this->{'model_' . $this->modelExtension}->install('analytics', 'daemon_collector'); $this->{'model_' . $this->modelExtension}->install('analytics', 'daemon_collector');
@ -145,45 +99,48 @@ class ControllerExtensionModuleRetailcrm extends Controller
$this->document->setTitle($this->language->get('heading_title')); $this->document->setTitle($this->language->get('heading_title'));
$this->document->addStyle('/admin/view/stylesheet/retailcrm.css'); $this->document->addStyle('/admin/view/stylesheet/retailcrm.css');
$tokenTitle = $this->getTokenTitle(); $tokenTitle = $this->retailcrm->getTokenTitle();
$moduleTitle = $this->getModuleTitle();
$collector = $this->getCollectorTitle(); $collector = $this->getCollectorTitle();
$history_setting = $this->model_setting_setting->getSetting('retailcrm_history'); $history_setting = $this->model_setting_setting->getSetting('retailcrm_history');
if ($this->request->server['REQUEST_METHOD'] == 'POST' && $this->validate()) { if ($this->request->server['REQUEST_METHOD'] == 'POST' && $this->validate()) {
if ($this->checkEvents() === false) {
$this->deleteEvents();
$this->addEvents();
}
$analytics = $this->{'model_' . $this->modelExtension}->getInstalled('analytics'); $analytics = $this->{'model_' . $this->modelExtension}->getInstalled('analytics');
if ($this->request->post[$moduleTitle . '_collector_active'] == 1 && if ($this->request->post[$this->moduleTitle . '_collector_active'] == 1 &&
!in_array($collector, $analytics)) { !in_array($collector, $analytics)) {
$this->install_collector(); $this->install_collector();
} elseif ($this->request->post[$moduleTitle . '_collector_active'] == 0 && } elseif ($this->request->post[$this->moduleTitle . '_collector_active'] == 0 &&
in_array($collector, $analytics)) { in_array($collector, $analytics)) {
$this->uninstall_collector(); $this->uninstall_collector();
} }
if (parse_url($this->request->post[$moduleTitle . '_url'])) { if (parse_url($this->request->post[$this->moduleTitle . '_url'])) {
$crm_url = parse_url($this->request->post[$moduleTitle . '_url'], PHP_URL_HOST); $crm_url = parse_url($this->request->post[$this->moduleTitle . '_url'], PHP_URL_HOST);
$this->request->post[$moduleTitle . '_url'] = 'https://'.$crm_url; $this->request->post[$this->moduleTitle . '_url'] = 'https://'.$crm_url;
} }
if (isset($this->request->post[$moduleTitle . '_custom_field_active']) && if (isset($this->request->post[$this->moduleTitle . '_custom_field_active']) &&
$this->request->post[$moduleTitle . '_custom_field_active'] == 0 $this->request->post[$this->moduleTitle . '_custom_field_active'] == 0
) { ) {
unset($this->request->post[$moduleTitle . '_custom_field']); unset($this->request->post[$this->moduleTitle . '_custom_field']);
} }
$this->model_setting_setting->editSetting( $this->model_setting_setting->editSetting(
$moduleTitle, $this->moduleTitle,
$this->request->post $this->request->post
); );
if ($this->request->post[$moduleTitle . '_apiversion'] != 'v3') { if ($this->request->post[$this->moduleTitle . '_apiversion'] != 'v3') {
if (!isset($history_setting['retailcrm_history_orders']) && !isset($history_setting['retailcrm_history_customers'])) { if (!isset($history_setting['retailcrm_history_orders']) && !isset($history_setting['retailcrm_history_customers'])) {
$api = new RetailcrmProxy( $api = $this->retailcrm->getApiClient(
$this->request->post[$moduleTitle . '_url'], $this->request->post[$this->moduleTitle . '_url'],
$this->request->post[$moduleTitle . '_apikey'], $this->request->post[$this->moduleTitle . '_apikey'],
DIR_SYSTEM . 'storage/logs/retailcrm.log', $this->request->post[$this->moduleTitle . '_apiversion']
$this->request->post[$moduleTitle . '_apiversion']
); );
$ordersHistory = $api->ordersHistory(); $ordersHistory = $api->ordersHistory();
@ -283,7 +240,9 @@ class ControllerExtensionModuleRetailcrm extends Controller
'text_custom_field_activity', 'text_custom_field_activity',
'text_orders_custom_fields', 'text_orders_custom_fields',
'text_customers_custom_fields', 'text_customers_custom_fields',
'text_confirm_log' 'text_confirm_log',
'text_error_delivery',
'retailcrm_missing_status'
); );
$_data = &$data; $_data = &$data;
@ -294,27 +253,20 @@ class ControllerExtensionModuleRetailcrm extends Controller
$_data['retailcrm_errors'] = array(); $_data['retailcrm_errors'] = array();
$_data['saved_settings'] = $this->model_setting_setting $_data['saved_settings'] = $this->model_setting_setting
->getSetting($moduleTitle); ->getSetting($this->moduleTitle);
$url = isset($_data['saved_settings'][$moduleTitle . '_url']) $url = isset($_data['saved_settings'][$this->moduleTitle . '_url'])
? $_data['saved_settings'][$moduleTitle . '_url'] ? $_data['saved_settings'][$this->moduleTitle . '_url']
: null; : null;
$key = isset($_data['saved_settings'][$moduleTitle . '_apikey']) $key = isset($_data['saved_settings'][$this->moduleTitle . '_apikey'])
? $_data['saved_settings'][$moduleTitle . '_apikey'] ? $_data['saved_settings'][$this->moduleTitle . '_apikey']
: null; : null;
$apiVersion = isset($_data['saved_settings'][$moduleTitle . '_apiversion']) $apiVersion = isset($_data['saved_settings'][$this->moduleTitle . '_apiversion'])
? $_data['saved_settings'][$moduleTitle . '_apiversion'] ? $_data['saved_settings'][$this->moduleTitle . '_apiversion']
: null; : null;
if (!empty($url) && !empty($key)) { if (!empty($url) && !empty($key)) {
$this->retailcrm = new RetailcrmProxy(
$url,
$key,
DIR_SYSTEM . 'storage/logs/retailcrm.log',
$apiVersion
);
$_data['delivery'] = $this->model_extension_retailcrm_references $_data['delivery'] = $this->model_extension_retailcrm_references
->getDeliveryTypes(); ->getDeliveryTypes();
$_data['statuses'] = $this->model_extension_retailcrm_references $_data['statuses'] = $this->model_extension_retailcrm_references
@ -329,7 +281,7 @@ class ControllerExtensionModuleRetailcrm extends Controller
} }
$config_data = array( $config_data = array(
$moduleTitle . '_status' $this->moduleTitle . '_status'
); );
foreach ($config_data as $conf) { foreach ($config_data as $conf) {
@ -451,11 +403,10 @@ class ControllerExtensionModuleRetailcrm extends Controller
*/ */
public function history() public function history()
{ {
$moduleTitle = $this->getModuleTitle();
$this->load->model('setting/setting'); $this->load->model('setting/setting');
$settings = $this->model_setting_setting->getSetting($moduleTitle); $settings = $this->model_setting_setting->getSetting($this->moduleTitle);
if ($settings[$moduleTitle . '_apiversion'] == 'v3') { if ($settings[$this->moduleTitle . '_apiversion'] == 'v3') {
if (file_exists(DIR_APPLICATION . 'model/extension/retailcrm/custom/history/v3.php')) { if (file_exists(DIR_APPLICATION . 'model/extension/retailcrm/custom/history/v3.php')) {
$this->load->model('extension/retailcrm/custom/history/v3'); $this->load->model('extension/retailcrm/custom/history/v3');
$this->model_extension_retailcrm_custom_history_v3->request(); $this->model_extension_retailcrm_custom_history_v3->request();
@ -562,7 +513,6 @@ class ControllerExtensionModuleRetailcrm extends Controller
{ {
$order_id = isset($this->request->get['order_id']) ? $this->request->get['order_id'] : ''; $order_id = isset($this->request->get['order_id']) ? $this->request->get['order_id'] : '';
$this->load->model('sale/order'); $this->load->model('sale/order');
$moduleTitle = $this->getModuleTitle();
$data = $this->model_sale_order->getOrder($order_id); $data = $this->model_sale_order->getOrder($order_id);
$data['products'] = $this->model_sale_order->getOrderProducts($order_id); $data['products'] = $this->model_sale_order->getOrderProducts($order_id);
@ -570,8 +520,8 @@ class ControllerExtensionModuleRetailcrm extends Controller
if (!isset($data['fromApi'])) { if (!isset($data['fromApi'])) {
$this->load->model('setting/setting'); $this->load->model('setting/setting');
$status = $this->model_setting_setting->getSetting($moduleTitle); $status = $this->model_setting_setting->getSetting($this->moduleTitle);
$data['order_status'] = $status[$moduleTitle . '_status'][$data['order_status_id']]; $data['order_status'] = $status[$this->moduleTitle . '_status'][$data['order_status_id']];
$this->load->model('extension/retailcrm/order'); $this->load->model('extension/retailcrm/order');
$response = $this->model_extension_retailcrm_order->uploadOrder($data); $response = $this->model_extension_retailcrm_order->uploadOrder($data);
@ -584,17 +534,21 @@ class ControllerExtensionModuleRetailcrm extends Controller
$error = $response->getErrorMsg(); $error = $response->getErrorMsg();
} }
echo json_encode( $this->response->setOutput(
json_encode(
array( array(
'status_code' => $response->getStatusCode(), 'status_code' => $response->getStatusCode(),
'error_msg' => $error 'error_msg' => $error
) )
)
); );
} else { } else {
echo json_encode( $this->response->setOutPut(
json_encode(
array( array(
'status_code' => $response->getStatusCode() 'status_code' => $response->getStatusCode()
) )
)
); );
} }
} }
@ -632,7 +586,7 @@ class ControllerExtensionModuleRetailcrm extends Controller
$this->load->model('extension/retailcrm/order'); $this->load->model('extension/retailcrm/order');
$this->model_extension_retailcrm_order->uploadToCrm($fullOrders); $this->model_extension_retailcrm_order->uploadToCrm($fullOrders);
$file = fopen(DIR_SYSTEM . '/cron/export_done', "x"); fopen(DIR_SYSTEM . '/cron/export_done', "x");
} }
/** /**
@ -642,27 +596,23 @@ class ControllerExtensionModuleRetailcrm extends Controller
*/ */
private function validate() private function validate()
{ {
$moduleTitle = $this->getModuleTitle();
$versionsMap = array( $versionsMap = array(
'v3' => '3.0', 'v3' => '3.0',
'v4' => '4.0', 'v4' => '4.0',
'v5' => '5.0' 'v5' => '5.0'
); );
if (!empty($this->request->post[$moduleTitle . '_url']) && !empty($this->request->post[$moduleTitle . '_apikey'])) { if (!empty($this->request->post[$this->moduleTitle . '_url']) && !empty($this->request->post[$this->moduleTitle . '_apikey'])) {
$apiClient = $this->retailcrm->getApiClient(
$this->retailcrm = new RetailcrmProxy( $this->request->post[$this->moduleTitle . '_url'],
$this->request->post[$moduleTitle . '_url'], $this->request->post[$this->moduleTitle . '_apikey']
$this->request->post[$moduleTitle . '_apikey'],
DIR_SYSTEM . 'storage/logs/retailcrm.log'
); );
} }
$response = $this->retailcrm->apiVersions(); $response = $apiClient->apiVersions();
if ($response && $response->isSuccessful()) { if ($response && $response->isSuccessful()) {
if (!in_array($versionsMap[$this->request->post[$moduleTitle . '_apiversion']], $response['versions'])) { if (!in_array($versionsMap[$this->request->post[$this->moduleTitle . '_apiversion']], $response['versions'])) {
$this->_error['warning'] = $this->language->get('text_error_api'); $this->_error['warning'] = $this->language->get('text_error_api');
} }
} else { } else {
@ -673,9 +623,9 @@ class ControllerExtensionModuleRetailcrm extends Controller
$this->_error['warning'] = $this->language->get('error_permission'); $this->_error['warning'] = $this->language->get('error_permission');
} }
if (isset($this->request->post[$moduleTitle . '_collector']['custom']) && if (isset($this->request->post[$this->moduleTitle . '_collector']['custom']) &&
$this->request->post[$moduleTitle . '_collector']['custom_form'] == 1) { $this->request->post[$this->moduleTitle . '_collector']['custom_form'] == 1) {
$customField = $this->request->post[$moduleTitle . '_collector']['custom']; $customField = $this->request->post[$this->moduleTitle . '_collector']['custom'];
if (empty($customField['name']) && empty($customField['email']) && empty($customField['phone'])) { if (empty($customField['name']) && empty($customField['email']) && empty($customField['phone'])) {
$this->_error['fields'] = $this->language->get('text_error_collector_fields'); $this->_error['fields'] = $this->language->get('text_error_collector_fields');
@ -755,38 +705,6 @@ class ControllerExtensionModuleRetailcrm extends Controller
} }
} }
/**
* Get token param name
*
* @return string
*/
private function getTokenTitle()
{
if (version_compare(VERSION, '3.0', '<')) {
$token = 'token';
} else {
$token = 'user_token';
}
return $token;
}
/**
* Get module name
*
* @return string
*/
private function getModuleTitle()
{
if (version_compare(VERSION, '3.0', '<')) {
$title = 'retailcrm';
} else {
$title = 'module_retailcrm';
}
return $title;
}
/** /**
* Get collector module name * Get collector module name
* *
@ -824,4 +742,92 @@ class ControllerExtensionModuleRetailcrm extends Controller
return $logs; return $logs;
} }
/**
* Add events to db
*
* @return void
*/
private function addEvents()
{
$this->loadModels();
$this->{'model_' . $this->modelEvent}
->addEvent(
$this->moduleTitle,
'catalog/model/checkout/order/addOrder/after',
'extension/module/retailcrm/order_create'
);
$this->{'model_' . $this->modelEvent}
->addEvent(
$this->moduleTitle,
'catalog/model/checkout/order/addOrderHistory/after',
'extension/module/retailcrm/order_edit'
);
$this->{'model_' . $this->modelEvent}
->addEvent(
$this->moduleTitle,
'catalog/model/account/customer/addCustomer/after',
'extension/module/retailcrm/customer_create'
);
$this->{'model_' . $this->modelEvent}
->addEvent(
$this->moduleTitle,
'catalog/model/account/customer/editCustomer/after',
'extension/module/retailcrm/customer_edit'
);
$this->{'model_' . $this->modelEvent}
->addEvent(
$this->moduleTitle,
'catalog/model/account/address/editAddress/after',
'extension/module/retailcrm/customer_edit'
);
$this->{'model_' . $this->modelEvent}
->addEvent(
$this->moduleTitle,
'admin/model/customer/customer/editCustomer/after',
'extension/module/retailcrm/customer_edit'
);
}
/**
* Check events in db
*
* @return boolean
*/
private function checkEvents()
{
$events = $this->{'model_' . $this->modelEvent}->getEvent(
'retailcrm',
'catalog/model/checkout/order/addOrder/after',
'extension/module/retailcrm/order_create'
);
if (!empty($events)) {
return true;
}
return false;
}
/**
* Delete events from db
*
* @return void
*/
private function deleteEvents()
{
$this->loadModels();
if (version_compare(VERSION, '3.0', '<')) {
$this->{'model_' . $this->modelEvent}->deleteEvent($this->moduleTitle);
} else {
$this->{'model_' . $this->modelEvent}->deleteEventByCode($this->moduleTitle);
}
}
} }

View File

@ -54,6 +54,7 @@ $_['text_error_cf_opencart'] = 'None custom fields in Opencart';
$_['text_error_cf_retailcrm'] = 'None custom fields in RetailCRM'; $_['text_error_cf_retailcrm'] = 'None custom fields in RetailCRM';
$_['text_error_save'] = 'Error saving settings'; $_['text_error_save'] = 'Error saving settings';
$_['text_error_log'] = 'Log size more than 2MB'; $_['text_error_log'] = 'Log size more than 2MB';
$_['text_error_delivery'] = 'Not found delivery methods';
$_['text_confirm_log'] = 'Are you sure you want to clear the log?'; $_['text_confirm_log'] = 'Are you sure you want to clear the log?';
$_['retailcrm_dict_delivery'] = 'Shipment methods'; $_['retailcrm_dict_delivery'] = 'Shipment methods';
@ -61,6 +62,7 @@ $_['retailcrm_dict_status'] = 'Order statuses';
$_['retailcrm_dict_payment'] = 'Payment methods'; $_['retailcrm_dict_payment'] = 'Payment methods';
$_['retailcrm_dict_custom_fields'] = 'Configure custom fields'; $_['retailcrm_dict_custom_fields'] = 'Configure custom fields';
$_['retailcrm_dict_default'] = 'Default'; $_['retailcrm_dict_default'] = 'Default';
$_['retailcrm_missing_status'] = 'Missing orders status';
$_['column_total'] = 'Total'; $_['column_total'] = 'Total';
$_['product_summ'] = 'Amount'; $_['product_summ'] = 'Amount';
@ -74,4 +76,3 @@ $_['text_yes'] = 'Yes';
$_['text_no'] = 'No'; $_['text_no'] = 'No';
// Errors // Errors
$_['error_permission'] = 'Warning! You do not have permission to modify module'; $_['error_permission'] = 'Warning! You do not have permission to modify module';

View File

@ -54,13 +54,15 @@ $_['text_error_cf_opencart'] = 'Отсутствуют пользовате
$_['text_error_cf_retailcrm'] = 'Отсутствуют пользовательские поля в RetailCRM'; $_['text_error_cf_retailcrm'] = 'Отсутствуют пользовательские поля в RetailCRM';
$_['text_error_save'] = 'Ошибка сохранения настроек'; $_['text_error_save'] = 'Ошибка сохранения настроек';
$_['text_error_log'] = 'Размер лога более 2MB'; $_['text_error_log'] = 'Размер лога более 2MB';
$_['text_error_delivery'] = 'Не найдены типы доставки';
$_['text_confirm_log'] = 'Вы уверены, что хотите очистить лог?'; $_['text_confirm_log'] = 'Вы уверены, что хотите очистить лог?';
$_['retailcrm_dict_delivery'] = 'Способы доставки'; $_['retailcrm_dict_delivery'] = 'Способы доставки';
$_['retailcrm_dict_status'] = 'Статусы'; $_['retailcrm_dict_status'] = 'Статусы';
$_['retailcrm_dict_payment'] = 'Способы оплаты'; $_['retailcrm_dict_payment'] = 'Способы оплаты';
$_['retailcrm_dict_custom_fields'] = 'Настройка пользовательских полей'; $_['retailcrm_dict_custom_fields'] = 'Настройка пользовательских полей';
$_['retailcrm_dict_default'] = 'По умалчанию'; $_['retailcrm_dict_default'] = 'По умолчанию';
$_['retailcrm_missing_status'] = 'Статус пропавших заказов';
$_['column_total'] = 'Итого'; $_['column_total'] = 'Итого';
$_['product_summ'] = 'Сумма'; $_['product_summ'] = 'Сумма';
@ -74,4 +76,3 @@ $_['text_yes'] = 'Да';
$_['text_no'] = 'Нет'; $_['text_no'] = 'Нет';
// Errors // Errors
$_['error_permission'] = 'У вас недостаточно прав на изменение настроек модуля'; $_['error_permission'] = 'У вас недостаточно прав на изменение настроек модуля';

View File

@ -1,13 +1,33 @@
<?php <?php
class ModelExtensionRetailcrmCustomer extends Model { class ModelExtensionRetailcrmCustomer extends Model {
protected $settings;
protected $moduleTitle;
protected $retailcrmApiClient;
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();
}
/**
* Upload customers
*
* @param array $customers
*
* @return void
*/
public function uploadToCrm($customers) public function uploadToCrm($customers)
{ {
$this->initApi(); if ($this->retailcrmApiClient === false || empty($customers)) {
return;
if(empty($customers)) }
return false;
$customersToCrm = array(); $customersToCrm = array();
@ -18,25 +38,37 @@ class ModelExtensionRetailcrmCustomer extends Model {
$chunkedCustomers = array_chunk($customersToCrm, 50); $chunkedCustomers = array_chunk($customersToCrm, 50);
foreach($chunkedCustomers as $customersPart) { foreach($chunkedCustomers as $customersPart) {
$this->retailcrmApi->customersUpload($customersPart); $this->retailcrmApiClient->customersUpload($customersPart);
} }
} }
/**
* Edit customer
*
* @param array $customer
*
* @return void
*/
public function changeInCrm($customer) public function changeInCrm($customer)
{ {
$this->initApi(); if ($this->retailcrmApiClient === false || empty($customer)) {
return;
if(empty($customer)) {
return false;
} }
$customerToCrm = $this->process($customer); $customerToCrm = $this->process($customer);
$this->retailcrmApi->customersEdit($customerToCrm); $this->retailcrmApiClient->customersEdit($customerToCrm);
} }
private function process($customer) { /**
$moduleTitle = $this->getModuleTitle(); * Process customer
*
* @param array $customer
*
* @return array $customerToCrm
*/
private function process($customer)
{
$customerToCrm = array( $customerToCrm = array(
'externalId' => $customer['customer_id'], 'externalId' => $customer['customer_id'],
@ -61,12 +93,12 @@ class ModelExtensionRetailcrmCustomer extends Model {
); );
} }
if (isset($this->settings[$moduleTitle . '_custom_field']) && $customer['custom_field']) { if (isset($this->settings[$this->moduleTitle . '_custom_field']) && $customer['custom_field']) {
$customFields = json_decode($customer['custom_field']); $customFields = json_decode($customer['custom_field']);
foreach ($customFields as $key => $value) { foreach ($customFields as $key => $value) {
if (isset($this->settings[$moduleTitle . '_custom_field']['c_' . $key])) { if (isset($this->settings[$this->moduleTitle . '_custom_field']['c_' . $key])) {
$customFieldsToCrm[$this->settings[$moduleTitle . '_custom_field']['c_' . $key]] = $value; $customFieldsToCrm[$this->settings[$this->moduleTitle . '_custom_field']['c_' . $key]] = $value;
} }
} }
@ -77,34 +109,4 @@ class ModelExtensionRetailcrmCustomer extends Model {
return $customerToCrm; return $customerToCrm;
} }
protected function initApi()
{
$moduleTitle = $this->getModuleTitle();
$this->load->model('setting/setting');
$this->settings = $this->model_setting_setting->getSetting($moduleTitle);
if(empty($this->settings[$moduleTitle . '_url']) || empty($this->settings[$moduleTitle . '_apikey']))
return false;
require_once DIR_SYSTEM . 'library/retailcrm/bootstrap.php';
$this->retailcrmApi = new RetailcrmProxy(
$this->settings[$moduleTitle . '_url'],
$this->settings[$moduleTitle . '_apikey'],
DIR_SYSTEM . 'storage/logs/retailcrm.log',
$this->settings[$moduleTitle . '_apiversion']
);
}
private function getModuleTitle()
{
if (version_compare(VERSION, '3.0', '<')) {
$title = 'retailcrm';
} else {
$title = 'module_retailcrm';
}
return $title;
}
} }

View File

@ -1,10 +1,33 @@
<?php <?php
class ModelExtensionRetailcrmOrder extends Model { class ModelExtensionRetailcrmOrder extends Model {
protected $settings;
protected $moduleTitle;
protected $retailcrmApiClient;
public function uploadToCrm($orders) { public function __construct($registry)
{
parent::__construct($registry);
$this->load->model('setting/setting');
$this->load->library('retailcrm/retailcrm');
$this->initApi(); $this->moduleTitle = $this->retailcrm->getModuleTitle();
$this->settings = $this->model_setting_setting->getSetting($this->moduleTitle);
$this->retailcrmApiClient = $this->retailcrm->getApiClient();
}
/**
* Upload orders to CRM
*
* @param array $orders
*
* @return void
*/
public function uploadToCrm($orders)
{
if ($this->retailcrmApiClient === false) {
return;
}
$ordersToCrm = array(); $ordersToCrm = array();
@ -15,18 +38,28 @@ class ModelExtensionRetailcrmOrder extends Model {
$chunkedOrders = array_chunk($ordersToCrm, 50); $chunkedOrders = array_chunk($ordersToCrm, 50);
foreach($chunkedOrders as $ordersPart) { foreach($chunkedOrders as $ordersPart) {
$this->retailcrm->ordersUpload($ordersPart); $this->retailcrmApiClient->ordersUpload($ordersPart);
} }
} }
/**
* Send one order by id
*
* @param array $order_data
*
* @return object $result
*/
public function uploadOrder($order_data) public function uploadOrder($order_data)
{ {
if(isset($this->request->post['fromApi'])) return; if ($this->retailcrmApiClient === false) {
return;
}
$moduleTitle = $this->getModuleTitle(); if(isset($this->request->post['fromApi'])) {
$this->initApi(); return;
}
$customers = $this->retailcrm->customersList( $customers = $this->retailcrmApiClient->customersList(
array( array(
'name' => $order_data['telephone'], 'name' => $order_data['telephone'],
'email' => $order_data['email'] 'email' => $order_data['email']
@ -45,7 +78,7 @@ class ModelExtensionRetailcrmOrder extends Model {
unset($customers); unset($customers);
$result = $this->retailcrm->ordersCreate($order); $result = $this->retailcrmApiClient->ordersCreate($order);
if ($this->settings[$this->moduleTitle . '_apiversion'] == 'v5' && $result->isSuccessful()) { if ($this->settings[$this->moduleTitle . '_apiversion'] == 'v5' && $result->isSuccessful()) {
$this->createPayment($order_data, $order_data['order_id']); $this->createPayment($order_data, $order_data['order_id']);
@ -54,14 +87,32 @@ class ModelExtensionRetailcrmOrder extends Model {
return $result; return $result;
} }
/**
* Process order
*
* @param array $order_data
*
* @return array $order
*/
private function process($order_data) { private function process($order_data) {
$order = array(); $order = array();
$this->load->model('catalog/product'); $this->load->model('catalog/product');
$this->moduleTitle = $this->getModuleTitle();
$payment_code = $order_data['payment_code']; $payment_code = $order_data['payment_code'];
$delivery_code = $order_data['shipping_code'];
if (!empty($order_data['payment_code']) && isset($this->settings[$this->moduleTitle . '_payment'][$order_data['payment_code']])) {
$payment_code = $this->settings[$this->moduleTitle . '_payment'][$order_data['payment_code']];
} else {
$payment_code = '';
}
if (!empty($order_data['shipping_code']) && isset($this->settings[$this->moduleTitle . '_delivery'][$order_data['shipping_code']])) {
$delivery_code = $this->settings[$this->moduleTitle . '_delivery'][$order_data['shipping_code']];
} else {
$delivery_code = '';
}
$order['number'] = $order_data['order_id'];
$order['externalId'] = $order_data['order_id']; $order['externalId'] = $order_data['order_id'];
$order['firstName'] = $order_data['firstname']; $order['firstName'] = $order_data['firstname'];
$order['lastName'] = $order_data['lastname']; $order['lastName'] = $order_data['lastname'];
@ -88,14 +139,14 @@ class ModelExtensionRetailcrmOrder extends Model {
$order['createdAt'] = $order_data['date_added']; $order['createdAt'] = $order_data['date_added'];
if ($this->settings[$this->moduleTitle . '_apiversion'] != 'v5') { if ($this->settings[$this->moduleTitle . '_apiversion'] != 'v5') {
$order['paymentType'] = $this->settings[$this->moduleTitle . '_payment'][$payment_code]; $order['paymentType'] = $payment_code;
} }
$country = (isset($order_data['shipping_country'])) ? $order_data['shipping_country'] : '' ; $country = (isset($order_data['shipping_country'])) ? $order_data['shipping_country'] : '' ;
$order['delivery'] = array( $order['delivery'] = array(
'code' => !empty($delivery_code) ? $this->settings[$this->moduleTitle . '_delivery'][$delivery_code] : '', 'code' => $delivery_code,
'cost' => $deliveryCost, 'cost' => $deliveryCost,
'address' => array( 'address' => array(
'index' => $order_data['shipping_postcode'], 'index' => $order_data['shipping_postcode'],
@ -179,6 +230,17 @@ class ModelExtensionRetailcrmOrder extends Model {
$order['status'] = $this->settings[$this->moduleTitle . '_status'][$order_data['order_status_id']]; $order['status'] = $this->settings[$this->moduleTitle . '_status'][$order_data['order_status_id']];
} }
if ($this->settings[$this->moduleTitle . '_apiversion'] == 'v5') {
if ($payment_code) {
$payment = array(
'externalId' => $order_data['order_id'],
'type' => $payment_code
);
$order['payments'][] = $payment;
}
}
if (isset($this->settings[$this->moduleTitle . '_custom_field']) && $order_data['custom_field']) { if (isset($this->settings[$this->moduleTitle . '_custom_field']) && $order_data['custom_field']) {
$customFields = json_decode($order_data['custom_field']); $customFields = json_decode($order_data['custom_field']);
@ -196,14 +258,22 @@ class ModelExtensionRetailcrmOrder extends Model {
return $order; return $order;
} }
/**
* Create payment
*
* @param array $order
* @param int $order_id
*
* @return void
*/
protected function createPayment($order, $order_id) protected function createPayment($order, $order_id)
{ {
$this->moduleTitle = $this->getModuleTitle();
$payment_code = $order['payment_code']; $payment_code = $order['payment_code'];
foreach ($order['totals'] as $total) { foreach ($order['totals'] as $total) {
if ($total['code'] == 'total') $amount = $total['value']; if ($total['code'] == 'total') {
$amount = $total['value'];
}
} }
$payment = array( $payment = array(
@ -216,36 +286,6 @@ class ModelExtensionRetailcrmOrder extends Model {
'externalId' => $order_id 'externalId' => $order_id
); );
$this->retailcrm->ordersPaymentCreate($payment); $this->retailcrmApiClient->ordersPaymentCreate($payment);
}
private function initApi()
{
$moduleTitle = $this->getModuleTitle();
$this->load->model('setting/setting');
$this->settings = $this->model_setting_setting->getSetting($moduleTitle);
if(!empty($this->settings[$moduleTitle . '_url']) && !empty($this->settings[$moduleTitle . '_apikey'])) {
require_once DIR_SYSTEM . 'library/retailcrm/bootstrap.php';
$this->retailcrm = new RetailcrmProxy(
$this->settings[$moduleTitle . '_url'],
$this->settings[$moduleTitle . '_apikey'],
DIR_SYSTEM . 'storage/logs/retailcrm.log',
$this->settings[$moduleTitle . '_apiversion']
);
}
}
private function getModuleTitle()
{
if (version_compare(VERSION, '3.0', '<')) {
$title = 'retailcrm';
} else {
$title = 'module_retailcrm';
}
return $title;
} }
} }

View File

@ -1,16 +1,26 @@
<?php <?php
require_once DIR_SYSTEM . 'library/retailcrm/bootstrap.php'; class ModelExtensionRetailcrmReferences extends Model {
protected $settings;
class ModelExtensionRetailcrmReferences extends Model protected $moduleTitle;
{ protected $retailcrmApiClient;
protected $retailcrm;
private $opencartApiClient; 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();
}
public function getOpercartDeliveryTypes() public function getOpercartDeliveryTypes()
{ {
$this->load->model('user/api'); $this->opencartApiClient = $this->retailcrm->getOcApiClient($this->registry);
$this->opencartApiClient = new OpencartApiClient($this->registry);
return $this->opencartApiClient->request('retailcrm/getDeliveryTypes', array(), array()); return $this->opencartApiClient->request('retailcrm/getDeliveryTypes', array(), array());
} }
@ -94,37 +104,29 @@ class ModelExtensionRetailcrmReferences extends Model
public function getApiDeliveryTypes() public function getApiDeliveryTypes()
{ {
$this->initApi(); $response = $this->retailcrmApiClient->deliveryTypesList();
$response = $this->retailcrm->deliveryTypesList();
return (!$response->isSuccessful()) ? array() : $response->deliveryTypes; return (!$response->isSuccessful()) ? array() : $response->deliveryTypes;
} }
public function getApiOrderStatuses() public function getApiOrderStatuses()
{ {
$this->initApi(); $response = $this->retailcrmApiClient->statusesList();
$response = $this->retailcrm->statusesList();
return (!$response->isSuccessful()) ? array() : $response->statuses; return (!$response->isSuccessful()) ? array() : $response->statuses;
} }
public function getApiPaymentTypes() public function getApiPaymentTypes()
{ {
$this->initApi(); $response = $this->retailcrmApiClient->paymentTypesList();
$response = $this->retailcrm->paymentTypesList();
return (!$response->isSuccessful()) ? array() : $response->paymentTypes; return (!$response->isSuccessful()) ? array() : $response->paymentTypes;
} }
public function getApiCustomFields() public function getApiCustomFields()
{ {
$this->initApi(); $customers = $this->retailcrmApiClient->customFieldsList(array('entity' => 'customer'));
$orders = $this->retailcrmApiClient->customFieldsList(array('entity' => 'order'));
$customers = $this->retailcrm->customFieldsList(array('entity' => 'customer'));
$orders = $this->retailcrm->customFieldsList(array('entity' => 'order'));
$customFieldsCustomers = (!$customers->isSuccessful()) ? array() : $customers->customFields; $customFieldsCustomers = (!$customers->isSuccessful()) ? array() : $customers->customFields;
$customFieldsOrders = (!$orders->isSuccessful()) ? array() : $orders->customFields; $customFieldsOrders = (!$orders->isSuccessful()) ? array() : $orders->customFields;
@ -135,31 +137,4 @@ class ModelExtensionRetailcrmReferences extends Model
return array('customers' => $customFieldsCustomers, 'orders' => $customFieldsOrders); return array('customers' => $customFieldsCustomers, 'orders' => $customFieldsOrders);
} }
protected function initApi()
{
$moduleTitle = $this->getModuleTitle();
$this->load->model('setting/setting');
$settings = $this->model_setting_setting->getSetting($moduleTitle);
if(!empty($settings[$moduleTitle . '_url']) && !empty($settings[$moduleTitle . '_apikey'])) {
$this->retailcrm = new RetailcrmProxy(
$settings[$moduleTitle . '_url'],
$settings[$moduleTitle . '_apikey'],
DIR_SYSTEM . 'storage/logs/retailcrm.log',
$settings[$moduleTitle . '_apiversion']
);
}
}
private function getModuleTitle()
{
if (version_compare(VERSION, '3.0', '<')) {
$title = 'retailcrm';
} else {
$title = 'module_retailcrm';
}
return $title;
}
} }

View File

@ -104,6 +104,7 @@
<h3><?php echo $retailcrm_dict_settings; ?></h3> <h3><?php echo $retailcrm_dict_settings; ?></h3>
<h4><?php echo $retailcrm_dict_delivery; ?></h4> <h4><?php echo $retailcrm_dict_delivery; ?></h4>
<?php if ($delivery['opencart']) :?>
<?php foreach($delivery['opencart'] as $value): ?> <?php foreach($delivery['opencart'] as $value): ?>
<div class="pm"><?php echo $value['title'].':'; ?></div> <div class="pm"><?php echo $value['title'].':'; ?></div>
@ -121,7 +122,12 @@
</div> </div>
<?php endforeach; ?> <?php endforeach; ?>
<?php endforeach; ?> <?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; ?>
<h4><?php echo $retailcrm_dict_status; ?></h4> <h4><?php echo $retailcrm_dict_status; ?></h4>
<?php foreach ($statuses['opencart'] as $status): ?> <?php foreach ($statuses['opencart'] as $status): ?>
<?php $uid = $status['order_status_id']?> <?php $uid = $status['order_status_id']?>
@ -176,6 +182,17 @@
</select> </select>
<label for="retailcrm_default_payment"><?php echo $text_shipping; ?></label> <label for="retailcrm_default_payment"><?php echo $text_shipping; ?></label>
</div> </div>
<h4><?php echo $retailcrm_missing_status; ?></h4>
<div class="retailcrm_unit">
<select id="retailcrm_missing_status" name="retailcrm_missing_status">
<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>
<?php endif; ?> <?php endif; ?>
<?php endif; ?> <?php endif; ?>

View File

@ -176,7 +176,18 @@
</optgroup> </optgroup>
{% endfor %} {% endfor %}
</select> </select>
<label for="module_retailcrm_default_payment">{{ text_shipping }}</label> <label for="module_retailcrm_default_shipping">{{ text_shipping }}</label>
</div>
<h4>{{ retailcrm_missing_status }}</h4>
<div class="retailcrm_unit">
<select id="retailcrm_missing_status" name="retailcrm_missing_status">
<option></option>
{% for k, v in statuses.retailcrm %}
<option value="{{ k }}" {% if saved_settings.retailcrm_missing_status is defined and k == saved_settings.retailcrm_missing_status %} selected="selected" {% endif %}>
{{ v.name }}
</option>
{% endfor %}
</select>
</div> </div>
{% endif %} {% endif %}

View File

@ -5,7 +5,8 @@ class ControllerApiRetailcrm extends Controller
{ {
$this->load->model('localisation/country'); $this->load->model('localisation/country');
$this->load->model('setting/setting'); $this->load->model('setting/setting');
$moduleTitle = $this->getModuleTitle(); $this->load->library('retailcrm/retailcrm');
$moduleTitle = $this->retailcrm->getModuleTitle();
$countries = $this->model_setting_setting->getSetting($moduleTitle)[$moduleTitle . '_country']; $countries = $this->model_setting_setting->getSetting($moduleTitle)[$moduleTitle . '_country'];
$deliveryTypes = array(); $deliveryTypes = array();
@ -96,15 +97,4 @@ class ControllerApiRetailcrm extends Controller
$this->modelExtension = 'setting_extension'; $this->modelExtension = 'setting_extension';
} }
} }
private function getModuleTitle()
{
if (version_compare(VERSION, '3.0', '<')) {
$title = 'retailcrm';
} else {
$title = 'module_retailcrm';
}
return $title;
}
} }

View File

@ -2,7 +2,8 @@
class ControllerExtensionAnalyticsDaemonCollector extends Controller { class ControllerExtensionAnalyticsDaemonCollector extends Controller {
public function index() { public function index() {
$this->load->model('setting/setting'); $this->load->model('setting/setting');
$moduleTitle = $this->getModuleTitle(); $this->load->library('retailcrm/retailcrm');
$moduleTitle = $this->retailcrm->getModuleTitle();
$settings = $this->model_setting_setting->getSetting($moduleTitle); $settings = $this->model_setting_setting->getSetting($moduleTitle);
$setting = $settings[$moduleTitle . '_collector']; $setting = $settings[$moduleTitle . '_collector'];
@ -87,15 +88,4 @@ class ControllerExtensionAnalyticsDaemonCollector extends Controller {
return html_entity_decode($js, ENT_QUOTES, 'UTF-8'); return html_entity_decode($js, ENT_QUOTES, 'UTF-8');
} }
private function getModuleTitle()
{
if (version_compare(VERSION, '3.0', '<')) {
$title = 'retailcrm';
} else {
$title = 'module_retailcrm';
}
return $title;
}
} }

View File

@ -20,12 +20,12 @@ class ControllerExtensionModuleRetailcrm extends Controller
*/ */
public function order_create($parameter1, $parameter2 = null, $parameter3 = null) public function order_create($parameter1, $parameter2 = null, $parameter3 = null)
{ {
$moduleTitle = $this->getModuleTitle();
$this->load->model('checkout/order'); $this->load->model('checkout/order');
$this->load->model('account/order'); $this->load->model('account/order');
$this->load->library('retailcrm/retailcrm');
$moduleTitle = $this->retailcrm->getModuleTitle();
$order_id = $parameter3; $order_id = $parameter3;
$data = $this->model_checkout_order->getOrder($order_id); $data = $this->model_checkout_order->getOrder($order_id);
$data['totals'] = $this->model_account_order->getOrderTotals($order_id); $data['totals'] = $this->model_account_order->getOrderTotals($order_id);
@ -62,12 +62,13 @@ class ControllerExtensionModuleRetailcrm extends Controller
* @return void * @return void
*/ */
public function order_edit($parameter1, $parameter2 = null) { public function order_edit($parameter1, $parameter2 = null) {
$moduleTitle = $this->getModuleTitle();
$order_id = $parameter2[0]; $order_id = $parameter2[0];
$this->load->model('checkout/order'); $this->load->model('checkout/order');
$this->load->model('account/order'); $this->load->model('account/order');
$this->load->library('retailcrm/retailcrm');
$moduleTitle = $this->retailcrm->getModuleTitle();
$data = $this->model_checkout_order->getOrder($order_id); $data = $this->model_checkout_order->getOrder($order_id);
if($data['order_status_id'] == 0) return; if($data['order_status_id'] == 0) return;
@ -162,15 +163,4 @@ class ControllerExtensionModuleRetailcrm extends Controller
$this->model_extension_retailcrm_customer->changeInCrm($customer); $this->model_extension_retailcrm_customer->changeInCrm($customer);
} }
} }
private function getModuleTitle()
{
if (version_compare(VERSION, '3.0', '<')) {
$title = 'retailcrm';
} else {
$title = 'module_retailcrm';
}
return $title;
}
} }

View File

@ -1,33 +1,65 @@
<?php <?php
class ModelExtensionRetailcrmCustomer extends Model { class ModelExtensionRetailcrmCustomer extends Model {
protected $settings;
protected $moduleTitle;
protected $retailcrmApiClient;
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();
}
/**
* Create customer
*
* @param array $customer
*
* @return void
*/
public function sendToCrm($customer) public function sendToCrm($customer)
{ {
$this->initApi(); if(empty($customer) || $this->retailcrmApiClient === false) {
if(empty($customer))
return false; return false;
}
$customerToCrm = $this->process($customer); $customerToCrm = $this->process($customer);
$this->retailcrmApi->customersCreate($customerToCrm); $this->retailcrmApiClient->customersCreate($customerToCrm);
} }
/**
* Edit customer
*
* @param array $customer
*
* @return void
*/
public function changeInCrm($customer) public function changeInCrm($customer)
{ {
$this->initApi(); if(empty($customer) || $this->retailcrmApiClient === false) {
if(empty($customer))
return false; return false;
}
$customerToCrm = $this->process($customer); $customerToCrm = $this->process($customer);
$this->retailcrmApi->customersEdit($customerToCrm); $this->retailcrmApiClient->customersEdit($customerToCrm);
} }
/**
* Process customer
*
* @param array $customer
*
* @return array $customerToCrm
*/
private function process($customer) { private function process($customer) {
$moduleTitle = $this->getModuleTitle();
$customerToCrm = array( $customerToCrm = array(
'externalId' => $customer['customer_id'], 'externalId' => $customer['customer_id'],
'firstName' => $customer['firstname'], 'firstName' => $customer['firstname'],
@ -51,12 +83,12 @@ class ModelExtensionRetailcrmCustomer extends Model {
); );
} }
if (isset($this->settings[$moduleTitle . '_custom_field']) && $customer['custom_field']) { if (isset($this->settings[$this->moduleTitle . '_custom_field']) && $customer['custom_field']) {
$customFields = json_decode($customer['custom_field']); $customFields = json_decode($customer['custom_field']);
foreach ($customFields as $key => $value) { foreach ($customFields as $key => $value) {
if (isset($this->settings[$moduleTitle . '_custom_field']['c_' . $key])) { if (isset($this->settings[$this->moduleTitle . '_custom_field']['c_' . $key])) {
$customFieldsToCrm[$this->settings[$moduleTitle . '_custom_field']['c_' . $key]] = $value; $customFieldsToCrm[$this->settings[$this->moduleTitle . '_custom_field']['c_' . $key]] = $value;
} }
} }
@ -67,34 +99,4 @@ class ModelExtensionRetailcrmCustomer extends Model {
return $customerToCrm; return $customerToCrm;
} }
protected function initApi()
{
$this->load->model('setting/setting');
$moduleTitle = $this->getModuleTitle();
$this->settings = $this->model_setting_setting->getSetting($moduleTitle);
if(empty($this->settings[$moduleTitle . '_url']) || empty($this->settings[$moduleTitle . '_apikey']))
return false;
require_once DIR_SYSTEM . 'library/retailcrm/bootstrap.php';
$this->retailcrmApi = new RetailcrmProxy(
$this->settings[$moduleTitle . '_url'],
$this->settings[$moduleTitle . '_apikey'],
DIR_SYSTEM . 'storage/logs/retailcrm.log',
$this->settings[$moduleTitle . '_apiversion']
);
}
private function getModuleTitle()
{
if (version_compare(VERSION, '3.0', '<')) {
$title = 'retailcrm';
} else {
$title = 'module_retailcrm';
}
return $title;
}
} }

View File

@ -1,16 +1,38 @@
<?php <?php
class ModelExtensionRetailcrmOrder extends Model { class ModelExtensionRetailcrmOrder extends Model {
protected $settings;
protected $moduleTitle;
protected $retailcrmApiClient;
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();
}
/**
* Create order in CRM
*
* @param array $order_data
* @param int $order_id
*
* @return void
*/
public function sendToCrm($order_data, $order_id) public function sendToCrm($order_data, $order_id)
{ {
if(isset($this->request->post['fromApi'])) return; if(isset($this->request->post['fromApi']) || $this->retailcrmApiClient === false) {
return;
$this->initApi(); }
$order = $this->processOrder($order_data, $order_id); $order = $this->processOrder($order_data, $order_id);
$customers = $this->retailcrm->customersList( $customers = $this->retailcrmApiClient->customersList(
array( array(
'name' => $order_data['telephone'], 'name' => $order_data['telephone'],
'email' => $order_data['email'] 'email' => $order_data['email']
@ -27,22 +49,30 @@ class ModelExtensionRetailcrmOrder extends Model {
unset($customers); unset($customers);
$response = $this->retailcrm->ordersCreate($order); $response = $this->retailcrmApiClient->ordersCreate($order);
if ($this->settings[$this->moduleTitle . '_apiversion'] == 'v5' && $response->isSuccessful()) { if ($this->settings[$this->moduleTitle . '_apiversion'] == 'v5' && $response->isSuccessful()) {
$this->createPayment($order_data, $order_id); $this->createPayment($order_data, $order_id);
} }
} }
/**
* Edit order in CRM
*
* @param array $order_data
* @param int $order_id
*
* @return void
*/
public function changeInCrm($order_data, $order_id) public function changeInCrm($order_data, $order_id)
{ {
if(isset($this->request->post['fromApi'])) return; if(isset($this->request->post['fromApi']) || $this->retailcrmApiClient === false) {
return;
$this->initApi(); }
$order = $this->processOrder($order_data, $order_id); $order = $this->processOrder($order_data, $order_id);
$customers = $this->retailcrm->customersList( $customers = $this->retailcrmApiClient->customersList(
array( array(
'name' => $order_data['telephone'], 'name' => $order_data['telephone'],
'email' => $order_data['email'] 'email' => $order_data['email']
@ -59,10 +89,10 @@ class ModelExtensionRetailcrmOrder extends Model {
unset($customers); unset($customers);
$response = $this->retailcrm->ordersEdit($order); $response = $this->retailcrmApiClient->ordersEdit($order);
if ($this->settings[$this->moduleTitle . '_apiversion'] == 'v5' && $response->isSuccessful()) { if ($this->settings[$this->moduleTitle . '_apiversion'] == 'v5' && $response->isSuccessful()) {
$response_order = $this->retailcrm->ordersGet($order_id); $response_order = $this->retailcrmApiClient->ordersGet($order_id);
if ($response_order->isSuccessful()) { if ($response_order->isSuccessful()) {
$order_info = $response_order['order']; $order_info = $response_order['order'];
} }
@ -74,7 +104,7 @@ class ModelExtensionRetailcrmOrder extends Model {
} }
if (isset($payment) && $payment['type'] != $this->settings[$this->moduleTitle . '_payment'][$order_data['payment_code']]) { if (isset($payment) && $payment['type'] != $this->settings[$this->moduleTitle . '_payment'][$order_data['payment_code']]) {
$response = $this->retailcrm->ordersPaymentDelete($payment['id']); $response = $this->retailcrmApiClient->ordersPaymentDelete($payment['id']);
if ($response->isSuccessful()) { if ($response->isSuccessful()) {
$this->createPayment($order_data, $order_id); $this->createPayment($order_data, $order_id);
@ -85,14 +115,33 @@ class ModelExtensionRetailcrmOrder extends Model {
} }
} }
/**
* Process order
*
* @param array $order_data
* @param int $order_id
*
* @return array $order
*/
protected function processOrder($order_data, $order_id) protected function processOrder($order_data, $order_id)
{ {
$this->moduleTitle = $this->getModuleTitle();
$this->load->model('setting/setting'); $this->load->model('setting/setting');
$this->load->model('catalog/product'); $this->load->model('catalog/product');
$this->settings = $this->model_setting_setting->getSetting($this->moduleTitle); $this->settings = $this->model_setting_setting->getSetting($this->moduleTitle);
$payment_code = $order_data['payment_code']; if (!empty($order_data['payment_code']) && isset($this->settings[$this->moduleTitle . '_payment'][$order_data['payment_code']])) {
$payment_code = $this->settings[$this->moduleTitle . '_payment'][$order_data['payment_code']];
} else {
$payment_code = '';
}
if (!empty($order_data['shipping_code']) && isset($this->settings[$this->moduleTitle . '_delivery'][$order_data['shipping_code']])) {
$delivery_code = $this->settings[$this->moduleTitle . '_delivery'][$order_data['shipping_code']];
} else {
$delivery_code = '';
}
$order['number'] = $order_data['order_id'];
$order['externalId'] = $order_id; $order['externalId'] = $order_id;
$order['firstName'] = $order_data['firstname']; $order['firstName'] = $order_data['firstname'];
$order['lastName'] = $order_data['lastname']; $order['lastName'] = $order_data['lastname'];
@ -119,7 +168,7 @@ class ModelExtensionRetailcrmOrder extends Model {
$order['createdAt'] = $order_data['date_added']; $order['createdAt'] = $order_data['date_added'];
if ($this->settings[$this->moduleTitle . '_apiversion'] != 'v5') { if ($this->settings[$this->moduleTitle . '_apiversion'] != 'v5') {
$order['paymentType'] = $this->settings[$this->moduleTitle . '_payment'][$payment_code]; $order['paymentType'] = $payment_code;
if (isset($couponTotal)) $order['discount'] = $couponTotal; if (isset($couponTotal)) $order['discount'] = $couponTotal;
} else { } else {
if (isset($couponTotal)) $order['discountManualAmount'] = $couponTotal; if (isset($couponTotal)) $order['discountManualAmount'] = $couponTotal;
@ -127,14 +176,8 @@ class ModelExtensionRetailcrmOrder extends Model {
$country = (isset($order_data['shipping_country'])) ? $order_data['shipping_country'] : '' ; $country = (isset($order_data['shipping_country'])) ? $order_data['shipping_country'] : '' ;
if(isset($this->settings[$this->moduleTitle . '_delivery'][$order_data['shipping_code']])) {
$delivery_code = $order_data['shipping_code'];
} else {
$delivery_code = stristr($order_data['shipping_code'], '.', TRUE);
}
$order['delivery'] = array( $order['delivery'] = array(
'code' => !empty($delivery_code) ? $this->settings[$this->moduleTitle . '_delivery'][$delivery_code] : '', 'code' => $delivery_code,
'address' => array( 'address' => array(
'index' => $order_data['shipping_postcode'], 'index' => $order_data['shipping_postcode'],
'city' => $order_data['shipping_city'], 'city' => $order_data['shipping_city'],
@ -219,6 +262,8 @@ class ModelExtensionRetailcrmOrder extends Model {
if (isset($order_data['order_status_id']) && $order_data['order_status_id'] > 0) { if (isset($order_data['order_status_id']) && $order_data['order_status_id'] > 0) {
$order['status'] = $this->settings[$this->moduleTitle . '_status'][$order_data['order_status_id']]; $order['status'] = $this->settings[$this->moduleTitle . '_status'][$order_data['order_status_id']];
} elseif (isset($order_data['order_status_id']) && $order_data['order_status_id'] == 0) {
$order['status'] = $this->settings[$this->moduleTitle . '_missing_status'];
} }
if (isset($this->settings[$this->moduleTitle . '_custom_field']) && $order_data['custom_field']) { if (isset($this->settings[$this->moduleTitle . '_custom_field']) && $order_data['custom_field']) {
@ -239,12 +284,22 @@ class ModelExtensionRetailcrmOrder extends Model {
return $order; return $order;
} }
/**
* Create payment
*
* @param array $order
* @param int $order_id
*
* @return void
*/
protected function createPayment($order, $order_id) protected function createPayment($order, $order_id)
{ {
$payment_code = $order['payment_code']; $payment_code = $order['payment_code'];
foreach ($order['totals'] as $total) { foreach ($order['totals'] as $total) {
if ($total['code'] == 'total') $amount = $total['value']; if ($total['code'] == 'total') {
$amount = $total['value'];
}
} }
$payment = array( $payment = array(
@ -257,9 +312,17 @@ class ModelExtensionRetailcrmOrder extends Model {
'externalId' => $order_id 'externalId' => $order_id
); );
$this->retailcrm->ordersPaymentCreate($payment); $this->retailcrmApiClient->ordersPaymentCreate($payment);
} }
/**
* Edit payment
*
* @param array $order
* @param int $order_id
*
* @return void
*/
protected function editPayment($order, $order_id) protected function editPayment($order, $order_id)
{ {
$payment_code = $order['payment_code']; $payment_code = $order['payment_code'];
@ -276,37 +339,6 @@ class ModelExtensionRetailcrmOrder extends Model {
'amount' => $amount 'amount' => $amount
); );
$this->retailcrm->ordersPaymentEdit($payment); $this->retailcrmApiClient->ordersPaymentEdit($payment);
}
private function initApi()
{
$moduleTitle = $this->getModuleTitle();
$this->load->model('setting/setting');
$settings = $this->model_setting_setting->getSetting($moduleTitle);
if(!empty($settings[$moduleTitle . '_url']) && !empty($settings[$moduleTitle . '_apikey'])) {
require_once DIR_SYSTEM . 'library/retailcrm/bootstrap.php';
$this->retailcrm = new RetailcrmProxy(
$settings[$moduleTitle . '_url'],
$settings[$moduleTitle . '_apikey'],
DIR_SYSTEM . 'storage/logs/retailcrm.log',
$settings[$moduleTitle . '_apiversion']
);
} }
} }
private function getModuleTitle()
{
if (version_compare(VERSION, '3.0', '<')) {
$title = 'retailcrm';
} else {
$title = 'module_retailcrm';
}
return $title;
}
}

View File

@ -89,6 +89,10 @@ class OpencartApiClient {
curl_close($curl); curl_close($curl);
if (!$json && json_last_error() !== JSON_ERROR_NONE) {
return false;
}
if (isset($json['error'])) { if (isset($json['error'])) {
if (is_array($json['error'])) { if (is_array($json['error'])) {
foreach ($json['error'] as $error) { foreach ($json['error'] as $error) {
@ -103,6 +107,8 @@ class OpencartApiClient {
} }
private function auth() { private function auth() {
$this->load->model('user/api');
$apiUsers = $this->model_user_api->getApis(); $apiUsers = $this->model_user_api->getApis();
$api = array(); $api = array();

View File

@ -41,12 +41,20 @@ class RetailcrmHistoryHelper {
$orders[$change['order']['id']]['items'][$change['item']['id']] = $change['item']; $orders[$change['order']['id']]['items'][$change['item']['id']] = $change['item'];
} }
if(empty($change['oldValue']) && $change['field'] == 'order_product') { if (isset($change['oldValue'])
&& empty($change['oldValue'])
&& $change['field'] == 'order_product'
) {
$orders[$change['order']['id']]['items'][$change['item']['id']]['create'] = true; $orders[$change['order']['id']]['items'][$change['item']['id']]['create'] = true;
} }
if(empty($change['newValue']) && $change['field'] == 'order_product') {
if (isset($change['newValue'])
&& empty($change['newValue'])
&& $change['field'] == 'order_product'
) {
$orders[$change['order']['id']]['items'][$change['item']['id']]['delete'] = true; $orders[$change['order']['id']]['items'][$change['item']['id']]['delete'] = true;
} }
if (!isset($orders[$change['order']['id']]['items'][$change['item']['id']]['create']) && $fields['item'][$change['field']]) { if (!isset($orders[$change['order']['id']]['items'][$change['item']['id']]['create']) && $fields['item'][$change['field']]) {
$orders[$change['order']['id']]['items'][$change['item']['id']][$fields['item'][$change['field']]] = $change['newValue']; $orders[$change['order']['id']]['items'][$change['item']['id']][$fields['item'][$change['field']]] = $change['newValue'];
} }
@ -63,7 +71,7 @@ class RetailcrmHistoryHelper {
$orders[$change['order']['id']][$fields['customerContragent'][$change['field']]] = self::newValue($change['newValue']); $orders[$change['order']['id']][$fields['customerContragent'][$change['field']]] = self::newValue($change['newValue']);
} elseif(strripos($change['field'], 'custom_') !== false) { } elseif(strripos($change['field'], 'custom_') !== false) {
$orders[$change['order']['id']]['customFields'][str_replace('custom_', '', $change['field'])] = self::newValue($change['newValue']); $orders[$change['order']['id']]['customFields'][str_replace('custom_', '', $change['field'])] = self::newValue($change['newValue']);
} elseif($fields['order'][$change['field']]) { } elseif(isset($fields['order'][$change['field']]) && $fields['order'][$change['field']]) {
$orders[$change['order']['id']][$fields['order'][$change['field']]] = self::newValue($change['newValue']); $orders[$change['order']['id']][$fields['order'][$change['field']]] = self::newValue($change['newValue']);
} }

View File

@ -81,7 +81,6 @@ class RetailcrmHttpClient
$curlHandler = curl_init(); $curlHandler = curl_init();
curl_setopt($curlHandler, CURLOPT_URL, $url); curl_setopt($curlHandler, CURLOPT_URL, $url);
curl_setopt($curlHandler, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curlHandler, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curlHandler, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curlHandler, CURLOPT_FAILONERROR, false); curl_setopt($curlHandler, CURLOPT_FAILONERROR, false);
curl_setopt($curlHandler, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curlHandler, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curlHandler, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($curlHandler, CURLOPT_SSL_VERIFYHOST, false);

View File

@ -0,0 +1,92 @@
<?php
namespace retailcrm;
require_once 'bootstrap.php';
class Retailcrm {
protected $apiClient;
protected $registry;
public function __construct($registry)
{
$this->registry = $registry;
}
public function __get($name) {
return $this->registry->get($name);
}
/**
* Get api client object
*
* @param string $apiUrl (default = null)
* @param string $apiKey (default = null)
* @param string $apiVersion (default = null)
*
* @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());
if ($apiUrl === null && $apiKey === null) {
$apiUrl = $setting[$this->getModuleTitle() . '_url'];
$apiKey = $setting[$this->getModuleTitle() . '_apikey'];
$apiVersion = $setting[$this->getModuleTitle() . '_apiversion'];
}
if ($apiUrl && $apiKey) {
$this->apiClient = new \RetailcrmProxy($apiUrl, $apiKey, DIR_LOGS . 'retailcrm.log', $apiVersion);
return $this->apiClient;
}
return false;
}
/**
* Get opencart api client
*
* @param object $registry
*
* @return \OpencartApiClient
*/
public function getOcApiClient($registry)
{
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;
}
}