From cdc1c9cf6b6faf48640fa0fc1597855b892d1f9d Mon Sep 17 00:00:00 2001 From: Akolzin Dmitry Date: Fri, 15 Sep 2017 15:47:38 +0300 Subject: [PATCH] fix history, new objects in object.xml --- CHANGELOG.md | 9 + .../controller/extension/module/retailcrm.php | 99 ++++- .../en-gb/extension/module/retailcrm.php | 11 +- .../ru-ru/extension/module/retailcrm.php | 13 +- admin/model/extension/retailcrm/customer.php | 29 +- .../model/extension/retailcrm/history/v3.php | 260 +++++++++---- .../extension/retailcrm/history/v4_5.php | 352 ++++++++++++------ .../model/extension/retailcrm/references.php | 29 +- .../template/extension/module/retailcrm.tpl | 40 +- .../template/extension/module/retailcrm.twig | 37 +- catalog/controller/api/retailcrm.php | 160 ++++---- .../model/extension/retailcrm/customer.php | 24 +- .../library/retailcrm/OpencartApiClient.php | 16 +- .../library/retailcrm/RetailcrmApiClient3.php | 22 +- .../library/retailcrm/RetailcrmApiClient4.php | 22 +- .../library/retailcrm/RetailcrmApiClient5.php | 22 +- .../retailcrm/RetailcrmHistoryHelper.php | 6 +- system/library/retailcrm/RetailcrmProxy.php | 14 +- system/library/retailcrm/objects.xml | 11 +- 19 files changed, 840 insertions(+), 336 deletions(-) create mode 100644 CHANGELOG.md diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..43eddab --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,9 @@ +## 2017-09-07 v.2.4.0 +* Добавлена возможность работы на 3 версиях API (v3, v4, v5) +* Добавлена совместимость с Opencart 3.0 + +## 2017-09-04 v.2.4.1 +* Исправлена работа истории (доработана обработка адресов, добавлена обработка заказов с пустыми полями, доработана история по клиентам) +* История теперь синхронизируется по sinceId +* Проверка доступных версий API через метод /api/versions +* Добавлена возможность сопоставления кастомных полей(для API v5) \ No newline at end of file diff --git a/admin/controller/extension/module/retailcrm.php b/admin/controller/extension/module/retailcrm.php index 08c355c..8ff26b7 100644 --- a/admin/controller/extension/module/retailcrm.php +++ b/admin/controller/extension/module/retailcrm.php @@ -91,9 +91,8 @@ class ControllerExtensionModuleRetailcrm extends Controller $this->load->model('setting/setting'); $this->model_setting_setting ->editSetting($moduleTitle, array($moduleTitle . '_status' => 0)); - + $this->model_setting_setting->deleteSetting('retailcrm_history'); $this->loadModels(); - $this->{'model_' . $this->modelEvent}->deleteEvent($moduleTitle); } @@ -144,6 +143,7 @@ class ControllerExtensionModuleRetailcrm extends Controller $tokenTitle = $this->getTokenTitle(); $moduleTitle = $this->getModuleTitle(); $collector = $this->getCollectorTitle(); + $history_setting = $this->model_setting_setting->getSetting('retailcrm_history'); if ($this->request->server['REQUEST_METHOD'] == 'POST' && $this->validate()) { $analytics = $this->{'model_' . $this->modelExtension}->getInstalled('analytics'); @@ -156,15 +156,60 @@ class ControllerExtensionModuleRetailcrm extends Controller $this->uninstall_collector(); } - if (parse_url($this->request->post[$moduleTitle . '_url'])){ + if (parse_url($this->request->post[$moduleTitle . '_url'])) { $crm_url = parse_url($this->request->post[$moduleTitle . '_url'], PHP_URL_HOST); $this->request->post[$moduleTitle . '_url'] = 'https://'.$crm_url; } + $this->model_setting_setting->editSetting( $moduleTitle, $this->request->post ); + if ($this->request->post[$moduleTitle . '_apiversion'] != 'v3') { + if (!isset($history_setting['retailcrm_history_orders']) && !isset($history_setting['retailcrm_history_customers'])) { + $api = new RetailcrmProxy( + $this->request->post[$moduleTitle . '_url'], + $this->request->post[$moduleTitle . '_apikey'], + DIR_SYSTEM . 'storage/logs/retailcrm.log', + $this->request->post[$moduleTitle . '_apiversion'] + ); + + $ordersHistory = $api->ordersHistory(); + + if ($ordersHistory->isSuccessful()) { + $ordersHistory = $api->ordersHistory(array(), $ordersHistory['pagination']['totalPageCount']); + + if ($ordersHistory->isSuccessful()) { + + $lastChangeOrders = end($ordersHistory['history']); + $sinceIdOrders = $lastChangeOrders['id']; + $generatedAt = $ordersHistory['generatedAt']; + } + } + + $customersHistory = $api->customersHistory(); + + if ($customersHistory->isSuccessful()) { + $customersHistory = $api->customersHistory(array(), $customersHistory['pagination']['totalPageCount']); + + if ($customersHistory->isSuccessful()) { + $lastChangeCustomers = end($customersHistory['history']); + $sinceIdCustomers = $lastChangeCustomers['id']; + } + } + + $this->model_setting_setting->editSetting( + 'retailcrm_history', + array( + 'retailcrm_history_orders' => $sinceIdOrders, + 'retailcrm_history_customers' => $sinceIdCustomers, + 'retailcrm_history_datetime' => $generatedAt + ) + ); + } + } + $this->session->data['success'] = $this->language->get('text_success'); $redirect = $this->url->link( 'extension/module/retailcrm', $tokenTitle . '=' . $this->session->data[$tokenTitle], @@ -213,7 +258,12 @@ class ControllerExtensionModuleRetailcrm extends Controller 'text_label_promo', 'text_label_send', 'collector_custom_text', - 'text_require' + 'text_require', + 'custom_fields_tab_text', + 'text_error_custom_field', + 'text_error_cf_opencart', + 'text_error_cf_retailcrm', + 'retailcrm_dict_custom_fields' ); $_data = &$data; @@ -251,7 +301,11 @@ class ControllerExtensionModuleRetailcrm extends Controller ->getOrderStatuses(); $_data['payments'] = $this->model_extension_retailcrm_references ->getPaymentTypes(); - + + if ($apiVersion == 'v5') { + $_data['customFields'] = $this->model_extension_retailcrm_references + ->getCustomFields(); + } } $config_data = array( @@ -363,7 +417,6 @@ class ControllerExtensionModuleRetailcrm extends Controller $settings = $this->model_setting_setting->getSetting($moduleTitle); if ($settings[$moduleTitle . '_apiversion'] == 'v3') { - if (file_exists(DIR_APPLICATION . 'model/extension/retailcrm/custom/history/v3.php')) { $this->load->model('extension/retailcrm/custom/history/v3'); $this->model_extension_retailcrm_custom_history_v3->request(); @@ -372,7 +425,6 @@ class ControllerExtensionModuleRetailcrm extends Controller $this->model_extension_retailcrm_history_v3->request(); } } else { - if (file_exists(DIR_APPLICATION . 'model/extension/retailcrm/custom/history/v4-5.php')) { $this->load->model('extension/retailcrm/custom/history/v4-5'); $this->model_extension_retailcrm_custom_history_v4_5->request(); @@ -461,14 +513,14 @@ class ControllerExtensionModuleRetailcrm extends Controller $this->load->model('extension/retailcrm/customer'); $this->model_extension_retailcrm_customer->changeInCrm($customer); } - + /** * Export single order * * */ public function exportOrder() - { + { $order_id = isset($this->request->get['order_id']) ? $this->request->get['order_id'] : ''; $this->load->model('sale/order'); $moduleTitle = $this->getModuleTitle(); @@ -486,7 +538,7 @@ class ControllerExtensionModuleRetailcrm extends Controller $result = $this->model_extension_retailcrm_order->uploadOrder($data); } - echo json_encode($result); + echo json_encode($result->getStatusCode()); } /** @@ -495,7 +547,7 @@ class ControllerExtensionModuleRetailcrm extends Controller * */ public function export() { - + $this->load->model('customer/customer'); $customers = $this->model_customer_customer->getCustomers(); @@ -506,7 +558,7 @@ class ControllerExtensionModuleRetailcrm extends Controller $orders = $this->model_sale_order->getOrders(); $fullOrders = array(); - + foreach($orders as $order) { $fullOrder = $this->model_sale_order->getOrder($order['order_id']); @@ -534,22 +586,31 @@ class ControllerExtensionModuleRetailcrm extends Controller { $moduleTitle = $this->getModuleTitle(); + $versionsMap = array( + 'v3' => '3.0', + 'v4' => '4.0', + 'v5' => '5.0' + ); + if (!empty($this->request->post[$moduleTitle . '_url']) && !empty($this->request->post[$moduleTitle . '_apikey'])) { $this->retailcrm = new RetailcrmProxy( $this->request->post[$moduleTitle . '_url'], $this->request->post[$moduleTitle . '_apikey'], - DIR_SYSTEM . 'storage/logs/retailcrm.log', - $this->request->post[$moduleTitle . '_apiversion'] + DIR_SYSTEM . 'storage/logs/retailcrm.log' ); } - $response = $this->retailcrm->deliveryTypesList(); + $response = $this->retailcrm->apiVersions(); - if (!$response->isSuccessful()) { - $this->_error['warning'] = $this->language->get('text_error_api'); + if ($response && $response->isSuccessful()) { + if (!in_array($versionsMap[$this->request->post[$moduleTitle . '_apiversion']], $response['versions'])) { + $this->_error['warning'] = $this->language->get('text_error_api'); + } + } else { + $this->_error['warning'] = $this->language->get('text_error_save'); } - + if (!$this->user->hasPermission('modify', 'extension/module/retailcrm')) { $this->_error['warning'] = $this->language->get('error_permission'); } @@ -557,7 +618,7 @@ class ControllerExtensionModuleRetailcrm extends Controller if (isset($this->request->post[$moduleTitle . '_collector']['custom']) && $this->request->post[$moduleTitle . '_collector']['custom_form'] == 1) { $customField = $this->request->post[$moduleTitle . '_collector']['custom']; - + if (empty($customField['name']) && empty($customField['email']) && empty($customField['phone'])) { $this->_error['fields'] = $this->language->get('text_error_collector_fields'); } diff --git a/admin/language/en-gb/extension/module/retailcrm.php b/admin/language/en-gb/extension/module/retailcrm.php index 7ad2027..4f9451e 100644 --- a/admin/language/en-gb/extension/module/retailcrm.php +++ b/admin/language/en-gb/extension/module/retailcrm.php @@ -15,9 +15,9 @@ $_['retailcrm_upload_order'] = 'Unload single order'; $_['daemon_collector'] = 'Daemon Collector'; $_['general_tab_text'] = 'General'; $_['references_tab_text'] = 'References'; -$_['collector_tab_text'] = 'Collector'; +$_['collector_tab_text'] = 'Daemon Collector'; $_['collector_custom_text'] = 'Custom form'; - +$_['custom_fields_tab_text'] = 'Пользовательские поля'; $_['retailcrm_apiversion'] = 'API Version'; $_['retailcrm_url'] = 'RetailCRM URL'; $_['retailcrm_apikey'] = 'RetailCRM API Key'; @@ -41,11 +41,16 @@ $_['field_email'] = 'Email'; $_['field_phone'] = 'Phone'; $_['text_require'] = 'Require'; $_['text_error_collector_fields']= 'Fill in the field names Daemon Collector'; -$_['text_error_api'] = 'The selected version of the API or method is unavailable'; +$_['text_error_api'] = 'The selected version of the API is unavailable'; +$_['text_error_custom_field'] = 'Создайте пользовательские поля в карточке клиента в Opencart и RetailCRM, чтобы настроить их передачу'; +$_['text_error_cf_opencart'] = 'Отсутствуют пользовательские поля в Opencart'; +$_['text_error_cf_retailcrm'] = 'Отсутствуют пользовательские поля в RetailCRM'; +$_['text_error_save'] = 'Ошибка сохранения настроек'; $_['retailcrm_dict_delivery'] = 'Shipment methods'; $_['retailcrm_dict_status'] = 'Order statuses'; $_['retailcrm_dict_payment'] = 'Payment methods'; +$_['retailcrm_dict_custom_fields'] = 'Настройка пользовательских полей'; $_['column_total'] = 'Total'; $_['product_summ'] = 'Amount'; diff --git a/admin/language/ru-ru/extension/module/retailcrm.php b/admin/language/ru-ru/extension/module/retailcrm.php index 6bfdd57..15656f5 100644 --- a/admin/language/ru-ru/extension/module/retailcrm.php +++ b/admin/language/ru-ru/extension/module/retailcrm.php @@ -15,9 +15,9 @@ $_['retailcrm_upload_order'] = 'Выгрузка одного заказа'; $_['daemon_collector'] = 'Демон Collector'; $_['general_tab_text'] = 'Главная'; $_['references_tab_text'] = 'Справочники'; -$_['collector_tab_text'] = 'Collector'; +$_['collector_tab_text'] = 'Daemon Collector'; $_['collector_custom_text'] = 'Настройка полей формы'; - +$_['custom_fields_tab_text'] = 'Пользовательские поля'; $_['retailcrm_apiversion'] = 'Версия API'; $_['retailcrm_url'] = 'Адрес RetailCRM'; $_['retailcrm_apikey'] = 'Api ключ RetailCRM'; @@ -41,11 +41,16 @@ $_['field_email'] = 'Email'; $_['field_phone'] = 'Телефон'; $_['text_require'] = 'Обязательно для заполнения'; $_['text_error_collector_fields']= 'Заполните названия полей формы Демон Collector'; -$_['text_error_api'] = 'Недоступна выбранная версия API или метод.'; - +$_['text_error_api'] = 'Недоступна выбранная версия API.'; +$_['text_error_custom_field'] = 'Создайте пользовательские поля в карточке клиента в Opencart и RetailCRM, чтобы настроить их передачу'; +$_['text_error_cf_opencart'] = 'Отсутствуют пользовательские поля в Opencart'; +$_['text_error_cf_retailcrm'] = 'Отсутствуют пользовательские поля в RetailCRM'; +$_['text_error_save'] = 'Ошибка сохранения настроек'; + $_['retailcrm_dict_delivery'] = 'Способы доставки'; $_['retailcrm_dict_status'] = 'Статусы'; $_['retailcrm_dict_payment'] = 'Способы оплаты'; +$_['retailcrm_dict_custom_fields'] = 'Настройка пользовательских полей'; $_['column_total'] = 'Итого'; $_['product_summ'] = 'Сумма'; diff --git a/admin/model/extension/retailcrm/customer.php b/admin/model/extension/retailcrm/customer.php index 1448b0b..7e5f320 100644 --- a/admin/model/extension/retailcrm/customer.php +++ b/admin/model/extension/retailcrm/customer.php @@ -26,8 +26,9 @@ class ModelExtensionRetailcrmCustomer extends Model { { $this->initApi(); - if(empty($customer)) + if(empty($customer)) { return false; + } $customerToCrm = $this->process($customer); @@ -35,6 +36,8 @@ class ModelExtensionRetailcrmCustomer extends Model { } private function process($customer) { + $moduleTitle = $this->getModuleTitle(); + $customerToCrm = array( 'externalId' => $customer['customer_id'], 'firstName' => $customer['firstname'], @@ -57,7 +60,19 @@ class ModelExtensionRetailcrmCustomer extends Model { 'text' => $customer['address']['address_1'] . ' ' . $customer['address']['address_2'] ); } - + + if (isset($this->settings[$moduleTitle . '_custom_field']) && $customer['custom_field']) { + $customFields = json_decode($customer['custom_field']); + + foreach ($customFields as $key => $value) { + if (isset($this->settings[$moduleTitle . '_custom_field'][$key])) { + $customFieldsToCrm[$this->settings[$moduleTitle . '_custom_field'][$key]] = $value; + } + } + + $customerToCrm['customFields'] = $customFieldsToCrm; + } + return $customerToCrm; } @@ -65,18 +80,18 @@ class ModelExtensionRetailcrmCustomer extends Model { { $moduleTitle = $this->getModuleTitle(); $this->load->model('setting/setting'); - $settings = $this->model_setting_setting->getSetting($moduleTitle); + $this->settings = $this->model_setting_setting->getSetting($moduleTitle); - if(empty($settings[$moduleTitle . '_url']) || empty($settings[$moduleTitle . '_apikey'])) + 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( - $settings[$moduleTitle . '_url'], - $settings[$moduleTitle . '_apikey'], + $this->settings[$moduleTitle . '_url'], + $this->settings[$moduleTitle . '_apikey'], DIR_SYSTEM . 'storage/logs/retailcrm.log', - $settings[$moduleTitle . '_apiversion'] + $this->settings[$moduleTitle . '_apiversion'] ); } diff --git a/admin/model/extension/retailcrm/history/v3.php b/admin/model/extension/retailcrm/history/v3.php index f486c26..7128e3b 100644 --- a/admin/model/extension/retailcrm/history/v3.php +++ b/admin/model/extension/retailcrm/history/v3.php @@ -42,20 +42,22 @@ class ModelExtensionRetailcrmHistoryV3 extends Model $settings[$moduleTitle . '_apiversion'] ); - $lastRun = !empty($history['retailcrm_history']) - ? new DateTime($history['retailcrm_history']) + $lastRun = !empty($history['retailcrm_history_datetime']) + ? new DateTime($history['retailcrm_history_datetime']) : new DateTime(date('Y-m-d H:i:s', strtotime('-1 days', strtotime(date('Y-m-d H:i:s'))))); $packsOrders = $crm->ordersHistory($lastRun); - if(!$packsOrders->isSuccessful() && count($packsOrders['orders']) <= 0) + if(!$packsOrders->isSuccessful() && count($packsOrders['orders']) <= 0) { return false; - + } + $generatedAt = $packsOrders['generatedAt']; - $this->subtotalSettings = $this->model_setting_setting->getSetting('sub_total'); - $this->totalSettings = $this->model_setting_setting->getSetting('total'); - $this->shippingSettings = $this->model_setting_setting->getSetting('shipping'); + $this->totalTitle = $this->totalTitles(); + $this->subtotalSettings = $this->model_setting_setting->getSetting($this->totalTitle . 'sub_total'); + $this->totalSettings = $this->model_setting_setting->getSetting($this->totalTitle . 'total'); + $this->shippingSettings = $this->model_setting_setting->getSetting($this->totalTitle . 'shipping'); $this->delivery = array_flip($settings[$moduleTitle . '_delivery']); $this->payment = array_flip($settings[$moduleTitle . '_payment']); @@ -99,7 +101,7 @@ class ModelExtensionRetailcrmHistoryV3 extends Model } } - $this->model_setting_setting->editSetting('retailcrm_history', array('retailcrm_history' => $generatedAt)); + $this->model_setting_setting->editSetting('retailcrm_history', array('retailcrm_history_datetime' => $generatedAt)); if (!empty($this->createResult['customers'])) { $crm->customersFixExternalIds($this->createResult['customers']); @@ -117,20 +119,28 @@ class ModelExtensionRetailcrmHistoryV3 extends Model $data = array(); + $mail = isset($order['email']) ? $order['email'] : $order['customer']['email']; + $phone = isset($order['phone']) ? $order['phone'] : ''; + + if (!$phone) { + $data['telephone'] = $order['customer']['phones'] ? $order['customer']['phones'][0]['number'] : '80000000000'; + } else { + $data['telephone'] = $phone; + } + $data['store_id'] = $store == null ? 0 : $store; $data['customer'] = $order['firstName']; - $data['customer_id'] = (!empty($order['customer']['externalId'])) ? $order['customer']['externalId'] : 0; + $data['customer_id'] = isset($order['customer']['externalId']) ? $order['customer']['externalId'] : 0; $data['customer_group_id'] = 1; $data['firstname'] = $order['firstName']; - $data['lastname'] = (!empty($order['lastName'])) ? $order['lastName'] : ' '; - $data['email'] = $order['email']; - $data['telephone'] = (!empty($order['phone'])) ? $order['phone'] : ''; + $data['lastname'] = isset($order['lastName']) ? $order['lastName'] : $order['firstName']; + $data['email'] = $mail ? $mail : uniqid() . '@retailrcm.ru'; $data['comment'] = !empty($order['customerComment']) ? $order['customerComment'] : ''; $data['fax'] = ''; $data['payment_address'] = '0'; $data['payment_firstname'] = $order['firstName']; - $data['payment_lastname'] = (!empty($order['lastName'])) ? $order['lastName'] : ' '; + $data['payment_lastname'] = isset($order['lastName']) ? $order['lastName'] : $order['firstName']; $data['payment_address_1'] = isset($order['customer']['address']) ? $order['customer']['address']['text'] : ''; $data['payment_address_2'] = ''; $data['payment_company'] = ''; @@ -138,27 +148,47 @@ class ModelExtensionRetailcrmHistoryV3 extends Model $data['payment_city'] = !empty($order['customer']['address']['city']) ? $order['customer']['address']['city'] : $order['delivery']['address']['city']; $data['payment_postcode'] = !empty( $order['customer']['address']['index'] ) ? $order['customer']['address']['index'] : $order['delivery']['address']['index']; - $region = ''; + $shippingZone = ''; if (is_int($order['delivery']['address']['region'])) { - $region = $order['delivery']['address']['region']; + $shippingZone = $order['delivery']['address']['region']; } else { - foreach ($this->zones as $zone) { - if ($order['delivery']['address']['region'] == $zone['name']) { - $region = $zone['zone_id']; - } + $shippingZone = $this->getZoneByName($order['delivery']['address']['region']); + + if ($shippingZone) { + $shipping_zone_id = $shippingZone['zone_id']; + } else { + $shipping_zone_id = 0; } } - $data['payment_country_id'] = !empty($order['delivery']['address']['country']) ? $order['delivery']['address']['country'] : 0; - $data['payment_zone_id'] = !empty($order['delivery']['address']['region']) ? $order['delivery']['address']['region'] : $region; + if (isset($order['customer']['address']['region'])) { + $paymentZone = $this->getZoneByName($order['customer']['address']['region']); - $data['shipping_country_id'] = !empty($order['delivery']['address']['country']) ? $order['delivery']['address']['country'] : 0; - $data['shipping_zone_id'] = $region; + if ($paymentZone) { + $payment_zone_id = $paymentZone['zone_id']; + } else { + $payment_zone_id = 0; + } + } + + if (isset($order['delivery']['address']['countryIso'])) { + $shippingCountry = $this->getCountryByIsoCode($order['delivery']['address']['countryIso']); + } + + if (isset($order['customer']['address']['countryIso'])) { + $paymentCountry = $this->getCountryByIsoCode($order['customer']['address']['countryIso']); + } + + $data['payment_country_id'] = isset($paymentCountry) ? $paymentCountry['country_id'] : 0; + $data['payment_zone_id'] = $payment_zone_id; + + $data['shipping_country_id'] = isset($shippingCountry) ? $shippingCountry['country_id'] : 0; + $data['shipping_zone_id'] = $shipping_zone_id; $data['shipping_address'] = '0'; $data['shipping_firstname'] = $order['firstName']; - $data['shipping_lastname'] = (!empty($order['lastName'])) ? $order['lastName'] : ' '; + $data['shipping_lastname'] = isset($order['lastName']) ? $order['lastName'] : $order['firstName']; $data['shipping_address_1'] = $order['delivery']['address']['text']; $data['shipping_address_2'] = ''; $data['shipping_company'] = ''; @@ -192,7 +222,6 @@ class ModelExtensionRetailcrmHistoryV3 extends Model $data['order_product'] = array(); foreach ($order['items'] as $item) { - //$product = $this->model_catalog_product->getProduct($item['offer']['externalId']); $productId = $item['offer']['externalId']; $options = array(); if(mb_strpos($item['offer']['externalId'], '#') > 1) { @@ -251,7 +280,7 @@ class ModelExtensionRetailcrmHistoryV3 extends Model 'title' => $this->ocDelivery[$data['shipping_code']], 'value' => $deliveryCost, 'text' => $deliveryCost, - 'sort_order' => $this->shippingSettings['shipping_sort_order'] + 'sort_order' => $this->shippingSettings[$this->totalTitle . 'shipping_sort_order'] ), array( 'order_total_id' => '', @@ -259,7 +288,7 @@ class ModelExtensionRetailcrmHistoryV3 extends Model 'title' => $this->language->get('column_total'), 'value' => isset($order['totalSumm']) ? $order['totalSumm'] : $order['summ'] + $deliveryCost, 'text' => isset($order['totalSumm']) ? $order['totalSumm'] : $order['summ'] + $deliveryCost, - 'sort_order' => $this->totalSettings['total_sort_order'] + 'sort_order' => $this->totalSettings[$this->totalTitle . 'total_sort_order'] ) ); @@ -291,21 +320,35 @@ class ModelExtensionRetailcrmHistoryV3 extends Model $data = array(); if ($customer_id == 0) { + if (isset($order['customer']['address']['countryIso'])) { + $customerCountry = $this->getCountryByIsoCode($order['customer']['address']['countryIso']); + } else { + $customerCountry = $this->getCountryByIsoCode($order['delivery']['address']['countryIso']); + } + + if (isset($order['customer']['address']['region'])) { + $customerZone = $this->getZoneByName($order['customer']['address']['region']); + } else { + $customerZone = $this->getZoneByName($order['delivery']['address']['region']); + } + $cData = array( 'store_id' => 0, 'customer_group_id' => '1', - 'firstname' => $order['firstName'], - 'lastname' => (!empty($order['lastName'])) ? $order['lastName'] : ' ', - 'email' => $order['email'], - 'telephone' => (!empty($order['customer']['phones'][0]['number']) ) ? $order['customer']['phones'][0]['number'] : ' ', + 'firstname' => isset($order['patronymic']) ? $order['firstName'] . ' ' . $order['patronymic'] : $order['firstName'], + 'lastname' => (!empty($order['customer']['lastName'])) ? $order['customer']['lastName'] : ' ', + 'email' => $order['customer']['email'], + 'telephone' => $order['customer']['phones'] ? $order['customer']['phones'][0]['number'] : ' ', 'fax' => '', 'newsletter' => 0, 'password' => 'tmppass', 'status' => 1, + 'approved' => 1, + 'safe' => 0, 'address' => array( array( - 'firstname' => $order['firstName'], - 'lastname' => (!empty($order['lastName'])) ? $order['lastName'] : ' ', + 'firstname' => isset($order['patronymic']) ? $order['firstName'] . ' ' . $order['patronymic'] : $order['firstName'], + 'lastname' => (!empty($order['customer']['lastName'])) ? $order['customer']['lastName'] : ' ', 'address_1' => $order['customer']['address']['text'], 'address_2' => ' ', 'city' => !empty($order['customer']['address']['city']) ? $order['customer']['address']['city'] : $order['delivery']['address']['city'], @@ -313,39 +356,39 @@ class ModelExtensionRetailcrmHistoryV3 extends Model 'tax_id' => '1', 'company' => '', 'company_id' => '', - 'zone_id' => '0', - 'country_id' => 0 + 'zone_id' => $customerZone ? $customerZone['zone_id'] : 0, + 'country_id' => $customerCountry ? $customerCountry['country_id'] : 0, + 'default' => '1' ) ), ); - - $this->model_customer_customer->addCustomer($cData); - - if (!empty($order['email'])) { - $tryToFind = $this->model_customer_customer->getCustomerByEmail($order['email']); - $customer_id = $tryToFind['customer_id']; - } else { - $last = $this->model_customer_customer->getCustomers($data = array('order' => 'DESC', 'limit' => 1)); - $customer_id = $last[0]['customer_id']; - } + $customer_id = $this->model_customer_customer->addCustomer($cData); $customersIdsFix[] = array('id' => $order['customer']['id'], 'externalId' => (int)$customer_id); } + $mail = isset($order['email']) ? $order['email'] : $order['customer']['email']; + $phone = isset($order['phone']) ? $order['phone'] : ''; + + if (!$phone) { + $data['telephone'] = $order['customer']['phones'] ? $order['customer']['phones'][0]['number'] : '80000000000'; + } else { + $data['telephone'] = $phone; + } + $data['store_id'] = $store == null ? 0 : $store; $data['customer'] = $order['firstName']; $data['customer_id'] = $customer_id; $data['customer_group_id'] = 1; $data['firstname'] = $order['firstName']; - $data['lastname'] = (!empty($order['lastName'])) ? $order['lastName'] : ' '; - $data['email'] = $order['email']; - $data['telephone'] = (!empty($order['customer']['phones'][0]['number'])) ? $order['customer']['phones'][0]['number'] : ' '; + $data['lastname'] = isset($order['lastName']) ? $order['lastName'] : $order['firstName']; + $data['email'] = $mail ? $mail : uniqid() . '@retailrcm.ru'; $data['comment'] = !empty($order['customerComment']) ? $order['customerComment'] : ''; $data['fax'] = ''; $data['payment_address'] = '0'; $data['payment_firstname'] = $order['firstName']; - $data['payment_lastname'] = (!empty($order['lastName'])) ? $order['lastName'] : ' '; + $data['payment_lastname'] = isset($order['lastName']) ? $order['lastName'] : $order['firstName']; $data['payment_address_1'] = $order['customer']['address']['text']; $data['payment_address_2'] = ''; $data['payment_company'] = ''; @@ -353,25 +396,45 @@ class ModelExtensionRetailcrmHistoryV3 extends Model $data['payment_city'] = !empty($order['customer']['address']['city']) ? $order['customer']['address']['city'] : $order['delivery']['address']['city']; $data['payment_postcode'] = !empty($order['customer']['address']['index']) ? $order['customer']['address']['index'] : $order['delivery']['address']['index']; - $region = ''; + $shippingZone = ''; - if (!empty($order['delivery']['address']['region']) && is_int($order['delivery']['address']['region'])) { - $region = $order['delivery']['address']['region']; + if (is_int($order['delivery']['address']['region'])) { + $shippingZone = $order['delivery']['address']['region']; } else { - foreach ($this->zones as $zone) { - if ($order['delivery']['address']['region'] == $zone['name']) { - $region = $zone['zone_id']; - } + $shippingZone = $this->getZoneByName($order['delivery']['address']['region']); + + if ($shippingZone) { + $shipping_zone_id = $shippingZone['zone_id']; + } else { + $shipping_zone_id = 0; } } - $data['payment_country_id'] = !empty($order['delivery']['address']['country']) ? $order['delivery']['address']['country'] : 0; - $data['payment_zone_id'] = !empty($order['delivery']['address']['region']) ? $order['delivery']['address']['region'] : $region; - $data['shipping_country_id'] = !empty($order['delivery']['address']['country']) ? $order['delivery']['address']['country'] : 0; - $data['shipping_zone_id'] = $region; + if (isset($order['customer']['address']['region'])) { + $paymentZone = $this->getZoneByName($order['customer']['address']['region']); + + if ($paymentZone) { + $payment_zone_id = $paymentZone['zone_id']; + } else { + $payment_zone_id = 0; + } + } + + if (isset($order['delivery']['address']['countryIso'])) { + $shippingCountry = $this->getCountryByIsoCode($order['delivery']['address']['countryIso']); + } + + if (isset($order['customer']['address']['countryIso'])) { + $paymentCountry = $this->getCountryByIsoCode($order['customer']['address']['countryIso']); + } + + $data['payment_country_id'] = $paymentCountry ? $paymentCountry['country_id'] : 0; + $data['payment_zone_id'] = $payment_zone_id; + $data['shipping_country_id'] = $shippingCountry ? $shippingCountry['country_id'] : 0; + $data['shipping_zone_id'] = $shipping_zone_id; $data['shipping_address'] = '0'; $data['shipping_firstname'] = $order['firstName']; - $data['shipping_lastname'] = (!empty($order['lastName'])) ? $order['lastName'] : ' '; + $data['shipping_lastname'] = isset($order['lastName']) ? $order['lastName'] : $order['firstName']; $data['shipping_address_1'] = $order['delivery']['address']['text']; $data['shipping_address_2'] = ''; $data['shipping_company'] = ''; @@ -404,19 +467,35 @@ class ModelExtensionRetailcrmHistoryV3 extends Model $data['order_product'] = array(); foreach ($order['items'] as $item) { - $product = $this->model_catalog_product->getProduct($item['offer']['externalId']); - $data['order_product'][] = array( - 'product_id' => $item['offer']['externalId'], - 'name' => $item['offer']['name'], - 'quantity' => $item['quantity'], - 'price' => $item['initialPrice'], - 'total' => $item['initialPrice'] * $item['quantity'], - 'model' => $product['model'], + $productId = $item['offer']['externalId']; + $options = array(); + if(mb_strpos($item['offer']['externalId'], '#') > 1) { + $offer = explode('#', $item['offer']['externalId']); + $productId = $offer[0]; + $optionsFromCRM = explode('_', $offer[1]); - // this data will not retrive from crm - 'order_product_id' => '', - 'tax' => 0, - 'reward' => 0 + foreach($optionsFromCRM as $optionFromCRM) { + $optionData = explode('-', $optionFromCRM); + $productOptionId = $optionData[0]; + $optionValueId = $optionData[1]; + + $productOptions = $this->model_catalog_product->getProductOptions($productId); + + foreach($productOptions as $productOption) { + if($productOptionId == $productOption['product_option_id']) { + foreach($productOption['product_option_value'] as $productOptionValue) { + if($productOptionValue['option_value_id'] == $optionValueId) { + $options[$productOptionId] = $productOptionValue['product_option_value_id']; + } + } + } + } + } + } + $data['order_product'][] = array( + 'product_id' => $productId, + 'quantity' => $item['quantity'], + 'option' => $options ); } @@ -437,7 +516,7 @@ class ModelExtensionRetailcrmHistoryV3 extends Model 'title' => $this->ocDelivery[$data['shipping_code']], 'value' => $deliveryCost, 'text' => $deliveryCost, - 'sort_order' => $this->shippingSettings['shipping_sort_order'] + 'sort_order' => $this->shippingSettings[$this->totalTitle . 'shipping_sort_order'] ), array( 'order_total_id' => '', @@ -445,18 +524,16 @@ class ModelExtensionRetailcrmHistoryV3 extends Model 'title' => $this->language->get('column_total'), 'value' => !empty($order['totalSumm']) ? $order['totalSumm'] : $order['summ'] + $deliveryCost, 'text' => isset($order['totalSumm']) ? $order['totalSumm'] : $order['summ'] + $deliveryCost, - 'sort_order' => $this->totalSettings['total_sort_order'] + 'sort_order' => $this->totalSettings[$this->totalTitle . 'total_sort_order'] ) ); $data['fromApi'] = true; $data['order_status_id'] = 1; - $this->opencartApiClient->addOrder($data); + $order_id = $this->opencartApiClient->addOrder($data); - $last = $this->model_sale_order->getOrders($data = array('order' => 'DESC', 'limit' => 1, 'start' => 0)); - - $ordersIdsFix[] = array('id' => $order['id'], 'externalId' => (int) $last[0]['order_id']); + $ordersIdsFix[] = array('id' => $order['id'], 'externalId' => (int) $order_id); } return array('customers' => $customersIdsFix, 'orders' => $ordersIdsFix); @@ -472,4 +549,29 @@ class ModelExtensionRetailcrmHistoryV3 extends Model return $title; } + + private function totalTitles() + { + if (version_compare(VERSION, '3.0', '<')) { + $title = ''; + } else { + $title = 'total_'; + } + + return $title; + } + + public function getCountryByIsoCode($isoCode) + { + $query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "country` WHERE iso_code_2 = '" . $isoCode . "'"); + + return $query->row; + } + + public function getZoneByName($name) + { + $query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "zone` WHERE name = '" . $name . "'"); + + return $query->row; + } } diff --git a/admin/model/extension/retailcrm/history/v4_5.php b/admin/model/extension/retailcrm/history/v4_5.php index 6c56b07..0e3ee02 100644 --- a/admin/model/extension/retailcrm/history/v4_5.php +++ b/admin/model/extension/retailcrm/history/v4_5.php @@ -8,7 +8,7 @@ class ModelExtensionRetailcrmHistoryV45 extends Model public function request() { - $moduleTitle = $this->getModuleTitle(); + $this->moduleTitle = $this->getModuleTitle(); $this->load->model('setting/setting'); $this->load->model('setting/store'); $this->load->model('user/api'); @@ -21,12 +21,12 @@ class ModelExtensionRetailcrmHistoryV45 extends Model $this->load->language('extension/module/retailcrm'); - $settings = $this->model_setting_setting->getSetting($moduleTitle); + $settings = $this->model_setting_setting->getSetting($this->moduleTitle); $history = $this->model_setting_setting->getSetting('retailcrm_history'); $settings['domain'] = parse_url(HTTP_SERVER, PHP_URL_HOST); - $url = isset($settings[$moduleTitle . '_url']) ? $settings[$moduleTitle . '_url'] : null; - $key = isset($settings[$moduleTitle . '_apikey']) ? $settings[$moduleTitle . '_apikey'] : null; + $url = isset($settings[$this->moduleTitle . '_url']) ? $settings[$this->moduleTitle . '_url'] : null; + $key = isset($settings[$this->moduleTitle . '_apikey']) ? $settings[$this->moduleTitle . '_apikey'] : null; if (empty($url) || empty($key)) { $this->log->addNotice('You need to configure retailcrm module first.'); @@ -36,43 +36,57 @@ class ModelExtensionRetailcrmHistoryV45 extends Model $this->opencartApiClient = new OpencartApiClient($this->registry); $crm = new RetailcrmProxy( - $settings[$moduleTitle . '_url'], - $settings[$moduleTitle . '_apikey'], + $settings[$this->moduleTitle . '_url'], + $settings[$this->moduleTitle . '_apikey'], DIR_SYSTEM . 'storage/logs/retailcrm.log', - $settings[$moduleTitle . '_apiversion'] + $settings[$this->moduleTitle . '_apiversion'] ); - $lastRun = !empty($history['retailcrm_history']) - ? new DateTime($history['retailcrm_history']) - : new DateTime(date('Y-m-d H:i:s', strtotime('-1 days', strtotime(date('Y-m-d H:i:s'))))); + $sinceIdOrders = $history['retailcrm_history_orders'] ? $history['retailcrm_history_orders'] : null; + $sinceIdCustomers = $history['retailcrm_history_customers'] ? $history['retailcrm_history_customers'] : null; $packsOrders = $crm->ordersHistory(array( - 'startDate' => $lastRun->format('Y-m-d H:i:s'), + 'sinceId' => $sinceIdOrders ? $sinceIdOrders : 0 ), 1, 100); $packsCustomers = $crm->customersHistory(array( - 'startDate' => $lastRun->format('Y-m-d H:i:s'), + 'sinceId' => $sinceIdCustomers ? $sinceIdCustomers : 0 ), 1, 100); - if(!$packsOrders->isSuccessful() && count($packsOrders->history) <= 0 && !$packsCustomers->isSuccessful() && count($Customers->history) <= 0) + + if(!$packsOrders->isSuccessful() && count($packsOrders->history) <= 0 && !$packsCustomers->isSuccessful() && count($packsCustomers->history) <= 0) { return false; - + } + + $generatedAt = $packsOrders['generatedAt']; $orders = RetailcrmHistoryHelper::assemblyOrder($packsOrders->history); $customers = RetailcrmHistoryHelper::assemblyCustomer($packsCustomers->history); - $generatedAt = $packsOrders['generatedAt']; + $ordersHistory = $packsOrders->history; + $customersHistory = $packsCustomers->history; + + $lastChangeOrders = $ordersHistory ? end($ordersHistory) : null; + $lastChangeCustomers = $customersHistory ? end($customersHistory) : null; + + if ($lastChangeOrders !== null) { + $sinceIdOrders = $lastChangeOrders['id']; + } + + if ($lastChangeCustomers !== null) { + $sinceIdCustomers = $lastChangeCustomers['id']; + } $this->totalTitle = $this->totalTitles(); $this->subtotalSettings = $this->model_setting_setting->getSetting($this->totalTitle . 'sub_total'); $this->totalSettings = $this->model_setting_setting->getSetting($this->totalTitle . 'total'); $this->shippingSettings = $this->model_setting_setting->getSetting($this->totalTitle . 'shipping'); - $this->delivery = array_flip($settings[$moduleTitle . '_delivery']); - $this->payment = array_flip($settings[$moduleTitle . '_payment']); - $this->status = array_flip($settings[$moduleTitle . '_status']); + $this->delivery = array_flip($settings[$this->moduleTitle . '_delivery']); + $this->payment = array_flip($settings[$this->moduleTitle . '_payment']); + $this->status = array_flip($settings[$this->moduleTitle . '_status']); $this->ocPayment = $this->model_extension_retailcrm_references ->getOpercartPaymentTypes(); - $this->ocDelivery = $settings[$moduleTitle . '_delivery']; + $this->ocDelivery = $settings[$this->moduleTitle . '_delivery']; $this->zones = $this->model_localisation_zone->getZones(); @@ -105,6 +119,13 @@ class ModelExtensionRetailcrmHistoryV45 extends Model unset($customers); + if (!empty($updateCustomers)) { + $customers = $crm->customersList($filter = array('ids' => $updateCustomers)); + if ($customers) { + $this->updateCustomers($customers['customers']); + } + } + if (!empty($newOrders)) { $orders = $crm->ordersList($filter = array('ids' => $newOrders)); if ($orders) { @@ -119,14 +140,14 @@ class ModelExtensionRetailcrmHistoryV45 extends Model } } - if (!empty($updateCustomers)) { - $customers = $crm->customersList($filter = array('ids' => $updateCustomers)); - if ($customers) { - $this->updateCustomers($customers['customers']); - } - } - - $this->model_setting_setting->editSetting('retailcrm_history', array('retailcrm_history' => $generatedAt)); + $this->model_setting_setting->editSetting( + 'retailcrm_history', + array( + 'retailcrm_history_orders' => $sinceIdOrders, + 'retailcrm_history_customers' => $sinceIdCustomers, + 'retailcrm_history_datetime' => $generatedAt + ) + ); if (!empty($this->createResult['customers'])) { $crm->customersFixExternalIds($this->createResult['customers']); @@ -153,25 +174,33 @@ class ModelExtensionRetailcrmHistoryV45 extends Model $payment = end($order['payments']); } } elseif (isset($order['paymentType'])) { - $payment = $order['paymentType']; + $payment['type'] = $order['paymentType']; } $data = array(); + $mail = isset($order['email']) ? $order['email'] : $order['customer']['email']; + $phone = isset($order['phone']) ? $order['phone'] : ''; + + if (!$phone) { + $data['telephone'] = $order['customer']['phones'] ? $order['customer']['phones'][0]['number'] : '80000000000'; + } else { + $data['telephone'] = $phone; + } + $data['store_id'] = $store == null ? 0 : $store; $data['customer'] = $order['firstName']; $data['customer_id'] = (!empty($order['customer']['externalId'])) ? $order['customer']['externalId'] : 0; $data['customer_group_id'] = 1; $data['firstname'] = $order['firstName']; - $data['lastname'] = (!empty($order['lastName'])) ? $order['lastName'] : ' '; - $data['email'] = $order['email']; - $data['telephone'] = (!empty($order['phone'])) ? $order['phone'] : ''; + $data['lastname'] = isset($order['lastName']) ? $order['lastName'] : $order['firstName']; + $data['email'] = $mail ? $mail : uniqid() . '@retailrcm.ru'; $data['comment'] = !empty($order['customerComment']) ? $order['customerComment'] : ''; $data['fax'] = ''; $data['payment_address'] = '0'; $data['payment_firstname'] = $order['firstName']; - $data['payment_lastname'] = (!empty($order['lastName'])) ? $order['lastName'] : ' '; + $data['payment_lastname'] = isset($order['lastName']) ? $order['lastName'] : $order['firstName']; $data['payment_address_1'] = isset($order['customer']['address']) ? $order['customer']['address']['text'] : ''; $data['payment_address_2'] = ''; $data['payment_company'] = ''; @@ -179,34 +208,51 @@ class ModelExtensionRetailcrmHistoryV45 extends Model $data['payment_city'] = !empty($order['customer']['address']['city']) ? $order['customer']['address']['city'] : $order['delivery']['address']['city']; $data['payment_postcode'] = !empty( $order['customer']['address']['index'] ) ? $order['customer']['address']['index'] : $order['delivery']['address']['index']; - $region = ''; + $shippingZone = ''; if (is_int($order['delivery']['address']['region'])) { - $region = $order['delivery']['address']['region']; + $shippingZone = $order['delivery']['address']['region']; } else { - foreach ($this->zones as $zone) { - if ($order['delivery']['address']['region'] == $zone['name']) { - $region = $zone['zone_id']; - } + $shippingZone = $this->getZoneByName($order['delivery']['address']['region']); + + if ($shippingZone) { + $shipping_zone_id = $shippingZone['zone_id']; + } else { + $shipping_zone_id = 0; } } - $data['payment_country_id'] = !empty($order['delivery']['address']['country']) ? $order['delivery']['address']['country'] : 0; - $data['payment_zone_id'] = !empty($order['delivery']['address']['region']) ? $order['delivery']['address']['region'] : $region; + if (isset($order['customer']['address']['region'])) { + $paymentZone = $this->getZoneByName($order['customer']['address']['region']); - $data['shipping_country_id'] = !empty($order['delivery']['address']['country']) ? $order['delivery']['address']['country'] : 0; - $data['shipping_zone_id'] = $region; + if ($paymentZone) { + $payment_zone_id = $paymentZone['zone_id']; + } else { + $payment_zone_id = 0; + } + } + if (isset($order['delivery']['address']['countryIso'])) { + $shippingCountry = $this->getCountryByIsoCode($order['delivery']['address']['countryIso']); + } + + if (isset($order['customer']['address']['countryIso'])) { + $paymentCountry = $this->getCountryByIsoCode($order['customer']['address']['countryIso']); + } + + $data['payment_country_id'] = $paymentCountry ? $paymentCountry['country_id'] : 0; + $data['payment_zone_id'] = $payment_zone_id; + $data['shipping_country_id'] = $shippingCountry ? $shippingCountry['country_id'] : 0; + $data['shipping_zone_id'] = $shipping_zone_id; $data['shipping_address'] = '0'; $data['shipping_firstname'] = $order['firstName']; - $data['shipping_lastname'] = (!empty($order['lastName'])) ? $order['lastName'] : ' '; + $data['shipping_lastname'] = isset($order['lastName']) ? $order['lastName'] : $order['firstName']; $data['shipping_address_1'] = $order['delivery']['address']['text']; $data['shipping_address_2'] = ''; $data['shipping_company'] = ''; $data['shipping_company_id'] = ''; $data['shipping_city'] = $order['delivery']['address']['city']; $data['shipping_postcode'] = $order['delivery']['address']['index']; - $data['shipping'] = $this->delivery[$order['delivery']['code']]; $data['shipping_method'] = $this->ocDelivery[$data['shipping']]; $data['shipping_code'] = $this->delivery[$order['delivery']['code']]; @@ -240,7 +286,6 @@ class ModelExtensionRetailcrmHistoryV45 extends Model $data['order_product'] = array(); foreach ($order['items'] as $item) { - //$product = $this->model_catalog_product->getProduct($item['offer']['externalId']); $productId = $item['offer']['externalId']; $options = array(); if(mb_strpos($item['offer']['externalId'], '#') > 1) { @@ -248,7 +293,7 @@ class ModelExtensionRetailcrmHistoryV45 extends Model $productId = $offer[0]; $optionsFromCRM = explode('_', $offer[1]); - foreach($optionsFromCRM as $optionFromCRM) { + foreach ($optionsFromCRM as $optionFromCRM) { $optionData = explode('-', $optionFromCRM); $productOptionId = $optionData[0]; $optionValueId = $optionData[1]; @@ -283,7 +328,7 @@ class ModelExtensionRetailcrmHistoryV45 extends Model } } } - + $data['order_total'] = array( array( 'order_total_id' => '', @@ -335,7 +380,7 @@ class ModelExtensionRetailcrmHistoryV45 extends Model if (isset($order['payments'])) { $payment = end($order['payments']); } elseif (isset($order['paymentType'])) { - $payment = $order['paymentType']; + $payment['type'] = $order['paymentType']; } $customer_id = (!empty($order['customer']['externalId'])) @@ -345,21 +390,35 @@ class ModelExtensionRetailcrmHistoryV45 extends Model $data = array(); if ($customer_id == 0) { + if (isset($order['customer']['address']['countryIso'])) { + $customerCountry = $this->getCountryByIsoCode($order['customer']['address']['countryIso']); + } else { + $customerCountry = $this->getCountryByIsoCode($order['delivery']['address']['countryIso']); + } + + if (isset($order['customer']['address']['region'])) { + $customerZone = $this->getZoneByName($order['customer']['address']['region']); + } else { + $customerZone = $this->getZoneByName($order['delivery']['address']['region']); + } + $cData = array( 'store_id' => 0, 'customer_group_id' => '1', - 'firstname' => $order['firstName'], - 'lastname' => (!empty($order['lastName'])) ? $order['lastName'] : ' ', - 'email' => $order['email'], - 'telephone' => (!empty($order['customer']['phones'][0]['number']) ) ? $order['customer']['phones'][0]['number'] : ' ', + 'firstname' => isset($order['patronymic']) ? $order['firstName'] . ' ' . $order['patronymic'] : $order['firstName'], + 'lastname' => (!empty($order['customer']['lastName'])) ? $order['customer']['lastName'] : ' ', + 'email' => $order['customer']['email'], + 'telephone' => $order['customer']['phones'] ? $order['customer']['phones'][0]['number'] : ' ', 'fax' => '', 'newsletter' => 0, 'password' => 'tmppass', 'status' => 1, + 'approved' => 1, + 'safe' => 0, 'address' => array( array( - 'firstname' => $order['firstName'], - 'lastname' => (!empty($order['lastName'])) ? $order['lastName'] : ' ', + 'firstname' => isset($order['patronymic']) ? $order['firstName'] . ' ' . $order['patronymic'] : $order['firstName'], + 'lastname' => (!empty($order['customer']['lastName'])) ? $order['customer']['lastName'] : ' ', 'address_1' => $order['customer']['address']['text'], 'address_2' => ' ', 'city' => !empty($order['customer']['address']['city']) ? $order['customer']['address']['city'] : $order['delivery']['address']['city'], @@ -367,39 +426,39 @@ class ModelExtensionRetailcrmHistoryV45 extends Model 'tax_id' => '1', 'company' => '', 'company_id' => '', - 'zone_id' => '0', - 'country_id' => 0 + 'zone_id' => $customerZone ? $customerZone['zone_id'] : 0, + 'country_id' => $customerCountry ? $customerCountry['country_id'] : 0, + 'default' => '1' ) ), ); - - $this->model_customer_customer->addCustomer($cData); - - if (!empty($order['email'])) { - $tryToFind = $this->model_customer_customer->getCustomerByEmail($order['email']); - $customer_id = $tryToFind['customer_id']; - } else { - $last = $this->model_customer_customer->getCustomers($data = array('order' => 'DESC', 'limit' => 1)); - $customer_id = $last[0]['customer_id']; - } + $customer_id = $this->model_customer_customer->addCustomer($cData); $customersIdsFix[] = array('id' => $order['customer']['id'], 'externalId' => (int)$customer_id); } + $mail = isset($order['email']) ? $order['email'] : $order['customer']['email']; + $phone = isset($order['phone']) ? $order['phone'] : ''; + + if (!$phone) { + $data['telephone'] = $order['customer']['phones'] ? $order['customer']['phones'][0]['number'] : '80000000000'; + } else { + $data['telephone'] = $phone; + } + $data['store_id'] = $store == null ? 0 : $store; $data['customer'] = $order['firstName']; $data['customer_id'] = $customer_id; $data['customer_group_id'] = 1; $data['firstname'] = $order['firstName']; - $data['lastname'] = (!empty($order['lastName'])) ? $order['lastName'] : ' '; - $data['email'] = $order['email']; - $data['telephone'] = (!empty($order['customer']['phones'][0]['number'])) ? $order['customer']['phones'][0]['number'] : ' '; + $data['lastname'] = (isset($order['lastName'])) ? $order['lastName'] : $order['firstName']; + $data['email'] = $mail ? $mail : uniqid() . '@retailrcm.ru'; $data['comment'] = !empty($order['customerComment']) ? $order['customerComment'] : ''; $data['fax'] = ''; $data['payment_address'] = '0'; $data['payment_firstname'] = $order['firstName']; - $data['payment_lastname'] = (!empty($order['lastName'])) ? $order['lastName'] : ' '; + $data['payment_lastname'] = (isset($order['lastName'])) ? $order['lastName'] : $order['firstName']; $data['payment_address_1'] = $order['customer']['address']['text']; $data['payment_address_2'] = ''; $data['payment_company'] = ''; @@ -407,25 +466,45 @@ class ModelExtensionRetailcrmHistoryV45 extends Model $data['payment_city'] = !empty($order['customer']['address']['city']) ? $order['customer']['address']['city'] : $order['delivery']['address']['city']; $data['payment_postcode'] = !empty($order['customer']['address']['index']) ? $order['customer']['address']['index'] : $order['delivery']['address']['index']; - $region = ''; + $shippingZone = ''; if (!empty($order['delivery']['address']['region']) && is_int($order['delivery']['address']['region'])) { - $region = $order['delivery']['address']['region']; + $shippingZone = $order['delivery']['address']['region']; } else { - foreach ($this->zones as $zone) { - if ($order['delivery']['address']['region'] == $zone['name']) { - $region = $zone['zone_id']; - } + $shippingZone = $this->getZoneByName($order['delivery']['address']['region']); + + if ($shippingZone) { + $shipping_zone_id = $shippingZone['zone_id']; + } else { + $shipping_zone_id = 0; } } - $data['payment_country_id'] = !empty($order['delivery']['address']['country']) ? $order['delivery']['address']['country'] : 0; - $data['payment_zone_id'] = !empty($order['delivery']['address']['region']) ? $order['delivery']['address']['region'] : $region; - $data['shipping_country_id'] = !empty($order['delivery']['address']['country']) ? $order['delivery']['address']['country'] : 0; - $data['shipping_zone_id'] = $region; + if (isset($order['customer']['address']['region'])) { + $paymentZone = $this->getZoneByName($order['customer']['address']['region']); + + if ($paymentZone) { + $payment_zone_id = $paymentZone['zone_id']; + } else { + $payment_zone_id = 0; + } + } + + if (isset($order['delivery']['address']['countryIso'])) { + $shippingCountry = $this->getCountryByIsoCode($order['delivery']['address']['countryIso']); + } + + if (isset($order['customer']['address']['countryIso'])) { + $paymentCountry = $this->getCountryByIsoCode($order['customer']['address']['countryIso']); + } + + $data['payment_country_id'] = $paymentCountry ? $paymentCountry['country_id'] : 0; + $data['payment_zone_id'] = $payment_zone_id; + $data['shipping_country_id'] = $shippingCountry ? $shippingCountry['country_id'] : 0; + $data['shipping_zone_id'] = $shipping_zone_id; $data['shipping_address'] = '0'; $data['shipping_firstname'] = $order['firstName']; - $data['shipping_lastname'] = (!empty($order['lastName'])) ? $order['lastName'] : ' '; + $data['shipping_lastname'] = (isset($order['lastName'])) ? $order['lastName'] : $order['firstName']; $data['shipping_address_1'] = $order['delivery']['address']['text']; $data['shipping_address_2'] = ''; $data['shipping_company'] = ''; @@ -442,7 +521,7 @@ class ModelExtensionRetailcrmHistoryV45 extends Model $data['payment_method'] = $this->ocPayment[$data['payment']]; $data['payment_code'] = $this->payment[$payment['type']]; } - + // this data will not retrive from crm for now $data['tax'] = ''; $data['tax_id'] = ''; @@ -461,19 +540,35 @@ class ModelExtensionRetailcrmHistoryV45 extends Model $data['order_product'] = array(); foreach ($order['items'] as $item) { - $product = $this->model_catalog_product->getProduct($item['offer']['externalId']); - $data['order_product'][] = array( - 'product_id' => $item['offer']['externalId'], - 'name' => $item['offer']['name'], - 'quantity' => $item['quantity'], - 'price' => $item['initialPrice'], - 'total' => $item['initialPrice'] * $item['quantity'], - 'model' => $product['model'], + $productId = $item['offer']['externalId']; + $options = array(); + if(mb_strpos($item['offer']['externalId'], '#') > 1) { + $offer = explode('#', $item['offer']['externalId']); + $productId = $offer[0]; + $optionsFromCRM = explode('_', $offer[1]); - // this data will not retrive from crm - 'order_product_id' => '', - 'tax' => 0, - 'reward' => 0 + foreach ($optionsFromCRM as $optionFromCRM) { + $optionData = explode('-', $optionFromCRM); + $productOptionId = $optionData[0]; + $optionValueId = $optionData[1]; + + $productOptions = $this->model_catalog_product->getProductOptions($productId); + + foreach($productOptions as $productOption) { + if($productOptionId == $productOption['product_option_id']) { + foreach($productOption['product_option_value'] as $productOptionValue) { + if($productOptionValue['option_value_id'] == $optionValueId) { + $options[$productOptionId] = $productOptionValue['product_option_value_id']; + } + } + } + } + } + } + $data['order_product'][] = array( + 'product_id' => $productId, + 'quantity' => $item['quantity'], + 'option' => $options ); } @@ -509,11 +604,9 @@ class ModelExtensionRetailcrmHistoryV45 extends Model $data['fromApi'] = true; $data['order_status_id'] = 1; - $this->opencartApiClient->addOrder($data); + $order_id = $this->opencartApiClient->addOrder($data); - $last = $this->model_sale_order->getOrders($data = array('order' => 'DESC', 'limit' => 1, 'start' => 0)); - - $ordersIdsFix[] = array('id' => $order['id'], 'externalId' => (int) $last[0]['order_id']); + $ordersIdsFix[] = array('id' => $order['id'], 'externalId' => (int) $order_id); } return array('customers' => $customersIdsFix, 'orders' => $ordersIdsFix); @@ -521,25 +614,58 @@ class ModelExtensionRetailcrmHistoryV45 extends Model protected function updateCustomers($customers) { + $settings = $this->model_setting_setting->getSetting($this->moduleTitle); + + if (isset($settings[$this->moduleTitle . '_custom_field'])) { + $settings = array_flip($settings[$this->moduleTitle . '_custom_field']); + } + foreach ($customers as $customer) { $customer_id = $customer['externalId']; $customerData = $this->model_customer_customer->getCustomer($customer_id); - + $customerData['firstname'] = $customer['firstName']; - $customerData['lastname'] = $customer['lastName']; + $customerData['lastname'] = isset($customer['lastName']) ? $customer['lastName'] : ''; $customerData['email'] = $customer['email']; - $customerData['telephone'] = $customer['phones'][0]['number']; - + $customerData['telephone'] = $customer['phones'] ? $customer['phones'][0]['number'] : ''; + $customerAddress = $this->model_customer_customer->getAddress($customerData['address_id']); - - $customerAddress['firstname'] = $customer['firstName']; - $customerAddress['lastname'] = $customer['lastName']; + + if (isset($customer['address']['countryIso'])) { + $customerCountry = $this->getCountryByIsoCode($customer['address']['countryIso']); + } + + if (isset($customer['address']['region'])) { + $customerZone = $this->getZoneByName($customer['address']['region']); + } + + $customerAddress['firstname'] = isset($customer['patronymic']) ? $customer['firstName'] . ' ' . $customer['patronymic'] : $customer['firstName']; + $customerAddress['lastname'] = isset($customer['lastName']) ? $customer['lastName'] : ''; $customerAddress['address_1'] = $customer['address']['text']; $customerAddress['city'] = $customer['address']['city']; - $customerAddress['postcode'] = $customer['address']['index']; + $customerAddress['postcode'] = $customer['address']['index'] ? $customer['address']['index'] : ''; + + if (isset($customerCountry)) { + $customerAddress['country_id'] = $customerCountry['country_id']; + } + + if (isset($customerZone)) { + $customerAddress['zone_id'] = $customerZone['zone_id']; + } + $customerData['address'] = array($customerAddress); + if ($settings && $customer['customFields']) { + foreach ($customer['customFields'] as $code => $value) { + if (array_key_exists($code, $settings)) { + $customFields[$settings[$code]] = $value; + } + } + + $customerData['custom_field'] = isset($customFields) ? $customFields : ''; + } + $this->model_customer_customer->editCustomer($customer_id, $customerData); } } @@ -565,4 +691,18 @@ class ModelExtensionRetailcrmHistoryV45 extends Model return $title; } + + public function getCountryByIsoCode($isoCode) + { + $query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "country` WHERE iso_code_2 = '" . $isoCode . "'"); + + return $query->row; + } + + public function getZoneByName($name) + { + $query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "zone` WHERE name = '" . $name . "'"); + + return $query->row; + } } diff --git a/admin/model/extension/retailcrm/references.php b/admin/model/extension/retailcrm/references.php index d3b8768..b6ae835 100644 --- a/admin/model/extension/retailcrm/references.php +++ b/admin/model/extension/retailcrm/references.php @@ -40,7 +40,15 @@ class ModelExtensionRetailcrmReferences extends Model 'retailcrm' => $this->getApiPaymentTypes() ); } - + + public function getCustomFields() + { + return array( + 'opencart' => $this->getOpencartCustomFields(), + 'retailcrm' => $this->getApiCustomerCustomFields() + ); + } + public function getOpercartOrderStatuses() { $this->load->model('localisation/order_status'); @@ -76,7 +84,14 @@ class ModelExtensionRetailcrmReferences extends Model return $paymentTypes; } - + + public function getOpencartCustomFields() + { + $this->load->model('customer/custom_field'); + + return $this->model_customer_custom_field->getCustomFields(); + } + public function getApiDeliveryTypes() { $this->initApi(); @@ -103,6 +118,16 @@ class ModelExtensionRetailcrmReferences extends Model return (!$response->isSuccessful()) ? array() : $response->paymentTypes; } + + public function getApiCustomerCustomFields() + { + $this->initApi(); + + $filter = array('entity' => 'customer'); + $response = $this->retailcrm->customFieldsList($filter); + + return (!$response->isSuccessful()) ? array() : $response->customFields; + } protected function initApi() { diff --git a/admin/view/template/extension/module/retailcrm.tpl b/admin/view/template/extension/module/retailcrm.tpl index cd3d8eb..3648f36 100644 --- a/admin/view/template/extension/module/retailcrm.tpl +++ b/admin/view/template/extension/module/retailcrm.tpl @@ -43,6 +43,9 @@
  • + +
  • + @@ -235,6 +238,41 @@ + +
    +

    + + + +
    + + +
    + + +
    + + +
    + +
    + + +
    + +
    + + +
    + +
    + @@ -292,7 +330,7 @@ alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText); }, success: function(data, textStatus, jqXHR) { - if (jqXHR['responseText'] == 'false') { + if (jqXHR['responseText'] == '400') { $('.alert-danger').remove(); $('#content > .container-fluid').prepend('
    '); $('#export_order').button('reset'); diff --git a/admin/view/template/extension/module/retailcrm.twig b/admin/view/template/extension/module/retailcrm.twig index f76247b..2446bd5 100644 --- a/admin/view/template/extension/module/retailcrm.twig +++ b/admin/view/template/extension/module/retailcrm.twig @@ -236,6 +236,41 @@ {% endif %} {% endif %} + {% if saved_settings.retailcrm_apiversion is defined and saved_settings.retailcrm_apiversion == 'v5' and customFields is defined %} +
    +

    {{ retailcrm_dict_custom_fields }}

    + {% if customFields.retailcrm is not empty and customFields.opencart is not empty %} + {% for customField in customFields.opencart %} + {% set fid = customField.custom_field_id %} +
    + + +
    + {% endfor %} + {% elseif customFields.retailcrm is empty and customFields.opencart is empty %} +
    + + {{ text_error_custom_field }} +
    + {% elseif customFields.retailcrm is empty %} +
    + + {{ text_error_cf_retailcrm }} +
    + {% elseif customFields.opencart is empty %} +
    + + {{ text_error_cf_opencart }} +
    + {% endif %} +
    + {% endif %} @@ -293,7 +328,7 @@ alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText); }, success: function(data, textStatus, jqXHR) { - if (jqXHR['responseText'] == 'false') { + if (jqXHR['responseText'] == '400') { $('.alert-danger').remove(); $('#content > .container-fluid').prepend('
    {{ text_error_order }}
    '); $('#export_order').button('reset'); diff --git a/catalog/controller/api/retailcrm.php b/catalog/controller/api/retailcrm.php index b77f04d..2308cd8 100644 --- a/catalog/controller/api/retailcrm.php +++ b/catalog/controller/api/retailcrm.php @@ -1,95 +1,103 @@ load->model('localisation/country'); - $this->load->model('setting/setting'); - $moduleTitle = $this->getModuleTitle(); - $countries = $this->model_setting_setting->getSetting($moduleTitle)[$moduleTitle . '_country']; - $deliveryTypes = array(); +{ + public function getDeliveryTypes() + { + $this->load->model('localisation/country'); + $this->load->model('setting/setting'); + $moduleTitle = $this->getModuleTitle(); + $countries = $this->model_setting_setting->getSetting($moduleTitle)[$moduleTitle . '_country']; + $deliveryTypes = array(); - foreach ($countries as $country) { - $deliveryTypes = array_merge($deliveryTypes, $this->getDeliveryTypesByZones($country)); - } + 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'); - } + 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)); - } + $this->response->addHeader('Content-Type: application/json'); + $this->response->setOutput(json_encode($deliveryTypes)); + } - protected function getDeliveryTypesByZones($country_id) - { - $this->loadModels(); - $this->load->model('localisation/zone'); - $this->load->model('localisation/country'); + protected function getDeliveryTypesByZones($country_id) + { + $this->loadModels(); + $this->load->model('localisation/zone'); + $this->load->model('localisation/country'); - $shippingModules = $this->{'model_' . $this->modelExtension}->getExtensions('shipping'); - $zones = $this->model_localisation_zone->getZonesByCountryId($country_id); - $country = $this->model_localisation_country->getCountry($country_id); - $quote_data = array(); + $shippingModules = $this->{'model_' . $this->modelExtension}->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 (version_compare(VERSION, '3.0', '<')) { - $shippingCode = $shippingModule['code']; - } else { - $shippingCode = 'shipping_' . $shippingModule['code']; - } + 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 (version_compare(VERSION, '3.0', '<')) { + $shippingCode = $shippingModule['code']; + } else { + $shippingCode = 'shipping_' . $shippingModule['code']; + } - if ($this->config->get($shippingCode . '_status')) { - if($this->{'model_extension_shipping_' . $shippingModule['code']}->getQuote($address)) { - $quote_data[] = $this->{'model_extension_shipping_' . $shippingModule['code']}->getQuote($address); - } - } - } - } + if ($this->config->get($shippingCode . '_status')) { + if ($shippingCode == 'free') { + $free_total = $this->config->get('free_total'); - $deliveryTypes = array(); + if ($free_total > 0) { + $this->config->set('free_total', 0); + } + } + + if($this->{'model_extension_shipping_' . $shippingModule['code']}->getQuote($address)) { + $quote_data[] = $this->{'model_extension_shipping_' . $shippingModule['code']}->getQuote($address); + } + } + } + } - foreach ($quote_data as $shipping) { - - foreach ($shipping['quote'] as $shippingMethod) { - $deliveryTypes[$shipping['code']]['title'] = $shipping['title']; - $deliveryTypes[$shipping['code']][$shippingMethod['code']] = $shippingMethod; - } - - } + $deliveryTypes = array(); - return $deliveryTypes; - } + foreach ($quote_data as $shipping) { + + foreach ($shipping['quote'] as $shippingMethod) { + $deliveryTypes[$shipping['code']]['title'] = $shipping['title']; + $deliveryTypes[$shipping['code']][$shippingMethod['code']] = $shippingMethod; + } + + } - private function loadModels() - { - if (version_compare(VERSION, '3.0', '<')) { - $this->load->model('extension/extension'); + return $deliveryTypes; + } - $this->modelExtension = 'extension_extension'; - } else { - $this->load->model('setting/extension'); + private function loadModels() + { + if (version_compare(VERSION, '3.0', '<')) { + $this->load->model('extension/extension'); - $this->modelExtension = 'setting_extension'; - } - } + $this->modelExtension = 'extension_extension'; + } else { + $this->load->model('setting/extension'); - private function getModuleTitle() + $this->modelExtension = 'setting_extension'; + } + } + + private function getModuleTitle() { if (version_compare(VERSION, '3.0', '<')) { $title = 'retailcrm'; diff --git a/catalog/model/extension/retailcrm/customer.php b/catalog/model/extension/retailcrm/customer.php index c51f73a..4f7700c 100644 --- a/catalog/model/extension/retailcrm/customer.php +++ b/catalog/model/extension/retailcrm/customer.php @@ -26,6 +26,8 @@ class ModelExtensionRetailcrmCustomer extends Model { } private function process($customer) { + $moduleTitle = $this->getModuleTitle(); + $customerToCrm = array( 'externalId' => $customer['customer_id'], 'firstName' => $customer['firstname'], @@ -48,6 +50,18 @@ class ModelExtensionRetailcrmCustomer extends Model { 'text' => $customer['address']['address_1'] . ' ' . $customer['address']['address_2'] ); } + + if (isset($this->settings[$moduleTitle . '_custom_field']) && $customer['custom_field']) { + $customFields = json_decode($customer['custom_field']); + + foreach ($customFields as $key => $value) { + if (isset($this->settings[$moduleTitle . '_custom_field'][$key])) { + $customFieldsToCrm[$this->settings[$moduleTitle . '_custom_field'][$key]] = $value; + } + } + + $customerToCrm['customFields'] = $customFieldsToCrm; + } return $customerToCrm; } @@ -56,18 +70,18 @@ class ModelExtensionRetailcrmCustomer extends Model { { $this->load->model('setting/setting'); $moduleTitle = $this->getModuleTitle(); - $settings = $this->model_setting_setting->getSetting($moduleTitle); + $this->settings = $this->model_setting_setting->getSetting($moduleTitle); - if(empty($settings[$moduleTitle . '_url']) || empty($settings[$moduleTitle . '_apikey'])) + 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( - $settings[$moduleTitle . '_url'], - $settings[$moduleTitle . '_apikey'], + $this->settings[$moduleTitle . '_url'], + $this->settings[$moduleTitle . '_apikey'], DIR_SYSTEM . 'storage/logs/retailcrm.log', - $settings[$moduleTitle . '_apiversion'] + $this->settings[$moduleTitle . '_apiversion'] ); } diff --git a/system/library/retailcrm/OpencartApiClient.php b/system/library/retailcrm/OpencartApiClient.php index e9255e5..514dbda 100644 --- a/system/library/retailcrm/OpencartApiClient.php +++ b/system/library/retailcrm/OpencartApiClient.php @@ -223,12 +223,12 @@ class OpencartApiClient { $this->request('customer', array(), $customer); $products = array(); - foreach($data['order_product'] as $product) { - $product = array( - 'product_id' => $product['product_id'], - 'quantity' => $product['quantity'], + foreach ($data['order_product'] as $order_product) { + $products[] = array( + 'product_id' => $order_product['product_id'], + 'quantity' => $order_product['quantity'], + 'option' => $order_product['option'] ); - $products[] = $product; } $this->request('cart/add', array(), array('product' => $products)); @@ -279,7 +279,11 @@ class OpencartApiClient { 'comment' => $data['comment'], 'affiliate_id' => $data['affiliate_id'], ); - $this->request('order/add', array(), $order); + $response = $this->request('order/add', array(), $order); + + if (isset($response['order_id'])) { + return $response['order_id']; + } } private function getInnerIpAddr() { diff --git a/system/library/retailcrm/RetailcrmApiClient3.php b/system/library/retailcrm/RetailcrmApiClient3.php index 7a6d7df..d61d3e3 100644 --- a/system/library/retailcrm/RetailcrmApiClient3.php +++ b/system/library/retailcrm/RetailcrmApiClient3.php @@ -12,8 +12,6 @@ */ class RetailcrmApiClient3 { - const VERSION = 'v3'; - protected $client; /** @@ -29,18 +27,32 @@ class RetailcrmApiClient3 * @param string $site * @return mixed */ - public function __construct($url, $apiKey, $site = null) + public function __construct($url, $apiKey, $version = null, $site = null) { if ('/' != substr($url, strlen($url) - 1, 1)) { $url .= '/'; } - $url = $url . 'api/' . self::VERSION; + $url = $version == null ? $url . 'api' : $url . 'api/' . $version; $this->client = new RetailcrmHttpClient($url, array('apiKey' => $apiKey)); $this->siteCode = $site; } - + + /** + * Returns api versions list + * + * @throws \RetailCrm\Exception\InvalidJsonException + * @throws \RetailCrm\Exception\CurlException + * @throws \InvalidArgumentException + * + * @return ApiResponse + */ + public function apiVersions() + { + return $this->client->makeRequest('/api-versions', RetailcrmHttpClient::METHOD_GET); + } + /** * Create a order * diff --git a/system/library/retailcrm/RetailcrmApiClient4.php b/system/library/retailcrm/RetailcrmApiClient4.php index 5a406f1..5fee131 100644 --- a/system/library/retailcrm/RetailcrmApiClient4.php +++ b/system/library/retailcrm/RetailcrmApiClient4.php @@ -12,8 +12,6 @@ */ class RetailcrmApiClient4 { - const VERSION = 'v4'; - protected $client; /** @@ -32,17 +30,31 @@ class RetailcrmApiClient4 * * @return mixed */ - public function __construct($url, $apiKey, $site = null) + public function __construct($url, $apiKey, $version = null, $site = null) { if ('/' !== $url[strlen($url) - 1]) { $url .= '/'; } - - $url = $url . 'api/' . self::VERSION; + + $url = $version == null ? $url . 'api' : $url . 'api/' . $version; $this->client = new RetailcrmHttpClient($url, array('apiKey' => $apiKey)); $this->siteCode = $site; } + + /** + * Returns api versions list + * + * @throws \RetailCrm\Exception\InvalidJsonException + * @throws \RetailCrm\Exception\CurlException + * @throws \InvalidArgumentException + * + * @return ApiResponse + */ + public function apiVersions() + { + return $this->client->makeRequest('/api-versions', RetailcrmHttpClient::METHOD_GET); + } /** * Returns users list diff --git a/system/library/retailcrm/RetailcrmApiClient5.php b/system/library/retailcrm/RetailcrmApiClient5.php index 2c71346..8ffd4e1 100644 --- a/system/library/retailcrm/RetailcrmApiClient5.php +++ b/system/library/retailcrm/RetailcrmApiClient5.php @@ -12,8 +12,6 @@ */ class RetailcrmApiClient5 { - const VERSION = 'v5'; - protected $client; /** @@ -32,18 +30,32 @@ class RetailcrmApiClient5 * * @return mixed */ - public function __construct($url, $apiKey, $site = null) + public function __construct($url, $apiKey, $version = null, $site = null) { if ('/' !== $url[strlen($url) - 1]) { $url .= '/'; } - $url = $url . 'api/' . self::VERSION; + $url = $version == null ? $url . 'api' : $url . 'api/' . $version; $this->client = new RetailcrmHttpClient($url, array('apiKey' => $apiKey)); $this->siteCode = $site; } - + + /** + * Returns api versions list + * + * @throws \RetailCrm\Exception\InvalidJsonException + * @throws \RetailCrm\Exception\CurlException + * @throws \InvalidArgumentException + * + * @return ApiResponse + */ + public function apiVersions() + { + return $this->client->makeRequest('/api-versions', RetailcrmHttpClient::METHOD_GET); + } + /** * Returns users list * diff --git a/system/library/retailcrm/RetailcrmHistoryHelper.php b/system/library/retailcrm/RetailcrmHistoryHelper.php index 604cf3e..5247020 100644 --- a/system/library/retailcrm/RetailcrmHistoryHelper.php +++ b/system/library/retailcrm/RetailcrmHistoryHelper.php @@ -28,14 +28,14 @@ class RetailcrmHistoryHelper { unset($change['order']['contragent']); } - if(!empty($orders) && $orders[$change['order']['id']]) { + if(!empty($orders) && isset($orders[$change['order']['id']])) { $orders[$change['order']['id']] = array_merge($orders[$change['order']['id']], $change['order']); } else { $orders[$change['order']['id']] = $change['order']; } if(isset($change['item']) && $change['item']) { - if($orders[$change['order']['id']]['items'][$change['item']['id']]) { + if(isset($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 { $orders[$change['order']['id']]['items'][$change['item']['id']] = $change['item']; @@ -47,7 +47,7 @@ class RetailcrmHistoryHelper { if(empty($change['newValue']) && $change['field'] == 'order_product') { $orders[$change['order']['id']]['items'][$change['item']['id']]['delete'] = true; } - if(!$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']; } } else { diff --git a/system/library/retailcrm/RetailcrmProxy.php b/system/library/retailcrm/RetailcrmProxy.php index 872026e..bbf687f 100644 --- a/system/library/retailcrm/RetailcrmProxy.php +++ b/system/library/retailcrm/RetailcrmProxy.php @@ -10,20 +10,20 @@ class RetailcrmProxy private $api; private $log; - public function __construct($url, $key, $log, $version) + public function __construct($url, $key, $log, $version = null) { - if (!$version) $version = 'v4'; switch ($version) { case 'v5': - $this->api = new RetailcrmApiClient5($url, $key); + $this->api = new RetailcrmApiClient5($url, $key, $version); break; - case 'v4': - $this->api = new RetailcrmApiClient4($url, $key); + $this->api = new RetailcrmApiClient4($url, $key, $version); break; - case 'v3': - $this->api = new RetailcrmApiClient3($url, $key); + $this->api = new RetailcrmApiClient3($url, $key, $version); + break; + case null: + $this->api = new RetailcrmApiClient3($url, $key, $version); break; } diff --git a/system/library/retailcrm/objects.xml b/system/library/retailcrm/objects.xml index 4f4996e..45068e7 100644 --- a/system/library/retailcrm/objects.xml +++ b/system/library/retailcrm/objects.xml @@ -63,14 +63,21 @@ shipmentDate shipped - + payments + amount + paidAt + comment + type + status + id initialPrice discount discountPercent quantity status - + summ + code service date