Compare commits

...

25 commits

Author SHA1 Message Date
Alex Lushpai
8763be0133
Merge pull request #86 from iyzoer/v2.2
Bonus points, fix customer group in history
2018-03-23 13:21:07 +03:00
Akolzin Dmitry
98b485cba0 Bonus points, fix customer group in history 2018-03-23 13:08:19 +03:00
Akolzin Dmitry
784677cc9c Edit changelog 2018-03-23 13:08:19 +03:00
Alex Lushpai
43656e4004
Merge pull request #77 from iyzoer/v2.2
Fix session for api methods
2018-02-28 17:27:25 +03:00
Akolzin Dmitry
2d1e9f820c Fix session for api methods 2018-02-28 17:03:11 +03:00
Akolzin Dmitry
ab06d10a81
New model for history, api auth by key or pass (#75) 2018-02-26 13:23:36 +03:00
Akolzin Dmitry
1bf6d6f41a
Fix admin order model (#64) 2017-11-21 13:02:47 +03:00
Akolzin Dmitry
6eecca5f93
Status in orders upload (#62) 2017-11-10 17:23:12 +03:00
Akolzin Dmitry
dd3c32ea4c
Coupon discount (#58) 2017-10-30 13:33:57 +03:00
Sergey
023f7f7677 fix bug (#55) 2017-10-04 21:38:54 +03:00
Akolzin Dmitry
1ae106d7ad Merge pull request #49 from iyzoer/v2.2
V2.2
2017-09-22 16:53:05 +02:00
Akolzin Dmitry
9ac3fe699b Merge branch 'v2.2' into v2.2 2017-09-22 16:52:55 +02:00
Akolzin Dmitry
1ebc6e04f6 edit changelog 2017-09-22 17:34:40 +03:00
Akolzin Dmitry
db00b14872 fix getting shipping methods 2017-09-22 11:24:35 +03:00
Alex Lushpai
cceb82df92 Update order.php 2017-07-04 17:08:33 +03:00
Alex Lushpai
0f6b57f3fa Update customer.php 2017-07-04 17:07:47 +03:00
Alex Lushpai
84391dd804 Update history.php 2017-07-03 12:12:20 +03:00
iyzoer
58e6e66579 v2.2 (#35) 2017-06-22 00:45:28 +03:00
iyzoer
5178c5a4cd Merge branch 'v2.2' into v2.2 2017-06-19 10:34:46 +03:00
iyzoer
e6ce2cbb89 fix call setLogs method 2017-06-19 10:31:14 +03:00
iyzoer
3a28b7c94d V2.2 (#34)
* fix quantity offers in icml
2017-06-07 16:25:56 +03:00
iyzoer
d221554bce fix logs 2017-06-07 15:28:27 +03:00
iyzoer
707e818aac fix quantity offers in icml (#32)
* fix quantity offers in icml
* fix icml
2017-06-02 15:53:04 +03:00
iyzoer
364a715d1f fix icml 2017-06-02 15:51:04 +03:00
iyzoer
2d79091a9d fix quantity offers in icml 2017-06-02 15:43:28 +03:00
19 changed files with 935 additions and 358 deletions

View file

@ -1,14 +1,28 @@
Changelog
=========
## v.2.0.5
* Добавлена проверка группы пользователя в заказе при редактировании
* Добавлена передача скидки по бонусным баллам
####v0.3.0
## v.2.0.4
* Исправление мелких багов
## v.2.0.3
* Улучшена механика выгрузки изменений из RetailCRM
* Улучшена механика выборки и настройки способов доставки
## v.1.0.1
* Добавлена передача скидки по купону
## v.1.0
* Улучшена модель получения способов доставки
* Устранены ошибки пакетной выгрузки
## v0.3.0
* Расширена библиотека клиента
* Добавлена возможность кастомизации моделей заказа через vqmod
* Устранены мелкие баги, проведен рефакторинг кода.
####v0.2.0
## v0.2.0
Общие изменения
@ -26,12 +40,12 @@ Changelog
* Скорректировано указание активности офера
* Убрана генерация размера офера вследствие кастомизации этого параметра в разных магазинах
####v0.1.1
## v0.1.1
* Устранена ошибка редактирования, при которой терялась часть данных при получении истории из CRM
* Оптимизирован код получения и обработки истории заказов
* Актуализированы переводы
####v.0.1
## v.0.1
* Реализован интерфейс настроек модуля
* Реализована отправка данных о заказе/клиенте в CRM
* Реализована выгрузка каталога (cron only)

View file

@ -26,7 +26,10 @@ class ControllerModuleRetailcrm extends Controller
{
$this->load->model('setting/setting');
$this->model_setting_setting
->editSetting('retailcrm', array('retailcrm_status' => 1));
->editSetting('retailcrm', array(
'retailcrm_status' => 1,
'retailcrm_country' => array($this->config->get('config_country_id'))
));
$this->load->model('extension/event');
@ -78,6 +81,7 @@ class ControllerModuleRetailcrm extends Controller
$this->load->model('setting/setting');
$this->load->model('extension/module');
$this->load->model('retailcrm/references');
$this->load->model('localisation/country');
$this->load->language('module/retailcrm');
$this->document->setTitle($this->language->get('heading_title'));
$this->document->addStyle('/admin/view/stylesheet/retailcrm.css');
@ -112,6 +116,7 @@ class ControllerModuleRetailcrm extends Controller
'retailcrm_dict_delivery',
'retailcrm_dict_status',
'retailcrm_dict_payment',
'retailcrm_countries_settings'
);
$this->load->model('extension/extension');
@ -137,7 +142,7 @@ class ControllerModuleRetailcrm extends Controller
$this->retailcrm = new RetailcrmProxy(
$url,
$key,
DIR_SYSTEM . 'logs/retailcrm.log'
$this->setLogs()
);
$_data['delivery'] = $this->model_retailcrm_references
@ -216,7 +221,7 @@ class ControllerModuleRetailcrm extends Controller
$this->load->model('design/layout');
$_data['layouts'] = $this->model_design_layout->getLayouts();
$_data['countries'] = $this->model_localisation_country->getCountries();
$_data['header'] = $this->load->controller('common/header');
$_data['column_left'] = $this->load->controller('common/column_left');
$_data['footer'] = $this->load->controller('common/footer');
@ -338,4 +343,15 @@ class ControllerModuleRetailcrm extends Controller
return false;
}
}
private function setLogs()
{
if (version_compare(VERSION, '2.1', '>')) {
$logs = DIR_SYSTEM . 'storage/logs/retailcrm.log';
} else {
$logs = DIR_SYSTEM . 'logs/retailcrm.log';
}
return $logs;
}
}

View file

@ -10,6 +10,7 @@ $_['text_success'] = 'Setting saved';
$_['text_notice'] = 'Warning! Timezone in CRM & your shop must be equal, you must setup it here:';
$_['retailcrm_base_settings'] = 'Connection settings';
$_['retailcrm_dict_settings'] = 'Dictionary settings';
$_['retailcrm_countries_settings'] = 'Trading zones setting';
$_['retailcrm_url'] = 'RetailCRM URL';
$_['retailcrm_apikey'] = 'RetailCRM API Key';

View file

@ -10,6 +10,7 @@ $_['text_success'] = 'Настройки успешно сохра
$_['text_notice'] = 'Внимание! Часовой пояс в CRM должен совпадать с часовым поясом в магазине, настроки часового пояса CRM можно задать по адресу:';
$_['retailcrm_base_settings'] = 'Настройки соединения';
$_['retailcrm_dict_settings'] = 'Настройки соответствия справочников';
$_['retailcrm_countries_settings'] = 'Настройка торговых зон';
$_['retailcrm_url'] = 'Адрес RetailCRM';
$_['retailcrm_apikey'] = 'Api ключ RetailCRM';

View file

@ -0,0 +1,194 @@
<?php
class ModelRetailcrmBaseHistory extends Model
{
/**
* Create order in OC
*
* @param array $order
*
* @return int $order_id
*/
public function addOrder($order)
{
$this->db->query("INSERT INTO `" . DB_PREFIX . "order` SET store_url = '" . $this->db->escape($order['store_url']) . "', store_id = '" . (int)$order['store_id'] . "', store_name = '" . $order['store_name'] . "', customer_id = '" . (int)$order['customer_id'] . "', customer_group_id = '" . (int)$order['customer_group_id'] . "', firstname = '" . $this->db->escape($order['firstname']) . "', lastname = '" . $this->db->escape($order['lastname']) . "', email = '" . $this->db->escape($order['email']) . "', telephone = '" . $this->db->escape($order['telephone']) . "', custom_field = '" . $this->db->escape(isset($order['custom_field']) ? json_encode($order['custom_field']) : '') . "', payment_firstname = '" . $this->db->escape($order['payment_firstname']) . "', payment_lastname = '" . $this->db->escape($order['payment_lastname']) . "', payment_address_1 = '" . $this->db->escape($order['payment_address_1']) . "', payment_city = '" . $this->db->escape($order['payment_city']) . "', payment_postcode = '" . $this->db->escape($order['payment_postcode']) . "', payment_country = '" . $this->db->escape($order['payment_country']) . "', payment_country_id = '" . (int)$order['payment_country_id'] . "', payment_zone = '" . $this->db->escape($order['payment_zone']) . "', payment_zone_id = '" . (int)$order['payment_zone_id'] . "', payment_method = '" . $this->db->escape($order['payment_method']) . "', payment_code = '" . $this->db->escape($order['payment_code']) . "', shipping_firstname = '" . $this->db->escape($order['shipping_firstname']) . "', shipping_lastname = '" . $this->db->escape($order['shipping_lastname']) . "', shipping_address_1 = '" . $this->db->escape($order['shipping_address_1']) . "', shipping_address_2 = '" . $this->db->escape($order['shipping_address_2']) . "', shipping_city = '" . $this->db->escape($order['shipping_city']) . "', shipping_postcode = '" . $this->db->escape($order['shipping_postcode']) . "', shipping_country = '" . $this->db->escape($order['shipping_country']) . "', shipping_country_id = '" . (int)$order['shipping_country_id'] . "', shipping_zone = '" . $this->db->escape($order['shipping_zone']) . "', shipping_zone_id = '" . (int)$order['shipping_zone_id'] . "', shipping_method = '" . $this->db->escape($order['shipping_method']) . "', shipping_code = '" . $this->db->escape($order['shipping_code']) . "', comment = '" . $this->db->escape($order['comment']) . "', total = '" . (float)$order['total'] . "', affiliate_id = '" . (int)$order['affiliate_id'] . "', language_id = '" . (int)$order['language_id'] . "', currency_id = '" . (int)$order['currency_id'] . "', currency_code = '" . $this->db->escape($order['currency_code']) . "', currency_value = '" . (float)$order['currency_value'] . "', order_status_id = '" . (int)$order['order_status_id'] . "', date_added = NOW(), date_modified = NOW()");
$order_id = $this->db->getLastId();
// Products
if (isset($order['order_product']) && $order['order_product']) {
$this->addOrderProducts($order_id, $order['order_product']);
}
// Totals
if (isset($order['order_total'])) {
$this->addOrderTotals($order_id, $order['order_total']);
}
return $order_id;
}
/**
* Edit order in OC
*
* @param int $order_id
* @param array $order
*
* @return void
*/
public function editOrder($order_id, $order)
{
$this->db->query("UPDATE `" . DB_PREFIX . "order` SET customer_id = '" . (int)$order['customer_id'] . "', customer_group_id = '" . (int)$order['customer_group_id'] . "', firstname = '" . $this->db->escape($order['firstname']) . "', lastname = '" . $this->db->escape($order['lastname']) . "', email = '" . $this->db->escape($order['email']) . "', telephone = '" . $this->db->escape($order['telephone']) . "', custom_field = '" . $this->db->escape(json_encode($order['custom_field'])) . "', payment_firstname = '" . $this->db->escape($order['payment_firstname']) . "', payment_lastname = '" . $this->db->escape($order['payment_lastname']) . "', payment_address_1 = '" . $this->db->escape($order['payment_address_1']) . "', payment_address_2 = '" . $this->db->escape($order['payment_address_2']) . "', payment_city = '" . $this->db->escape($order['payment_city']) . "', payment_postcode = '" . $this->db->escape($order['payment_postcode']) . "', payment_country = '" . $this->db->escape($order['payment_country']) . "', payment_country_id = '" . (int)$order['payment_country_id'] . "', payment_zone = '" . $this->db->escape($order['payment_zone']) . "', payment_zone_id = '" . (int)$order['payment_zone_id'] . "', payment_method = '" . $this->db->escape($order['payment_method']) . "', payment_code = '" . $this->db->escape($order['payment_code']) . "', shipping_firstname = '" . $this->db->escape($order['shipping_firstname']) . "', shipping_lastname = '" . $this->db->escape($order['shipping_lastname']) . "', shipping_address_1 = '" . $this->db->escape($order['shipping_address_1']) . "', shipping_address_2 = '" . $this->db->escape($order['shipping_address_2']) . "', shipping_city = '" . $this->db->escape($order['shipping_city']) . "', shipping_postcode = '" . $this->db->escape($order['shipping_postcode']) . "', shipping_country = '" . $this->db->escape($order['shipping_country']) . "', shipping_country_id = '" . (int)$order['shipping_country_id'] . "', shipping_zone = '" . $this->db->escape($order['shipping_zone']) . "', shipping_zone_id = '" . (int)$order['shipping_zone_id'] . "', shipping_method = '" . $this->db->escape($order['shipping_method']) . "', shipping_code = '" . $this->db->escape($order['shipping_code']) . "', comment = '" . $this->db->escape($order['comment']) . "', total = '" . (float)$order['total'] . "', order_status_id = '" . (int)$order['order_status_id'] . "', date_modified = NOW() WHERE order_id = '" . (int)$order_id . "'");
$this->db->query("DELETE FROM " . DB_PREFIX . "order_product WHERE order_id = '" . (int)$order_id . "'");
// Products
if (isset($order['order_product']) && $order['order_product']) {
$this->addOrderProducts($order_id, $order['order_product']);
}
// Totals
$this->db->query("DELETE FROM " . DB_PREFIX . "order_total WHERE order_id = '" . (int)$order_id . "'");
if (isset($order['order_total'])) {
$this->addOrderTotals($order_id, $order['order_total']);
}
}
/**
* Add order products
*
* @param int $order_id
* @param array $products
*
* @return void
*/
public function addOrderProducts($order_id, $products)
{
foreach ($products as $product) {
$this->db->query("INSERT INTO " . DB_PREFIX . "order_product SET order_id = '" . (int)$order_id . "', product_id = '" . (int)$product['product_id'] . "', name = '" . $this->db->escape($product['name']) . "', model = '" . $this->db->escape($product['model']) . "', quantity = '" . (int)$product['quantity'] . "', price = '" . (float)$product['price'] . "', total = '" . (float)$product['total'] . "'");
$order_product_id = $this->db->getLastId();
foreach ($product['option'] as $option) {
$this->db->query("INSERT INTO " . DB_PREFIX . "order_option SET order_id = '" . (int)$order_id . "', order_product_id = '" . (int)$order_product_id . "', product_option_id = '" . (int)$option['product_option_id'] . "', product_option_value_id = '" . (int)$option['product_option_value_id'] . "', name = '" . $this->db->escape($option['name']) . "', `value` = '" . $this->db->escape($option['value']) . "', `type` = '" . $this->db->escape($option['type']) . "'");
}
}
}
/**
* Add order totals
*
* @param int $order_id
* @param array $totals
*
* @return void
*/
public function addOrderTotals($order_id, $totals)
{
foreach ($totals as $total) {
$this->db->query("INSERT INTO " . DB_PREFIX . "order_total SET order_id = '" . (int)$order_id . "', code = '" . $this->db->escape($total['code']) . "', title = '" . $this->db->escape($total['title']) . "', `value` = '" . (float)$total['value'] . "', sort_order = '" . (int)$total['sort_order'] . "'");
}
}
/**
* Get total titles
*
* @return string $title
*/
protected function totalTitles()
{
if (version_compare(VERSION, '3.0', '<')) {
$title = '';
} else {
$title = 'total_';
}
return $title;
}
/**
* Get country by iso code 2
*
* @param string $isoCode
*
* @return array
*/
public function getCountryByIsoCode($isoCode)
{
$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "country` WHERE iso_code_2 = '" . $isoCode . "'");
return $query->row;
}
/**
* Get zone by name
*
* @param string $name
*
* @return array
*/
public function getZoneByName($name)
{
$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "zone` WHERE name = '" . $name . "'");
return $query->row;
}
/**
* Get currency
*
* @param string $code
* @param string $field (default = '')
*
* @return mixed array | string
*/
public function getCurrencyByCode($code, $field = '')
{
$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "currency` WHERE code = '" . $code . "'");
if (!$field) {
return $query->row;
}
return $query->row[$field];
}
/**
* Get language
*
* @param string $code
* @param string $field (default = '')
*
* @return mixed array | string
*/
public function getLanguageByCode($code, $field = '')
{
$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "language` WHERE code = '" . $code . "'");
if (!$field) {
return $query->row;
}
return $query->row[$field];
}
/**
* Get product option value
*
* @param int $option_value_id
* @param string $field
*
* @return mixed array | string
*/
public function getOptionValue($option_value_id, $field = '')
{
$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "option_value_description` WHERE option_value_id = '" . $option_value_id . "'");
if (!$field) {
return $query->row;
}
return $query->row[$field];
}
}

