fix history, new objects in object.xml

This commit is contained in:
Akolzin Dmitry 2017-09-15 15:47:38 +03:00
parent 45fde808b7
commit cdc1c9cf6b
19 changed files with 840 additions and 336 deletions

9
CHANGELOG.md Normal file
View File

@ -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)

View File

@ -91,9 +91,8 @@ class ControllerExtensionModuleRetailcrm extends Controller
$this->load->model('setting/setting'); $this->load->model('setting/setting');
$this->model_setting_setting $this->model_setting_setting
->editSetting($moduleTitle, array($moduleTitle . '_status' => 0)); ->editSetting($moduleTitle, array($moduleTitle . '_status' => 0));
$this->model_setting_setting->deleteSetting('retailcrm_history');
$this->loadModels(); $this->loadModels();
$this->{'model_' . $this->modelEvent}->deleteEvent($moduleTitle); $this->{'model_' . $this->modelEvent}->deleteEvent($moduleTitle);
} }
@ -144,6 +143,7 @@ class ControllerExtensionModuleRetailcrm extends Controller
$tokenTitle = $this->getTokenTitle(); $tokenTitle = $this->getTokenTitle();
$moduleTitle = $this->getModuleTitle(); $moduleTitle = $this->getModuleTitle();
$collector = $this->getCollectorTitle(); $collector = $this->getCollectorTitle();
$history_setting = $this->model_setting_setting->getSetting('retailcrm_history');
if ($this->request->server['REQUEST_METHOD'] == 'POST' && $this->validate()) { if ($this->request->server['REQUEST_METHOD'] == 'POST' && $this->validate()) {
$analytics = $this->{'model_' . $this->modelExtension}->getInstalled('analytics'); $analytics = $this->{'model_' . $this->modelExtension}->getInstalled('analytics');
@ -160,11 +160,56 @@ class ControllerExtensionModuleRetailcrm extends Controller
$crm_url = parse_url($this->request->post[$moduleTitle . '_url'], PHP_URL_HOST); $crm_url = parse_url($this->request->post[$moduleTitle . '_url'], PHP_URL_HOST);
$this->request->post[$moduleTitle . '_url'] = 'https://'.$crm_url; $this->request->post[$moduleTitle . '_url'] = 'https://'.$crm_url;
} }
$this->model_setting_setting->editSetting( $this->model_setting_setting->editSetting(
$moduleTitle, $moduleTitle,
$this->request->post $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'); $this->session->data['success'] = $this->language->get('text_success');
$redirect = $this->url->link( $redirect = $this->url->link(
'extension/module/retailcrm', $tokenTitle . '=' . $this->session->data[$tokenTitle], 'extension/module/retailcrm', $tokenTitle . '=' . $this->session->data[$tokenTitle],
@ -213,7 +258,12 @@ class ControllerExtensionModuleRetailcrm extends Controller
'text_label_promo', 'text_label_promo',
'text_label_send', 'text_label_send',
'collector_custom_text', '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; $_data = &$data;
@ -252,6 +302,10 @@ class ControllerExtensionModuleRetailcrm extends Controller
$_data['payments'] = $this->model_extension_retailcrm_references $_data['payments'] = $this->model_extension_retailcrm_references
->getPaymentTypes(); ->getPaymentTypes();
if ($apiVersion == 'v5') {
$_data['customFields'] = $this->model_extension_retailcrm_references
->getCustomFields();
}
} }
$config_data = array( $config_data = array(
@ -363,7 +417,6 @@ class ControllerExtensionModuleRetailcrm extends Controller
$settings = $this->model_setting_setting->getSetting($moduleTitle); $settings = $this->model_setting_setting->getSetting($moduleTitle);
if ($settings[$moduleTitle . '_apiversion'] == 'v3') { if ($settings[$moduleTitle . '_apiversion'] == 'v3') {
if (file_exists(DIR_APPLICATION . 'model/extension/retailcrm/custom/history/v3.php')) { if (file_exists(DIR_APPLICATION . 'model/extension/retailcrm/custom/history/v3.php')) {
$this->load->model('extension/retailcrm/custom/history/v3'); $this->load->model('extension/retailcrm/custom/history/v3');
$this->model_extension_retailcrm_custom_history_v3->request(); $this->model_extension_retailcrm_custom_history_v3->request();
@ -372,7 +425,6 @@ class ControllerExtensionModuleRetailcrm extends Controller
$this->model_extension_retailcrm_history_v3->request(); $this->model_extension_retailcrm_history_v3->request();
} }
} else { } else {
if (file_exists(DIR_APPLICATION . 'model/extension/retailcrm/custom/history/v4-5.php')) { if (file_exists(DIR_APPLICATION . 'model/extension/retailcrm/custom/history/v4-5.php')) {
$this->load->model('extension/retailcrm/custom/history/v4-5'); $this->load->model('extension/retailcrm/custom/history/v4-5');
$this->model_extension_retailcrm_custom_history_v4_5->request(); $this->model_extension_retailcrm_custom_history_v4_5->request();
@ -486,7 +538,7 @@ class ControllerExtensionModuleRetailcrm extends Controller
$result = $this->model_extension_retailcrm_order->uploadOrder($data); $result = $this->model_extension_retailcrm_order->uploadOrder($data);
} }
echo json_encode($result); echo json_encode($result->getStatusCode());
} }
/** /**
@ -534,21 +586,30 @@ class ControllerExtensionModuleRetailcrm extends Controller
{ {
$moduleTitle = $this->getModuleTitle(); $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'])) { if (!empty($this->request->post[$moduleTitle . '_url']) && !empty($this->request->post[$moduleTitle . '_apikey'])) {
$this->retailcrm = new RetailcrmProxy( $this->retailcrm = new RetailcrmProxy(
$this->request->post[$moduleTitle . '_url'], $this->request->post[$moduleTitle . '_url'],
$this->request->post[$moduleTitle . '_apikey'], $this->request->post[$moduleTitle . '_apikey'],
DIR_SYSTEM . 'storage/logs/retailcrm.log', DIR_SYSTEM . 'storage/logs/retailcrm.log'
$this->request->post[$moduleTitle . '_apiversion']
); );
} }
$response = $this->retailcrm->deliveryTypesList(); $response = $this->retailcrm->apiVersions();
if (!$response->isSuccessful()) { if ($response && $response->isSuccessful()) {
if (!in_array($versionsMap[$this->request->post[$moduleTitle . '_apiversion']], $response['versions'])) {
$this->_error['warning'] = $this->language->get('text_error_api'); $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')) { if (!$this->user->hasPermission('modify', 'extension/module/retailcrm')) {
$this->_error['warning'] = $this->language->get('error_permission'); $this->_error['warning'] = $this->language->get('error_permission');

View File

@ -15,9 +15,9 @@ $_['retailcrm_upload_order'] = 'Unload single order';
$_['daemon_collector'] = 'Daemon Collector'; $_['daemon_collector'] = 'Daemon Collector';
$_['general_tab_text'] = 'General'; $_['general_tab_text'] = 'General';
$_['references_tab_text'] = 'References'; $_['references_tab_text'] = 'References';
$_['collector_tab_text'] = 'Collector'; $_['collector_tab_text'] = 'Daemon Collector';
$_['collector_custom_text'] = 'Custom form'; $_['collector_custom_text'] = 'Custom form';
$_['custom_fields_tab_text'] = 'Пользовательские поля';
$_['retailcrm_apiversion'] = 'API Version'; $_['retailcrm_apiversion'] = 'API Version';
$_['retailcrm_url'] = 'RetailCRM URL'; $_['retailcrm_url'] = 'RetailCRM URL';
$_['retailcrm_apikey'] = 'RetailCRM API Key'; $_['retailcrm_apikey'] = 'RetailCRM API Key';
@ -41,11 +41,16 @@ $_['field_email'] = 'Email';
$_['field_phone'] = 'Phone'; $_['field_phone'] = 'Phone';
$_['text_require'] = 'Require'; $_['text_require'] = 'Require';
$_['text_error_collector_fields']= 'Fill in the field names Daemon Collector'; $_['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_delivery'] = 'Shipment methods';
$_['retailcrm_dict_status'] = 'Order statuses'; $_['retailcrm_dict_status'] = 'Order statuses';
$_['retailcrm_dict_payment'] = 'Payment methods'; $_['retailcrm_dict_payment'] = 'Payment methods';
$_['retailcrm_dict_custom_fields'] = 'Настройка пользовательских полей';
$_['column_total'] = 'Total'; $_['column_total'] = 'Total';
$_['product_summ'] = 'Amount'; $_['product_summ'] = 'Amount';

View File

@ -15,9 +15,9 @@ $_['retailcrm_upload_order'] = 'Выгрузка одного заказа';
$_['daemon_collector'] = 'Демон Collector'; $_['daemon_collector'] = 'Демон Collector';
$_['general_tab_text'] = 'Главная'; $_['general_tab_text'] = 'Главная';
$_['references_tab_text'] = 'Справочники'; $_['references_tab_text'] = 'Справочники';
$_['collector_tab_text'] = 'Collector'; $_['collector_tab_text'] = 'Daemon Collector';
$_['collector_custom_text'] = 'Настройка полей формы'; $_['collector_custom_text'] = 'Настройка полей формы';
$_['custom_fields_tab_text'] = 'Пользовательские поля';
$_['retailcrm_apiversion'] = 'Версия API'; $_['retailcrm_apiversion'] = 'Версия API';
$_['retailcrm_url'] = 'Адрес RetailCRM'; $_['retailcrm_url'] = 'Адрес RetailCRM';
$_['retailcrm_apikey'] = 'Api ключ RetailCRM'; $_['retailcrm_apikey'] = 'Api ключ RetailCRM';
@ -41,11 +41,16 @@ $_['field_email'] = 'Email';
$_['field_phone'] = 'Телефон'; $_['field_phone'] = 'Телефон';
$_['text_require'] = 'Обязательно для заполнения'; $_['text_require'] = 'Обязательно для заполнения';
$_['text_error_collector_fields']= 'Заполните названия полей формы Демон Collector'; $_['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_delivery'] = 'Способы доставки';
$_['retailcrm_dict_status'] = 'Статусы'; $_['retailcrm_dict_status'] = 'Статусы';
$_['retailcrm_dict_payment'] = 'Способы оплаты'; $_['retailcrm_dict_payment'] = 'Способы оплаты';
$_['retailcrm_dict_custom_fields'] = 'Настройка пользовательских полей';
$_['column_total'] = 'Итого'; $_['column_total'] = 'Итого';
$_['product_summ'] = 'Сумма'; $_['product_summ'] = 'Сумма';

View File

@ -26,8 +26,9 @@ class ModelExtensionRetailcrmCustomer extends Model {
{ {
$this->initApi(); $this->initApi();
if(empty($customer)) if(empty($customer)) {
return false; return false;
}
$customerToCrm = $this->process($customer); $customerToCrm = $this->process($customer);
@ -35,6 +36,8 @@ class ModelExtensionRetailcrmCustomer extends Model {
} }
private function process($customer) { private function process($customer) {
$moduleTitle = $this->getModuleTitle();
$customerToCrm = array( $customerToCrm = array(
'externalId' => $customer['customer_id'], 'externalId' => $customer['customer_id'],
'firstName' => $customer['firstname'], 'firstName' => $customer['firstname'],
@ -58,6 +61,18 @@ class ModelExtensionRetailcrmCustomer extends Model {
); );
} }
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; return $customerToCrm;
} }
@ -65,18 +80,18 @@ class ModelExtensionRetailcrmCustomer extends Model {
{ {
$moduleTitle = $this->getModuleTitle(); $moduleTitle = $this->getModuleTitle();
$this->load->model('setting/setting'); $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; return false;
require_once DIR_SYSTEM . 'library/retailcrm/bootstrap.php'; require_once DIR_SYSTEM . 'library/retailcrm/bootstrap.php';
$this->retailcrmApi = new RetailcrmProxy( $this->retailcrmApi = new RetailcrmProxy(
$settings[$moduleTitle . '_url'], $this->settings[$moduleTitle . '_url'],
$settings[$moduleTitle . '_apikey'], $this->settings[$moduleTitle . '_apikey'],
DIR_SYSTEM . 'storage/logs/retailcrm.log', DIR_SYSTEM . 'storage/logs/retailcrm.log',
$settings[$moduleTitle . '_apiversion'] $this->settings[$moduleTitle . '_apiversion']
); );
} }

View File

@ -42,20 +42,22 @@ class ModelExtensionRetailcrmHistoryV3 extends Model
$settings[$moduleTitle . '_apiversion'] $settings[$moduleTitle . '_apiversion']
); );
$lastRun = !empty($history['retailcrm_history']) $lastRun = !empty($history['retailcrm_history_datetime'])
? new DateTime($history['retailcrm_history']) ? 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'))))); : new DateTime(date('Y-m-d H:i:s', strtotime('-1 days', strtotime(date('Y-m-d H:i:s')))));
$packsOrders = $crm->ordersHistory($lastRun); $packsOrders = $crm->ordersHistory($lastRun);
if(!$packsOrders->isSuccessful() && count($packsOrders['orders']) <= 0) if(!$packsOrders->isSuccessful() && count($packsOrders['orders']) <= 0) {
return false; return false;
}
$generatedAt = $packsOrders['generatedAt']; $generatedAt = $packsOrders['generatedAt'];
$this->subtotalSettings = $this->model_setting_setting->getSetting('sub_total'); $this->totalTitle = $this->totalTitles();
$this->totalSettings = $this->model_setting_setting->getSetting('total'); $this->subtotalSettings = $this->model_setting_setting->getSetting($this->totalTitle . 'sub_total');
$this->shippingSettings = $this->model_setting_setting->getSetting('shipping'); $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->delivery = array_flip($settings[$moduleTitle . '_delivery']);
$this->payment = array_flip($settings[$moduleTitle . '_payment']); $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'])) { if (!empty($this->createResult['customers'])) {
$crm->customersFixExternalIds($this->createResult['customers']); $crm->customersFixExternalIds($this->createResult['customers']);
@ -117,20 +119,28 @@ class ModelExtensionRetailcrmHistoryV3 extends Model
$data = array(); $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['store_id'] = $store == null ? 0 : $store;
$data['customer'] = $order['firstName']; $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['customer_group_id'] = 1;
$data['firstname'] = $order['firstName']; $data['firstname'] = $order['firstName'];
$data['lastname'] = (!empty($order['lastName'])) ? $order['lastName'] : ' '; $data['lastname'] = isset($order['lastName']) ? $order['lastName'] : $order['firstName'];
$data['email'] = $order['email']; $data['email'] = $mail ? $mail : uniqid() . '@retailrcm.ru';
$data['telephone'] = (!empty($order['phone'])) ? $order['phone'] : '';
$data['comment'] = !empty($order['customerComment']) ? $order['customerComment'] : ''; $data['comment'] = !empty($order['customerComment']) ? $order['customerComment'] : '';
$data['fax'] = ''; $data['fax'] = '';
$data['payment_address'] = '0'; $data['payment_address'] = '0';
$data['payment_firstname'] = $order['firstName']; $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_1'] = isset($order['customer']['address']) ? $order['customer']['address']['text'] : '';
$data['payment_address_2'] = ''; $data['payment_address_2'] = '';
$data['payment_company'] = ''; $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_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']; $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'])) { if (is_int($order['delivery']['address']['region'])) {
$region = $order['delivery']['address']['region']; $shippingZone = $order['delivery']['address']['region'];
} else { } else {
foreach ($this->zones as $zone) { $shippingZone = $this->getZoneByName($order['delivery']['address']['region']);
if ($order['delivery']['address']['region'] == $zone['name']) {
$region = $zone['zone_id']; 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; if (isset($order['customer']['address']['region'])) {
$data['payment_zone_id'] = !empty($order['delivery']['address']['region']) ? $order['delivery']['address']['region'] : $region; $paymentZone = $this->getZoneByName($order['customer']['address']['region']);
$data['shipping_country_id'] = !empty($order['delivery']['address']['country']) ? $order['delivery']['address']['country'] : 0; if ($paymentZone) {
$data['shipping_zone_id'] = $region; $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_address'] = '0';
$data['shipping_firstname'] = $order['firstName']; $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_1'] = $order['delivery']['address']['text'];
$data['shipping_address_2'] = ''; $data['shipping_address_2'] = '';
$data['shipping_company'] = ''; $data['shipping_company'] = '';
@ -192,7 +222,6 @@ class ModelExtensionRetailcrmHistoryV3 extends Model
$data['order_product'] = array(); $data['order_product'] = array();
foreach ($order['items'] as $item) { foreach ($order['items'] as $item) {
//$product = $this->model_catalog_product->getProduct($item['offer']['externalId']);
$productId = $item['offer']['externalId']; $productId = $item['offer']['externalId'];
$options = array(); $options = array();
if(mb_strpos($item['offer']['externalId'], '#') > 1) { if(mb_strpos($item['offer']['externalId'], '#') > 1) {
@ -251,7 +280,7 @@ class ModelExtensionRetailcrmHistoryV3 extends Model
'title' => $this->ocDelivery[$data['shipping_code']], 'title' => $this->ocDelivery[$data['shipping_code']],
'value' => $deliveryCost, 'value' => $deliveryCost,
'text' => $deliveryCost, 'text' => $deliveryCost,
'sort_order' => $this->shippingSettings['shipping_sort_order'] 'sort_order' => $this->shippingSettings[$this->totalTitle . 'shipping_sort_order']
), ),
array( array(
'order_total_id' => '', 'order_total_id' => '',
@ -259,7 +288,7 @@ class ModelExtensionRetailcrmHistoryV3 extends Model
'title' => $this->language->get('column_total'), 'title' => $this->language->get('column_total'),
'value' => isset($order['totalSumm']) ? $order['totalSumm'] : $order['summ'] + $deliveryCost, 'value' => isset($order['totalSumm']) ? $order['totalSumm'] : $order['summ'] + $deliveryCost,
'text' => 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(); $data = array();
if ($customer_id == 0) { 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( $cData = array(
'store_id' => 0, 'store_id' => 0,
'customer_group_id' => '1', 'customer_group_id' => '1',
'firstname' => $order['firstName'], 'firstname' => isset($order['patronymic']) ? $order['firstName'] . ' ' . $order['patronymic'] : $order['firstName'],
'lastname' => (!empty($order['lastName'])) ? $order['lastName'] : ' ', 'lastname' => (!empty($order['customer']['lastName'])) ? $order['customer']['lastName'] : ' ',
'email' => $order['email'], 'email' => $order['customer']['email'],
'telephone' => (!empty($order['customer']['phones'][0]['number']) ) ? $order['customer']['phones'][0]['number'] : ' ', 'telephone' => $order['customer']['phones'] ? $order['customer']['phones'][0]['number'] : ' ',
'fax' => '', 'fax' => '',
'newsletter' => 0, 'newsletter' => 0,
'password' => 'tmppass', 'password' => 'tmppass',
'status' => 1, 'status' => 1,
'approved' => 1,
'safe' => 0,
'address' => array( 'address' => array(
array( array(
'firstname' => $order['firstName'], 'firstname' => isset($order['patronymic']) ? $order['firstName'] . ' ' . $order['patronymic'] : $order['firstName'],
'lastname' => (!empty($order['lastName'])) ? $order['lastName'] : ' ', 'lastname' => (!empty($order['customer']['lastName'])) ? $order['customer']['lastName'] : ' ',
'address_1' => $order['customer']['address']['text'], 'address_1' => $order['customer']['address']['text'],
'address_2' => ' ', 'address_2' => ' ',
'city' => !empty($order['customer']['address']['city']) ? $order['customer']['address']['city'] : $order['delivery']['address']['city'], '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', 'tax_id' => '1',
'company' => '', 'company' => '',
'company_id' => '', 'company_id' => '',
'zone_id' => '0', 'zone_id' => $customerZone ? $customerZone['zone_id'] : 0,
'country_id' => 0 'country_id' => $customerCountry ? $customerCountry['country_id'] : 0,
'default' => '1'
) )
), ),
); );
$customer_id = $this->model_customer_customer->addCustomer($cData);
$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'];
}
$customersIdsFix[] = array('id' => $order['customer']['id'], 'externalId' => (int)$customer_id); $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['store_id'] = $store == null ? 0 : $store;
$data['customer'] = $order['firstName']; $data['customer'] = $order['firstName'];
$data['customer_id'] = $customer_id; $data['customer_id'] = $customer_id;
$data['customer_group_id'] = 1; $data['customer_group_id'] = 1;
$data['firstname'] = $order['firstName']; $data['firstname'] = $order['firstName'];
$data['lastname'] = (!empty($order['lastName'])) ? $order['lastName'] : ' '; $data['lastname'] = isset($order['lastName']) ? $order['lastName'] : $order['firstName'];
$data['email'] = $order['email']; $data['email'] = $mail ? $mail : uniqid() . '@retailrcm.ru';
$data['telephone'] = (!empty($order['customer']['phones'][0]['number'])) ? $order['customer']['phones'][0]['number'] : ' ';
$data['comment'] = !empty($order['customerComment']) ? $order['customerComment'] : ''; $data['comment'] = !empty($order['customerComment']) ? $order['customerComment'] : '';
$data['fax'] = ''; $data['fax'] = '';
$data['payment_address'] = '0'; $data['payment_address'] = '0';
$data['payment_firstname'] = $order['firstName']; $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_1'] = $order['customer']['address']['text'];
$data['payment_address_2'] = ''; $data['payment_address_2'] = '';
$data['payment_company'] = ''; $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_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']; $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'])) { if (is_int($order['delivery']['address']['region'])) {
$region = $order['delivery']['address']['region']; $shippingZone = $order['delivery']['address']['region'];
} else { } else {
foreach ($this->zones as $zone) { $shippingZone = $this->getZoneByName($order['delivery']['address']['region']);
if ($order['delivery']['address']['region'] == $zone['name']) {
$region = $zone['zone_id']; 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; if (isset($order['customer']['address']['region'])) {
$data['payment_zone_id'] = !empty($order['delivery']['address']['region']) ? $order['delivery']['address']['region'] : $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_address'] = '0';
$data['shipping_firstname'] = $order['firstName']; $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_1'] = $order['delivery']['address']['text'];
$data['shipping_address_2'] = ''; $data['shipping_address_2'] = '';
$data['shipping_company'] = ''; $data['shipping_company'] = '';
@ -404,19 +467,35 @@ class ModelExtensionRetailcrmHistoryV3 extends Model
$data['order_product'] = array(); $data['order_product'] = array();
foreach ($order['items'] as $item) { foreach ($order['items'] as $item) {
$product = $this->model_catalog_product->getProduct($item['offer']['externalId']); $productId = $item['offer']['externalId'];
$data['order_product'][] = array( $options = array();
'product_id' => $item['offer']['externalId'], if(mb_strpos($item['offer']['externalId'], '#') > 1) {
'name' => $item['offer']['name'], $offer = explode('#', $item['offer']['externalId']);
'quantity' => $item['quantity'], $productId = $offer[0];
'price' => $item['initialPrice'], $optionsFromCRM = explode('_', $offer[1]);
'total' => $item['initialPrice'] * $item['quantity'],
'model' => $product['model'],
// this data will not retrive from crm foreach($optionsFromCRM as $optionFromCRM) {
'order_product_id' => '', $optionData = explode('-', $optionFromCRM);
'tax' => 0, $productOptionId = $optionData[0];
'reward' => 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']], 'title' => $this->ocDelivery[$data['shipping_code']],
'value' => $deliveryCost, 'value' => $deliveryCost,
'text' => $deliveryCost, 'text' => $deliveryCost,
'sort_order' => $this->shippingSettings['shipping_sort_order'] 'sort_order' => $this->shippingSettings[$this->totalTitle . 'shipping_sort_order']
), ),
array( array(
'order_total_id' => '', 'order_total_id' => '',
@ -445,18 +524,16 @@ class ModelExtensionRetailcrmHistoryV3 extends Model
'title' => $this->language->get('column_total'), 'title' => $this->language->get('column_total'),
'value' => !empty($order['totalSumm']) ? $order['totalSumm'] : $order['summ'] + $deliveryCost, 'value' => !empty($order['totalSumm']) ? $order['totalSumm'] : $order['summ'] + $deliveryCost,
'text' => 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']
) )
); );
$data['fromApi'] = true; $data['fromApi'] = true;
$data['order_status_id'] = 1; $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) $order_id);
$ordersIdsFix[] = array('id' => $order['id'], 'externalId' => (int) $last[0]['order_id']);
} }
return array('customers' => $customersIdsFix, 'orders' => $ordersIdsFix); return array('customers' => $customersIdsFix, 'orders' => $ordersIdsFix);
@ -472,4 +549,29 @@ class ModelExtensionRetailcrmHistoryV3 extends Model
return $title; 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;
}
} }

View File

@ -8,7 +8,7 @@ class ModelExtensionRetailcrmHistoryV45 extends Model
public function request() public function request()
{ {
$moduleTitle = $this->getModuleTitle(); $this->moduleTitle = $this->getModuleTitle();
$this->load->model('setting/setting'); $this->load->model('setting/setting');
$this->load->model('setting/store'); $this->load->model('setting/store');
$this->load->model('user/api'); $this->load->model('user/api');
@ -21,12 +21,12 @@ class ModelExtensionRetailcrmHistoryV45 extends Model
$this->load->language('extension/module/retailcrm'); $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'); $history = $this->model_setting_setting->getSetting('retailcrm_history');
$settings['domain'] = parse_url(HTTP_SERVER, PHP_URL_HOST); $settings['domain'] = parse_url(HTTP_SERVER, PHP_URL_HOST);
$url = isset($settings[$moduleTitle . '_url']) ? $settings[$moduleTitle . '_url'] : null; $url = isset($settings[$this->moduleTitle . '_url']) ? $settings[$this->moduleTitle . '_url'] : null;
$key = isset($settings[$moduleTitle . '_apikey']) ? $settings[$moduleTitle . '_apikey'] : null; $key = isset($settings[$this->moduleTitle . '_apikey']) ? $settings[$this->moduleTitle . '_apikey'] : null;
if (empty($url) || empty($key)) { if (empty($url) || empty($key)) {
$this->log->addNotice('You need to configure retailcrm module first.'); $this->log->addNotice('You need to configure retailcrm module first.');
@ -36,43 +36,57 @@ class ModelExtensionRetailcrmHistoryV45 extends Model
$this->opencartApiClient = new OpencartApiClient($this->registry); $this->opencartApiClient = new OpencartApiClient($this->registry);
$crm = new RetailcrmProxy( $crm = new RetailcrmProxy(
$settings[$moduleTitle . '_url'], $settings[$this->moduleTitle . '_url'],
$settings[$moduleTitle . '_apikey'], $settings[$this->moduleTitle . '_apikey'],
DIR_SYSTEM . 'storage/logs/retailcrm.log', DIR_SYSTEM . 'storage/logs/retailcrm.log',
$settings[$moduleTitle . '_apiversion'] $settings[$this->moduleTitle . '_apiversion']
); );
$lastRun = !empty($history['retailcrm_history']) $sinceIdOrders = $history['retailcrm_history_orders'] ? $history['retailcrm_history_orders'] : null;
? new DateTime($history['retailcrm_history']) $sinceIdCustomers = $history['retailcrm_history_customers'] ? $history['retailcrm_history_customers'] : null;
: new DateTime(date('Y-m-d H:i:s', strtotime('-1 days', strtotime(date('Y-m-d H:i:s')))));
$packsOrders = $crm->ordersHistory(array( $packsOrders = $crm->ordersHistory(array(
'startDate' => $lastRun->format('Y-m-d H:i:s'), 'sinceId' => $sinceIdOrders ? $sinceIdOrders : 0
), 1, 100); ), 1, 100);
$packsCustomers = $crm->customersHistory(array( $packsCustomers = $crm->customersHistory(array(
'startDate' => $lastRun->format('Y-m-d H:i:s'), 'sinceId' => $sinceIdCustomers ? $sinceIdCustomers : 0
), 1, 100); ), 1, 100);
if(!$packsOrders->isSuccessful() && count($packsOrders->history) <= 0 && !$packsCustomers->isSuccessful() && count($Customers->history) <= 0)
return false;
if(!$packsOrders->isSuccessful() && count($packsOrders->history) <= 0 && !$packsCustomers->isSuccessful() && count($packsCustomers->history) <= 0) {
return false;
}
$generatedAt = $packsOrders['generatedAt'];
$orders = RetailcrmHistoryHelper::assemblyOrder($packsOrders->history); $orders = RetailcrmHistoryHelper::assemblyOrder($packsOrders->history);
$customers = RetailcrmHistoryHelper::assemblyCustomer($packsCustomers->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->totalTitle = $this->totalTitles();
$this->subtotalSettings = $this->model_setting_setting->getSetting($this->totalTitle . 'sub_total'); $this->subtotalSettings = $this->model_setting_setting->getSetting($this->totalTitle . 'sub_total');
$this->totalSettings = $this->model_setting_setting->getSetting($this->totalTitle . 'total'); $this->totalSettings = $this->model_setting_setting->getSetting($this->totalTitle . 'total');
$this->shippingSettings = $this->model_setting_setting->getSetting($this->totalTitle . 'shipping'); $this->shippingSettings = $this->model_setting_setting->getSetting($this->totalTitle . 'shipping');
$this->delivery = array_flip($settings[$moduleTitle . '_delivery']); $this->delivery = array_flip($settings[$this->moduleTitle . '_delivery']);
$this->payment = array_flip($settings[$moduleTitle . '_payment']); $this->payment = array_flip($settings[$this->moduleTitle . '_payment']);
$this->status = array_flip($settings[$moduleTitle . '_status']); $this->status = array_flip($settings[$this->moduleTitle . '_status']);
$this->ocPayment = $this->model_extension_retailcrm_references $this->ocPayment = $this->model_extension_retailcrm_references
->getOpercartPaymentTypes(); ->getOpercartPaymentTypes();
$this->ocDelivery = $settings[$moduleTitle . '_delivery']; $this->ocDelivery = $settings[$this->moduleTitle . '_delivery'];
$this->zones = $this->model_localisation_zone->getZones(); $this->zones = $this->model_localisation_zone->getZones();
@ -105,6 +119,13 @@ class ModelExtensionRetailcrmHistoryV45 extends Model
unset($customers); unset($customers);
if (!empty($updateCustomers)) {
$customers = $crm->customersList($filter = array('ids' => $updateCustomers));
if ($customers) {
$this->updateCustomers($customers['customers']);
}
}
if (!empty($newOrders)) { if (!empty($newOrders)) {
$orders = $crm->ordersList($filter = array('ids' => $newOrders)); $orders = $crm->ordersList($filter = array('ids' => $newOrders));
if ($orders) { if ($orders) {
@ -119,14 +140,14 @@ class ModelExtensionRetailcrmHistoryV45 extends Model
} }
} }
if (!empty($updateCustomers)) { $this->model_setting_setting->editSetting(
$customers = $crm->customersList($filter = array('ids' => $updateCustomers)); 'retailcrm_history',
if ($customers) { array(
$this->updateCustomers($customers['customers']); 'retailcrm_history_orders' => $sinceIdOrders,
} 'retailcrm_history_customers' => $sinceIdCustomers,
} 'retailcrm_history_datetime' => $generatedAt
)
$this->model_setting_setting->editSetting('retailcrm_history', array('retailcrm_history' => $generatedAt)); );
if (!empty($this->createResult['customers'])) { if (!empty($this->createResult['customers'])) {
$crm->customersFixExternalIds($this->createResult['customers']); $crm->customersFixExternalIds($this->createResult['customers']);
@ -153,25 +174,33 @@ class ModelExtensionRetailcrmHistoryV45 extends Model
$payment = end($order['payments']); $payment = end($order['payments']);
} }
} elseif (isset($order['paymentType'])) { } elseif (isset($order['paymentType'])) {
$payment = $order['paymentType']; $payment['type'] = $order['paymentType'];
} }
$data = array(); $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['store_id'] = $store == null ? 0 : $store;
$data['customer'] = $order['firstName']; $data['customer'] = $order['firstName'];
$data['customer_id'] = (!empty($order['customer']['externalId'])) ? $order['customer']['externalId'] : 0; $data['customer_id'] = (!empty($order['customer']['externalId'])) ? $order['customer']['externalId'] : 0;
$data['customer_group_id'] = 1; $data['customer_group_id'] = 1;
$data['firstname'] = $order['firstName']; $data['firstname'] = $order['firstName'];
$data['lastname'] = (!empty($order['lastName'])) ? $order['lastName'] : ' '; $data['lastname'] = isset($order['lastName']) ? $order['lastName'] : $order['firstName'];
$data['email'] = $order['email']; $data['email'] = $mail ? $mail : uniqid() . '@retailrcm.ru';
$data['telephone'] = (!empty($order['phone'])) ? $order['phone'] : '';
$data['comment'] = !empty($order['customerComment']) ? $order['customerComment'] : ''; $data['comment'] = !empty($order['customerComment']) ? $order['customerComment'] : '';
$data['fax'] = ''; $data['fax'] = '';
$data['payment_address'] = '0'; $data['payment_address'] = '0';
$data['payment_firstname'] = $order['firstName']; $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_1'] = isset($order['customer']['address']) ? $order['customer']['address']['text'] : '';
$data['payment_address_2'] = ''; $data['payment_address_2'] = '';
$data['payment_company'] = ''; $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_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']; $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'])) { if (is_int($order['delivery']['address']['region'])) {
$region = $order['delivery']['address']['region']; $shippingZone = $order['delivery']['address']['region'];
} else { } else {
foreach ($this->zones as $zone) { $shippingZone = $this->getZoneByName($order['delivery']['address']['region']);
if ($order['delivery']['address']['region'] == $zone['name']) {
$region = $zone['zone_id']; 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; if (isset($order['customer']['address']['region'])) {
$data['payment_zone_id'] = !empty($order['delivery']['address']['region']) ? $order['delivery']['address']['region'] : $region; $paymentZone = $this->getZoneByName($order['customer']['address']['region']);
$data['shipping_country_id'] = !empty($order['delivery']['address']['country']) ? $order['delivery']['address']['country'] : 0; if ($paymentZone) {
$data['shipping_zone_id'] = $region; $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_address'] = '0';
$data['shipping_firstname'] = $order['firstName']; $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_1'] = $order['delivery']['address']['text'];
$data['shipping_address_2'] = ''; $data['shipping_address_2'] = '';
$data['shipping_company'] = ''; $data['shipping_company'] = '';
$data['shipping_company_id'] = ''; $data['shipping_company_id'] = '';
$data['shipping_city'] = $order['delivery']['address']['city']; $data['shipping_city'] = $order['delivery']['address']['city'];
$data['shipping_postcode'] = $order['delivery']['address']['index']; $data['shipping_postcode'] = $order['delivery']['address']['index'];
$data['shipping'] = $this->delivery[$order['delivery']['code']]; $data['shipping'] = $this->delivery[$order['delivery']['code']];
$data['shipping_method'] = $this->ocDelivery[$data['shipping']]; $data['shipping_method'] = $this->ocDelivery[$data['shipping']];
$data['shipping_code'] = $this->delivery[$order['delivery']['code']]; $data['shipping_code'] = $this->delivery[$order['delivery']['code']];
@ -240,7 +286,6 @@ class ModelExtensionRetailcrmHistoryV45 extends Model
$data['order_product'] = array(); $data['order_product'] = array();
foreach ($order['items'] as $item) { foreach ($order['items'] as $item) {
//$product = $this->model_catalog_product->getProduct($item['offer']['externalId']);
$productId = $item['offer']['externalId']; $productId = $item['offer']['externalId'];
$options = array(); $options = array();
if(mb_strpos($item['offer']['externalId'], '#') > 1) { if(mb_strpos($item['offer']['externalId'], '#') > 1) {
@ -335,7 +380,7 @@ class ModelExtensionRetailcrmHistoryV45 extends Model
if (isset($order['payments'])) { if (isset($order['payments'])) {
$payment = end($order['payments']); $payment = end($order['payments']);
} elseif (isset($order['paymentType'])) { } elseif (isset($order['paymentType'])) {
$payment = $order['paymentType']; $payment['type'] = $order['paymentType'];
} }
$customer_id = (!empty($order['customer']['externalId'])) $customer_id = (!empty($order['customer']['externalId']))
@ -345,21 +390,35 @@ class ModelExtensionRetailcrmHistoryV45 extends Model
$data = array(); $data = array();
if ($customer_id == 0) { 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( $cData = array(
'store_id' => 0, 'store_id' => 0,
'customer_group_id' => '1', 'customer_group_id' => '1',
'firstname' => $order['firstName'], 'firstname' => isset($order['patronymic']) ? $order['firstName'] . ' ' . $order['patronymic'] : $order['firstName'],
'lastname' => (!empty($order['lastName'])) ? $order['lastName'] : ' ', 'lastname' => (!empty($order['customer']['lastName'])) ? $order['customer']['lastName'] : ' ',
'email' => $order['email'], 'email' => $order['customer']['email'],
'telephone' => (!empty($order['customer']['phones'][0]['number']) ) ? $order['customer']['phones'][0]['number'] : ' ', 'telephone' => $order['customer']['phones'] ? $order['customer']['phones'][0]['number'] : ' ',
'fax' => '', 'fax' => '',
'newsletter' => 0, 'newsletter' => 0,
'password' => 'tmppass', 'password' => 'tmppass',
'status' => 1, 'status' => 1,
'approved' => 1,
'safe' => 0,
'address' => array( 'address' => array(
array( array(
'firstname' => $order['firstName'], 'firstname' => isset($order['patronymic']) ? $order['firstName'] . ' ' . $order['patronymic'] : $order['firstName'],
'lastname' => (!empty($order['lastName'])) ? $order['lastName'] : ' ', 'lastname' => (!empty($order['customer']['lastName'])) ? $order['customer']['lastName'] : ' ',
'address_1' => $order['customer']['address']['text'], 'address_1' => $order['customer']['address']['text'],
'address_2' => ' ', 'address_2' => ' ',
'city' => !empty($order['customer']['address']['city']) ? $order['customer']['address']['city'] : $order['delivery']['address']['city'], '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', 'tax_id' => '1',
'company' => '', 'company' => '',
'company_id' => '', 'company_id' => '',
'zone_id' => '0', 'zone_id' => $customerZone ? $customerZone['zone_id'] : 0,
'country_id' => 0 'country_id' => $customerCountry ? $customerCountry['country_id'] : 0,
'default' => '1'
) )
), ),
); );
$customer_id = $this->model_customer_customer->addCustomer($cData);
$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'];
}
$customersIdsFix[] = array('id' => $order['customer']['id'], 'externalId' => (int)$customer_id); $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['store_id'] = $store == null ? 0 : $store;
$data['customer'] = $order['firstName']; $data['customer'] = $order['firstName'];
$data['customer_id'] = $customer_id; $data['customer_id'] = $customer_id;
$data['customer_group_id'] = 1; $data['customer_group_id'] = 1;
$data['firstname'] = $order['firstName']; $data['firstname'] = $order['firstName'];
$data['lastname'] = (!empty($order['lastName'])) ? $order['lastName'] : ' '; $data['lastname'] = (isset($order['lastName'])) ? $order['lastName'] : $order['firstName'];
$data['email'] = $order['email']; $data['email'] = $mail ? $mail : uniqid() . '@retailrcm.ru';
$data['telephone'] = (!empty($order['customer']['phones'][0]['number'])) ? $order['customer']['phones'][0]['number'] : ' ';
$data['comment'] = !empty($order['customerComment']) ? $order['customerComment'] : ''; $data['comment'] = !empty($order['customerComment']) ? $order['customerComment'] : '';
$data['fax'] = ''; $data['fax'] = '';
$data['payment_address'] = '0'; $data['payment_address'] = '0';
$data['payment_firstname'] = $order['firstName']; $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_1'] = $order['customer']['address']['text'];
$data['payment_address_2'] = ''; $data['payment_address_2'] = '';
$data['payment_company'] = ''; $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_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']; $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'])) { if (!empty($order['delivery']['address']['region']) && is_int($order['delivery']['address']['region'])) {
$region = $order['delivery']['address']['region']; $shippingZone = $order['delivery']['address']['region'];
} else { } else {
foreach ($this->zones as $zone) { $shippingZone = $this->getZoneByName($order['delivery']['address']['region']);
if ($order['delivery']['address']['region'] == $zone['name']) {
$region = $zone['zone_id']; 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; if (isset($order['customer']['address']['region'])) {
$data['payment_zone_id'] = !empty($order['delivery']['address']['region']) ? $order['delivery']['address']['region'] : $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_address'] = '0';
$data['shipping_firstname'] = $order['firstName']; $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_1'] = $order['delivery']['address']['text'];
$data['shipping_address_2'] = ''; $data['shipping_address_2'] = '';
$data['shipping_company'] = ''; $data['shipping_company'] = '';
@ -461,19 +540,35 @@ class ModelExtensionRetailcrmHistoryV45 extends Model
$data['order_product'] = array(); $data['order_product'] = array();
foreach ($order['items'] as $item) { foreach ($order['items'] as $item) {
$product = $this->model_catalog_product->getProduct($item['offer']['externalId']); $productId = $item['offer']['externalId'];
$data['order_product'][] = array( $options = array();
'product_id' => $item['offer']['externalId'], if(mb_strpos($item['offer']['externalId'], '#') > 1) {
'name' => $item['offer']['name'], $offer = explode('#', $item['offer']['externalId']);
'quantity' => $item['quantity'], $productId = $offer[0];
'price' => $item['initialPrice'], $optionsFromCRM = explode('_', $offer[1]);
'total' => $item['initialPrice'] * $item['quantity'],
'model' => $product['model'],
// this data will not retrive from crm foreach ($optionsFromCRM as $optionFromCRM) {
'order_product_id' => '', $optionData = explode('-', $optionFromCRM);
'tax' => 0, $productOptionId = $optionData[0];
'reward' => 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['fromApi'] = true;
$data['order_status_id'] = 1; $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) $order_id);
$ordersIdsFix[] = array('id' => $order['id'], 'externalId' => (int) $last[0]['order_id']);
} }
return array('customers' => $customersIdsFix, 'orders' => $ordersIdsFix); return array('customers' => $customersIdsFix, 'orders' => $ordersIdsFix);
@ -521,25 +614,58 @@ class ModelExtensionRetailcrmHistoryV45 extends Model
protected function updateCustomers($customers) 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) { foreach ($customers as $customer) {
$customer_id = $customer['externalId']; $customer_id = $customer['externalId'];
$customerData = $this->model_customer_customer->getCustomer($customer_id); $customerData = $this->model_customer_customer->getCustomer($customer_id);
$customerData['firstname'] = $customer['firstName']; $customerData['firstname'] = $customer['firstName'];
$customerData['lastname'] = $customer['lastName']; $customerData['lastname'] = isset($customer['lastName']) ? $customer['lastName'] : '';
$customerData['email'] = $customer['email']; $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 = $this->model_customer_customer->getAddress($customerData['address_id']);
$customerAddress['firstname'] = $customer['firstName']; if (isset($customer['address']['countryIso'])) {
$customerAddress['lastname'] = $customer['lastName']; $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['address_1'] = $customer['address']['text'];
$customerAddress['city'] = $customer['address']['city']; $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); $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); $this->model_customer_customer->editCustomer($customer_id, $customerData);
} }
} }
@ -565,4 +691,18 @@ class ModelExtensionRetailcrmHistoryV45 extends Model
return $title; 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;
}
} }

View File

@ -41,6 +41,14 @@ class ModelExtensionRetailcrmReferences extends Model
); );
} }
public function getCustomFields()
{
return array(
'opencart' => $this->getOpencartCustomFields(),
'retailcrm' => $this->getApiCustomerCustomFields()
);
}
public function getOpercartOrderStatuses() public function getOpercartOrderStatuses()
{ {
$this->load->model('localisation/order_status'); $this->load->model('localisation/order_status');
@ -77,6 +85,13 @@ class ModelExtensionRetailcrmReferences extends Model
return $paymentTypes; return $paymentTypes;
} }
public function getOpencartCustomFields()
{
$this->load->model('customer/custom_field');
return $this->model_customer_custom_field->getCustomFields();
}
public function getApiDeliveryTypes() public function getApiDeliveryTypes()
{ {
$this->initApi(); $this->initApi();
@ -104,6 +119,16 @@ class ModelExtensionRetailcrmReferences extends Model
return (!$response->isSuccessful()) ? array() : $response->paymentTypes; 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() protected function initApi()
{ {
$moduleTitle = $this->getModuleTitle(); $moduleTitle = $this->getModuleTitle();

View File

@ -43,6 +43,9 @@
<?php if (isset($saved_settings['retailcrm_apikey']) && $saved_settings['retailcrm_apikey'] != '' && isset($saved_settings['retailcrm_url']) && $saved_settings['retailcrm_url'] != ''): ?> <?php if (isset($saved_settings['retailcrm_apikey']) && $saved_settings['retailcrm_apikey'] != '' && isset($saved_settings['retailcrm_url']) && $saved_settings['retailcrm_url'] != ''): ?>
<li><a href="#tab-references" data-toggle="tab"><?php echo $references_tab_text; ?></a></li> <li><a href="#tab-references" data-toggle="tab"><?php echo $references_tab_text; ?></a></li>
<li><a href="#tab-collector" data-toggle="tab"><?php echo $collector_tab_text; ?></a></li> <li><a href="#tab-collector" data-toggle="tab"><?php echo $collector_tab_text; ?></a></li>
<?php if ($saved_settings['retailcrm_apiversion'] == 'v5') : ?>
<li><a href="#tab-custom_fields" data-toggle="tab"><?php echo $custom_fields_tab_text; ?></a></li>
<?php endif; ?>
<?php endif; ?> <?php endif; ?>
</ul> </ul>
@ -235,6 +238,41 @@
<?php endif; ?> <?php endif; ?>
<?php endif; ?> <?php endif; ?>
</div> </div>
<?php if (isset($saved_settings['retailcrm_apiversion']) && $saved_settings['retailcrm_apiversion'] == 'v5' && isset($customFields)) : ?>
<div class="tab-pane" id="tab-custom_fields">
<h4><?php echo $retailcrm_dict_custom_fields; ?></h4>
<?php if ($customFields['retailcrm'] && $customFields['opencart']) : ?>
<?php foreach ($customFields['opencart'] as $customField) : ?>
<?php $fid = $customField['custom_field_id'] ?>
<div class="retailcrm_unit">
<select id="retailcrm_custom_field_<?php echo $fid; ?>" name="retailcrm_custom_field[<?php echo $fid; ?>]" >
<?php foreach ($customFields['retailcrm'] as $v): ?>
<option value="<?php echo $v['code'];?>" <?php if(isset($saved_settings['retailcrm_custom_field'][$fid]) && $v['code'] == $saved_settings['retailcrm_custom_field'][$fid]):?>selected="selected"<?php endif;?>>
<?php echo $v['name'];?>
</option>
<?php endforeach; ?>
</select>
<label for="retailcrm_custom_field_<?php echo $fid; ?>"><?php echo $customField['name']; ?></label>
</div>
<?php endforeach; ?>
<?php elseif (!$customFields['retailcrm'] && !$customFields['opencart']) : ?>
<div class="alert alert-info"><i class="fa fa-exclamation-circle"></i>
<button type="button" class="close" data-dismiss="alert">&times;</button>
<?php echo $text_error_custom_field; ?>
</div>
<?php elseif (!$customFields['retailcrm']) : ?>
<div class="alert alert-info"><i class="fa fa-exclamation-circle"></i>
<button type="button" class="close" data-dismiss="alert">&times;</button>
<?php echo $text_error_cf_retailcrm; ?>
</div>
<?php elseif (!$customFields['opencart']) : ?>
<div class="alert alert-info"><i class="fa fa-exclamation-circle"></i>
<button type="button" class="close" data-dismiss="alert">&times;</button>
<?php echo $text_error_cf_opencart; ?>
</div>
<?php endif; ?>
</div>
<?php endif; ?>
</div> </div>
</form> </form>
</div> </div>
@ -292,7 +330,7 @@
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText); alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}, },
success: function(data, textStatus, jqXHR) { success: function(data, textStatus, jqXHR) {
if (jqXHR['responseText'] == 'false') { if (jqXHR['responseText'] == '400') {
$('.alert-danger').remove(); $('.alert-danger').remove();
$('#content > .container-fluid').prepend('<div class="alert alert-danger"><i class="fa fa-exclamation-circle"></i><?php echo $text_error_order; ?></div>'); $('#content > .container-fluid').prepend('<div class="alert alert-danger"><i class="fa fa-exclamation-circle"></i><?php echo $text_error_order; ?></div>');
$('#export_order').button('reset'); $('#export_order').button('reset');

View File

@ -236,6 +236,41 @@
{% endif %} {% endif %}
{% endif %} {% endif %}
</div> </div>
{% if saved_settings.retailcrm_apiversion is defined and saved_settings.retailcrm_apiversion == 'v5' and customFields is defined %}
<div class="tab-pane" id="tab-custom_fields">
<h4>{{ retailcrm_dict_custom_fields }}</h4>
{% if customFields.retailcrm is not empty and customFields.opencart is not empty %}
{% for customField in customFields.opencart %}
{% set fid = customField.custom_field_id %}
<div class="retailcrm_unit">
<select id="retailcrm_custom_field_{{ fid }}" name="retailcrm_custom_field[{{ fid }}]" >
{% for v in customFields.retailcrm %}
<option value="{{ v.code }}" {% if saved_settings.retailcrm_custom_field.fid is defined and v.code == saved_settings.retailcrm_custom_field.fid %} selected="selected" {% endif %}>
{{ v.name }}
</option>
{% endfor %}
</select>
<label for="retailcrm_custom_field_{{ fid }}">{{ customField.name }}</label>
</div>
{% endfor %}
{% elseif customFields.retailcrm is empty and customFields.opencart is empty %}
<div class="alert alert-info"><i class="fa fa-exclamation-circle"></i>
<button type="button" class="close" data-dismiss="alert">&times;</button>
{{ text_error_custom_field }}
</div>
{% elseif customFields.retailcrm is empty %}
<div class="alert alert-info"><i class="fa fa-exclamation-circle"></i>
<button type="button" class="close" data-dismiss="alert">&times;</button>
{{ text_error_cf_retailcrm }}
</div>
{% elseif customFields.opencart is empty %}
<div class="alert alert-info"><i class="fa fa-exclamation-circle"></i>
<button type="button" class="close" data-dismiss="alert">&times;</button>
{{ text_error_cf_opencart }}
</div>
{% endif %}
</div>
{% endif %}
</div> </div>
</form> </form>
</div> </div>
@ -293,7 +328,7 @@
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText); alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}, },
success: function(data, textStatus, jqXHR) { success: function(data, textStatus, jqXHR) {
if (jqXHR['responseText'] == 'false') { if (jqXHR['responseText'] == '400') {
$('.alert-danger').remove(); $('.alert-danger').remove();
$('#content > .container-fluid').prepend('<div class="alert alert-danger"><i class="fa fa-exclamation-circle"></i>{{ text_error_order }}</div>'); $('#content > .container-fluid').prepend('<div class="alert alert-danger"><i class="fa fa-exclamation-circle"></i>{{ text_error_order }}</div>');
$('#export_order').button('reset'); $('#export_order').button('reset');

View File

@ -55,6 +55,14 @@ class ControllerApiRetailcrm extends Controller
} }
if ($this->config->get($shippingCode . '_status')) { if ($this->config->get($shippingCode . '_status')) {
if ($shippingCode == 'free') {
$free_total = $this->config->get('free_total');
if ($free_total > 0) {
$this->config->set('free_total', 0);
}
}
if($this->{'model_extension_shipping_' . $shippingModule['code']}->getQuote($address)) { if($this->{'model_extension_shipping_' . $shippingModule['code']}->getQuote($address)) {
$quote_data[] = $this->{'model_extension_shipping_' . $shippingModule['code']}->getQuote($address); $quote_data[] = $this->{'model_extension_shipping_' . $shippingModule['code']}->getQuote($address);
} }

View File

@ -26,6 +26,8 @@ class ModelExtensionRetailcrmCustomer extends Model {
} }
private function process($customer) { private function process($customer) {
$moduleTitle = $this->getModuleTitle();
$customerToCrm = array( $customerToCrm = array(
'externalId' => $customer['customer_id'], 'externalId' => $customer['customer_id'],
'firstName' => $customer['firstname'], 'firstName' => $customer['firstname'],
@ -49,6 +51,18 @@ class ModelExtensionRetailcrmCustomer extends Model {
); );
} }
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; return $customerToCrm;
} }
@ -56,18 +70,18 @@ class ModelExtensionRetailcrmCustomer extends Model {
{ {
$this->load->model('setting/setting'); $this->load->model('setting/setting');
$moduleTitle = $this->getModuleTitle(); $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; return false;
require_once DIR_SYSTEM . 'library/retailcrm/bootstrap.php'; require_once DIR_SYSTEM . 'library/retailcrm/bootstrap.php';
$this->retailcrmApi = new RetailcrmProxy( $this->retailcrmApi = new RetailcrmProxy(
$settings[$moduleTitle . '_url'], $this->settings[$moduleTitle . '_url'],
$settings[$moduleTitle . '_apikey'], $this->settings[$moduleTitle . '_apikey'],
DIR_SYSTEM . 'storage/logs/retailcrm.log', DIR_SYSTEM . 'storage/logs/retailcrm.log',
$settings[$moduleTitle . '_apiversion'] $this->settings[$moduleTitle . '_apiversion']
); );
} }

View File

@ -223,12 +223,12 @@ class OpencartApiClient {
$this->request('customer', array(), $customer); $this->request('customer', array(), $customer);
$products = array(); $products = array();
foreach($data['order_product'] as $product) { foreach ($data['order_product'] as $order_product) {
$product = array( $products[] = array(
'product_id' => $product['product_id'], 'product_id' => $order_product['product_id'],
'quantity' => $product['quantity'], 'quantity' => $order_product['quantity'],
'option' => $order_product['option']
); );
$products[] = $product;
} }
$this->request('cart/add', array(), array('product' => $products)); $this->request('cart/add', array(), array('product' => $products));
@ -279,7 +279,11 @@ class OpencartApiClient {
'comment' => $data['comment'], 'comment' => $data['comment'],
'affiliate_id' => $data['affiliate_id'], '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() { private function getInnerIpAddr() {

View File

@ -12,8 +12,6 @@
*/ */
class RetailcrmApiClient3 class RetailcrmApiClient3
{ {
const VERSION = 'v3';
protected $client; protected $client;
/** /**
@ -29,18 +27,32 @@ class RetailcrmApiClient3
* @param string $site * @param string $site
* @return mixed * @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)) { if ('/' != substr($url, strlen($url) - 1, 1)) {
$url .= '/'; $url .= '/';
} }
$url = $url . 'api/' . self::VERSION; $url = $version == null ? $url . 'api' : $url . 'api/' . $version;
$this->client = new RetailcrmHttpClient($url, array('apiKey' => $apiKey)); $this->client = new RetailcrmHttpClient($url, array('apiKey' => $apiKey));
$this->siteCode = $site; $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 * Create a order
* *

View File

@ -12,8 +12,6 @@
*/ */
class RetailcrmApiClient4 class RetailcrmApiClient4
{ {
const VERSION = 'v4';
protected $client; protected $client;
/** /**
@ -32,18 +30,32 @@ class RetailcrmApiClient4
* *
* @return mixed * @return mixed
*/ */
public function __construct($url, $apiKey, $site = null) public function __construct($url, $apiKey, $version = null, $site = null)
{ {
if ('/' !== $url[strlen($url) - 1]) { if ('/' !== $url[strlen($url) - 1]) {
$url .= '/'; $url .= '/';
} }
$url = $url . 'api/' . self::VERSION; $url = $version == null ? $url . 'api' : $url . 'api/' . $version;
$this->client = new RetailcrmHttpClient($url, array('apiKey' => $apiKey)); $this->client = new RetailcrmHttpClient($url, array('apiKey' => $apiKey));
$this->siteCode = $site; $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 * Returns users list
* *

View File

@ -12,8 +12,6 @@
*/ */
class RetailcrmApiClient5 class RetailcrmApiClient5
{ {
const VERSION = 'v5';
protected $client; protected $client;
/** /**
@ -32,18 +30,32 @@ class RetailcrmApiClient5
* *
* @return mixed * @return mixed
*/ */
public function __construct($url, $apiKey, $site = null) public function __construct($url, $apiKey, $version = null, $site = null)
{ {
if ('/' !== $url[strlen($url) - 1]) { if ('/' !== $url[strlen($url) - 1]) {
$url .= '/'; $url .= '/';
} }
$url = $url . 'api/' . self::VERSION; $url = $version == null ? $url . 'api' : $url . 'api/' . $version;
$this->client = new RetailcrmHttpClient($url, array('apiKey' => $apiKey)); $this->client = new RetailcrmHttpClient($url, array('apiKey' => $apiKey));
$this->siteCode = $site; $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 * Returns users list
* *

View File

@ -28,14 +28,14 @@ class RetailcrmHistoryHelper {
unset($change['order']['contragent']); 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']); $orders[$change['order']['id']] = array_merge($orders[$change['order']['id']], $change['order']);
} else { } else {
$orders[$change['order']['id']] = $change['order']; $orders[$change['order']['id']] = $change['order'];
} }
if(isset($change['item']) && $change['item']) { 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']); $orders[$change['order']['id']]['items'][$change['item']['id']] = array_merge($orders[$change['order']['id']]['items'][$change['item']['id']], $change['item']);
} else { } else {
$orders[$change['order']['id']]['items'][$change['item']['id']] = $change['item']; $orders[$change['order']['id']]['items'][$change['item']['id']] = $change['item'];
@ -47,7 +47,7 @@ class RetailcrmHistoryHelper {
if(empty($change['newValue']) && $change['field'] == 'order_product') { if(empty($change['newValue']) && $change['field'] == 'order_product') {
$orders[$change['order']['id']]['items'][$change['item']['id']]['delete'] = true; $orders[$change['order']['id']]['items'][$change['item']['id']]['delete'] = true;
} }
if(!$orders[$change['order']['id']]['items'][$change['item']['id']]['create'] && $fields['item'][$change['field']]) { if(!isset($orders[$change['order']['id']]['items'][$change['item']['id']]['create']) && $fields['item'][$change['field']]) {
$orders[$change['order']['id']]['items'][$change['item']['id']][$fields['item'][$change['field']]] = $change['newValue']; $orders[$change['order']['id']]['items'][$change['item']['id']][$fields['item'][$change['field']]] = $change['newValue'];
} }
} else { } else {

View File

@ -10,20 +10,20 @@ class RetailcrmProxy
private $api; private $api;
private $log; private $log;
public function __construct($url, $key, $log, $version) public function __construct($url, $key, $log, $version = null)
{ {
if (!$version) $version = 'v4';
switch ($version) { switch ($version) {
case 'v5': case 'v5':
$this->api = new RetailcrmApiClient5($url, $key); $this->api = new RetailcrmApiClient5($url, $key, $version);
break; break;
case 'v4': case 'v4':
$this->api = new RetailcrmApiClient4($url, $key); $this->api = new RetailcrmApiClient4($url, $key, $version);
break; break;
case 'v3': 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; break;
} }

View File

@ -63,6 +63,12 @@
<field id="shipment_date" group="order">shipmentDate</field> <field id="shipment_date" group="order">shipmentDate</field>
<field id="shipped" group="order">shipped</field> <field id="shipped" group="order">shipped</field>
<!--<field id="order_product" group="order">item</field>--> <!--<field id="order_product" group="order">item</field>-->
<field id="payment" group="order">payments</field>
<field id="payments.amount" group="order">amount</field>
<field id="payments.paid_at" group="order">paidAt</field>
<field id="payments.comment" group="order">comment</field>
<field id="payments.type" group="order">type</field>
<field id="payments.status" group="order">status</field>
<field id="order_product.id" group="item">id</field> <field id="order_product.id" group="item">id</field>
<field id="order_product.initial_price" group="item">initialPrice</field> <field id="order_product.initial_price" group="item">initialPrice</field>
@ -70,6 +76,7 @@
<field id="order_product.discount_percent" group="item">discountPercent</field> <field id="order_product.discount_percent" group="item">discountPercent</field>
<field id="order_product.quantity" group="item">quantity</field> <field id="order_product.quantity" group="item">quantity</field>
<field id="order_product.status" group="item">status</field> <field id="order_product.status" group="item">status</field>
<field id="order_product.summ" group="item">summ</field>
<field id="delivery_type" group="delivery">code</field> <field id="delivery_type" group="delivery">code</field>
<field id="delivery_service" group="delivery">service</field> <field id="delivery_service" group="delivery">service</field>