Bug fix, error logs in admin interface (#63)

This commit is contained in:
Akolzin Dmitry 2017-11-17 16:32:18 +03:00 committed by GitHub
parent 51404a5533
commit 9535f2de8e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 230 additions and 28 deletions

View File

@ -166,7 +166,9 @@ class ControllerExtensionModuleRetailcrm extends Controller
$this->request->post[$moduleTitle . '_url'] = 'https://'.$crm_url; $this->request->post[$moduleTitle . '_url'] = 'https://'.$crm_url;
} }
if ($this->request->post[$moduleTitle . '_custom_field_active'] == 0) { if (isset($this->request->post[$moduleTitle . '_custom_field_active']) &&
$this->request->post[$moduleTitle . '_custom_field_active'] == 0
) {
unset($this->request->post[$moduleTitle . '_custom_field']); unset($this->request->post[$moduleTitle . '_custom_field']);
} }
@ -190,8 +192,8 @@ class ControllerExtensionModuleRetailcrm extends Controller
$ordersHistory = $api->ordersHistory(array(), $ordersHistory['pagination']['totalPageCount']); $ordersHistory = $api->ordersHistory(array(), $ordersHistory['pagination']['totalPageCount']);
if ($ordersHistory->isSuccessful()) { if ($ordersHistory->isSuccessful()) {
$ordersHistoryArr = $ordersHistory['history'];
$lastChangeOrders = end($ordersHistory['history']); $lastChangeOrders = end($ordersHistoryArr);
$sinceIdOrders = $lastChangeOrders['id']; $sinceIdOrders = $lastChangeOrders['id'];
$generatedAt = $ordersHistory['generatedAt']; $generatedAt = $ordersHistory['generatedAt'];
} }
@ -203,7 +205,8 @@ class ControllerExtensionModuleRetailcrm extends Controller
$customersHistory = $api->customersHistory(array(), $customersHistory['pagination']['totalPageCount']); $customersHistory = $api->customersHistory(array(), $customersHistory['pagination']['totalPageCount']);
if ($customersHistory->isSuccessful()) { if ($customersHistory->isSuccessful()) {
$lastChangeCustomers = end($customersHistory['history']); $customersHistoryArr = $customersHistory['history'];
$lastChangeCustomers = end($customersHistoryArr);
$sinceIdCustomers = $lastChangeCustomers['id']; $sinceIdCustomers = $lastChangeCustomers['id'];
} }
} }
@ -258,6 +261,7 @@ class ControllerExtensionModuleRetailcrm extends Controller
'general_tab_text', 'general_tab_text',
'references_tab_text', 'references_tab_text',
'collector_tab_text', 'collector_tab_text',
'logs_tab_text',
'text_yes', 'text_yes',
'text_no', 'text_no',
'collector_site_key', 'collector_site_key',
@ -278,7 +282,8 @@ class ControllerExtensionModuleRetailcrm extends Controller
'retailcrm_dict_default', 'retailcrm_dict_default',
'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'
); );
$_data = &$data; $_data = &$data;
@ -414,6 +419,25 @@ class ControllerExtensionModuleRetailcrm extends Controller
$_data['api_versions'] = array('v3', 'v4', 'v5'); $_data['api_versions'] = array('v3', 'v4', 'v5');
$_data['default_apiversion'] = 'v4'; $_data['default_apiversion'] = 'v4';
$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);
} else {
$_data['logs']['retailcrm_error'] = $this->language->get('text_error_log');
}
if ($this->checkLogFile($ocApiLog) !== false) {
$_data['logs']['oc_api_log'] = $this->checkLogFile($ocApiLog);
} else {
$_data['logs']['oc_error'] = $this->language->get('text_error_log');
}
$_data['clear_retailcrm'] = $this->url->link('extension/module/retailcrm/clear_retailcrm', $tokenTitle . '=' . $this->session->data[$tokenTitle], true);
$_data['clear_opencart'] = $this->url->link('extension/module/retailcrm/clear_opencart', $tokenTitle . '=' . $this->session->data[$tokenTitle], true);
$_data['button_clear'] = $this->language->get('button_clear');
$this->response->setOutput( $this->response->setOutput(
$this->load->view('extension/module/retailcrm', $_data) $this->load->view('extension/module/retailcrm', $_data)
); );
@ -578,7 +602,7 @@ class ControllerExtensionModuleRetailcrm extends Controller
/** /**
* Export orders * Export orders
* *
* * @return void
*/ */
public function export() { public function export() {
@ -665,6 +689,51 @@ class ControllerExtensionModuleRetailcrm extends Controller
} }
} }
/**
* Clear retailcrm log file
*
* @return void
*/
public function clear_retailcrm()
{
$tokenTitle = $this->getTokenTitle();
if ($this->user->hasPermission('modify', 'extension/module/retailcrm')) {
$file = DIR_LOGS . 'retailcrm.log';
$handle = fopen($file, 'w+');
fclose($handle);
}
$this->response->redirect($this->url->link('extension/module/retailcrm', $tokenTitle . '=' . $this->session->data[$tokenTitle], true));
}
/**
* Clear opencart API log file
*
* @return void
*/
public function clear_opencart()
{
$tokenTitle = $this->getTokenTitle();
if ($this->user->hasPermission('modify', 'extension/module/retailcrm')) {
$file = DIR_LOGS . 'opencartapi.log';
$handle = fopen($file, 'w+');
fclose($handle);
}
$this->response->redirect($this->url->link('extension/module/retailcrm', $tokenTitle . '=' . $this->session->data[$tokenTitle], true));
}
/**
* Method for load modelds
*
* @return void
*/
private function loadModels() private function loadModels()
{ {
if (version_compare(VERSION, '3.0', '<')) { if (version_compare(VERSION, '3.0', '<')) {
@ -686,6 +755,11 @@ class ControllerExtensionModuleRetailcrm extends Controller
} }
} }
/**
* Get token param name
*
* @return string
*/
private function getTokenTitle() private function getTokenTitle()
{ {
if (version_compare(VERSION, '3.0', '<')) { if (version_compare(VERSION, '3.0', '<')) {
@ -697,6 +771,11 @@ class ControllerExtensionModuleRetailcrm extends Controller
return $token; return $token;
} }
/**
* Get module name
*
* @return string
*/
private function getModuleTitle() private function getModuleTitle()
{ {
if (version_compare(VERSION, '3.0', '<')) { if (version_compare(VERSION, '3.0', '<')) {
@ -708,6 +787,11 @@ class ControllerExtensionModuleRetailcrm extends Controller
return $title; return $title;
} }
/**
* Get collector module name
*
* @return string
*/
private function getCollectorTitle() private function getCollectorTitle()
{ {
if (version_compare(VERSION, '3.0', '<')) { if (version_compare(VERSION, '3.0', '<')) {
@ -718,4 +802,26 @@ class ControllerExtensionModuleRetailcrm extends Controller
return $title; return $title;
} }
/**
* Check file size
*
* @return string
*/
private function checkLogFile($file)
{
$logs = '';
if ($file === false) {
return $logs;
}
if (filesize($file) < 2097152) {
$logs .= file_get_contents($file, FILE_USE_INCLUDE_PATH, null);
} else {
return false;
}
return $logs;
}
} }

View File

@ -16,6 +16,7 @@ $_['daemon_collector'] = 'Daemon Collector';
$_['general_tab_text'] = 'General'; $_['general_tab_text'] = 'General';
$_['references_tab_text'] = 'References'; $_['references_tab_text'] = 'References';
$_['collector_tab_text'] = 'Daemon Collector'; $_['collector_tab_text'] = 'Daemon Collector';
$_['logs_tab_text'] = 'Logs';
$_['collector_custom_text'] = 'Custom form'; $_['collector_custom_text'] = 'Custom form';
$_['custom_fields_tab_text'] = 'Custom fields'; $_['custom_fields_tab_text'] = 'Custom fields';
$_['retailcrm_apiversion'] = 'API Version'; $_['retailcrm_apiversion'] = 'API Version';
@ -28,6 +29,7 @@ $_['text_success_export_order'] = 'Order successfully unloaded';
$_['text_button_export'] = 'Unload all orders and customers'; $_['text_button_export'] = 'Unload all orders and customers';
$_['text_button_export_order'] = 'Unload order'; $_['text_button_export_order'] = 'Unload order';
$_['text_button_catalog'] = 'Unload catalog'; $_['text_button_catalog'] = 'Unload catalog';
$_['text_button_clear'] = 'Clear';
$_['text_success_catalog'] = 'Catalog successfully unloaded'; $_['text_success_catalog'] = 'Catalog successfully unloaded';
$_['text_error_order'] = 'Error! Order is not unloaded!'; $_['text_error_order'] = 'Error! Order is not unloaded!';
$_['text_error_order_id'] = 'Error! Enter the correct order number!'; $_['text_error_order_id'] = 'Error! Enter the correct order number!';
@ -51,6 +53,8 @@ $_['text_error_custom_field'] = 'Create custom fields for customer in Opencar
$_['text_error_cf_opencart'] = 'None custom fields in Opencart'; $_['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_confirm_log'] = 'Are you sure you want to clear the log?';
$_['retailcrm_dict_delivery'] = 'Shipment methods'; $_['retailcrm_dict_delivery'] = 'Shipment methods';
$_['retailcrm_dict_status'] = 'Order statuses'; $_['retailcrm_dict_status'] = 'Order statuses';

View File

@ -16,6 +16,7 @@ $_['daemon_collector'] = 'Демон Collector';
$_['general_tab_text'] = 'Главная'; $_['general_tab_text'] = 'Главная';
$_['references_tab_text'] = 'Справочники'; $_['references_tab_text'] = 'Справочники';
$_['collector_tab_text'] = 'Daemon Collector'; $_['collector_tab_text'] = 'Daemon Collector';
$_['logs_tab_text'] = 'Логи';
$_['collector_custom_text'] = 'Настройка полей формы'; $_['collector_custom_text'] = 'Настройка полей формы';
$_['custom_fields_tab_text'] = 'Пользовательские поля'; $_['custom_fields_tab_text'] = 'Пользовательские поля';
$_['retailcrm_apiversion'] = 'Версия API'; $_['retailcrm_apiversion'] = 'Версия API';
@ -28,6 +29,7 @@ $_['text_success_export_order'] = 'Заказ успешно выгружен';
$_['text_button_export'] = 'Выгрузить все заказы и клиентов'; $_['text_button_export'] = 'Выгрузить все заказы и клиентов';
$_['text_button_export_order'] = 'Выгрузить заказ'; $_['text_button_export_order'] = 'Выгрузить заказ';
$_['text_button_catalog'] = 'Выгрузить каталог'; $_['text_button_catalog'] = 'Выгрузить каталог';
$_['text_button_clear'] = 'Очистить';
$_['text_success_catalog'] = 'Каталог успешно выгружен'; $_['text_success_catalog'] = 'Каталог успешно выгружен';
$_['text_error_order'] = 'Ошибка! Заказ не выгружен!'; $_['text_error_order'] = 'Ошибка! Заказ не выгружен!';
$_['text_error_order_id'] = 'Ошибка! Введите корректный номер заказа!'; $_['text_error_order_id'] = 'Ошибка! Введите корректный номер заказа!';
@ -51,6 +53,8 @@ $_['text_error_custom_field'] = 'Создайте пользовательс
$_['text_error_cf_opencart'] = 'Отсутствуют пользовательские поля в Opencart'; $_['text_error_cf_opencart'] = 'Отсутствуют пользовательские поля в Opencart';
$_['text_error_cf_retailcrm'] = 'Отсутствуют пользовательские поля в RetailCRM'; $_['text_error_cf_retailcrm'] = 'Отсутствуют пользовательские поля в RetailCRM';
$_['text_error_save'] = 'Ошибка сохранения настроек'; $_['text_error_save'] = 'Ошибка сохранения настроек';
$_['text_error_log'] = 'Размер лога более 2MB';
$_['text_confirm_log'] = 'Вы уверены, что хотите очистить лог?';
$_['retailcrm_dict_delivery'] = 'Способы доставки'; $_['retailcrm_dict_delivery'] = 'Способы доставки';
$_['retailcrm_dict_status'] = 'Статусы'; $_['retailcrm_dict_status'] = 'Статусы';

View File

@ -46,6 +46,7 @@
<?php if ($saved_settings['retailcrm_apiversion'] == 'v5') : ?> <?php if ($saved_settings['retailcrm_apiversion'] == 'v5') : ?>
<li><a href="#tab-custom_fields" data-toggle="tab"><?php echo $custom_fields_tab_text; ?></a></li> <li><a href="#tab-custom_fields" data-toggle="tab"><?php echo $custom_fields_tab_text; ?></a></li>
<?php endif; ?> <?php endif; ?>
<li><a href="#tab-logs" data-toggle="tab"><?php echo $logs_tab_text; ?></a></li>
<?php endif; ?> <?php endif; ?>
</ul> </ul>
@ -319,6 +320,34 @@
<?php endif; ?> <?php endif; ?>
</div> </div>
<?php endif; ?> <?php endif; ?>
<div class="tab-pane" id="tab-logs">
<div class="retailcrm_unit">
<span>Retailcrm API error log</span>
<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></a>
</div>
<?php if (isset($logs['retailcrm_log'])) : ?>
<div class="panel-body">
<textarea wrap="off" rows="15" readonly class="form-control"><?php echo $logs['retailcrm_log']; ?></textarea>
</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; ?>
<div class="retailcrm_unit">
<span>Opencart API error log</span>
<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></a>
</div>
<?php if (isset($logs['oc_api_log'])) : ?>
<div class="panel-body">
<textarea wrap="off" rows="15" readonly class="form-control"><?php echo $logs['oc_api_log']; ?></textarea>
</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; ?>
</div>
</div> </div>
</form> </form>
</div> </div>

View File

@ -45,6 +45,7 @@
{% if saved_settings.module_retailcrm_apiversion == 'v5' %} {% if saved_settings.module_retailcrm_apiversion == 'v5' %}
<li><a href="#tab-custom_fields" data-toggle="tab"> {{ custom_fields_tab_text }} </a></li> <li><a href="#tab-custom_fields" data-toggle="tab"> {{ custom_fields_tab_text }} </a></li>
{% endif %} {% endif %}
<li><a href="#tab-logs" data-toggle="tab">{{ logs_tab_text }}</a></li>
{% endif %} {% endif %}
</ul> </ul>
@ -152,17 +153,17 @@
{% endfor %} {% endfor %}
<h4>{{ retailcrm_dict_default }}</h4> <h4>{{ retailcrm_dict_default }}</h4>
<div class="retailcrm_unit"> <div class="retailcrm_unit">
<select id="retailcrm_default_payment" name="retailcrm_default_payment" > <select id="module_retailcrm_default_payment" name="module_retailcrm_default_payment" >
{% for k, v in payments.opencart %} {% for k, v in payments.opencart %}
<option value="{{ k }}" {% if saved_settings.retailcrm_default_payment is defined and k == saved_settings.retailcrm_default_payment %} selected="selected" {% endif %}> <option value="{{ k }}" {% if saved_settings.retailcrm_default_payment is defined and k == saved_settings.retailcrm_default_payment %} selected="selected" {% endif %}>
{{ v }} {{ v }}
</option> </option>
{% endfor %} {% endfor %}
</select> </select>
<label for="retailcrm_default_payment">{{ text_payment }}</label> <label for="module_retailcrm_default_payment">{{ text_payment }}</label>
</div> </div>
<div class="retailcrm_unit"> <div class="retailcrm_unit">
<select id="retailcrm_default_shipping" name="retailcrm_default_shipping" > <select id="module_retailcrm_default_shipping" name="module_retailcrm_default_shipping" >
{% for key, value in delivery.opencart %} {% for key, value in delivery.opencart %}
<optgroup label="{{ value.title }}"> <optgroup label="{{ value.title }}">
{% for k, v in value %} {% for k, v in value %}
@ -175,7 +176,7 @@
</optgroup> </optgroup>
{% endfor %} {% endfor %}
</select> </select>
<label for="retailcrm_default_payment">{{ text_shipping }}</label> <label for="module_retailcrm_default_payment">{{ text_shipping }}</label>
</div> </div>
{% endif %} {% endif %}
@ -321,6 +322,34 @@
{% endif %} {% endif %}
</div> </div>
{% endif %} {% endif %}
<div class="tab-pane" id="tab-logs">
<div class="retailcrm_unit">
<span>Retailcrm API error log</span>
<a onclick="confirm('{{ text_confirm_log }}') ? location.href='{{ clear_retailcrm }}' : false;" data-toggle="tooltip" title="{{ button_clear }}" class="btn btn-danger"><i class="fa fa-eraser"></i></a>
</div>
{% if logs.retailcrm_log is defined %}
<div class="panel-body">
<textarea wrap="off" rows="15" readonly class="form-control">{{ logs.retailcrm_log }}</textarea>
</div>
{% elseif logs.retailcrm_error is defined %}
<div class="alert alert-danger alert-dismissible"><i class="fa fa-exclamation-circle"></i> {{ logs.retailcrm_error }}
<button type="button" class="close" data-dismiss="alert">&times;</button>
</div>
{% endif %}
<div class="retailcrm_unit">
<span>Opencart API error log</span>
<a onclick="confirm('{{ text_confirm_log }}') ? location.href='{{ clear_opencart }}' : false;" data-toggle="tooltip" title="{{ button_clear }}" class="btn btn-danger"><i class="fa fa-eraser"></i></a>
</div>
{% if logs.oc_api_log is defined %}
<div class="panel-body">
<textarea wrap="off" rows="15" readonly class="form-control">{{ logs.oc_api_log }}</textarea>
</div>
{% elseif logs.oc_error is defined %}
<div class="alert alert-danger alert-dismissible"><i class="fa fa-exclamation-circle"></i> {{ logs.oc_error }}
<button type="button" class="close" data-dismiss="alert">&times;</button>
</div>
{% endif %}
</div>
</div> </div>
</form> </form>
</div> </div>

View File

@ -22,7 +22,11 @@ class OpencartApiClient {
} }
private function getCookieValue($cookieName) { private function getCookieValue($cookieName) {
$cookieFile = file_get_contents(DIR_APPLICATION . '/' . $this->cookieFileName . '.txt'); if (!file_exists(DIR_APPLICATION . $this->cookieFileName . '.txt')) {
return false;
}
$cookieFile = file_get_contents(DIR_APPLICATION . $this->cookieFileName . '.txt');
$cookieFile = explode("\n", $cookieFile); $cookieFile = explode("\n", $cookieFile);
$cookies = array(); $cookies = array();
@ -78,14 +82,24 @@ class OpencartApiClient {
curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($postParams)); curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($postParams));
curl_setopt($curl, CURLOPT_COOKIEFILE, DIR_APPLICATION . '/' . $this->cookieFileName . '.txt'); curl_setopt($curl, CURLOPT_COOKIEFILE, DIR_APPLICATION . $this->cookieFileName . '.txt');
curl_setopt($curl, CURLOPT_COOKIEJAR, DIR_APPLICATION . '/' . $this->cookieFileName . '.txt'); curl_setopt($curl, CURLOPT_COOKIEJAR, DIR_APPLICATION . $this->cookieFileName . '.txt');
$json = json_decode(curl_exec($curl), true); $json = json_decode(curl_exec($curl), true);
curl_close($curl); curl_close($curl);
return $json; if (isset($json['error'])) {
if (is_array($json['error'])) {
foreach ($json['error'] as $error) {
error_log(date('Y-m-d H:i:s') . " @ " . "[$method]" . ' - ' . $error . "\n", 3, DIR_LOGS . "opencartapi.log");
}
} else {
error_log(date('Y-m-d H:i:s') . " @ " . "[$method]" . ' - ' . $json['error'] . "\n", 3, DIR_LOGS . "opencartapi.log");
}
} else {
return $json;
}
} }
private function auth() { private function auth() {
@ -321,26 +335,42 @@ class OpencartApiClient {
/** /**
* Login api user for opencart version > 3.0 * Login api user for opencart version > 3.0
* *
* @return string
*/ */
private function apiLogin() { private function apiLogin() {
$this->load->model('user/api'); $this->load->model('user/api');
$registry = new Registry();
$config = new Config();
$config->load('default');
$api_info = $this->model_user_api->getApi($this->config->get('config_api_id')); $api_info = $this->model_user_api->getApi($this->config->get('config_api_id'));
$session = new Session($this->config->get('session_engine'), $this->registry);
$session->start();
$this->model_user_api->deleteApiSessionBySessonId($session->getId()); if ($this->session->data) {
$this->model_user_api->addApiSession($api_info['api_id'], $session->getId(), $this->request->server['REMOTE_ADDR']); $this->session->data['api_id'] = $api_info['api_id'];
$api_token = $this->session->getId();
} else {
$session = new Session($this->config->get('session_engine'), $this->registry);
$session_id = $this->getCookieValue('OCSESSID');
$session->data['api_id'] = $api_info['api_id']; if ($session_id) {
$api_token = $session->getId(); $session->start($session_id);
} else {
$session->start();
}
$this->model_user_api->deleteApiSessionBySessonId($session->getId());
$this->model_user_api->addApiSession($api_info['api_id'], $session->getId(), $this->getInnerIpAddr());
$session->data['api_id'] = $api_info['api_id'];
$api_token = $session->getId();
$this->registry->set('session', $session);
}
return $api_token; return $api_token;
} }
/**
* Get module name
*
* @return string
*/
private function getModuleTitle() private function getModuleTitle()
{ {
if (version_compare(VERSION, '3.0', '<')){ if (version_compare(VERSION, '3.0', '<')){