View file

@ -16,7 +16,7 @@ class ModelRetailcrmCustomer extends Model {
$this->retailcrmApi = new RetailcrmProxy(
$settings['retailcrm_url'],
$settings['retailcrm_apikey'],
DIR_SYSTEM . 'logs/retailcrm.log'
$this->setLogs()
);
$customersToCrm = array();
@ -48,4 +48,15 @@ class ModelRetailcrmCustomer extends Model {
return $customerToCrm;
}
private function setLogs()
{
if (version_compare(VERSION, '2.1', '>')) {
$logs = DIR_SYSTEM . 'storage/logs/retailcrm.log';
} else {
$logs = DIR_SYSTEM . 'logs/retailcrm.log';
}
return $logs;
}
}

View file

@ -1,6 +1,8 @@
<?php
class ModelRetailcrmHistory extends Model
require_once 'base_history.php';
class ModelRetailcrmHistory extends ModelRetailcrmBaseHistory
{
protected $createResult;
@ -41,7 +43,7 @@ class ModelRetailcrmHistory extends Model
$crm = new RetailcrmProxy(
$settings['retailcrm_url'],
$settings['retailcrm_apikey'],
DIR_SYSTEM . 'logs/retailcrm.log'
$this->setLogs()
);
$lastRun = !empty($history['retailcrm_history'])
@ -51,8 +53,11 @@ class ModelRetailcrmHistory extends Model
$packs = $crm->ordersHistory(array(
'startDate' => $lastRun->format('Y-m-d H:i:s'),
), 1, 100);
if(!$packs->isSuccessful() && count($packs->history) <= 0)
if (!$packs->isSuccessful() && count($packs->history) <= 0) {
return false;
}
$orders = RetailcrmHistoryHelper::assemblyOrder($packs->history);
$generatedAt = $packs['generatedAt'];
@ -64,7 +69,7 @@ class ModelRetailcrmHistory extends Model
$this->delivery = array_flip($settings['retailcrm_delivery']);
$this->payment = array_flip($settings['retailcrm_payment']);
$this->status = array_flip($settings['retailcrm_status']);
$this->settings = $settings;
$this->ocPayment = $this->model_retailcrm_references
->getOpercartPaymentTypes();
@ -78,7 +83,9 @@ class ModelRetailcrmHistory extends Model
foreach ($orders as $order) {
if (isset($order['deleted'])) continue;
if (isset($order['deleted'])) {
continue;
}
if (isset($order['externalId'])) {
$updatedOrders[] = $order['id'];
@ -117,52 +124,92 @@ class ModelRetailcrmHistory extends Model
protected function updateOrders($orders)
{
foreach ($orders as $order) {
$store = $this->config->get('config_store_id');
$ocOrder = $this->model_sale_order->getOrder($order['externalId']);
if (isset($order['paymentType'])) {
$payment['type'] = $order['paymentType'];
}
$data = array();
$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['comment'] = !empty($order['customerComment']) ? $order['customerComment'] : '';
$data['fax'] = '';
$mail = isset($order['email']) ? $order['email'] : $order['customer']['email'];
$phone = isset($order['phone']) ? $order['phone'] : '';
$data['payment_address'] = '0';
$data['payment_firstname'] = $order['firstName'];
$data['payment_lastname'] = (!empty($order['lastName'])) ? $order['lastName'] : ' ';
$data['payment_address_1'] = isset($order['customer']['address']) ? $order['customer']['address']['text'] : '';
$data['payment_address_2'] = '';
$data['payment_company'] = '';
$data['payment_company_id'] = '';
$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 = '';
if (is_int($order['delivery']['address']['region'])) {
$region = $order['delivery']['address']['region'];
if (!$phone) {
$data['telephone'] = $order['customer']['phones'] ? $order['customer']['phones'][0]['number'] : '80000000000';
} else {
foreach ($this->zones as $zone) {
if ($order['delivery']['address']['region'] == $zone['name']) {
$region = $zone['zone_id'];
}
$data['telephone'] = $phone;
}
if (isset($order['customer']['externalId']) && $order['customer']['externalId']) {
if (version_compare(VERSION, '2.1.0.0', '>=')) {
$customer = $this->model_customer_customer->getCustomer($order['customer']['externalId']);
} else {
$customer = $this->model_sale_customer->getCustomer($order['customer']['externalId']);
}
}
$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['customer'] = $order['firstName'];
$data['customer_id'] = (!empty($order['customer']['externalId'])) ? $order['customer']['externalId'] : 0;
$data['customer_group_id'] = (isset($customer)) ? $customer['customer_group_id'] : 1;
$data['firstname'] = $order['firstName'];
$data['lastname'] = isset($order['lastName']) ? $order['lastName'] : $order['firstName'];
$data['email'] = $mail ? $mail : uniqid() . '@retailrcm.ru';
$data['comment'] = !empty($order['customerComment']) ? $order['customerComment'] : '';
$data['payment_address'] = '0';
$data['payment_firstname'] = $order['firstName'];
$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_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['shipping_country_id'] = !empty($order['delivery']['address']['country']) ? $order['delivery']['address']['country'] : 0;
$data['shipping_zone_id'] = $region;
$shippingZone = '';
if (is_int($order['delivery']['address']['region'])) {
$shippingZone = $order['delivery']['address']['region'];
} else {
$shippingZone = $this->getZoneByName($order['delivery']['address']['region']);
if ($shippingZone) {
$shipping_zone_id = $shippingZone['zone_id'];
} else {
$shipping_zone_id = 0;
}
}
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['countryIso']) && !empty($order['countryIso'])) {
$shippingCountry = $this->getCountryByIsoCode($order['countryIso']);
}
if (isset($order['customer']['address']['countryIso']) && !empty($order['customer']['address']['countryIso'])) {
$paymentCountry = $this->getCountryByIsoCode($order['customer']['address']['countryIso']);
} else {
$paymentCountry = $this->getCountryByIsoCode($order['countryIso']);
}
$delivery = isset($order['delivery']['code']) ? $order['delivery']['code'] : null;
$data['payment_country_id'] = $paymentCountry ? $paymentCountry['country_id'] : $ocOrder['payment_country_id'];
$data['payment_country'] = isset($paymentCountry) ? $paymentCountry['name'] : $ocOrder['payment_country'];
$data['payment_zone_id'] = $payment_zone_id ? $payment_zone_id : $ocOrder['payment_zone_id'];
$data['payment_zone'] = isset($order['customer']['address']['region']) ? $order['customer']['address']['region'] : $ocOrder['payment_zone'];
$data['shipping_country_id'] = $shippingCountry ? $shippingCountry['country_id'] : $ocOrder['shipping_country_id'];
$data['shipping_country'] = $shippingCountry ? $shippingCountry['name'] : $ocOrder['shipping_country'];
$data['shipping_zone_id'] = $shipping_zone_id ? $shipping_zone_id : $ocOrder['shipping_zone_id'];
$data['shipping_zone'] = $shippingZone ? $shippingZone['name'] : $ocOrder['shipping_zone'];
$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'] = '';
@ -170,13 +217,44 @@ class ModelRetailcrmHistory extends Model
$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']];
if ($delivery !== null) {
if (isset($this->settings['retailcrm_delivery'][$ocOrder['shipping_code']])
&& isset($this->delivery[$delivery])
) {
$data['shipping'] = $this->delivery[$delivery];
$data['payment'] = $this->payment[$order['paymentType']];
$data['payment_method'] = $this->ocPayment[$data['payment']];
$data['payment_code'] = $this->payment[$order['paymentType']];
$shipping = explode('.', $data['shipping']);
$shippingModule = $shipping[0];
if (isset($this->ocDelivery[$shippingModule][$data['shipping']]['title'])) {
$data['shipping_method'] = $this->ocDelivery[$shippingModule][$data['shipping']]['title'];
} else {
$data['shipping_method'] =$this->ocDelivery[$shippingModule]['title'];
}
$data['shipping_code'] = $data['shipping'];
} elseif (!isset($this->settings['retailcrm_delivery'][$ocOrder['shipping_code']])
) {
$data['shipping_method'] = $ocOrder['shipping_method'];
$data['shipping_code'] = $ocOrder['shipping_code'];
}
} else {
if (!isset($this->settings[$ocOrder['shipping_code']])
|| !isset($this->delivery[$delivery])
) {
$data['shipping_method'] = $ocOrder['shipping_method'];
$data['shipping_code'] = $ocOrder['shipping_code'];
}
}
if (isset($payment)) {
$data['payment'] = $this->payment[$payment['type']];
$data['payment_method'] = isset($this->ocPayment[$data['payment']]) ? $this->ocPayment[$data['payment']] : $ocOrder['payment_method'];
$data['payment_code'] = isset($this->payment[$payment['type']]) ? $this->payment[$payment['type']] : $ocOrder['payment_code'];
} else {
$data['payment_method'] = $ocOrder['payment_method'];
$data['payment_code'] = $ocOrder['payment_code'];
}
// this data will not retrive from crm for now
$data['tax'] = '';
@ -196,15 +274,15 @@ class ModelRetailcrmHistory 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) {
if (mb_strpos($item['offer']['externalId'], '#') > 1) {
$offer = explode('#', $item['offer']['externalId']);
$productId = $offer[0];
$optionsFromCRM = explode('_', $offer[1]);
foreach($optionsFromCRM as $optionFromCRM) {
foreach ($optionsFromCRM as $optionFromCRM) {
$optionData = explode('-', $optionFromCRM);
$productOptionId = $optionData[0];
$optionValueId = $optionData[1];
@ -215,14 +293,27 @@ class ModelRetailcrmHistory extends Model
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'];
$options[] = array(
'product_option_id' => $productOptionId,
'product_option_value_id' => $productOptionValue['product_option_value_id'],
'value' => $this->getOptionValue($productOptionValue['option_value_id'], 'name'),
'type' => $productOption['type'],
'name' => $productOption['name'],
);
}
}
}
}
}
}
$product = $this->model_catalog_product->getProduct($productId);
$data['order_product'][] = array(
'name' => $product['name'],
'model' => $product['model'],
'price' => $item['initialPrice'],
'total' => (float)($item['initialPrice'] * $item['quantity']),
'product_id' => $productId,
'quantity' => $item['quantity'],
'option' => $options
@ -231,6 +322,7 @@ class ModelRetailcrmHistory extends Model
$deliveryCost = !empty($order['delivery']['cost']) ? $order['delivery']['cost'] : 0;
$data['total'] = $order['totalSumm'];
$data['order_total'] = array(
array(
'order_total_id' => '',
@ -243,10 +335,10 @@ class ModelRetailcrmHistory extends Model
array(
'order_total_id' => '',
'code' => 'shipping',
'title' => $this->ocDelivery[$data['shipping_code']],
'title' => $data['shipping_method'],
'value' => $deliveryCost,
'text' => $deliveryCost,
'sort_order' => $this->shippingSettings['shipping_sort_order']
'sort_order' => $this->shippingSettings[$this->totalTitle . 'shipping_sort_order']
),
array(
'order_total_id' => '',
@ -254,10 +346,21 @@ class ModelRetailcrmHistory 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']
)
);
if (isset($order['discount']) && $order['discount'] > 0) {
$orderTotals = $this->model_sale_order->getOrderTotals($order['externalId']);
foreach($orderTotals as $orderTotal) {
if ($orderTotal['code'] == 'coupon'
|| $orderTotal['code'] == 'reward'
) {
$data['order_total'][] = $orderTotal;
}
}
}
$data['fromApi'] = true;
if (array_key_exists($order['status'], $this->status)) {
@ -267,7 +370,8 @@ class ModelRetailcrmHistory extends Model
$data['order_status_id'] = $tmpOrder['order_status_id'];
}
$this->opencartApiClient->editOrder($order['externalId'], $data);
$this->editOrder($order['externalId'], $data);
$this->opencartApiClient->addHistory($order['externalId'], $data['order_status_id']);
}
}
@ -279,6 +383,10 @@ class ModelRetailcrmHistory extends Model
foreach ($orders as $order) {
$store = $this->config->get('config_store_id');
if (isset($order['paymentType'])) {
$payment['type'] = $order['paymentType'];
}
$customer_id = (!empty($order['customer']['externalId']))
? $order['customer']['externalId']
: 0;
@ -297,6 +405,8 @@ class ModelRetailcrmHistory extends Model
'newsletter' => 0,
'password' => 'tmppass',
'status' => 1,
'approved' => 1,
'safe' => 0,
'address' => array(
array(
'firstname' => $order['firstName'],
@ -339,19 +449,33 @@ class ModelRetailcrmHistory extends Model
$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_url'] = $this->config->get('config_url');
$data['currency_code'] = $this->config->get('config_currency');
$data['currency_value'] = $this->getCurrencyByCode($data['currency_code'], 'value');
$data['currency_id'] = $this->getCurrencyByCode($data['currency_code'], 'currency_id');
$data['language_id'] = $this->getLanguageByCode($this->config->get('config_language'), 'language_id');
$data['store_id'] = $store == null ? 0 : $store;
$data['store_name'] = $this->config->get('config_name');
$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'] = '';
@ -359,38 +483,77 @@ class ModelRetailcrmHistory 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']);
}
$delivery = isset($order['delivery']['code']) ? $order['delivery']['code'] : null;
$data['payment_country_id'] = $paymentCountry ? $paymentCountry['country_id'] : 0;
$data['payment_country'] = isset($paymentCountry) ? $paymentCountry['name'] : '';
$data['payment_zone_id'] = $payment_zone_id;
$data['payment_zone'] = isset($order['customer']['address']['region']) ? $order['customer']['address']['region'] : '';
$data['shipping_country_id'] = $shippingCountry ? $shippingCountry['country_id'] : 0;
$data['shipping_country'] = $shippingCountry ? $shippingCountry['name'] : '';
$data['shipping_zone_id'] = $shipping_zone_id;
$data['shipping_zone'] = $shippingZone ? $shippingZone['name'] : $data['payment_zone'];
$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'] = $delivery != null ? $this->delivery[$delivery] : '';
$data['shipping_code'] = $delivery != null ? $this->delivery[$delivery] : '';
$data['shipping'] = $this->delivery[$order['delivery']['code']];
$data['shipping_method'] = $this->ocDelivery[$data['shipping']];
$data['shipping_code'] = $this->delivery[$order['delivery']['code']];
$data['payment'] = $this->payment[$order['paymentType']];
$data['payment_method'] = $this->ocPayment[$data['payment']];
$data['payment_code'] = $this->payment[$order['paymentType']];
$shipping = explode('.', $data['shipping']);
$shippingModule = $shipping[0];
if (isset($this->ocDelivery[$shippingModule][$data['shipping']]['title'])) {
$data['shipping_method'] = $this->ocDelivery[$shippingModule][$data['shipping']]['title'];
} else {
$data['shipping_method'] =$this->ocDelivery[$shippingModule]['title'];
}
if (isset($payment)) {
$data['payment'] = $this->payment[$payment['type']];
$data['payment_method'] = $this->ocPayment[$data['payment']];
$data['payment_code'] = $this->payment[$payment['type']];
} else {
$data['payment'] = 'free_checkout';
$data['payment_method'] = $this->ocPayment[$data['payment']];
$data['payment_code'] = 'free_checkout';
}
// this data will not retrive from crm for now
$data['tax'] = '';
@ -399,7 +562,7 @@ class ModelRetailcrmHistory extends Model
$data['product_id'] = '';
$data['reward'] = '';
$data['affiliate'] = '';
$data['affiliate_id'] = '';
$data['affiliate_id'] = 0;
$data['payment_tax_id'] = '';
$data['order_product_id'] = '';
$data['payment_company'] = '';
@ -410,24 +573,55 @@ class ModelRetailcrmHistory 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();
// this data will not retrive from crm
'order_product_id' => '',
'tax' => 0,
'reward' => 0
if(mb_strpos($item['offer']['externalId'], '#') > 1) {
$offer = explode('#', $item['offer']['externalId']);
$productId = $offer[0];
$optionsFromCRM = explode('_', $offer[1]);
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[] = array(
'product_option_id' => $productOptionId,
'product_option_value_id' => $productOptionValue['product_option_value_id'],
'value' => $this->getOptionValue($productOptionValue['option_value_id'], 'name'),
'type' => $productOption['type'],
'name' => $productOption['name'],
);
}
}
}
}
}
}
$product = $this->model_catalog_product->getProduct($productId);
$data['order_product'][] = array(
'name' => $product['name'],
'model' => $product['model'],
'price' => $item['initialPrice'],
'total' => (float)($item['initialPrice'] * $item['quantity']),
'product_id' => $productId,
'quantity' => $item['quantity'],
'option' => $options
);
}
$deliveryCost = !empty($order['delivery']['cost']) ? $order['delivery']['cost'] : 0;
$data['total'] = $order['totalSumm'];
$data['order_total'] = array(
array(
'order_total_id' => '',
@ -440,10 +634,10 @@ class ModelRetailcrmHistory extends Model
array(
'order_total_id' => '',
'code' => 'shipping',
'title' => $this->ocDelivery[$data['shipping_code']],
'title' => $data['shipping_method'],
'value' => $deliveryCost,
'text' => $deliveryCost,
'sort_order' => $this->shippingSettings['shipping_sort_order']
'sort_order' => $this->shippingSettings[$this->totalTitle . 'shipping_sort_order']
),
array(
'order_total_id' => '',
@ -451,20 +645,29 @@ class ModelRetailcrmHistory 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->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);
}
private function setLogs()
{
if (version_compare(VERSION, '2.1', '>')) {
$logs = DIR_SYSTEM . 'storage/logs/retailcrm.log';
} else {
$logs = DIR_SYSTEM . 'logs/retailcrm.log';
}
return $logs;
}
}

