From 9535f2de8e618c849fab2406d5f3011af27511a0 Mon Sep 17 00:00:00 2001 From: Akolzin Dmitry Date: Fri, 17 Nov 2017 16:32:18 +0300 Subject: [PATCH] Bug fix, error logs in admin interface (#63) --- .../controller/extension/module/retailcrm.php | 124 ++++++++++++++++-- .../en-gb/extension/module/retailcrm.php | 4 + .../ru-ru/extension/module/retailcrm.php | 4 + .../template/extension/module/retailcrm.tpl | 29 ++++ .../template/extension/module/retailcrm.twig | 37 +++++- .../library/retailcrm/OpencartApiClient.php | 60 ++++++--- 6 files changed, 230 insertions(+), 28 deletions(-) diff --git a/admin/controller/extension/module/retailcrm.php b/admin/controller/extension/module/retailcrm.php index e1b87c7..6c9d75f 100644 --- a/admin/controller/extension/module/retailcrm.php +++ b/admin/controller/extension/module/retailcrm.php @@ -166,7 +166,9 @@ class ControllerExtensionModuleRetailcrm extends Controller $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']); } @@ -190,8 +192,8 @@ class ControllerExtensionModuleRetailcrm extends Controller $ordersHistory = $api->ordersHistory(array(), $ordersHistory['pagination']['totalPageCount']); if ($ordersHistory->isSuccessful()) { - - $lastChangeOrders = end($ordersHistory['history']); + $ordersHistoryArr = $ordersHistory['history']; + $lastChangeOrders = end($ordersHistoryArr); $sinceIdOrders = $lastChangeOrders['id']; $generatedAt = $ordersHistory['generatedAt']; } @@ -203,7 +205,8 @@ class ControllerExtensionModuleRetailcrm extends Controller $customersHistory = $api->customersHistory(array(), $customersHistory['pagination']['totalPageCount']); if ($customersHistory->isSuccessful()) { - $lastChangeCustomers = end($customersHistory['history']); + $customersHistoryArr = $customersHistory['history']; + $lastChangeCustomers = end($customersHistoryArr); $sinceIdCustomers = $lastChangeCustomers['id']; } } @@ -258,6 +261,7 @@ class ControllerExtensionModuleRetailcrm extends Controller 'general_tab_text', 'references_tab_text', 'collector_tab_text', + 'logs_tab_text', 'text_yes', 'text_no', 'collector_site_key', @@ -278,7 +282,8 @@ class ControllerExtensionModuleRetailcrm extends Controller 'retailcrm_dict_default', 'text_custom_field_activity', 'text_orders_custom_fields', - 'text_customers_custom_fields' + 'text_customers_custom_fields', + 'text_confirm_log' ); $_data = &$data; @@ -403,7 +408,7 @@ class ControllerExtensionModuleRetailcrm extends Controller } else { $_data['export_file'] = true; } - + $collectorFields = array( 'name' => $this->language->get('field_name'), 'email' => $this->language->get('field_email'), @@ -413,11 +418,30 @@ class ControllerExtensionModuleRetailcrm extends Controller $_data['collectorFields'] = $collectorFields; $_data['api_versions'] = array('v3', 'v4', 'v5'); $_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->load->view('extension/module/retailcrm', $_data) ); - + } /** @@ -578,7 +602,7 @@ class ControllerExtensionModuleRetailcrm extends Controller /** * Export orders * - * + * @return void */ 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() { if (version_compare(VERSION, '3.0', '<')) { @@ -686,6 +755,11 @@ class ControllerExtensionModuleRetailcrm extends Controller } } + /** + * Get token param name + * + * @return string + */ private function getTokenTitle() { if (version_compare(VERSION, '3.0', '<')) { @@ -697,6 +771,11 @@ class ControllerExtensionModuleRetailcrm extends Controller return $token; } + /** + * Get module name + * + * @return string + */ private function getModuleTitle() { if (version_compare(VERSION, '3.0', '<')) { @@ -708,6 +787,11 @@ class ControllerExtensionModuleRetailcrm extends Controller return $title; } + /** + * Get collector module name + * + * @return string + */ private function getCollectorTitle() { if (version_compare(VERSION, '3.0', '<')) { @@ -718,4 +802,26 @@ class ControllerExtensionModuleRetailcrm extends Controller 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; + } } diff --git a/admin/language/en-gb/extension/module/retailcrm.php b/admin/language/en-gb/extension/module/retailcrm.php index ae9447f..dbfa65d 100644 --- a/admin/language/en-gb/extension/module/retailcrm.php +++ b/admin/language/en-gb/extension/module/retailcrm.php @@ -16,6 +16,7 @@ $_['daemon_collector'] = 'Daemon Collector'; $_['general_tab_text'] = 'General'; $_['references_tab_text'] = 'References'; $_['collector_tab_text'] = 'Daemon Collector'; +$_['logs_tab_text'] = 'Logs'; $_['collector_custom_text'] = 'Custom form'; $_['custom_fields_tab_text'] = 'Custom fields'; $_['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_order'] = 'Unload order'; $_['text_button_catalog'] = 'Unload catalog'; +$_['text_button_clear'] = 'Clear'; $_['text_success_catalog'] = 'Catalog successfully unloaded'; $_['text_error_order'] = 'Error! Order is not unloaded!'; $_['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_retailcrm'] = 'None custom fields in RetailCRM'; $_['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_status'] = 'Order statuses'; diff --git a/admin/language/ru-ru/extension/module/retailcrm.php b/admin/language/ru-ru/extension/module/retailcrm.php index 5a86671..ec86848 100644 --- a/admin/language/ru-ru/extension/module/retailcrm.php +++ b/admin/language/ru-ru/extension/module/retailcrm.php @@ -16,6 +16,7 @@ $_['daemon_collector'] = 'Демон Collector'; $_['general_tab_text'] = 'Главная'; $_['references_tab_text'] = 'Справочники'; $_['collector_tab_text'] = 'Daemon Collector'; +$_['logs_tab_text'] = 'Логи'; $_['collector_custom_text'] = 'Настройка полей формы'; $_['custom_fields_tab_text'] = 'Пользовательские поля'; $_['retailcrm_apiversion'] = 'Версия API'; @@ -28,6 +29,7 @@ $_['text_success_export_order'] = 'Заказ успешно выгружен'; $_['text_button_export'] = 'Выгрузить все заказы и клиентов'; $_['text_button_export_order'] = 'Выгрузить заказ'; $_['text_button_catalog'] = 'Выгрузить каталог'; +$_['text_button_clear'] = 'Очистить'; $_['text_success_catalog'] = 'Каталог успешно выгружен'; $_['text_error_order'] = 'Ошибка! Заказ не выгружен!'; $_['text_error_order_id'] = 'Ошибка! Введите корректный номер заказа!'; @@ -51,6 +53,8 @@ $_['text_error_custom_field'] = 'Создайте пользовательс $_['text_error_cf_opencart'] = 'Отсутствуют пользовательские поля в Opencart'; $_['text_error_cf_retailcrm'] = 'Отсутствуют пользовательские поля в RetailCRM'; $_['text_error_save'] = 'Ошибка сохранения настроек'; +$_['text_error_log'] = 'Размер лога более 2MB'; +$_['text_confirm_log'] = 'Вы уверены, что хотите очистить лог?'; $_['retailcrm_dict_delivery'] = 'Способы доставки'; $_['retailcrm_dict_status'] = 'Статусы'; diff --git a/admin/view/template/extension/module/retailcrm.tpl b/admin/view/template/extension/module/retailcrm.tpl index d5ed8b2..651c828 100644 --- a/admin/view/template/extension/module/retailcrm.tpl +++ b/admin/view/template/extension/module/retailcrm.tpl @@ -46,6 +46,7 @@
  • +
  • @@ -319,6 +320,34 @@ +
    +
    + Retailcrm API error log + +
    + +
    + +
    + +
    + +
    + +
    + Opencart API error log + +
    + +
    + +
    + +
    + +
    + +
    diff --git a/admin/view/template/extension/module/retailcrm.twig b/admin/view/template/extension/module/retailcrm.twig index 2be398f..64454af 100644 --- a/admin/view/template/extension/module/retailcrm.twig +++ b/admin/view/template/extension/module/retailcrm.twig @@ -45,6 +45,7 @@ {% if saved_settings.module_retailcrm_apiversion == 'v5' %}
  • {{ custom_fields_tab_text }}
  • {% endif %} +
  • {{ logs_tab_text }}
  • {% endif %} @@ -152,17 +153,17 @@ {% endfor %}

    {{ retailcrm_dict_default }}

    - {% for k, v in payments.opencart %} {% endfor %} - +
    - {% for key, value in delivery.opencart %} {% for k, v in value %} @@ -175,7 +176,7 @@ {% endfor %} - +
    {% endif %} @@ -321,6 +322,34 @@ {% endif %} {% endif %} +
    +
    + Retailcrm API error log + +
    + {% if logs.retailcrm_log is defined %} +
    + +
    + {% elseif logs.retailcrm_error is defined %} +
    {{ logs.retailcrm_error }} + +
    + {% endif %} +
    + Opencart API error log + +
    + {% if logs.oc_api_log is defined %} +
    + +
    + {% elseif logs.oc_error is defined %} +
    {{ logs.oc_error }} + +
    + {% endif %} +
    diff --git a/system/library/retailcrm/OpencartApiClient.php b/system/library/retailcrm/OpencartApiClient.php index 0d33f7a..662f639 100644 --- a/system/library/retailcrm/OpencartApiClient.php +++ b/system/library/retailcrm/OpencartApiClient.php @@ -22,7 +22,11 @@ class OpencartApiClient { } 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); $cookies = array(); @@ -78,14 +82,24 @@ class OpencartApiClient { curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($postParams)); - curl_setopt($curl, CURLOPT_COOKIEFILE, DIR_APPLICATION . '/' . $this->cookieFileName . '.txt'); - curl_setopt($curl, CURLOPT_COOKIEJAR, 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'); $json = json_decode(curl_exec($curl), true); 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() { @@ -321,26 +335,42 @@ class OpencartApiClient { /** * Login api user for opencart version > 3.0 * + * @return string */ private function apiLogin() { $this->load->model('user/api'); - $registry = new Registry(); - $config = new Config(); - $config->load('default'); $api_info = $this->model_user_api->getApi($this->config->get('config_api_id')); - $session = new Session($this->config->get('session_engine'), $this->registry); - $session->start(); - - $this->model_user_api->deleteApiSessionBySessonId($session->getId()); - $this->model_user_api->addApiSession($api_info['api_id'], $session->getId(), $this->request->server['REMOTE_ADDR']); - - $session->data['api_id'] = $api_info['api_id']; - $api_token = $session->getId(); + + if ($this->session->data) { + $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'); + + if ($session_id) { + $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; } + /** + * Get module name + * + * @return string + */ private function getModuleTitle() { if (version_compare(VERSION, '3.0', '<')){