From 3be4ac76a970032c1c46b23e24576f00b22f2d33 Mon Sep 17 00:00:00 2001 From: iyzoer Date: Wed, 22 Mar 2017 12:12:54 +0300 Subject: [PATCH 1/3] Update to v2.3 (#22) * restruct for 2.3 * new files for 2.3 --- Changelog.md | 39 -------- README.md | 8 +- README.ru.md | 8 +- .../{ => extension}/module/retailcrm.php | 93 ++++++++++--------- .../extension}/module/retailcrm.php | 0 .../extension}/module/retailcrm.php | 0 .../{ => extension}/retailcrm/custom/.gitkeep | 0 .../{ => extension}/retailcrm/customer.php | 4 +- .../{ => extension}/retailcrm/history.php | 39 +++----- .../model/{ => extension}/retailcrm/icml.php | 23 +++-- .../model/{ => extension}/retailcrm/order.php | 2 +- .../{ => extension}/retailcrm/references.php | 16 ++-- .../{ => extension}/module/retailcrm.tpl | 0 .../{ => extension}/module/retailcrm.php | 35 +++---- .../{ => extension}/retailcrm/customer.php | 4 +- .../model/{ => extension}/retailcrm/order.php | 12 ++- system/cron/dispatch.php | 46 ++++----- system/cron/export.php | 2 +- system/cron/history.php | 2 +- system/cron/icml.php | 2 +- .../library/retailcrm/OpencartApiClient.php | 47 ++++------ .../retailcrm/RetailcrmHistoryHelper.php | 18 ++-- 22 files changed, 166 insertions(+), 234 deletions(-) delete mode 100644 Changelog.md rename admin/controller/{ => extension}/module/retailcrm.php (73%) rename admin/language/{english => en-gb/extension}/module/retailcrm.php (100%) rename admin/language/{russian => ru-ru/extension}/module/retailcrm.php (100%) rename admin/model/{ => extension}/retailcrm/custom/.gitkeep (100%) rename admin/model/{ => extension}/retailcrm/customer.php (92%) rename admin/model/{ => extension}/retailcrm/history.php (93%) rename admin/model/{ => extension}/retailcrm/icml.php (95%) rename admin/model/{ => extension}/retailcrm/order.php (98%) rename admin/model/{ => extension}/retailcrm/references.php (87%) rename admin/view/template/{ => extension}/module/retailcrm.tpl (100%) rename catalog/controller/{ => extension}/module/retailcrm.php (76%) rename catalog/model/{ => extension}/retailcrm/customer.php (91%) rename catalog/model/{ => extension}/retailcrm/order.php (97%) diff --git a/Changelog.md b/Changelog.md deleted file mode 100644 index 47bf1b0..0000000 --- a/Changelog.md +++ /dev/null @@ -1,39 +0,0 @@ -Changelog -========= - -####v0.3.0 - -* Расширена библиотека клиента -* Добавлена возможность кастомизации моделей заказа через vqmod -* Устранены мелкие баги, проведен рефакторинг кода. - - -####v0.2.0 - -Общие изменения - -* Код приведен в состоянии совместимости с PHP 5.2 -* Убрана необходимость собирать пакет через composer -* Библиотека api-client-php обновлена до последней версии и добавлена в стандартную поставку -* Переименованы методы, пути и значения ключей конфигурации в связи с ребрендингом -* Временая метка последнего запуска получения истории перенесена в таблицу конфигурации БД - -Выгрузка каталога (ICML) - -* Генерация обновлена в соответствии с последними измениями формата файла выгрузки -* Генерация вынесена в отдельный класс -* Добавлена возможность добавлять подкатегории -* Скорректировано указание активности офера -* Убрана генерация размера офера вследствие кастомизации этого параметра в разных магазинах - -####v0.1.1 -* Устранена ошибка редактирования, при которой терялась часть данных при получении истории из CRM -* Оптимизирован код получения и обработки истории заказов -* Актуализированы переводы - -####v.0.1 -* Реализован интерфейс настроек модуля -* Реализована отправка данных о заказе/клиенте в CRM -* Реализована выгрузка каталога (cron only) -* Реализовано получение данных о заказах, сделанных на стороне CRM (cron only) - diff --git a/README.md b/README.md index efa3e3e..417fc0e 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,13 @@ Opencart module =============== -Module allows integrate CMS Opencart 2.x with [retailCRM](http://retailcrm.pro) +Module allows integrate CMS Opencart >= 2.3 with [retailCRM](http://retailcrm.pro) + +### Previous versions: + +[v1.x](https://github.com/retailcrm/opencart-module/tree/v1.x) + +[v2.x (2.0, 2.1, 2.2)](https://github.com/retailcrm/opencart-module/tree/v2.2) #### Features: diff --git a/README.ru.md b/README.ru.md index 44bc3ef..0e5d119 100644 --- a/README.ru.md +++ b/README.ru.md @@ -1,7 +1,13 @@ Opencart module =============== -Модуль интеграции CMS Openacart 2.x c [RetailCRM](http://retailcrm.ru) +Модуль интеграции CMS Opencart >= 2.3 c [RetailCRM](http://retailcrm.ru) + +### Предыдущие версии: + +[v1.x](https://github.com/retailcrm/opencart-module/tree/v1.x) + +[v2.x (2.0, 2.1, 2.2)](https://github.com/retailcrm/opencart-module/tree/v2.2) #### Модуль позволяет: diff --git a/admin/controller/module/retailcrm.php b/admin/controller/extension/module/retailcrm.php similarity index 73% rename from admin/controller/module/retailcrm.php rename to admin/controller/extension/module/retailcrm.php index 3daf847..fc5500f 100644 --- a/admin/controller/module/retailcrm.php +++ b/admin/controller/extension/module/retailcrm.php @@ -11,7 +11,7 @@ require_once DIR_SYSTEM . 'library/retailcrm/bootstrap.php'; * @license https://opensource.org/licenses/MIT MIT License * @link http://www.retailcrm.ru/docs/Developers/ApiVersion3 */ -class ControllerModuleRetailcrm extends Controller +class ControllerExtensionModuleRetailcrm extends Controller { private $_error = array(); protected $log, $statuses, $payments, $deliveryTypes, $retailcrm; @@ -33,22 +33,29 @@ class ControllerModuleRetailcrm extends Controller $this->model_extension_event ->addEvent( 'retailcrm', - version_compare(VERSION, '2.2', '>=') ? 'catalog/model/checkout/order/addOrder/after' : 'post.order.add', - 'module/retailcrm/order_create' + 'catalog/model/checkout/order/addOrder/after', + 'extension/module/retailcrm/order_create' ); $this->model_extension_event ->addEvent( 'retailcrm', - version_compare(VERSION, '2.2', '>=') ? 'catalog/model/checkout/order/addOrderHistory/after' : 'post.order.history.add', - 'module/retailcrm/order_edit' + 'catalog/model/checkout/order/addOrderHistory/after', + 'extension/module/retailcrm/order_edit' ); $this->model_extension_event ->addEvent( 'retailcrm', - version_compare(VERSION, '2.2', '>=') ? 'catalog/model/account/customer/addCustomer/after' : 'post.customer.add', - 'module/retailcrm/customer_create' + 'catalog/model/account/customer/addCustomer/after', + 'extension/module/retailcrm/customer_create' + ); + + $this->model_extension_event + ->addEvent( + 'retailcrm', + 'catalog/model/checkout/order/editOrder/after', + 'extension/module/retailcrm/order_edit' ); } @@ -77,12 +84,16 @@ class ControllerModuleRetailcrm extends Controller $this->load->model('setting/setting'); $this->load->model('extension/module'); - $this->load->model('retailcrm/references'); - $this->load->language('module/retailcrm'); + $this->load->model('extension/retailcrm/references'); + $this->load->language('extension/module/retailcrm'); $this->document->setTitle($this->language->get('heading_title')); $this->document->addStyle('/admin/view/stylesheet/retailcrm.css'); if ($this->request->server['REQUEST_METHOD'] == 'POST' && $this->validate()) { + if (parse_url($this->request->post['retailcrm_url'])){ + $crm_url = parse_url($this->request->post['retailcrm_url'], PHP_URL_HOST); + $this->request->post['retailcrm_url'] = 'https://'.$crm_url; + } $this->model_setting_setting->editSetting( 'retailcrm', $this->request->post @@ -90,7 +101,7 @@ class ControllerModuleRetailcrm extends Controller $this->session->data['success'] = $this->language->get('text_success'); $redirect = $this->url->link( - 'module/retailcrm', 'token=' . $this->session->data['token'], + 'extension/module/retailcrm', 'token=' . $this->session->data['token'], 'SSL' ); @@ -137,14 +148,14 @@ class ControllerModuleRetailcrm extends Controller $this->retailcrm = new RetailcrmProxy( $url, $key, - DIR_SYSTEM . 'logs/retailcrm.log' + DIR_SYSTEM . 'storage/logs/retailcrm.log' ); - $_data['delivery'] = $this->model_retailcrm_references + $_data['delivery'] = $this->model_extension_retailcrm_references ->getDeliveryTypes(); - $_data['statuses'] = $this->model_retailcrm_references + $_data['statuses'] = $this->model_extension_retailcrm_references ->getOrderStatuses(); - $_data['payments'] = $this->model_retailcrm_references + $_data['payments'] = $this->model_extension_retailcrm_references ->getPaymentTypes(); } @@ -181,7 +192,7 @@ class ControllerModuleRetailcrm extends Controller $_data['breadcrumbs'][] = array( 'text' => $this->language->get('text_module'), 'href' => $this->url->link( - 'extension/module', + 'extension/extension/module', 'token=' . $this->session->data['token'], 'SSL' ), 'separator' => ' :: ' @@ -190,19 +201,19 @@ class ControllerModuleRetailcrm extends Controller $_data['breadcrumbs'][] = array( 'text' => $this->language->get('retailcrm_title'), 'href' => $this->url->link( - 'module/retailcrm', + 'extension/module/retailcrm', 'token=' . $this->session->data['token'], 'SSL' ), 'separator' => ' :: ' ); $_data['action'] = $this->url->link( - 'module/retailcrm', + 'extension/module/retailcrm', 'token=' . $this->session->data['token'], 'SSL' ); $_data['cancel'] = $this->url->link( - 'extension/module', + 'extension/extension', 'token=' . $this->session->data['token'], 'SSL' ); @@ -222,7 +233,7 @@ class ControllerModuleRetailcrm extends Controller $_data['footer'] = $this->load->controller('common/footer'); $this->response->setOutput( - $this->load->view('module/retailcrm.tpl', $_data) + $this->load->view('extension/module/retailcrm.tpl', $_data) ); } @@ -233,12 +244,12 @@ class ControllerModuleRetailcrm extends Controller */ public function history() { - if (file_exists(DIR_APPLICATION . 'model/retailcrm/custom/history.php')) { - $this->load->model('retailcrm/custom/history'); - $this->model_retailcrm_custom_history->request(); + if (file_exists(DIR_APPLICATION . 'model/extension/retailcrm/custom/history.php')) { + $this->load->model('extension/retailcrm/custom/history'); + $this->model_extension_retailcrm_custom_history->request(); } else { - $this->load->model('retailcrm/history'); - $this->model_retailcrm_history->request(); + $this->load->model('extension/retailcrm/history'); + $this->model_extension_retailcrm_history->request(); } } @@ -249,12 +260,12 @@ class ControllerModuleRetailcrm extends Controller */ public function icml() { - if (file_exists(DIR_APPLICATION . 'model/retailcrm/custom/icml.php')) { - $this->load->model('retailcrm/custom/icml'); - $this->model_retailcrm_custom_icml->generateICML(); + if (file_exists(DIR_APPLICATION . 'model/extension/retailcrm/custom/icml.php')) { + $this->load->model('extension/retailcrm/custom/icml'); + $this->model_extension_retailcrm_custom_icml->generateICML(); } else { - $this->load->model('retailcrm/icml'); - $this->model_retailcrm_icml->generateICML(); + $this->load->model('extension/retailcrm/icml'); + $this->model_extension_retailcrm_icml->generateICML(); } } @@ -278,8 +289,8 @@ class ControllerModuleRetailcrm extends Controller $status = $this->model_setting_setting->getSetting('retailcrm'); $data['order_status'] = $status['retailcrm_status'][$data['order_status_id']]; - $this->load->model('retailcrm/order'); - $this->model_retailcrm_order->sendToCrm($data, $data['order_id']); + $this->load->model('extension/retailcrm/order'); + $this->model_extension_retailcrm_order->sendToCrm($data, $data['order_id']); } } @@ -289,16 +300,12 @@ class ControllerModuleRetailcrm extends Controller * */ public function export() { - if(version_compare(VERSION, '2.1', '<')) { - $this->load->model('sale/customer'); - $customers = $this->model_sale_customer->getCustomers(); - } else { - $this->load->model('customer/customer'); - $customers = $this->model_customer_customer->getCustomers(); - } + + $this->load->model('customer/customer'); + $customers = $this->model_customer_customer->getCustomers(); - $this->load->model('retailcrm/customer'); - $this->model_retailcrm_customer->uploadToCrm($customers); + $this->load->model('extension/retailcrm/customer'); + $this->model_extension_retailcrm_customer->uploadToCrm($customers); $this->load->model('sale/order'); $orders = $this->model_sale_order->getOrders(); @@ -317,8 +324,8 @@ class ControllerModuleRetailcrm extends Controller $fullOrders[] = $fullOrder; } - $this->load->model('retailcrm/order'); - $this->model_retailcrm_order->uploadToCrm($fullOrders); + $this->load->model('extension/retailcrm/order'); + $this->model_extension_retailcrm_order->uploadToCrm($fullOrders); } /** @@ -328,7 +335,7 @@ class ControllerModuleRetailcrm extends Controller */ private function validate() { - if (!$this->user->hasPermission('modify', 'module/retailcrm')) { + if (!$this->user->hasPermission('modify', 'extension/module/retailcrm')) { $this->_error['warning'] = $this->language->get('error_permission'); } diff --git a/admin/language/english/module/retailcrm.php b/admin/language/en-gb/extension/module/retailcrm.php similarity index 100% rename from admin/language/english/module/retailcrm.php rename to admin/language/en-gb/extension/module/retailcrm.php diff --git a/admin/language/russian/module/retailcrm.php b/admin/language/ru-ru/extension/module/retailcrm.php similarity index 100% rename from admin/language/russian/module/retailcrm.php rename to admin/language/ru-ru/extension/module/retailcrm.php diff --git a/admin/model/retailcrm/custom/.gitkeep b/admin/model/extension/retailcrm/custom/.gitkeep similarity index 100% rename from admin/model/retailcrm/custom/.gitkeep rename to admin/model/extension/retailcrm/custom/.gitkeep diff --git a/admin/model/retailcrm/customer.php b/admin/model/extension/retailcrm/customer.php similarity index 92% rename from admin/model/retailcrm/customer.php rename to admin/model/extension/retailcrm/customer.php index a18c6c8..ab17ee6 100644 --- a/admin/model/retailcrm/customer.php +++ b/admin/model/extension/retailcrm/customer.php @@ -1,6 +1,6 @@ load->model('setting/setting'); @@ -16,7 +16,7 @@ class ModelRetailcrmCustomer extends Model { $this->retailcrmApi = new RetailcrmProxy( $settings['retailcrm_url'], $settings['retailcrm_apikey'], - DIR_SYSTEM . 'logs/retailcrm.log' + DIR_SYSTEM . 'storage/logs/retailcrm.log' ); $customersToCrm = array(); diff --git a/admin/model/retailcrm/history.php b/admin/model/extension/retailcrm/history.php similarity index 93% rename from admin/model/retailcrm/history.php rename to admin/model/extension/retailcrm/history.php index b984635..eb19ffb 100644 --- a/admin/model/retailcrm/history.php +++ b/admin/model/extension/retailcrm/history.php @@ -1,6 +1,6 @@ load->model('setting/store'); $this->load->model('user/api'); $this->load->model('sale/order'); - if (version_compare(VERSION, '2.1.0.0', '>=')) { - $this->load->model('customer/customer'); - } else { - $this->load->model('sale/customer'); - } - $this->load->model('retailcrm/references'); + $this->load->model('customer/customer'); + $this->load->model('extension/retailcrm/references'); $this->load->model('catalog/product'); $this->load->model('catalog/option'); $this->load->model('localisation/zone'); - $this->load->language('module/retailcrm'); + $this->load->language('extension/module/retailcrm'); $settings = $this->model_setting_setting->getSetting('retailcrm'); $history = $this->model_setting_setting->getSetting('retailcrm_history'); @@ -41,7 +37,7 @@ class ModelRetailcrmHistory extends Model $crm = new RetailcrmProxy( $settings['retailcrm_url'], $settings['retailcrm_apikey'], - DIR_SYSTEM . 'logs/retailcrm.log' + DIR_SYSTEM . 'storage/logs/retailcrm.log' ); $lastRun = !empty($history['retailcrm_history']) @@ -65,10 +61,10 @@ class ModelRetailcrmHistory extends Model $this->payment = array_flip($settings['retailcrm_payment']); $this->status = array_flip($settings['retailcrm_status']); - $this->ocPayment = $this->model_retailcrm_references + $this->ocPayment = $this->model_extension_retailcrm_references ->getOpercartPaymentTypes(); - $this->ocDelivery = $this->model_retailcrm_references + $this->ocDelivery = $this->model_extension_retailcrm_references ->getOpercartDeliveryTypes(); $this->zones = $this->model_localisation_zone->getZones(); @@ -314,25 +310,14 @@ class ModelRetailcrmHistory extends Model ), ); - if (version_compare(VERSION, '2.1.0.0', '>=')) { - $this->model_customer_customer->addCustomer($cData); - } else { - $this->model_sale_customer->addCustomer($cData); - } - + + $this->model_customer_customer->addCustomer($cData); + if (!empty($order['email'])) { - if (version_compare(VERSION, '2.1.0.0', '>=')) { - $tryToFind = $this->model_customer_customer->getCustomerByEmail($order['email']); - } else { - $tryToFind = $this->model_sale_customer->getCustomerByEmail($order['email']); - } + $tryToFind = $this->model_customer_customer->getCustomerByEmail($order['email']); $customer_id = $tryToFind['customer_id']; } else { - if (version_compare(VERSION, '2.1.0.0', '>=')) { - $last = $this->model_customer_customer->getCustomers($data = array('order' => 'DESC', 'limit' => 1)); - } else { - $last = $this->model_sale_customer->getCustomers($data = array('order' => 'DESC', 'limit' => 1)); - } + $last = $this->model_customer_customer->getCustomers($data = array('order' => 'DESC', 'limit' => 1)); $customer_id = $last[0]['customer_id']; } diff --git a/admin/model/retailcrm/icml.php b/admin/model/extension/retailcrm/icml.php similarity index 95% rename from admin/model/retailcrm/icml.php rename to admin/model/extension/retailcrm/icml.php index 2d6b5c5..f2f3d47 100644 --- a/admin/model/retailcrm/icml.php +++ b/admin/model/extension/retailcrm/icml.php @@ -1,6 +1,6 @@ load->language('module/retailcrm'); + $this->load->language('extension/module/retailcrm'); $this->load->model('catalog/category'); $this->load->model('catalog/product'); $this->load->model('catalog/option'); @@ -296,18 +296,17 @@ class ModelRetailcrmIcml extends Model private function generateImage($image) { $this->load->model('tool/image'); + + $currentTheme = $this->config->get('config_theme'); + $width = $this->config->get($currentTheme . '_image_related_width') ? $this->config->get($currentTheme . '_image_related_width') : 200; + $height = $this->config->get($currentTheme . '_image_related_height') ? $this->config->get($currentTheme . '_image_related_height') : 200; - if (version_compare(VERSION, '2.2', '>=')) { - $currentTheme = $this->config->get('config_theme'); - $width = $this->config->get($currentTheme . '_image_related_width') ? $this->config->get($currentTheme . '_image_related_width') : 200; - $height = $this->config->get($currentTheme . '_image_related_height') ? $this->config->get($currentTheme . '_image_related_height') : 200; + return $this->model_tool_image->resize( + $image, + $width, + $height + ); - return $this->model_tool_image->resize( - $image, - $width, - $height - ); - } return $this->model_tool_image->resize( $image, diff --git a/admin/model/retailcrm/order.php b/admin/model/extension/retailcrm/order.php similarity index 98% rename from admin/model/retailcrm/order.php rename to admin/model/extension/retailcrm/order.php index c9cd423..77fa54d 100644 --- a/admin/model/retailcrm/order.php +++ b/admin/model/extension/retailcrm/order.php @@ -1,6 +1,6 @@ load->model('catalog/product'); diff --git a/admin/model/retailcrm/references.php b/admin/model/extension/retailcrm/references.php similarity index 87% rename from admin/model/retailcrm/references.php rename to admin/model/extension/retailcrm/references.php index b5aef36..b764c55 100644 --- a/admin/model/retailcrm/references.php +++ b/admin/model/extension/retailcrm/references.php @@ -2,7 +2,7 @@ require_once DIR_SYSTEM . 'library/retailcrm/bootstrap.php'; -class ModelRetailcrmReferences extends Model +class ModelExtensionRetailcrmReferences extends Model { protected $retailcrm; @@ -33,13 +33,13 @@ class ModelRetailcrmReferences extends Model public function getOpercartDeliveryTypes() { $deliveryMethods = array(); - $files = glob(DIR_APPLICATION . 'controller/shipping/*.php'); + $files = glob(DIR_APPLICATION . 'controller/extension/shipping/*.php'); if ($files) { foreach ($files as $file) { $extension = basename($file, '.php'); - $this->load->language('shipping/' . $extension); + $this->load->language('extension/shipping/' . $extension); if ($this->config->get($extension . '_status')) { $deliveryMethods[$extension.'.'.$extension] = strip_tags( @@ -63,13 +63,13 @@ class ModelRetailcrmReferences extends Model public function getOpercartPaymentTypes() { $paymentTypes = array(); - $files = glob(DIR_APPLICATION . 'controller/payment/*.php'); + $files = glob(DIR_APPLICATION . 'controller/extension/payment/*.php'); if ($files) { foreach ($files as $file) { $extension = basename($file, '.php'); - $this->load->language('payment/' . $extension); + $this->load->language('extension/payment/' . $extension); if ($this->config->get($extension . '_status')) { $paymentTypes[$extension] = strip_tags( @@ -91,7 +91,7 @@ class ModelRetailcrmReferences extends Model $this->retailcrm = new RetailcrmProxy( $settings['retailcrm_url'], $settings['retailcrm_apikey'], - DIR_SYSTEM . 'logs/retailcrm.log' + DIR_SYSTEM . 'storage/logs/retailcrm.log' ); $response = $this->retailcrm->deliveryTypesList(); @@ -109,7 +109,7 @@ class ModelRetailcrmReferences extends Model $this->retailcrm = new RetailcrmProxy( $settings['retailcrm_url'], $settings['retailcrm_apikey'], - DIR_SYSTEM . 'logs/retailcrm.log' + DIR_SYSTEM . 'storage/logs/retailcrm.log' ); $response = $this->retailcrm->statusesList(); @@ -127,7 +127,7 @@ class ModelRetailcrmReferences extends Model $this->retailcrm = new RetailcrmProxy( $settings['retailcrm_url'], $settings['retailcrm_apikey'], - DIR_SYSTEM . 'logs/retailcrm.log' + DIR_SYSTEM . 'storage/logs/retailcrm.log' ); $response = $this->retailcrm->paymentTypesList(); diff --git a/admin/view/template/module/retailcrm.tpl b/admin/view/template/extension/module/retailcrm.tpl similarity index 100% rename from admin/view/template/module/retailcrm.tpl rename to admin/view/template/extension/module/retailcrm.tpl diff --git a/catalog/controller/module/retailcrm.php b/catalog/controller/extension/module/retailcrm.php similarity index 76% rename from catalog/controller/module/retailcrm.php rename to catalog/controller/extension/module/retailcrm.php index 27a368f..7b8455d 100644 --- a/catalog/controller/module/retailcrm.php +++ b/catalog/controller/extension/module/retailcrm.php @@ -9,7 +9,7 @@ * @license https://opensource.org/licenses/MIT MIT License * @link http://www.retailcrm.ru/docs/Developers/ApiVersion3 */ -class ControllerModuleRetailcrm extends Controller +class ControllerExtensionModuleRetailcrm extends Controller { /** * Create order on event @@ -18,15 +18,12 @@ class ControllerModuleRetailcrm extends Controller * * @return void */ - public function order_create($parameter1, $parameter2 = null) + public function order_create($parameter1, $parameter2 = null, $parameter3 = null) { $this->load->model('checkout/order'); $this->load->model('account/order'); - if($parameter2 != null) - $order_id = $parameter2; - else - $order_id = $parameter1; + $order_id = $parameter3; $data = $this->model_checkout_order->getOrder($order_id); @@ -50,16 +47,13 @@ class ControllerModuleRetailcrm extends Controller 'value' => $this->session->data['shipping_method']['cost'] ); - $this->load->model('retailcrm/order'); - $this->model_retailcrm_order->sendToCrm($data, $data['order_id']); + $this->load->model('extension/retailcrm/order'); + $this->model_extension_retailcrm_order->sendToCrm($data, $data['order_id']); } } - public function order_edit($parameter1, $parameter2 = null, $parameter3 = null, $parameter4 = null) { - if($parameter4 != null) - $order_id = $parameter3; - else - $order_id = $parameter1; + public function order_edit($parameter1, $parameter2 = null) { + $order_id = $parameter2[0]; $this->load->model('checkout/order'); $this->load->model('account/order'); @@ -90,8 +84,8 @@ class ControllerModuleRetailcrm extends Controller 'value' => isset($this->session->data['shipping_method']) ? $this->session->data['shipping_method']['cost'] : '' ); - $this->load->model('retailcrm/order'); - $this->model_retailcrm_order->changeInCrm($data, $data['order_id']); + $this->load->model('extension/retailcrm/order'); + $this->model_extension_retailcrm_order->changeInCrm($data, $data['order_id']); } } @@ -102,16 +96,13 @@ class ControllerModuleRetailcrm extends Controller * * @return void */ - public function customer_create($parameter1, $parameter2 = null) { - if($parameter2 != null) - $customerId = $parameter2; - else - $customerId = $parameter1; + public function customer_create($parameter1, $parameter2 = null, $parameter3 = null) { + $customerId = $parameter3; $this->load->model('account/customer'); $customer = $this->model_account_customer->getCustomer($customerId); - $this->load->model('retailcrm/customer'); - $this->model_retailcrm_customer->sendToCrm($customer); + $this->load->model('extension/retailcrm/customer'); + $this->model_extension_retailcrm_customer->sendToCrm($customer); } } diff --git a/catalog/model/retailcrm/customer.php b/catalog/model/extension/retailcrm/customer.php similarity index 91% rename from catalog/model/retailcrm/customer.php rename to catalog/model/extension/retailcrm/customer.php index 093a109..1b1f768 100644 --- a/catalog/model/retailcrm/customer.php +++ b/catalog/model/extension/retailcrm/customer.php @@ -1,6 +1,6 @@ load->model('setting/setting'); $settings = $this->model_setting_setting->getSetting('retailcrm'); @@ -15,7 +15,7 @@ class ModelRetailcrmCustomer extends Model { $this->retailcrmApi = new RetailcrmProxy( $settings['retailcrm_url'], $settings['retailcrm_apikey'], - DIR_SYSTEM . 'logs/retailcrm.log' + DIR_SYSTEM . 'storage/logs/retailcrm.log' ); $customerToCrm = $this->process($customer); diff --git a/catalog/model/retailcrm/order.php b/catalog/model/extension/retailcrm/order.php similarity index 97% rename from catalog/model/retailcrm/order.php rename to catalog/model/extension/retailcrm/order.php index f59f82d..873d2ff 100644 --- a/catalog/model/retailcrm/order.php +++ b/catalog/model/extension/retailcrm/order.php @@ -1,6 +1,6 @@ retailcrm = new RetailcrmProxy( $settings['retailcrm_url'], $settings['retailcrm_apikey'], - DIR_SYSTEM . 'logs/retailcrm.log' + DIR_SYSTEM . 'storage/logs/retailcrm.log' ); $order = array(); @@ -157,7 +157,7 @@ class ModelRetailcrmOrder extends Model { $this->retailcrm = new RetailcrmProxy( $settings['retailcrm_url'], $settings['retailcrm_apikey'], - DIR_SYSTEM . 'logs/retailcrm.log' + DIR_SYSTEM . 'storage/logs/retailcrm.log' ); $order = array(); @@ -191,7 +191,6 @@ class ModelRetailcrmOrder extends Model { $order['delivery'] = array( 'code' => !empty($delivery_code) ? $settings['retailcrm_delivery'][$delivery_code] : '', - 'cost' => $deliveryCost, 'address' => array( 'index' => $order_data['shipping_postcode'], 'city' => $order_data['shipping_city'], @@ -206,7 +205,10 @@ class ModelRetailcrmOrder extends Model { )) ) ); - + if(!empty($deliveryCost)){ + $order['delivery']['cost'] = $deliveryCost; + } + $orderProducts = isset($order_data['products']) ? $order_data['products'] : $order_data['order_product']; $offerOptions = array('select', 'radio'); diff --git a/system/cron/dispatch.php b/system/cron/dispatch.php index dfd546b..69ee0ed 100644 --- a/system/cron/dispatch.php +++ b/system/cron/dispatch.php @@ -34,17 +34,12 @@ if (!defined('DIR_APPLICATION')) { require_once(DIR_SYSTEM . 'startup.php'); // Application Classes -if (version_compare(VERSION, '2.2', '>=')) { - require_once(DIR_SYSTEM . 'library/cart/currency.php'); - require_once(DIR_SYSTEM . 'library/cart/user.php'); - require_once(DIR_SYSTEM . 'library/cart/weight.php'); - require_once(DIR_SYSTEM . 'library/cart/length.php'); -} else { - require_once(DIR_SYSTEM . 'library/currency.php'); - require_once(DIR_SYSTEM . 'library/user.php'); - require_once(DIR_SYSTEM . 'library/weight.php'); - require_once(DIR_SYSTEM . 'library/length.php'); -} +require_once(DIR_SYSTEM . 'library/cart/currency.php'); +require_once(DIR_SYSTEM . 'library/cart/user.php'); +require_once(DIR_SYSTEM . 'library/cart/weight.php'); +require_once(DIR_SYSTEM . 'library/cart/length.php'); + + // Registry $registry = new Registry(); @@ -68,10 +63,7 @@ foreach ($query->rows as $setting) { if (!$setting['serialized']) { $config->set($setting['key'], $setting['value']); } else { - if (version_compare(VERSION, '2.1', '>=')) - $config->set($setting['key'], json_decode($setting['value']), true); - else - $config->set($setting['key'], unserialize($setting['value'])); + $config->set($setting['key'], json_decode($setting['value']), true); } } @@ -85,10 +77,9 @@ $registry->set('log', $log); // Event -if (version_compare(VERSION, '2.2', '>=')) { - $event = new Event($registry); - $registry->set('event', $event); -} +$event = new Event($registry); +$registry->set('event', $event); + function error_handler($errno, $errstr, $errfile, $errline) { global $log, $config; @@ -153,17 +144,12 @@ $registry->set('language', $language); $document = new Document(); $registry->set('document', $document); -if (version_compare(VERSION, '2.2', '>=')) { - $registry->set('currency', new Cart\Currency($registry)); - $registry->set('weight', new Cart\Weight($registry)); - $registry->set('length', new Cart\Length($registry)); - $registry->set('user', new Cart\User($registry)); -} else { - $registry->set('currency', new Currency($registry)); - $registry->set('weight', new Weight($registry)); - $registry->set('length', new Length($registry)); - $registry->set('user', new User($registry)); -} + +$registry->set('currency', new Cart\Currency($registry)); +$registry->set('weight', new Cart\Weight($registry)); +$registry->set('length', new Cart\Length($registry)); +$registry->set('user', new Cart\User($registry)); + $controller = new Front($registry); $action = new Action($cli_action); diff --git a/system/cron/export.php b/system/cron/export.php index 8da82f4..5880920 100644 --- a/system/cron/export.php +++ b/system/cron/export.php @@ -1,3 +1,3 @@ model_setting_store->getStore($this->opencartStoreId); - if(version_compare(VERSION, '2.1.0', '>=') && !empty($this->apiToken)) { + if(!empty($this->apiToken)) { $getParams['token'] = $this->apiToken; } @@ -89,19 +89,10 @@ class OpencartApiClient { $api = array(); foreach ($apiUsers as $apiUser) { if($apiUser['status'] == 1) { - if(version_compare(VERSION, '2.1.0', '>=')) { - $api = array( - 'api_id' => $apiUser['api_id'], - 'key' => $apiUser['key'] - ); - } else { - $api = array( - 'api_id' => $apiUser['api_id'], - 'username' => $apiUser['username'], - 'password' => $apiUser['password'] - ); - } - + $api = array( + 'api_id' => $apiUser['api_id'], + 'key' => $apiUser['key'] + ); break; } } @@ -109,26 +100,24 @@ class OpencartApiClient { if(!isset($api['api_id'])) return false; - if(version_compare(VERSION, '2.1.0', '>=')) { - $alreadyBinded = false; + + $alreadyBinded = false; - $innerIp = $this->getInnerIpAddr(); - $apiIps = $this->model_user_api->getApiIps($api['api_id']); - foreach($apiIps as $apiIp) { - if($apiIp['ip'] == $innerIp) - $alreadyBinded = true; - } - - if(!$alreadyBinded) { - $this->model_user_api->addApiIp($api['api_id'], $innerIp); - } + $innerIp = $this->getInnerIpAddr(); + $apiIps = $this->model_user_api->getApiIps($api['api_id']); + foreach($apiIps as $apiIp) { + if($apiIp['ip'] == $innerIp) + $alreadyBinded = true; } + if(!$alreadyBinded) { + $this->model_user_api->addApiIp($api['api_id'], $innerIp); + } + + $apiAnswer = $this->request('login', array(), $apiUser); - if(version_compare(VERSION, '2.1.0', '>=')) { - $this->apiToken = $apiAnswer['token']; - } + $this->apiToken = $apiAnswer['token']; return $apiAnswer; } diff --git a/system/library/retailcrm/RetailcrmHistoryHelper.php b/system/library/retailcrm/RetailcrmHistoryHelper.php index bc5a718..d21b327 100644 --- a/system/library/retailcrm/RetailcrmHistoryHelper.php +++ b/system/library/retailcrm/RetailcrmHistoryHelper.php @@ -12,7 +12,7 @@ class RetailcrmHistoryHelper { $orders = array(); foreach ($orderHistory as $change) { $change['order'] = self::removeEmpty($change['order']); - if($change['order']['items']) { + if(isset($change['order']['items']) && $change['order']['items']) { $items = array(); foreach($change['order']['items'] as $item) { if(isset($change['created'])) { @@ -23,18 +23,18 @@ class RetailcrmHistoryHelper { $change['order']['items'] = $items; } - if($change['order']['contragent']['contragentType']) { + if(isset($change['order']['contragent']['contragentType']) && $change['order']['contragent']['contragentType']) { $change['order']['contragentType'] = $change['order']['contragent']['contragentType']; unset($change['order']['contragent']); } - if($orders[$change['order']['id']]) { + if(!empty($orders) && $orders[$change['order']['id']]) { $orders[$change['order']['id']] = array_merge($orders[$change['order']['id']], $change['order']); } else { $orders[$change['order']['id']] = $change['order']; } - if($change['item']) { + if(isset($change['item']) && $change['item']) { if($orders[$change['order']['id']]['items'][$change['item']['id']]) { $orders[$change['order']['id']]['items'][$change['item']['id']] = array_merge($orders[$change['order']['id']]['items'][$change['item']['id']], $change['item']); } else { @@ -51,15 +51,15 @@ class RetailcrmHistoryHelper { $orders[$change['order']['id']]['items'][$change['item']['id']][$fields['item'][$change['field']]] = $change['newValue']; } } else { - if($fields['delivery'][$change['field']] == 'service') { + if(isset($fields['delivery'][$change['field']]) && $fields['delivery'][$change['field']] == 'service'){ $orders[$change['order']['id']]['delivery']['service']['code'] = self::newValue($change['newValue']); - } elseif($fields['delivery'][$change['field']]) { + } elseif(isset($fields['delivery'][$change['field']]) && $fields['delivery'][$change['field']]) { $orders[$change['order']['id']]['delivery'][$fields['delivery'][$change['field']]] = self::newValue($change['newValue']); - } elseif($fields['orderAddress'][$change['field']]) { + } elseif(isset($fields['orderAddress'][$change['field']]) && $fields['orderAddress'][$change['field']]){ $orders[$change['order']['id']]['delivery']['address'][$fields['orderAddress'][$change['field']]] = $change['newValue']; - } elseif($fields['integrationDelivery'][$change['field']]) { + } elseif(isset($fields['integrationDelivery'][$change['field']]) && $fields['integrationDelivery'][$change['field']]) { $orders[$change['order']['id']]['delivery']['service'][$fields['integrationDelivery'][$change['field']]] = self::newValue($change['newValue']); - } elseif($fields['customerContragent'][$change['field']]) { + } elseif(isset($fields['customerContragent'][$change['field']]) && $fields['customerContragent'][$change['field']]) { $orders[$change['order']['id']][$fields['customerContragent'][$change['field']]] = self::newValue($change['newValue']); } elseif(strripos($change['field'], 'custom_') !== false) { $orders[$change['order']['id']]['customFields'][str_replace('custom_', '', $change['field'])] = self::newValue($change['newValue']); From c724392c36947816b67f9c5b6a8e4b3d1dc342a0 Mon Sep 17 00:00:00 2001 From: iyzoer Date: Fri, 7 Apr 2017 12:35:53 +0300 Subject: [PATCH 2/3] Advanced search for delivery methods (#25) Plugin's deliveries ICML export Order export --- README.md | 4 +- README.ru.md | 4 +- .../controller/extension/module/retailcrm.php | 52 ++++++++- .../en-gb/extension/module/retailcrm.php | 12 +- .../ru-ru/extension/module/retailcrm.php | 11 ++ admin/model/extension/retailcrm/history.php | 9 ++ admin/model/extension/retailcrm/icml.php | 1 + admin/model/extension/retailcrm/order.php | 43 +++++++ .../model/extension/retailcrm/references.php | 33 ++---- admin/view/stylesheet/retailcrm.css | 1 + .../template/extension/module/retailcrm.tpl | 107 +++++++++++++++++- catalog/controller/api/retailcrm.php | 74 ++++++++++++ .../controller/extension/module/retailcrm.php | 7 +- catalog/model/extension/retailcrm/order.php | 9 +- system/cron/export.php | 1 + system/library/retailcrm/RetailcrmProxy.php | 9 +- 16 files changed, 334 insertions(+), 43 deletions(-) create mode 100644 catalog/controller/api/retailcrm.php diff --git a/README.md b/README.md index 417fc0e..216764c 100644 --- a/README.md +++ b/README.md @@ -34,7 +34,7 @@ cp -r opencart-module/* /path/to/site/root Add to cron: ``` -*/5 * * * * /usr/bin/php /path/to/opencart/system/cron/history.php >> /path/to/opencart/system/logs/cronjob_history.log 2>&1 +*/5 * * * * /usr/bin/php /path/to/opencart/system/cron/history.php >> /path/to/opencart/system/storage/logs/cronjob_history.log 2>&1 ``` #### Setting product catalog export @@ -42,7 +42,7 @@ Add to cron: Add to cron: ``` -* */4 * * * /usr/bin/php /path/to/opencart/system/cron/icml.php >> /path/to/opencart/system/logs/cronjob_icml.log 2>&1 +* */4 * * * /usr/bin/php /path/to/opencart/system/cron/icml.php >> /path/to/opencart/system/storage/logs/cronjob_icml.log 2>&1 ``` Your export file will be available by following url diff --git a/README.ru.md b/README.ru.md index 0e5d119..b3b4f46 100644 --- a/README.ru.md +++ b/README.ru.md @@ -37,7 +37,7 @@ cp -r opencart-module/* /path/to/site/root Для получения изменений и новых данных добавьте в cron следующую запись: ``` -*/5 * * * * /usr/bin/php /path/to/opencart/system/cron/history.php >> /path/to/opencart/system/logs/cronjob_history.log 2>&1 +*/5 * * * * /usr/bin/php /path/to/opencart/system/cron/history.php >> /path/to/opencart/system/storage/logs/cronjob_history.log 2>&1 ``` #### Настройка экспорта каталога @@ -45,7 +45,7 @@ cp -r opencart-module/* /path/to/site/root Для периодической выгрузки каталога добавьте в cron следующую запись: ``` -* */4 * * * /usr/bin/php /path/to/opencart/system/cron/icml.php >> /path/to/opencart/system/logs/cronjob_icml.log 2>&1 +* */4 * * * /usr/bin/php /path/to/opencart/system/cron/icml.php >> /path/to/opencart/system/storage/logs/cronjob_icml.log 2>&1 ``` В настройках CRM установите путь к файлу выгрузки diff --git a/admin/controller/extension/module/retailcrm.php b/admin/controller/extension/module/retailcrm.php index fc5500f..d8d056a 100644 --- a/admin/controller/extension/module/retailcrm.php +++ b/admin/controller/extension/module/retailcrm.php @@ -26,7 +26,11 @@ class ControllerExtensionModuleRetailcrm extends Controller { $this->load->model('setting/setting'); $this->model_setting_setting - ->editSetting('retailcrm', array('retailcrm_status' => 1)); + ->editSetting('retailcrm', array( + 'retailcrm_status' => 1, + 'retailcrm_country' => array($this->config->get('config_country_id')) + ) + ); $this->load->model('extension/event'); @@ -82,6 +86,7 @@ class ControllerExtensionModuleRetailcrm extends Controller public function index() { + $this->load->model('localisation/country'); $this->load->model('setting/setting'); $this->load->model('extension/module'); $this->load->model('extension/retailcrm/references'); @@ -123,6 +128,16 @@ class ControllerExtensionModuleRetailcrm extends Controller 'retailcrm_dict_delivery', 'retailcrm_dict_status', 'retailcrm_dict_payment', + 'retailcrm_countries_settings', + 'text_success_export', + 'text_success_export_order', + 'text_button_export', + 'text_button_export_order', + 'text_button_catalog', + 'text_success_catalog', + 'retailcrm_upload_order', + 'text_error_order', + 'text_error_order_id' ); $this->load->model('extension/extension'); @@ -231,7 +246,16 @@ class ControllerExtensionModuleRetailcrm extends Controller $_data['header'] = $this->load->controller('common/header'); $_data['column_left'] = $this->load->controller('common/column_left'); $_data['footer'] = $this->load->controller('common/footer'); + $_data['countries'] = $this->model_localisation_country->getCountries(); + $_data['catalog'] = $this->request->server['HTTPS'] ? HTTPS_CATALOG : HTTP_CATALOG; + $_data['token'] = $this->request->get['token']; + if(file_exists(DIR_SYSTEM . '/cron/export_done.txt')) { + $_data['export_file'] = false; + } else { + $_data['export_file'] = true; + } + $this->response->setOutput( $this->load->view('extension/module/retailcrm.tpl', $_data) ); @@ -294,6 +318,32 @@ class ControllerExtensionModuleRetailcrm extends Controller } } + /** + * Export single order + * + * + */ + public function exportOrder() + { + $order_id = isset($this->request->get['order_id']) ? $this->request->get['order_id'] : ''; + $this->load->model('sale/order'); + + $data = $this->model_sale_order->getOrder($order_id); + $data['products'] = $this->model_sale_order->getOrderProducts($order_id); + $data['totals'] = $this->model_sale_order->getOrderTotals($order_id); + + if (!isset($data['fromApi'])) { + $this->load->model('setting/setting'); + $status = $this->model_setting_setting->getSetting('retailcrm'); + $data['order_status'] = $status['retailcrm_status'][$data['order_status_id']]; + + $this->load->model('extension/retailcrm/order'); + $result = $this->model_extension_retailcrm_order->uploadOrder($data); + } + + echo json_encode($result); + } + /** * Export orders * diff --git a/admin/language/en-gb/extension/module/retailcrm.php b/admin/language/en-gb/extension/module/retailcrm.php index f1baabb..0ca1927 100644 --- a/admin/language/en-gb/extension/module/retailcrm.php +++ b/admin/language/en-gb/extension/module/retailcrm.php @@ -10,10 +10,20 @@ $_['text_success'] = 'Setting saved'; $_['text_notice'] = 'Warning! Timezone in CRM & your shop must be equal, you must setup it here:'; $_['retailcrm_base_settings'] = 'Connection settings'; $_['retailcrm_dict_settings'] = 'Dictionary settings'; - +$_['retailcrm_countries_settings'] = 'Trading zones setting'; +$_['retailcrm_upload_order'] = 'Unload single order'; $_['retailcrm_url'] = 'RetailCRM URL'; $_['retailcrm_apikey'] = 'RetailCRM API Key'; +$_['text_success_export'] = 'Orders and customers successfully unloaded'; +$_['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_success_catalog'] = 'Catalog successfully unloaded'; +$_['text_error_order'] = 'Error! Order is not unloaded!'; +$_['text_error_order_id'] = 'Error! Enter the correct order number!'; + $_['retailcrm_dict_delivery'] = 'Shipment methods'; $_['retailcrm_dict_status'] = 'Order statuses'; $_['retailcrm_dict_payment'] = 'Payment methods'; diff --git a/admin/language/ru-ru/extension/module/retailcrm.php b/admin/language/ru-ru/extension/module/retailcrm.php index b2062ff..9672dd5 100644 --- a/admin/language/ru-ru/extension/module/retailcrm.php +++ b/admin/language/ru-ru/extension/module/retailcrm.php @@ -10,10 +10,21 @@ $_['text_success'] = 'Настройки успешно сохра $_['text_notice'] = 'Внимание! Часовой пояс в CRM должен совпадать с часовым поясом в магазине, настроки часового пояса CRM можно задать по адресу:'; $_['retailcrm_base_settings'] = 'Настройки соединения'; $_['retailcrm_dict_settings'] = 'Настройки соответствия справочников'; +$_['retailcrm_countries_settings'] = 'Настройка торговых зон'; +$_['retailcrm_upload_order'] = 'Выгрузка одного заказа'; $_['retailcrm_url'] = 'Адрес RetailCRM'; $_['retailcrm_apikey'] = 'Api ключ RetailCRM'; +$_['text_success_export'] = 'Заказы и клиенты успешно выгружены'; +$_['text_success_export_order'] = 'Заказ успешно выгружен'; +$_['text_button_export'] = 'Выгрузить все заказы и клиентов'; +$_['text_button_export_order'] = 'Выгрузить заказ'; +$_['text_button_catalog'] = 'Выгрузить каталог'; +$_['text_success_catalog'] = 'Каталог успешно выгружен'; +$_['text_error_order'] = 'Ошибка! Заказ не выгружен!'; +$_['text_error_order_id'] = 'Ошибка! Введите корректный номер заказа!'; + $_['retailcrm_dict_delivery'] = 'Способы доставки'; $_['retailcrm_dict_status'] = 'Статусы'; $_['retailcrm_dict_payment'] = 'Способы оплаты'; diff --git a/admin/model/extension/retailcrm/history.php b/admin/model/extension/retailcrm/history.php index eb19ffb..5e61bad 100644 --- a/admin/model/extension/retailcrm/history.php +++ b/admin/model/extension/retailcrm/history.php @@ -227,6 +227,15 @@ class ModelExtensionRetailcrmHistory extends Model $deliveryCost = !empty($order['delivery']['cost']) ? $order['delivery']['cost'] : 0; + if(isset($order['discount']) && $order['discount'] > 0) { + $orderTotals = $this->model_sale_order->getOrderTotals($order['externalId']); + foreach($orderTotals as $orderTotal) { + if($orderTotal['code'] == 'coupon') { + $data['order_total'][] = $orderTotal; + } + } + } + $data['order_total'] = array( array( 'order_total_id' => '', diff --git a/admin/model/extension/retailcrm/icml.php b/admin/model/extension/retailcrm/icml.php index f2f3d47..7a28c1f 100644 --- a/admin/model/extension/retailcrm/icml.php +++ b/admin/model/extension/retailcrm/icml.php @@ -220,6 +220,7 @@ class ModelExtensionRetailcrmIcml extends Model ->appendChild($this->dd->createTextNode($product['name'])); } $e->appendChild($this->dd->createElement('price')) + ->appendChild($this->dd->createTextNode($productPrice + $optionsTotalCost)); ->appendChild($this->dd->createTextNode($product['price'] + $optionsTotalCost)); /** * Vendor diff --git a/admin/model/extension/retailcrm/order.php b/admin/model/extension/retailcrm/order.php index 77fa54d..2c27169 100644 --- a/admin/model/extension/retailcrm/order.php +++ b/admin/model/extension/retailcrm/order.php @@ -20,6 +20,49 @@ class ModelExtensionRetailcrmOrder extends Model { } } + public function uploadOrder($order) + { + if(isset($this->request->post['fromApi'])) return; + + $this->load->model('setting/setting'); + $settings = $this->model_setting_setting->getSetting('retailcrm'); + + if(!empty($settings['retailcrm_url']) && !empty($settings['retailcrm_apikey'])) { + $this->load->model('catalog/product'); + + require_once DIR_SYSTEM . 'library/retailcrm/bootstrap.php'; + + $this->retailcrm = new RetailcrmProxy( + $settings['retailcrm_url'], + $settings['retailcrm_apikey'], + DIR_SYSTEM . 'storage/logs/retailcrm.log' + ); + + $customers = $this->retailcrm->customersList( + array( + 'name' => $order['telephone'], + 'email' => $order['email'] + ), + 1, + 100 + ); + + $order = $this->process($order); + + if($customers) { + foreach ($customers['customers'] as $customer) { + $order['customer']['id'] = $customer['id']; + } + } + + unset($customers); + + $result = $this->retailcrm->ordersCreate($order); + } + + return $result; + } + private function process($order_data) { $order = array(); diff --git a/admin/model/extension/retailcrm/references.php b/admin/model/extension/retailcrm/references.php index b764c55..79d7564 100644 --- a/admin/model/extension/retailcrm/references.php +++ b/admin/model/extension/retailcrm/references.php @@ -5,9 +5,20 @@ require_once DIR_SYSTEM . 'library/retailcrm/bootstrap.php'; class ModelExtensionRetailcrmReferences extends Model { protected $retailcrm; + private $opencartApiClient; + + public function getOpercartDeliveryTypes() + { + $this->load->model('user/api'); + $this->opencartApiClient = new OpencartApiClient($this->registry); + + return $this->opencartApiClient->request('retailcrm/getDeliveryTypes', array(), array()); + } public function getDeliveryTypes() { + $this->load->model('setting/store'); + return array( 'opencart' => $this->getOpercartDeliveryTypes(), 'retailcrm' => $this->getApiDeliveryTypes() @@ -30,28 +41,6 @@ class ModelExtensionRetailcrmReferences extends Model ); } - public function getOpercartDeliveryTypes() - { - $deliveryMethods = array(); - $files = glob(DIR_APPLICATION . 'controller/extension/shipping/*.php'); - - if ($files) { - foreach ($files as $file) { - $extension = basename($file, '.php'); - - $this->load->language('extension/shipping/' . $extension); - - if ($this->config->get($extension . '_status')) { - $deliveryMethods[$extension.'.'.$extension] = strip_tags( - $this->language->get('heading_title') - ); - } - } - } - - return $deliveryMethods; - } - public function getOpercartOrderStatuses() { $this->load->model('localisation/order_status'); diff --git a/admin/view/stylesheet/retailcrm.css b/admin/view/stylesheet/retailcrm.css index 43cbeb6..5c3b88f 100644 --- a/admin/view/stylesheet/retailcrm.css +++ b/admin/view/stylesheet/retailcrm.css @@ -1,2 +1,3 @@ .retailcrm_unit {margin-bottom: 10px;} .retailcrm_unit input {width: 30%;} +.checkbox input{width: auto;} diff --git a/admin/view/template/extension/module/retailcrm.tpl b/admin/view/template/extension/module/retailcrm.tpl index 144f68b..9afdbdd 100644 --- a/admin/view/template/extension/module/retailcrm.tpl +++ b/admin/view/template/extension/module/retailcrm.tpl @@ -5,6 +5,10 @@ + + diff --git a/catalog/controller/api/retailcrm.php b/catalog/controller/api/retailcrm.php new file mode 100644 index 0000000..00ad266 --- /dev/null +++ b/catalog/controller/api/retailcrm.php @@ -0,0 +1,74 @@ +load->model('localisation/country'); + $this->load->model('setting/setting'); + + $countries = $this->model_setting_setting->getSetting('retailcrm')['retailcrm_country']; + $deliveryTypes = array(); + + foreach ($countries as $country) { + $deliveryTypes = array_merge($deliveryTypes, $this->getDeliveryTypesByZones($country)); + } + + if (isset($this->request->server['HTTP_ORIGIN'])) { + $this->response->addHeader('Access-Control-Allow-Origin: ' . $this->request->server['HTTP_ORIGIN']); + $this->response->addHeader('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS'); + $this->response->addHeader('Access-Control-Max-Age: 1000'); + $this->response->addHeader('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With'); + } + + $this->response->addHeader('Content-Type: application/json'); + $this->response->setOutput(json_encode($deliveryTypes)); + } + + protected function getDeliveryTypesByZones($country_id) + { + $this->load->model('localisation/zone'); + $this->load->model('localisation/country'); + $this->load->model('extension/extension'); + + $shippingModules = $this->model_extension_extension->getExtensions('shipping'); + $zones = $this->model_localisation_zone->getZonesByCountryId($country_id); + $country = $this->model_localisation_country->getCountry($country_id); + $quote_data = array(); + + foreach ($zones as $zone) { + $address = array( + 'country_id' => $country_id, + 'zone_id' => $zone['zone_id'], + 'iso_code_2' => $country['iso_code_2'], + 'iso_code_3' => $country['iso_code_3'], + 'zone_code' => $zone['code'], + 'postcode' => '', + 'city' => '' + ); + + foreach ($shippingModules as $shippingModule) { + + $this->load->model('extension/shipping/' . $shippingModule['code']); + + if ($this->config->get($shippingModule['code'] . '_status')) { + if($this->{'model_extension_shipping_' . $shippingModule['code']}->getQuote($address)) { + $quote_data[] = $this->{'model_extension_shipping_' . $shippingModule['code']}->getQuote($address); + } + } + } + } + + $deliveryTypes = array(); + + foreach ($quote_data as $shipping) { + + foreach ($shipping['quote'] as $shippingMethod) { + $deliveryTypes[$shipping['code']]['title'] = $shipping['title']; + $deliveryTypes[$shipping['code']][$shippingMethod['code']] = $shippingMethod; + } + + } + + return $deliveryTypes; + } +} diff --git a/catalog/controller/extension/module/retailcrm.php b/catalog/controller/extension/module/retailcrm.php index 7b8455d..47777c3 100644 --- a/catalog/controller/extension/module/retailcrm.php +++ b/catalog/controller/extension/module/retailcrm.php @@ -26,6 +26,7 @@ class ControllerExtensionModuleRetailcrm extends Controller $order_id = $parameter3; $data = $this->model_checkout_order->getOrder($order_id); + $data['totals'] = $this->model_account_order->getOrderTotals($order_id); $data['products'] = $this->model_account_order->getOrderProducts($order_id); foreach($data['products'] as $key => $product) { @@ -63,6 +64,7 @@ class ControllerExtensionModuleRetailcrm extends Controller if($data['order_status_id'] == 0) return; $data['products'] = $this->model_account_order->getOrderProducts($order_id); + $data['totals'] = $this->model_account_order->getOrderTotals($order_id); foreach($data['products'] as $key => $product) { $productOptions = $this->model_account_order->getOrderOptions($order_id, $product['order_product_id']); @@ -79,11 +81,6 @@ class ControllerExtensionModuleRetailcrm extends Controller $data['order_status'] = $status['retailcrm_status'][$data['order_status_id']]; } - $data['totals'][] = array( - 'code' => 'shipping', - 'value' => isset($this->session->data['shipping_method']) ? $this->session->data['shipping_method']['cost'] : '' - ); - $this->load->model('extension/retailcrm/order'); $this->model_extension_retailcrm_order->changeInCrm($data, $data['order_id']); } diff --git a/catalog/model/extension/retailcrm/order.php b/catalog/model/extension/retailcrm/order.php index 873d2ff..7860ab4 100644 --- a/catalog/model/extension/retailcrm/order.php +++ b/catalog/model/extension/retailcrm/order.php @@ -52,15 +52,21 @@ class ModelExtensionRetailcrmOrder extends Model { $deliveryCost = 0; $altTotals = isset($order_data['order_total']) ? $order_data['order_total'] : ""; $orderTotals = isset($order_data['totals']) ? $order_data['totals'] : $altTotals ; + $couponTotal = 0; if (!empty($orderTotals)) { foreach ($orderTotals as $totals) { if ($totals['code'] == 'shipping') { $deliveryCost = $totals['value']; } + + if ($totals['code'] == 'coupon') { + $couponTotal = abs($totals['value']); + } } } + $order['discount'] = $couponTotal; $order['createdAt'] = $order_data['date_added']; $payment_code = $order_data['payment_code']; @@ -205,6 +211,7 @@ class ModelExtensionRetailcrmOrder extends Model { )) ) ); + if(!empty($deliveryCost)){ $order['delivery']['cost'] = $deliveryCost; } @@ -215,7 +222,7 @@ class ModelExtensionRetailcrmOrder extends Model { foreach ($orderProducts as $product) { $offerId = ''; - if(!empty($product['option'])) { + if (!empty($product['option'])) { $options = array(); $productOptions = $this->model_catalog_product->getProductOptions($product['product_id']); diff --git a/system/cron/export.php b/system/cron/export.php index 5880920..cbf86bf 100644 --- a/system/cron/export.php +++ b/system/cron/export.php @@ -1,3 +1,4 @@ api, $method), $arguments); + $date = date('[Y-m-d H:i:s]'); if (!$response->isSuccessful()) { - error_log("[$method] " . $response->getErrorMsg() . "\n", 3, $this->log); + error_log($date . " [$method] " . $response->getErrorMsg() . "\n", 3, $this->log); if (isset($response['errors'])) { $error = implode("\n", $response['errors']); - error_log($error . "\n", 3, $this->log); + error_log($date .' '. $error . "\n", 3, $this->log); } $response = false; } return $response; } catch (CurlException $e) { - error_log("[$method] " . $e->getMessage() . "\n", 3, $this->log); + error_log($date . " [$method] " . $e->getMessage() . "\n", 3, $this->log); return false; } catch (InvalidJsonException $e) { - error_log("[$method] " . $e->getMessage() . "\n", 3, $this->log); + error_log($date . " [$method] " . $e->getMessage() . "\n", 3, $this->log); return false; } } From 82e6d620766d6f21f0041e8744d92bbfc84da472 Mon Sep 17 00:00:00 2001 From: Cybernick Date: Mon, 10 Apr 2017 14:58:26 +0300 Subject: [PATCH 3/3] Fix catalog export (#26) --- admin/model/extension/retailcrm/icml.php | 1 - 1 file changed, 1 deletion(-) diff --git a/admin/model/extension/retailcrm/icml.php b/admin/model/extension/retailcrm/icml.php index 7a28c1f..f2f3d47 100644 --- a/admin/model/extension/retailcrm/icml.php +++ b/admin/model/extension/retailcrm/icml.php @@ -220,7 +220,6 @@ class ModelExtensionRetailcrmIcml extends Model ->appendChild($this->dd->createTextNode($product['name'])); } $e->appendChild($this->dd->createElement('price')) - ->appendChild($this->dd->createTextNode($productPrice + $optionsTotalCost)); ->appendChild($this->dd->createTextNode($product['price'] + $optionsTotalCost)); /** * Vendor