View file

@ -121,13 +121,20 @@ class ModelRetailcrmIcml extends Model
// Если первая итерация
if(empty($offers)) {
foreach($requiredOption['product_option_value'] as $optionValue) {
$offers[$requiredOption['product_option_id'].':'.$requiredOption['option_id'].'-'.$optionValue['option_value_id']] = (float)$optionValue['price'];
$offers[$requiredOption['product_option_id'].':'.$requiredOption['option_id'].'-'.$optionValue['option_value_id']] = array(
'price' => (float)$optionValue['price'],
'qty' => $optionValue['quantity']
);
}
} else {
foreach($offers as $optionKey => $optionCost) {
foreach($offers as $optionKey => $optionAttr) {
unset($offers[$optionKey]); // Работая в контексте обязательных опций не забываем удалять прошлые обязательные опции, т.к. они должны быть скомбинированы с другими обязательными опциями
foreach($requiredOption['product_option_value'] as $optionValue) {
$offers[$optionKey.'_'.$requiredOption['product_option_id'].':'.$requiredOption['option_id'].'-'.$optionValue['option_value_id']] = $optionCost + (float)$optionValue['price'];
$offers[$optionKey.'_'.$requiredOption['product_option_id'].':'.$requiredOption['option_id'].'-'.$optionValue['option_value_id']] = array(
'price' => $optionAttr['price'] + (float)$optionValue['price'],
'qty' => ($optionAttr['qty'] > $optionValue['quantity']) ?
$optionValue['quantity'] : $optionAttr['qty']
);
}
}
}
@ -138,21 +145,28 @@ class ModelRetailcrmIcml extends Model
if(empty($offers)) {
$offers['0:0-0'] = 0; // В случае работы с необязательными опциями мы должны учитывать товарное предложение без опций, поэтому создадим "пустую" опцию
foreach($notRequiredOption['product_option_value'] as $optionValue) {
$offers[$notRequiredOption['product_option_id'].':'.$notRequiredOption['option_id'].'-'.$optionValue['option_value_id']] = (float)$optionValue['price'];
$offers[$notRequiredOption['product_option_id'].':'.$notRequiredOption['option_id'].'-'.$optionValue['option_value_id']] = array(
'price' => (float)$optionValue['price'],
'qty' => $optionValue['quantity']
);
}
} else {
foreach($offers as $optionKey => $optionCost) {
foreach($offers as $optionKey => $optionAttr) {
foreach($notRequiredOption['product_option_value'] as $optionValue) {
$offers[$optionKey.'_'.$notRequiredOption['product_option_id'].':'.$notRequiredOption['option_id'].'-'.$optionValue['option_value_id']] = $optionCost + (float)$optionValue['price'];
$offers[$optionKey.'_'.$notRequiredOption['product_option_id'].':'.$notRequiredOption['option_id'].'-'.$optionValue['option_value_id']] = array(
'price' => $optionAttr['price'] + (float)$optionValue['price'],
'qty' => ($optionAttr['qty'] > $optionValue['quantity']) ?
$optionValue['quantity'] : $optionAttr['qty']
);
}
}
}
}
if(empty($offers)) {
$offers = array('0:0-0' => '0');
$offers = array('0:0-0' => array('price' => '0', 'qty' => '0'));
}
foreach($offers as $optionsString => $optionsTotalCost) {
foreach($offers as $optionsString => $optionsValues) {
$optionsString = explode('_', $optionsString);
$options = array();
foreach($optionsString as $optionString) {
@ -174,12 +188,17 @@ class ModelRetailcrmIcml extends Model
}
$offerId = implode('_', $offerId);
$e = $this->eOffers->appendChild($this->dd->createElement('offer'));
if(!empty($offerId))
if(!empty($offerId)) {
$e->setAttribute('id', $product['product_id'].'#'.$offerId);
else
$e->setAttribute('productId', $product['product_id']);
$e->setAttribute('quantity', $optionsValues['qty']);
}
else {
$e->setAttribute('id', $product['product_id']);
$e->setAttribute('productId', $product['product_id']);
$e->setAttribute('quantity', $product['quantity']);
$e->setAttribute('productId', $product['product_id']);
$e->setAttribute('quantity', $product['quantity']);
}
/**
* Offer activity
*/
@ -220,7 +239,7 @@ class ModelRetailcrmIcml extends Model
->appendChild($this->dd->createTextNode($product['name']));
}
$e->appendChild($this->dd->createElement('price'))
->appendChild($this->dd->createTextNode($product['price'] + $optionsTotalCost));
->appendChild($this->dd->createTextNode($product['price'] + $optionsValues['price']));
/**
* Vendor
*/

View file

@ -7,6 +7,19 @@ class ModelRetailcrmOrder extends Model {
$this->load->model('setting/setting');
$this->settings = $this->model_setting_setting->getSetting('retailcrm');
if(empty($orders))
return false;
if(empty($this->settings['retailcrm_url']) || empty($this->settings['retailcrm_apikey']))
return false;
require_once DIR_SYSTEM . 'library/retailcrm/bootstrap.php';
$this->retailcrmApi = new RetailcrmProxy(
$this->settings['retailcrm_url'],
$this->settings['retailcrm_apikey'],
$this->setLogs()
);
$ordersToCrm = array();
foreach($orders as $order) {
@ -104,13 +117,30 @@ class ModelRetailcrmOrder extends Model {
}
$order['items'][] = array(
'productId' => !empty($offerId) ? $product['product_id'].'#'.$offerId : $product['product_id'],
'offer' => array(
'externalId' => !empty($offerId) ? $product['product_id'].'#'.$offerId : $product['product_id']
),
'productName' => $product['name'],
'initialPrice' => $product['price'],
'quantity' => $product['quantity'],
);
}
if (isset($order_data['order_status_id']) && $order_data['order_status_id'] > 0) {
$order['status'] = $this->settings['retailcrm_status'][$order_data['order_status_id']];
}
return $order;
}
private function setLogs()
{
if (version_compare(VERSION, '2.1', '>')) {
$logs = DIR_SYSTEM . 'storage/logs/retailcrm.log';
} else {
$logs = DIR_SYSTEM . 'logs/retailcrm.log';
}
return $logs;
}
}

View file

@ -5,9 +5,20 @@ require_once DIR_SYSTEM . 'library/retailcrm/bootstrap.php';
class ModelRetailcrmReferences extends Model
{
protected $retailcrm;
private $opencartApiClient;
public function getOpercartDeliveryTypes()
{
$this->load->model('user/api');
$this->opencartApiClient = new OpencartApiClient($this->registry);
return $this->opencartApiClient->getDeliveryTypes();
}
public function getDeliveryTypes()
{
$this->load->model('setting/store');
return array(
'opencart' => $this->getOpercartDeliveryTypes(),
'retailcrm' => $this->getApiDeliveryTypes()
@ -30,28 +41,6 @@ class ModelRetailcrmReferences extends Model
);
}
public function getOpercartDeliveryTypes()
{
$deliveryMethods = array();
$files = glob(DIR_APPLICATION . 'controller/shipping/*.php');
if ($files) {
foreach ($files as $file) {
$extension = basename($file, '.php');
$this->load->language('shipping/' . $extension);
if ($this->config->get($extension . '_status')) {
$deliveryMethods[$extension.'.'.$extension] = strip_tags(
$this->language->get('heading_title')
);
}
}
}
return $deliveryMethods;
}
public function getOpercartOrderStatuses()
{
$this->load->model('localisation/order_status');
@ -91,7 +80,7 @@ class ModelRetailcrmReferences extends Model
$this->retailcrm = new RetailcrmProxy(
$settings['retailcrm_url'],
$settings['retailcrm_apikey'],
DIR_SYSTEM . 'logs/retailcrm.log'
$this->setLogs()
);
$response = $this->retailcrm->deliveryTypesList();
@ -109,7 +98,7 @@ class ModelRetailcrmReferences extends Model
$this->retailcrm = new RetailcrmProxy(
$settings['retailcrm_url'],
$settings['retailcrm_apikey'],
DIR_SYSTEM . 'logs/retailcrm.log'
$this->setLogs()
);
$response = $this->retailcrm->statusesList();
@ -127,7 +116,7 @@ class ModelRetailcrmReferences extends Model
$this->retailcrm = new RetailcrmProxy(
$settings['retailcrm_url'],
$settings['retailcrm_apikey'],
DIR_SYSTEM . 'logs/retailcrm.log'
$this->setLogs()
);
$response = $this->retailcrm->paymentTypesList();
@ -135,4 +124,15 @@ class ModelRetailcrmReferences extends Model
return ($response === false) ? array() : $response->paymentTypes;
}
}
private function setLogs()
{
if (version_compare(VERSION, '2.1', '>')) {
$logs = DIR_SYSTEM . 'storage/logs/retailcrm.log';
} else {
$logs = DIR_SYSTEM . 'logs/retailcrm.log';
}
return $logs;
}
}

View file

@ -1,2 +1,3 @@
.retailcrm_unit {margin-bottom: 10px;}
.retailcrm_unit input {width: 30%;}
.retailcrm_unit select {max-width: 500px;}

View file

@ -45,7 +45,19 @@
<label for="retailcrm_apikey"><?php echo $retailcrm_apikey; ?></label><br>
<input id="retailcrm_apikey" type="text" name="retailcrm_apikey" value="<?php if (isset($saved_settings['retailcrm_apikey'])): echo $saved_settings['retailcrm_apikey']; endif;?>">
</div>
<h3><?php echo $retailcrm_countries_settings; ?></h3>
<div class="retailcrm_unit">
<div class="well well-sm" style="height: 150px; overflow: auto; width: 30%;">
<?php foreach($countries as $country) : ?>
<div class="checkbox">
<label>
<input type="checkbox" name="<?php echo 'retailcrm_country[]'; ?>" value="<?php echo $country['country_id']; ?>" <?php if(isset($saved_settings['retailcrm_country']) && in_array($country['country_id'], $saved_settings['retailcrm_country'])): echo 'checked'; endif;?>>
<?php echo $country['name']; ?>
</label>
</div>
<?php endforeach; ?>
</div>
</div>
<?php if (isset($saved_settings['retailcrm_apikey']) && $saved_settings['retailcrm_apikey'] != '' && isset($saved_settings['retailcrm_url']) && $saved_settings['retailcrm_url'] != ''): ?>
<?php if (!empty($retailcrm_errors)) : ?>
@ -56,17 +68,21 @@
<h3><?php echo $retailcrm_dict_settings; ?></h3>
<h4><?php echo $retailcrm_dict_delivery; ?></h4>
<?php foreach ($delivery['opencart'] as $key => $value): ?>
<div class="retailcrm_unit">
<select id="retailcrm_delivery_<?php echo $key; ?>" name="retailcrm_delivery[<?php echo $key; ?>]" >
<?php foreach ($delivery['retailcrm'] as $k => $v): ?>
<option value="<?php echo $v['code'];?>" <?php if(isset($saved_settings['retailcrm_delivery'][$key]) && $v['code'] == $saved_settings['retailcrm_delivery'][$key]):?>selected="selected"<?php endif;?>>
<?php echo $v['name'];?>
</option>
<?php endforeach; ?>
</select>
<label for="retailcrm_delivery_<?php echo $key; ?>"><?php echo $value; ?></label>
</div>
<?php foreach($delivery['opencart'] as $value): ?>
<div class="pm"><?php echo $value['title'].':'; ?></div>
<?php unset($value['title']); ?>
<?php foreach ($value as $key => $val): ?>
<div class="retailcrm_unit">
<select id="retailcrm_delivery_<?php echo $val['code']; ?>" name="retailcrm_delivery[<?php echo $val['code']; ?>]" >
<?php foreach ($delivery['retailcrm'] as $k => $v): ?>
<option value="<?php echo $v['code'];?>" <?php if(isset($saved_settings['retailcrm_delivery'][$key]) && $v['code'] == $saved_settings['retailcrm_delivery'][$key]):?>selected="selected"<?php endif;?>>
<?php echo $v['name'];?>
</option>
<?php endforeach; ?>
</select>
<label for="retailcrm_pm_<?php echo $val['code']; ?>"><?php echo $val['title']; ?></label>
</div>
<?php endforeach; ?>
<?php endforeach; ?>
<h4><?php echo $retailcrm_dict_status; ?></h4>

View file

@ -0,0 +1,170 @@
<?php
class ControllerApiRetailcrm extends Controller
{
public function getDeliveryTypes()
{
$api = $this->auth();
if (isset($api['error'])) {
$response = $api;
} else {
$this->load->model('localisation/country');
$this->load->model('setting/setting');
$countries = $this->model_setting_setting->getSetting('retailcrm')['retailcrm_country'];
$response = array();
foreach ($countries as $country) {
$response = array_merge($response, $this->getDeliveryTypesByZones($country));
}
}
if (isset($this->request->server['HTTP_ORIGIN'])) {
$this->response->addHeader('Access-Control-Allow-Origin: ' . $this->request->server['HTTP_ORIGIN']);
$this->response->addHeader('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
$this->response->addHeader('Access-Control-Max-Age: 1000');
$this->response->addHeader('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($response));
}
public function addOrderHistory()
{
$api = $this->auth();
if (isset($api['error'])) {
$response = $api;
} elseif (!isset($this->request->post['order_id']) || !isset($this->request->post['order_status_id'])) {
$response = array('error' => 'Not found data');
} else {
$this->load->model('checkout/order');
$this->model_checkout_order->addOrderHistory($this->request->post['order_id'], $this->request->post['order_status_id']);
$response = array('success' => true);
}
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($response));
}
protected function getDeliveryTypesByZones($country_id)
{
$this->load->model('extension/extension');
$this->load->model('localisation/zone');
$this->load->model('localisation/country');
$shippingModules = $this->model_extension_extension->getExtensions('shipping');
$zones = $this->model_localisation_zone->getZonesByCountryId($country_id);
$country = $this->model_localisation_country->getCountry($country_id);
$quote_data = array();
foreach ($zones as $zone) {
$address = array(
'country_id' => $country_id,
'zone_id' => $zone['zone_id'],
'iso_code_2' => $country['iso_code_2'],
'iso_code_3' => $country['iso_code_3'],
'zone_code' => $zone['code'],
'postcode' => '',
'city' => ''
);
foreach ($shippingModules as $shippingModule) {
$this->load->model('shipping/' . $shippingModule['code']);
if ($this->config->get($shippingModule['code'] . '_status')) {
if ($shippingModule['code'] == 'free') {
$free_total = $this->config->get('free_total');
if ($free_total > 0) {
$this->config->set('free_total', 0);
}
}
if($this->{'model_shipping_' . $shippingModule['code']}->getQuote($address)) {
$quote_data[] = $this->{'model_shipping_' . $shippingModule['code']}->getQuote($address);
} else {
$this->load->language('shipping/' . $shippingModule['code']);
$quote_data[] = array(
'code' => $shippingModule['code'],
'title' => $this->language->get('text_title'),
'quote' => array(
array(
'code' => $shippingModule['code'],
'title' => $this->language->get('text_title')
)
)
);
}
}
}
}
$deliveryTypes = array();
foreach ($quote_data as $shipping) {
foreach ($shipping['quote'] as $shippingMethod) {
$deliveryTypes[$shipping['code']]['title'] = $shipping['title'];
$deliveryTypes[$shipping['code']][$shippingMethod['code']] = $shippingMethod;
}
}
return $deliveryTypes;
}
private function auth()
{
if (version_compare(VERSION, '2.1.0', '>=')) {
if (!isset($this->request->get['key'])
|| !$this->request->get['key']
) {
return array('error' => 'Not found api key');
}
if (isset($this->request->get['key'])
&& !empty($this->request->get['key'])
) {
$this->load->model('account/api');
$api = $this->model_account_api->getApiByKey($this->request->get['key']);
if (!empty($api)) {
return $api;
}
return array('error' => 'Invalid api key');
}
} else {
if (!isset($this->request->get['username'])
|| !$this->request->get['username']
|| !isset($this->request->get['password'])
|| !$this->request->get['password']
) {
return array('error' => 'Not found api user');
}
if (isset($this->request->get['username'])
&& !empty($this->request->get['username'])
&& isset($this->request->get['password'])
&& !empty($this->request->get['password'])
) {
$this->load->model('account/api');
$api = $this->model_account_api->login($this->request->get['username'], $this->request->get['password']);
if (!empty($api)) {
return $api;
}
return array('error' => 'Invalid api user');
}
}
}
}

View file

@ -38,6 +38,8 @@ class ControllerModuleRetailcrm extends Controller
$data['products'][$key]['option'] = $productOptions;
}
$data['totals'] = $this->model_account_order->getOrderTotals($order_id);
if (!isset($data['fromApi'])) {
$this->load->model('setting/setting');
$status = $this->model_setting_setting->getSetting('retailcrm');
@ -45,11 +47,6 @@ class ControllerModuleRetailcrm extends Controller
$data['order_status'] = $status['retailcrm_status'][$data['order_status_id']];
}
$data['totals'][] = array(
'code' => 'shipping',
'value' => $this->session->data['shipping_method']['cost']
);
$this->load->model('retailcrm/order');
$this->model_retailcrm_order->sendToCrm($data, $data['order_id']);
}
@ -77,6 +74,8 @@ class ControllerModuleRetailcrm extends Controller
$data['products'][$key]['option'] = $productOptions;
}
$data['totals'] = $this->model_account_order->getOrderTotals($order_id);
if (!isset($data['fromApi'])) {
$this->load->model('setting/setting');
$status = $this->model_setting_setting->getSetting('retailcrm');

View file

@ -15,7 +15,7 @@ class ModelRetailcrmCustomer extends Model {
$this->retailcrmApi = new RetailcrmProxy(
$settings['retailcrm_url'],
$settings['retailcrm_apikey'],
DIR_SYSTEM . 'logs/retailcrm.log'
$this->setLogs()
);
$customerToCrm = $this->process($customer);
@ -39,4 +39,15 @@ class ModelRetailcrmCustomer extends Model {
return $customerToCrm;
}
private function setLogs()
{
if (version_compare(VERSION, '2.1', '>')) {
$logs = DIR_SYSTEM . 'storage/logs/retailcrm.log';
} else {
$logs = DIR_SYSTEM . 'logs/retailcrm.log';
}
return $logs;
}
}

View file

@ -17,7 +17,7 @@ class ModelRetailcrmOrder extends Model {
$this->retailcrm = new RetailcrmProxy(
$settings['retailcrm_url'],
$settings['retailcrm_apikey'],
DIR_SYSTEM . 'logs/retailcrm.log'
$this->setLogs()
);
$order = array();
@ -50,6 +50,7 @@ class ModelRetailcrmOrder extends Model {
}
$deliveryCost = 0;
$couponTotal = 0;
$altTotals = isset($order_data['order_total']) ? $order_data['order_total'] : "";
$orderTotals = isset($order_data['totals']) ? $order_data['totals'] : $altTotals ;
@ -58,6 +59,12 @@ class ModelRetailcrmOrder extends Model {
if ($totals['code'] == 'shipping') {
$deliveryCost = $totals['value'];
}
if ($totals['code'] == 'coupon') {
$couponTotal += abs($totals['value']);
}
if ($totals['code'] == 'reward') {
$couponTotal += abs($totals['value']);
}
}
}
@ -72,6 +79,10 @@ class ModelRetailcrmOrder extends Model {
$order_data['shipping_iso_code_2'] = $shipping_country['iso_code_2'];
}
if (isset($couponTotal) && $couponTotal > 0) {
$order['discount'] = $couponTotal;
}
$delivery_code = $order_data['shipping_code'];
$order['delivery'] = array(
'code' => !empty($delivery_code) ? $settings['retailcrm_delivery'][$delivery_code] : '',
@ -157,7 +168,7 @@ class ModelRetailcrmOrder extends Model {
$this->retailcrm = new RetailcrmProxy(
$settings['retailcrm_url'],
$settings['retailcrm_apikey'],
DIR_SYSTEM . 'logs/retailcrm.log'
$this->setLogs()
);
$order = array();
@ -176,12 +187,19 @@ class ModelRetailcrmOrder extends Model {
}
$deliveryCost = 0;
$couponTotal = 0;
$orderTotals = isset($order_data['totals']) ? $order_data['totals'] : $order_data['order_total'] ;
foreach ($orderTotals as $totals) {
if ($totals['code'] == 'shipping') {
$deliveryCost = $totals['value'];
}
if ($totals['code'] == 'coupon') {
$couponTotal += abs($totals['value']);
}
if ($totals['code'] == 'reward') {
$couponTotal += abs($totals['value']);
}
}
$order['createdAt'] = $order_data['date_added'];
@ -189,6 +207,10 @@ class ModelRetailcrmOrder extends Model {
$country = (isset($order_data['shipping_country'])) ? $order_data['shipping_country'] : '' ;
if (isset($couponTotal) && $couponTotal > 0) {
$order['discount'] = $couponTotal;
}
$order['delivery'] = array(
'code' => !empty($delivery_code) ? $settings['retailcrm_delivery'][$delivery_code] : '',
'cost' => $deliveryCost,
@ -257,4 +279,15 @@ class ModelRetailcrmOrder extends Model {
$this->retailcrm->ordersEdit($order);
}
}
private function setLogs()
{
if (version_compare(VERSION, '2.1', '>')) {
$logs = DIR_SYSTEM . 'storage/logs/retailcrm.log';
} else {
$logs = DIR_SYSTEM . 'logs/retailcrm.log';
}
return $logs;
}
}

View file

@ -40,11 +40,13 @@ class OpencartApiClient {
return false;
}
public function request($method, $getParams, $postParams) {
private function request($method, $getParams, $postParams) {
$opencartStoreInfo = $this->model_setting_store->getStore($this->opencartStoreId);
if(version_compare(VERSION, '2.1.0', '>=') && !empty($this->apiToken)) {
$getParams['token'] = $this->apiToken;
if (version_compare(VERSION, '2.1.0', '>=') && !empty($this->apiToken)) {
$getParams['key'] = $this->apiToken;
} elseif (is_array($this->apiToken) && isset($this->apiToken['username'])) {
$getParams = $this->apiToken;
}
$postParams['fromApi'] = true;
@ -89,7 +91,7 @@ class OpencartApiClient {
$api = array();
foreach ($apiUsers as $apiUser) {
if($apiUser['status'] == 1) {
if(version_compare(VERSION, '2.1.0', '>=')) {
if (version_compare(VERSION, '2.1.0', '>=')) {
$api = array(
'api_id' => $apiUser['api_id'],
'key' => $apiUser['key']
@ -106,186 +108,34 @@ class OpencartApiClient {
}
}
if(!isset($api['api_id']))
if(!isset($api['api_id'])) {
return false;
if(version_compare(VERSION, '2.1.0', '>=')) {
$alreadyBinded = false;
$innerIp = $this->getInnerIpAddr();
$apiIps = $this->model_user_api->getApiIps($api['api_id']);
foreach($apiIps as $apiIp) {
if($apiIp['ip'] == $innerIp)
$alreadyBinded = true;
}
if(!$alreadyBinded) {
$this->model_user_api->addApiIp($api['api_id'], $innerIp);
}
}
$apiAnswer = $this->request('login', array(), $apiUser);
if(version_compare(VERSION, '2.1.0', '>=')) {
$this->apiToken = $apiAnswer['token'];
if (isset($api['key'])) {
$this->apiToken = $api['key'];
} elseif (isset($api['username'])) {
$this->apiToken = $api;
} else {
$this->apiToken = false;
}
return $apiAnswer;
}
public function editOrder($order_id, $data) {
$data['telephone'] = trim($data['telephone']);
$customer = array(
'currency' => isset($data['currency']) ? $data['currency'] : '',
'customer' => $data['customer'],
'customer_id' => $data['customer_id'],
'customer_group_id' => $data['customer_group_id'],
'firstname' => $data['firstname'],
'lastname' => $data['lastname'],
'email' => $data['email'],
'telephone' => !empty($data['telephone']) ? $data['telephone'] : '0000',
'fax' => $data['fax'],
);
$this->request('customer', array(), $customer);
$products = array();
foreach ($data['order_product'] as $order_product) {
$products[] = array(
'product_id' => $order_product['product_id'],
'quantity' => $order_product['quantity'],
'option' => $order_product['option']
);
}
$this->request('cart/add', array(), array('product' => $products));
$payment_address = array(
'payment_address' => $data['payment_address'],
'firstname' => $data['payment_firstname'],
'lastname' => $data['payment_lastname'],
'company' => $data['payment_company'],
'address_1'=> $data['payment_address_1'],
'address_2' => $data['payment_address_2'],
'city' => !empty($data['payment_city']) ? $data['payment_city'] : 'none',
'postcode' => $data['payment_postcode'],
'country_id' => $data['payment_country_id'],
'zone_id' => !empty($data['payment_zone_id']) ? $data['payment_zone_id'] : 0,
);
$this->request('payment/address', array(), $payment_address);
$this->request('payment/methods', array(), array());
$payment_method = array(
'payment_method' => $data['payment_code']
);
$this->request('payment/method', array(), $payment_method);
$shipping_address = array(
'shipping_address' => $data['shipping_address'],
'firstname' => $data['shipping_firstname'],
'lastname' => $data['shipping_lastname'],
'company' => $data['shipping_company'],
'address_1' => $data['shipping_address_1'],
'address_2' => $data['shipping_address_2'],
'city' => !empty($data['shipping_city']) ? $data['shipping_city'] : 'none',
'postcode' => $data['shipping_postcode'],
'country_id' => $data['shipping_country_id'],
'zone_id' => !empty($data['shipping_zone_id']) ? $data['shipping_zone_id'] : 0,
);
$this->request('shipping/address', array(), $shipping_address);
$this->request('shipping/methods', array(), array());
$shipping_method = array(
'shipping_method' => $data['shipping_code']
);
$this->request('shipping/method', array(), $shipping_method);
$order = array(
'shipping_method' => $data['shipping_code'],
'payment_method' => $data['payment_code'],
'order_status_id' => $data['order_status_id'],
'comment' => $data['comment'],
'affiliate_id' => $data['affiliate_id'],
);
$this->request('order/edit', array('order_id' => $order_id), $order);
/**
* Add history order
*
* @param int $order_id
* @param int $order_status_id
*
* @return void
*/
public function addHistory($order_id, $order_status_id)
{
$this->request('retailcrm/addOrderHistory', array(), array('order_id' => $order_id, 'order_status_id' => $order_status_id));
}
public function addOrder($data) {
$currency = $this->getCookieValue('currency');
if($currency) {
$a = $this->request('currency', array(), array('currency' => $currency));
}
$customer = array(
'store_id' => $data['store_id'],
'currency' => $currency != false ? $currency : '',
'customer' => $data['customer'],
'customer_id' => $data['customer_id'],
'customer_group_id' => $data['customer_group_id'],
'firstname' => $data['firstname'],
'lastname' => $data['lastname'],
'email' => $data['email'],
'telephone' => $data['telephone'],
'fax' => $data['fax'],
);
$this->request('customer', array(), $customer);
$products = array();
foreach($data['order_product'] as $product) {
$product = array(
'product_id' => $product['product_id'],
'quantity' => $product['quantity'],
);
$products[] = $product;
}
$this->request('cart/add', array(), array('product' => $products));
$payment_address = array(
'payment_address' => $data['payment_address'],
'firstname' => $data['payment_firstname'],
'lastname' => $data['payment_lastname'],
'company' => $data['payment_company'],
'address_1' => $data['payment_address_1'],
'address_2' => $data['payment_address_2'],
'city' => $data['payment_city'],
'postcode' => $data['payment_postcode'],
'country_id' => $data['payment_country_id'],
'zone_id' => $data['payment_zone_id'],
);
$this->request('payment/address', array(), $payment_address);
$shipping_address = array(
'shipping_address' => $data['shipping_address'],
'firstname' => $data['shipping_firstname'],
'lastname' => $data['shipping_lastname'],
'company' => $data['shipping_company'],
'address_1' => $data['shipping_address_1'],
'address_2' => $data['shipping_address_2'],
'city' => $data['shipping_city'],
'postcode' => $data['shipping_postcode'],
'country_id' => $data['shipping_country_id'],
'zone_id' => !empty($data['shipping_zone_id']) ? $data['shipping_zone_id'] : 0,
);
$this->request('shipping/address', array(), $shipping_address);
$this->request('shipping/methods', array(), array());
$shipping_method = array(
'shipping_method' => $data['shipping_code']
);
$this->request('shipping/method', array(), $shipping_method);
$this->request('payment/methods', array(), array());
$payment_method = array(
'payment_method' => $data['payment_code']
);
$this->request('payment/method', array(), $payment_method);
$order = array(
'shipping_method' => $data['shipping_code'],
'payment_method' => $data['payment_code'],
'order_status_id' => $data['order_status_id'],
'comment' => $data['comment'],
'affiliate_id' => $data['affiliate_id'],
);
$this->request('order/add', array(), $order);
public function getDeliveryTypes() {
return $this->request('retailcrm/getDeliveryTypes', array(), array());
}
private function getInnerIpAddr() {

View file

@ -10,10 +10,13 @@ class RetailcrmHistoryHelper {
}
}
$orders = array();
foreach ($orderHistory as $change) {
$change['order'] = self::removeEmpty($change['order']);
if($change['order']['items']) {
if(isset($change['order']['items']) && $change['order']['items']) {
$items = array();
foreach($change['order']['items'] as $item) {
if(isset($change['created'])) {
$item['create'] = 1;
@ -23,55 +26,61 @@ class RetailcrmHistoryHelper {
$change['order']['items'] = $items;
}
if($change['order']['contragent']['contragentType']) {
if (isset($change['order']['contragent']['contragentType'])
&& $change['order']['contragent']['contragentType']
) {
$change['order']['contragentType'] = $change['order']['contragent']['contragentType'];
unset($change['order']['contragent']);
}
if($orders[$change['order']['id']]) {
if (isset($orders[$change['order']['id']]) && $orders[$change['order']['id']]) {
$orders[$change['order']['id']] = array_merge($orders[$change['order']['id']], $change['order']);
} else {
$orders[$change['order']['id']] = $change['order'];
}
if($change['item']) {
if($orders[$change['order']['id']]['items'][$change['item']['id']]) {
if (isset($change['item']) && $change['item']) {
if (isset($orders[$change['order']['id']]['items'][$change['item']['id']])
&& $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'];
}
if(empty($change['oldValue']) && $change['field'] == 'order_product') {
if (empty($change['oldValue']) && $change['field'] == 'order_product') {
$orders[$change['order']['id']]['items'][$change['item']['id']]['create'] = true;
}
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;
}
if(!$orders[$change['order']['id']]['items'][$change['item']['id']]['create'] && $fields['item'][$change['field']]) {
if (!$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 {
if($fields['delivery'][$change['field']] == 'service') {
if (isset($fields['delivery'][$change['field']])
&& $fields['delivery'][$change['field']] == 'service'
) {
$orders[$change['order']['id']]['delivery']['service']['code'] = self::newValue($change['newValue']);
} elseif($fields['delivery'][$change['field']]) {
} elseif (isset($fields['delivery'][$change['field']]) && $fields['delivery'][$change['field']]) {
$orders[$change['order']['id']]['delivery'][$fields['delivery'][$change['field']]] = self::newValue($change['newValue']);
} elseif($fields['orderAddress'][$change['field']]) {
} elseif (isset($fields['orderAddress'][$change['field']]) && $fields['orderAddress'][$change['field']]) {
$orders[$change['order']['id']]['delivery']['address'][$fields['orderAddress'][$change['field']]] = $change['newValue'];
} elseif($fields['integrationDelivery'][$change['field']]) {
} elseif (isset($fields['integrationDelivery'][$change['field']]) && $fields['integrationDelivery'][$change['field']]) {
$orders[$change['order']['id']]['delivery']['service'][$fields['integrationDelivery'][$change['field']]] = self::newValue($change['newValue']);
} elseif($fields['customerContragent'][$change['field']]) {
} elseif (isset($fields['customerContragent'][$change['field']]) && $fields['customerContragent'][$change['field']]) {
$orders[$change['order']['id']][$fields['customerContragent'][$change['field']]] = self::newValue($change['newValue']);
} elseif(strripos($change['field'], 'custom_') !== false) {
} elseif (strripos($change['field'], 'custom_') !== false) {
$orders[$change['order']['id']]['customFields'][str_replace('custom_', '', $change['field'])] = self::newValue($change['newValue']);
} elseif($fields['order'][$change['field']]) {
} elseif (isset($fields['order'][$change['field']]) && $fields['order'][$change['field']]) {
$orders[$change['order']['id']][$fields['order'][$change['field']]] = self::newValue($change['newValue']);
}
if(isset($change['created'])) {
if (isset($change['created'])) {
$orders[$change['order']['id']]['create'] = 1;
}
if(isset($change['deleted'])) {
if (isset($change['deleted'])) {
$orders[$change['order']['id']]['deleted'] = 1;
}
}

View file

@ -81,7 +81,6 @@ class RetailcrmHttpClient
$curlHandler = curl_init();
curl_setopt($curlHandler, CURLOPT_URL, $url);
curl_setopt($curlHandler, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curlHandler, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curlHandler, CURLOPT_FAILONERROR, false);
curl_setopt($curlHandler, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curlHandler, CURLOPT_SSL_VERIFYHOST, false);