New library classes, refactoring for OC 3.1

This commit is contained in:
Akolzin Dmitry 2018-09-27 11:32:33 +03:00
parent a6abd523bb
commit 4885897f14
29 changed files with 1504 additions and 5091 deletions

View File

@ -73,8 +73,9 @@ class RoboFile extends \Robo\Tasks
$this->taskDeleteDir('www')->run(); $this->taskDeleteDir('www')->run();
$this->taskFileSystemStack() $this->taskFileSystemStack()
->mirror('vendor/opencart/opencart/upload', 'www') ->mirror('vendor/opencart/opencart/upload', 'www')
->copy('vendor/beyondit/opencart-test-suite/src/upload/system/config/test-config.php','www/system/config/test-config.php') ->copy('vendor/beyondit/opencart-test-suite/src/upload/system/config/test-config.php', 'www/system/config/test-config.php')
->copy('vendor/beyondit/opencart-test-suite/src/upload/catalog/controller/startup/test_startup.php','www/catalog/controller/startup/test_startup.php') ->copy('vendor/beyondit/opencart-test-suite/src/upload/system/library/session/test.php', 'www/system/library/session/test.php')
->copy('vendor/beyondit/opencart-test-suite/src/upload/admin/controller/startup/test_startup.php','www/admin/controller/startup/test_startup.php')
->chmod('www', 0777, 0000, true) ->chmod('www', 0777, 0000, true)
->run(); ->run();
@ -97,7 +98,9 @@ class RoboFile extends \Robo\Tasks
$install->run(); $install->run();
$this->taskDeleteDir('www/install')->run(); $this->taskDeleteDir('www/install')->run();
$this->restoreSampleData($conn); if (isset($conn)) {
$this->restoreSampleData($conn);
}
$conn = null; $conn = null;
} }

View File

@ -10,7 +10,7 @@
} }
], ],
"require-dev": { "require-dev": {
"opencart/opencart" : "3.0.2.0", "opencart/opencart" : "3.1.0.0_a1",
"vlucas/phpdotenv": "~1.1.0", "vlucas/phpdotenv": "~1.1.0",
"phpunit/phpunit" : "^6", "phpunit/phpunit" : "^6",
"beyondit/opencart-test-suite": "~3.0", "beyondit/opencart-test-suite": "~3.0",

3197
composer.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,7 @@
<?php
class ControllerCronIcml extends Controller {
public function index($cron_id, $code, $cycle, $date_added, $date_modified) {
$this->load->controller('extension/module/retailcrm/icml');
}
}

View File

@ -28,6 +28,7 @@ class ControllerExtensionModuleRetailcrm extends Controller {
) )
); );
$this->addCronJobs();
$this->addEvents(); $this->addEvents();
} }
@ -45,6 +46,7 @@ class ControllerExtensionModuleRetailcrm extends Controller {
array(\Retailcrm\Retailcrm::MODULE . '_status' => 0) array(\Retailcrm\Retailcrm::MODULE . '_status' => 0)
); );
$this->model_setting_setting->deleteSetting('retailcrm_history'); $this->model_setting_setting->deleteSetting('retailcrm_history');
$this->deleteCronJobs();
$this->deleteEvents(); $this->deleteEvents();
} }
@ -214,7 +216,9 @@ class ControllerExtensionModuleRetailcrm extends Controller {
'special_price_settings', 'special_price_settings',
'special_price', 'special_price',
'order_number', 'order_number',
'text_order_number' 'text_order_number',
'debug',
'text_debug'
); );
foreach ($text_strings as $text) { foreach ($text_strings as $text) {
@ -369,12 +373,14 @@ class ControllerExtensionModuleRetailcrm extends Controller {
*/ */
public function history() public function history()
{ {
if (file_exists(DIR_APPLICATION . 'model/extension/retailcrm/custom/history/v4-5.php')) { $this->load->library('retailcrm/retailcrm');
$this->load->model('extension/retailcrm/custom/history/v4-5');
$this->model_extension_retailcrm_custom_history_v4_5->request($this->retailcrm->getApiClient()); if (file_exists(DIR_APPLICATION . 'model/extension/retailcrm/custom/history.php')) {
$this->load->model('extension/retailcrm/custom/history');
$this->model_extension_retailcrm_custom_history->request($this->retailcrm->getApiClient());
} else { } else {
$this->load->model('extension/retailcrm/history/v4_5'); $this->load->model('extension/retailcrm/history');
$this->model_extension_retailcrm_history_v4_5->request($this->retailcrm->getApiClient()); $this->model_extension_retailcrm_history->request($this->retailcrm->getApiClient());
} }
} }
@ -385,6 +391,8 @@ class ControllerExtensionModuleRetailcrm extends Controller {
*/ */
public function icml() public function icml()
{ {
$this->load->library('retailcrm/retailcrm');
if (file_exists(DIR_APPLICATION . 'model/extension/retailcrm/custom/icml.php')) { if (file_exists(DIR_APPLICATION . 'model/extension/retailcrm/custom/icml.php')) {
$this->load->model('extension/retailcrm/custom/icml'); $this->load->model('extension/retailcrm/custom/icml');
$this->model_extension_retailcrm_custom_icml->generateICML(); $this->model_extension_retailcrm_custom_icml->generateICML();
@ -402,7 +410,7 @@ class ControllerExtensionModuleRetailcrm extends Controller {
* *
* @return void * @return void
*/ */
public function customer_edit($route, $customer) public function customerEdit($route, $customer)
{ {
$this->load->model('localisation/country'); $this->load->model('localisation/country');
$this->load->model('localisation/zone'); $this->load->model('localisation/zone');
@ -443,23 +451,18 @@ class ControllerExtensionModuleRetailcrm extends Controller {
$order_id = isset($this->request->get['order_id']) ? $this->request->get['order_id'] : ''; $order_id = isset($this->request->get['order_id']) ? $this->request->get['order_id'] : '';
$this->load->model('sale/order'); $this->load->model('sale/order');
$data = $this->model_sale_order->getOrder($order_id); $order = $this->model_sale_order->getOrder($order_id);
$data['products'] = $this->model_sale_order->getOrderProducts($order_id); $order['products'] = $this->model_sale_order->getOrderProducts($order_id);
$data['totals'] = $this->model_sale_order->getOrderTotals($order_id); $order['totals'] = $this->model_sale_order->getOrderTotals($order_id);
foreach ($data['products'] as $key => $product) { foreach ($order['products'] as $key => $product) {
$data['products'][$key]['option'] = $this->model_sale_order->getOrderOptions($product['order_id'], $product['order_product_id']); $order['products'][$key]['option'] = $this->model_sale_order->getOrderOptions($product['order_id'], $product['order_product_id']);
} }
if (!isset($data['fromApi'])) { $this->load->library('retailcrm/retailcrm');
$this->load->model('setting/setting'); $retailcrm_order = $this->retailcrm->createObject(\Retailcrm\Order::class);
$status = $this->model_setting_setting->getSetting(\Retailcrm\Retailcrm::MODULE); $retailcrm_order->prepare($order);
$data['order_status'] = $status[\Retailcrm\Retailcrm::MODULE . '_status'][$data['order_status_id']]; $response = $retailcrm_order->create($this->retailcrm->getApiClient());
$this->load->model('extension/retailcrm/order');
$this->model_extension_retailcrm_order->uploadOrder($data, $this->retailcrm->getApiClient());
$response = ModelExtensionRetailcrmOrder::getLastResponse();
}
if (!$response->isSuccessful()) { if (!$response->isSuccessful()) {
if (isset($response['errors'])) { if (isset($response['errors'])) {
@ -495,14 +498,17 @@ class ControllerExtensionModuleRetailcrm extends Controller {
public function export() public function export()
{ {
$this->load->model('customer/customer'); $this->load->model('customer/customer');
$this->load->model('extension/retailcrm/customer');
$this->load->model('extension/retailcrm/order');
$this->load->model('sale/order'); $this->load->model('sale/order');
$this->load->library('retailcrm/retailcrm');
$retailcrm_api_client = $this->retailcrm->getApiClient();
$retailcrm_customer = $this->retailcrm->createObject(\Retailcrm\Customer::class);
$retailcrm_order = $this->retailcrm->createObject(\Retailcrm\Order::class);
$customers = $this->model_customer_customer->getCustomers(); $customers = $this->model_customer_customer->getCustomers();
$this->model_extension_retailcrm_customer->uploadToCrm($customers, $this->retailcrm->getApiClient()); $retailcrm_customer->upload($retailcrm_api_client, $customers, 'customers');
$orders = $this->model_sale_order->getOrders();
$orders = $this->model_sale_order->getOrders();
$fullOrders = array(); $fullOrders = array();
foreach ($orders as $order) { foreach ($orders as $order) {
@ -511,15 +517,14 @@ class ControllerExtensionModuleRetailcrm extends Controller {
$fullOrder['totals'] = $this->model_sale_order->getOrderTotals($order['order_id']); $fullOrder['totals'] = $this->model_sale_order->getOrderTotals($order['order_id']);
$fullOrder['products'] = $this->model_sale_order->getOrderProducts($order['order_id']); $fullOrder['products'] = $this->model_sale_order->getOrderProducts($order['order_id']);
foreach($fullOrder['products'] as $key => $product) { foreach ($fullOrder['products'] as $key => $product) {
$fullOrder['products'][$key]['option'] = $this->model_sale_order->getOrderOptions($product['order_id'], $product['order_product_id']); $fullOrder['products'][$key]['option'] = $this->model_sale_order->getOrderOptions($product['order_id'], $product['order_product_id']);
} }
$fullOrders[] = $fullOrder; $fullOrders[] = $fullOrder;
} }
$this->model_extension_retailcrm_order->uploadToCrm($fullOrders, $this->retailcrm->getApiClient()); $retailcrm_order->upload($retailcrm_api_client, $fullOrders);
fopen(DIR_SYSTEM . '/cron/export_done', "x");
} }
/** /**
@ -530,6 +535,7 @@ class ControllerExtensionModuleRetailcrm extends Controller {
public function prices() public function prices()
{ {
$this->load->model('catalog/product'); $this->load->model('catalog/product');
$this->load->library('retailcrm/retailcrm');
$products = $this->model_catalog_product->getProducts(); $products = $this->model_catalog_product->getProducts();
if (file_exists(DIR_APPLICATION . 'model/extension/retailcrm/custom/prices.php')) { if (file_exists(DIR_APPLICATION . 'model/extension/retailcrm/custom/prices.php')) {
@ -670,42 +676,42 @@ class ControllerExtensionModuleRetailcrm extends Controller {
->addEvent( ->addEvent(
\Retailcrm\Retailcrm::MODULE, \Retailcrm\Retailcrm::MODULE,
'catalog/model/checkout/order/addOrder/after', 'catalog/model/checkout/order/addOrder/after',
'extension/module/retailcrm/order_create' 'extension/module/retailcrm/orderCreate'
); );
$this->model_setting_event $this->model_setting_event
->addEvent( ->addEvent(
\Retailcrm\Retailcrm::MODULE, \Retailcrm\Retailcrm::MODULE,
'catalog/model/checkout/order/addOrderHistory/after', 'catalog/model/checkout/order/editOrder/after',
'extension/module/retailcrm/order_edit' 'extension/module/retailcrm/orderEdit'
); );
$this->model_setting_event $this->model_setting_event
->addEvent( ->addEvent(
\Retailcrm\Retailcrm::MODULE, \Retailcrm\Retailcrm::MODULE,
'catalog/model/account/customer/addCustomer/after', 'catalog/model/account/customer/addCustomer/after',
'extension/module/retailcrm/customer_create' 'extension/module/retailcrm/customerCreate'
); );
$this->model_setting_event $this->model_setting_event
->addEvent( ->addEvent(
\Retailcrm\Retailcrm::MODULE, \Retailcrm\Retailcrm::MODULE,
'catalog/model/account/customer/editCustomer/after', 'catalog/model/account/customer/editCustomer/after',
'extension/module/retailcrm/customer_edit' 'extension/module/retailcrm/customerEdit'
); );
$this->model_setting_event $this->model_setting_event
->addEvent( ->addEvent(
\Retailcrm\Retailcrm::MODULE, \Retailcrm\Retailcrm::MODULE,
'catalog/model/account/address/editAddress/after', 'catalog/model/account/address/editAddress/after',
'extension/module/retailcrm/customer_edit' 'extension/module/retailcrm/customerEdit'
); );
$this->model_setting_event $this->model_setting_event
->addEvent( ->addEvent(
\Retailcrm\Retailcrm::MODULE, \Retailcrm\Retailcrm::MODULE,
'admin/model/customer/customer/editCustomer/after', 'admin/model/customer/customer/editCustomer/after',
'extension/module/retailcrm/customer_edit' 'extension/module/retailcrm/customerEdit'
); );
} }
@ -719,7 +725,7 @@ class ControllerExtensionModuleRetailcrm extends Controller {
$events = $this->model_setting_event->getEvent( $events = $this->model_setting_event->getEvent(
\Retailcrm\Retailcrm::MODULE, \Retailcrm\Retailcrm::MODULE,
'catalog/model/checkout/order/addOrder/after', 'catalog/model/checkout/order/addOrder/after',
'extension/module/retailcrm/order_create' 'extension/module/retailcrm/orderCreate'
); );
if (!empty($events)) { if (!empty($events)) {
@ -787,4 +793,16 @@ class ControllerExtensionModuleRetailcrm extends Controller {
) )
); );
} }
private function addCronJobs() {
$this->load->model('setting/cron');
$this->model_setting_cron->addCron('icml', 'day', 'cron/icml', 1);
$this->model_setting_cron->addCron('prices', 'day', 'cron/icml', 0);
}
private function deleteCronJobs() {
$this->load->model('setting/cron');
$this->model_setting_cron->deleteCronByCode('icml');
$this->model_setting_cron->deleteCronByCode('prices');
}
} }

View File

@ -69,6 +69,9 @@ $_['retailcrm_missing_status'] = 'Missing orders status';
$_['order_number'] = 'Order number'; $_['order_number'] = 'Order number';
$_['text_order_number'] = 'Transfer order number to retailCRM'; $_['text_order_number'] = 'Transfer order number to retailCRM';
$_['debug'] = 'Debug mode';
$_['text_debug'] = 'Enable debug mode';
$_['column_total'] = 'Total'; $_['column_total'] = 'Total';
$_['product_summ'] = 'Amount'; $_['product_summ'] = 'Amount';

View File

@ -69,6 +69,9 @@ $_['retailcrm_missing_status'] = 'Статус пропавших заказо
$_['order_number'] = 'Номер заказа'; $_['order_number'] = 'Номер заказа';
$_['text_order_number'] = 'Передавать номер заказа в retailCRM'; $_['text_order_number'] = 'Передавать номер заказа в retailCRM';
$_['debug'] = 'Debug режим';
$_['text_debug'] = 'Включить подробное логирование';
$_['column_total'] = 'Итого'; $_['column_total'] = 'Итого';
$_['product_summ'] = 'Сумма'; $_['product_summ'] = 'Сумма';

View File

@ -1,194 +1,825 @@
<?php <?php
class ModelExtensionRetailcrmHistory extends Model require_once 'order.php';
class ModelExtensionRetailcrmHistory extends ModelExtensionRetailcrmOrder
{ {
/** protected $createResult;
* Create order in OC protected $settings;
* protected $opencartApiClient;
* @param array $order
* private $customFieldSetting;
* @return int $order_id
*/ public function __construct($registry)
public function addOrder($order)
{ {
$this->db->query("INSERT INTO `" . DB_PREFIX . "order` SET 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()"); parent::__construct($registry);
$this->load->library('retailcrm/retailcrm');
$order_id = $this->db->getLastId(); $this->opencartApiClient = $this->retailcrm->getOcApiClient($registry);
// 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 * Getting changes from RetailCRM
* @param \RetailcrmProxy $retailcrmApiClient
* *
* @param int $order_id * @return boolean
* @param array $order
*
* @return void
*/ */
public function editOrder($order_id, $order) public function request($retailcrmApiClient)
{ {
$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->load->library('retailcrm/retailcrm');
$this->load->model('setting/setting');
$this->load->model('setting/store');
$this->load->model('user/api');
$this->load->model('sale/order');
$this->load->model('customer/customer');
$this->load->model('extension/retailcrm/references');
$this->load->model('catalog/product');
$this->load->model('catalog/option');
$this->load->model('localisation/zone');
$this->db->query("DELETE FROM " . DB_PREFIX . "order_product WHERE order_id = '" . (int)$order_id . "'"); $this->load->language('extension/module/retailcrm');
// Products $settings = $this->model_setting_setting->getSetting(\Retailcrm\Retailcrm::MODULE);
if (isset($order['order_product']) && $order['order_product']) { $history = $this->model_setting_setting->getSetting('retailcrm_history');
$this->addOrderProducts($order_id, $order['order_product']); $settings['domain'] = parse_url(HTTP_SERVER, PHP_URL_HOST);
$url = isset($settings[\Retailcrm\Retailcrm::MODULE . '_url']) ? $settings[\Retailcrm\Retailcrm::MODULE . '_url'] : null;
$key = isset($settings[\Retailcrm\Retailcrm::MODULE . '_apikey']) ? $settings[\Retailcrm\Retailcrm::MODULE . '_apikey'] : null;
if (empty($url) || empty($key)) {
$this->log->addNotice('You need to configure retailcrm module first.');
return false;
} }
// Totals $sinceIdOrders = $history['retailcrm_history_orders'] ? $history['retailcrm_history_orders'] : null;
$this->db->query("DELETE FROM " . DB_PREFIX . "order_total WHERE order_id = '" . (int)$order_id . "'"); $sinceIdCustomers = $history['retailcrm_history_customers'] ? $history['retailcrm_history_customers'] : null;
if (isset($order['order_total'])) { $packsOrders = $retailcrmApiClient->ordersHistory(array(
$this->addOrderTotals($order_id, $order['order_total']); 'sinceId' => $sinceIdOrders ? $sinceIdOrders : 0
), 1, 100);
$packsCustomers = $retailcrmApiClient->customersHistory(array(
'sinceId' => $sinceIdCustomers ? $sinceIdCustomers : 0
), 1, 100);
if(!$packsOrders->isSuccessful() && count($packsOrders->history) <= 0 && !$packsCustomers->isSuccessful() && count($packsCustomers->history) <= 0) {
return false;
} }
}
/** $generatedAt = $packsOrders['generatedAt'];
* Add order products $orders = RetailcrmHistoryHelper::assemblyOrder($packsOrders->history);
* $customers = RetailcrmHistoryHelper::assemblyCustomer($packsCustomers->history);
* @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'] . "', reward = '" . (float)$product['reward'] . "'");
$order_product_id = $this->db->getLastId(); $ordersHistory = $packsOrders->history;
$customersHistory = $packsCustomers->history;
foreach ($product['option'] as $option) { $lastChangeOrders = $ordersHistory ? end($ordersHistory) : null;
$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']) . "'"); $lastChangeCustomers = $customersHistory ? end($customersHistory) : null;
if ($lastChangeOrders !== null) {
$sinceIdOrders = $lastChangeOrders['id'];
}
if ($lastChangeCustomers !== null) {
$sinceIdCustomers = $lastChangeCustomers['id'];
}
$this->settings = $settings;
$this->totalTitle = $this->totalTitles();
$this->subtotalSettings = $this->model_setting_setting->getSetting($this->totalTitle . 'sub_total');
$this->totalSettings = $this->model_setting_setting->getSetting($this->totalTitle . 'total');
$this->shippingSettings = $this->model_setting_setting->getSetting($this->totalTitle . 'shipping');
$this->delivery = array_flip($settings[\Retailcrm\Retailcrm::MODULE . '_delivery']);
$this->payment = array_flip($settings[\Retailcrm\Retailcrm::MODULE . '_payment']);
$this->status = array_flip($settings[\Retailcrm\Retailcrm::MODULE . '_status']);
$this->delivery_default = $settings[\Retailcrm\Retailcrm::MODULE . '_default_shipping'];
$this->payment_default = $settings[\Retailcrm\Retailcrm::MODULE . '_default_payment'];
$this->ocPayment = $this->model_extension_retailcrm_references
->getOpercartPaymentTypes();
$this->ocDelivery = $this->model_extension_retailcrm_references
->getOpercartDeliveryTypes($this->opencartApiClient);
$this->zones = $this->model_localisation_zone->getZones();
if (isset($settings[\Retailcrm\Retailcrm::MODULE . '_custom_field'])) {
$this->customFieldSetting = array_flip($settings[\Retailcrm\Retailcrm::MODULE . '_custom_field']);
}
$updatedOrders = array();
$newOrders = array();
foreach ($orders as $order) {
if (isset($order['deleted'])) {
continue;
}
if (isset($order['externalId'])) {
$updatedOrders[] = $order['id'];
} else {
$newOrders[] = $order['id'];
} }
} }
unset($orders);
$updateCustomers = array();
foreach ($customers as $customer) {
if (isset($customer['deleted'])) {
continue;
}
if (isset($customer['externalId'])) {
$updateCustomers[] = $customer['id'];
}
}
unset($customers);
if (!empty($updateCustomers)) {
$customers = $retailcrmApiClient->customersList($filter = array('ids' => $updateCustomers));
if ($customers) {
$this->updateCustomers($customers['customers']);
}
}
if (!empty($newOrders)) {
$orders = $retailcrmApiClient->ordersList($filter = array('ids' => $newOrders));
if ($orders) {
$this->createResult = $this->createOrders($orders['orders']);
}
}
if (!empty($updatedOrders)) {
$orders = $retailcrmApiClient->ordersList($filter = array('ids' => $updatedOrders));
if ($orders) {
$this->updateOrders($orders['orders']);
}
}
$this->model_setting_setting->editSetting(
'retailcrm_history',
array(
'retailcrm_history_orders' => $sinceIdOrders,
'retailcrm_history_customers' => $sinceIdCustomers,
'retailcrm_history_datetime' => $generatedAt
)
);
if (!empty($this->createResult['customers'])) {
$retailcrmApiClient->customersFixExternalIds($this->createResult['customers']);
}
if (!empty($this->createResult['orders'])) {
$retailcrmApiClient->ordersFixExternalIds($this->createResult['orders']);
}
return true;
} }
/** /**
* Add order totals * Update orders from history
* *
* @param int $order_id * @param array $orders
* @param array $totals
* *
* @return void * @return void
*/ */
public function addOrderTotals($order_id, $totals) protected function updateOrders($orders)
{ {
foreach ($totals as $total) { foreach ($orders as $order) {
$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'] . "'"); $ocOrder = $this->model_sale_order->getOrder($order['externalId']);
if (isset($order['payments']) && $order['payments']) {
foreach ($order['payments'] as $orderPayment) {
if (isset($orderPayment['externalId'])) {
$payment = $orderPayment;
}
}
if (!isset($payment) && count($order['payments']) == 1) {
$payment = end($order['payments']);
}
} elseif (isset($order['paymentType'])) {
$payment['type'] = $order['paymentType'];
}
$data = array();
$mail = isset($order['email']) ? $order['email'] : $order['customer']['email'];
$phone = isset($order['phone']) ? $order['phone'] : '';
if (!$phone) {
$data['telephone'] = $order['customer']['phones'] ? $order['customer']['phones'][0]['number'] : '80000000000';
} else {
$data['telephone'] = $phone;
}
if (isset($order['customer']['externalId']) && $order['customer']['externalId']) {
$customer = $this->model_customer_customer->getCustomer($order['customer']['externalId']);
}
$data['customer'] = $order['firstName'];
$data['customer_id'] = (isset($customer)) ? $customer['customer_id'] : 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'];
$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'] = isset($shippingCountry) ? $shippingCountry['country_id'] : $ocOrder['shipping_country_id'];
$data['shipping_country'] = isset($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'] = 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'];
if ($delivery !== null) {
if (isset($this->settings[\Retailcrm\Retailcrm::MODULE . '_delivery'][$ocOrder['shipping_code']])
&& isset($this->delivery[$delivery])
) {
$data['shipping'] = $this->delivery[$delivery];
$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\Retailcrm::MODULE . '_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'] = '';
$data['tax_id'] = '';
$data['product'] = '';
$data['product_id'] = '';
$data['reward'] = '';
$data['affiliate'] = '';
$data['affiliate_id'] = '';
$data['payment_tax_id'] = '';
$data['order_product_id'] = '';
$data['payment_company'] = '';
$data['payment_company_id'] = '';
$data['company'] = '';
$data['company_id'] = '';
$data['order_product'] = array();
$discount = false;
foreach ($order['items'] as $item) {
$productId = $item['offer']['externalId'];
$options = array();
if (isset($item['discountTotal']) && $item['discountTotal'] > 0) {
$discount = true;
}
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);
$rewards = $this->model_catalog_product->getProductRewards($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,
'reward' => $rewards[$data['customer_group_id']]['points'] * $item['quantity']
);
}
if (isset($this->customFieldSetting) && $order['customFields']) {
foreach ($order['customFields'] as $code => $value) {
if (array_key_exists($code, $this->customFieldSetting)) {
$fieldCode = str_replace('o_', '', $this->customFieldSetting[$code]);
$customFields[$fieldCode] = $value;
}
}
$data['custom_field'] = isset($customFields) ? $customFields : '';
} else {
$data['custom_field'] = $ocOrder['custom_field'];
}
$deliveryCost = !empty($order['delivery']['cost']) ? $order['delivery']['cost'] : 0;
$data['total'] = $order['totalSumm'];
$data['order_total'] = array(
array(
'order_total_id' => '',
'code' => 'sub_total',
'title' => $this->language->get('product_summ'),
'value' => $order['summ'],
'text' => $order['summ'],
'sort_order' => $this->subtotalSettings['sub_total_sort_order']
),
array(
'order_total_id' => '',
'code' => 'shipping',
'title' => $data['shipping_method'],
'value' => $deliveryCost,
'text' => $deliveryCost,
'sort_order' => $this->shippingSettings[$this->totalTitle . 'shipping_sort_order']
),
array(
'order_total_id' => '',
'code' => 'total',
'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[$this->totalTitle . 'total_sort_order']
)
);
if ((isset($order['discount'])
&& $order['discount'] > 0)
|| $discount
) {
$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)) {
$data['order_status_id'] = $this->status[$order['status']];
} else {
$tmpOrder = $this->model_sale_order->getOrder($order['externalId']);
$data['order_status_id'] = $tmpOrder['order_status_id'];
}
$this->editOrder($order['externalId'], $data);
$this->opencartApiClient->addHistory($order['externalId'], $data['order_status_id']);
} }
} }
/** /**
* Get total titles * Create orders from history
* *
* @return string $title * @param array $orders
*/
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 * @return array
*/ */
public function getCountryByIsoCode($isoCode) protected function createOrders($orders)
{ {
$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "country` WHERE iso_code_2 = '" . $isoCode . "'"); $customersIdsFix = array();
$ordersIdsFix = array();
return $query->row; foreach ($orders as $order) {
} $store = $this->config->get('config_store_id');
/** if (isset($order['payments']) && $order['payments']) {
* Get zone by name $payment = end($order['payments']);
* } elseif (isset($order['paymentType'])) {
* @param string $name $payment['type'] = $order['paymentType'];
* }
* @return array
*/
public function getZoneByName($name)
{
$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "zone` WHERE name = '" . $name . "'");
return $query->row; $customer_id = (!empty($order['customer']['externalId']))
} ? $order['customer']['externalId']
: 0;
/** $data = array();
* 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) { if ($customer_id == 0) {
return $query->row; if (isset($order['customer']['address']['countryIso'])) {
$customerCountry = $this->getCountryByIsoCode($order['customer']['address']['countryIso']);
} else {
$customerCountry = $this->getCountryByIsoCode($order['delivery']['address']['countryIso']);
}
if (isset($order['customer']['address']['region'])) {
$customerZone = $this->getZoneByName($order['customer']['address']['region']);
} else {
$customerZone = $this->getZoneByName($order['delivery']['address']['region']);
}
$cData = array(
'store_id' => 0,
'customer_group_id' => '1',
'firstname' => isset($order['patronymic']) ? $order['firstName'] . ' ' . $order['patronymic'] : $order['firstName'],
'lastname' => (!empty($order['customer']['lastName'])) ? $order['customer']['lastName'] : ' ',
'email' => $order['customer']['email'],
'telephone' => $order['customer']['phones'] ? $order['customer']['phones'][0]['number'] : ' ',
'fax' => '',
'newsletter' => 0,
'password' => 'tmppass',
'status' => 1,
'approved' => 1,
'safe' => 0,
'affiliate' => '',
'address' => array(
array(
'firstname' => isset($order['patronymic']) ? $order['firstName'] . ' ' . $order['patronymic'] : $order['firstName'],
'lastname' => (!empty($order['customer']['lastName'])) ? $order['customer']['lastName'] : ' ',
'address_1' => $order['customer']['address']['text'],
'address_2' => ' ',
'city' => !empty($order['customer']['address']['city']) ? $order['customer']['address']['city'] : $order['delivery']['address']['city'],
'postcode' => isset($order['customer']['address']['index']) ? $order['customer']['address']['index'] : $order['delivery']['address']['index'],
'tax_id' => '1',
'company' => '',
'company_id' => '',
'zone_id' => $customerZone ? $customerZone['zone_id'] : 0,
'country_id' => $customerCountry ? $customerCountry['country_id'] : 0,
'default' => '1'
)
),
);
$customer_id = $this->model_customer_customer->addCustomer($cData);
$customersIdsFix[] = array('id' => $order['customer']['id'], 'externalId' => (int)$customer_id);
}
$mail = isset($order['email']) ? $order['email'] : $order['customer']['email'];
$phone = isset($order['phone']) ? $order['phone'] : '';
if (!$phone) {
$data['telephone'] = $order['customer']['phones'] ? $order['customer']['phones'][0]['number'] : '80000000000';
} else {
$data['telephone'] = $phone;
}
$data['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'] = (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'] = (isset($order['lastName'])) ? $order['lastName'] : $order['firstName'];
$data['payment_address_1'] = $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'];
$shippingZone = '';
if (!empty($order['delivery']['address']['region']) && 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'])) {
$shippingCountry = $this->getCountryByIsoCode($order['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'] = isset($shippingCountry) ? $shippingCountry['country_id'] : 0;
$data['shipping_country'] = isset($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'] = (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] : $this->delivery_default;
$data['shipping_code'] = $delivery != null ? $this->delivery[$delivery] : $this->delivery_default;
$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'] = $this->payment_default;
$data['payment_method'] = $this->ocPayment[$data['payment']];
$data['payment_code'] = $this->payment_default;
}
// this data will not retrive from crm for now
$data['tax'] = '';
$data['tax_id'] = '';
$data['product'] = '';
$data['product_id'] = '';
$data['reward'] = '';
$data['affiliate'] = '';
$data['affiliate_id'] = 0;
$data['payment_tax_id'] = '';
$data['order_product_id'] = '';
$data['payment_company'] = '';
$data['payment_company_id'] = '';
$data['company'] = '';
$data['company_id'] = '';
$data['order_product'] = array();
foreach ($order['items'] as $item) {
$productId = $item['offer']['externalId'];
$options = array();
if(mb_strpos($item['offer']['externalId'], '#') > 1) {
$offer = explode('#', $item['offer']['externalId']);
$productId = $offer[0];
$optionsFromCRM = explode('_', $offer[1]);
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);
$rewards = $this->model_catalog_product->getProductRewards($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,
'reward' => $rewards[$data['customer_group_id']]['points'] * $item['quantity']
);
}
if (isset($this->customFieldSetting) && $order['customFields']) {
foreach ($order['customFields'] as $code => $value) {
if (array_key_exists($code, $this->customFieldSetting)) {
$fieldCode = str_replace('o_', '', $this->customFieldSetting[$code]);
$customFields[$fieldCode] = $value;
}
}
$data['custom_field'] = isset($customFields) ? $customFields : '';
}
$deliveryCost = !empty($order['delivery']['cost']) ? $order['delivery']['cost'] : 0;
$data['total'] = $order['totalSumm'];
$data['order_total'] = array(
array(
'order_total_id' => '',
'code' => 'sub_total',
'title' => $this->language->get('product_summ'),
'value' => $order['summ'],
'text' => $order['summ'],
'sort_order' => $this->subtotalSettings['sub_total_sort_order']
),
array(
'order_total_id' => '',
'code' => 'shipping',
'title' => $data['shipping_method'],
'value' => $deliveryCost,
'text' => $deliveryCost,
'sort_order' => $this->shippingSettings[$this->totalTitle . 'shipping_sort_order']
),
array(
'order_total_id' => '',
'code' => 'total',
'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[$this->totalTitle . 'total_sort_order']
)
);
$data['fromApi'] = true;
$data['order_status_id'] = 1;
$order_id = $this->addOrder($data);
$ordersIdsFix[] = array('id' => $order['id'], 'externalId' => (int) $order_id);
} }
return $query->row[$field]; return array('customers' => $customersIdsFix, 'orders' => $ordersIdsFix);
} }
/** protected function updateCustomers($customers)
* 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 . "'"); foreach ($customers as $customer) {
$customer_id = $customer['externalId'];
$customerData = $this->model_customer_customer->getCustomer($customer_id);
$customerData['password'] = false;
if (!$field) { $customerData['firstname'] = $customer['firstName'];
return $query->row; $customerData['lastname'] = isset($customer['lastName']) ? $customer['lastName'] : '';
$customerData['email'] = $customer['email'];
$customerData['telephone'] = $customer['phones'] ? $customer['phones'][0]['number'] : '';
$customerAddress = $this->model_customer_customer->getAddress($customerData['address_id']);
if (isset($customer['address']['countryIso'])) {
$customerCountry = $this->getCountryByIsoCode($customer['address']['countryIso']);
}
if (isset($customer['address']['region'])) {
$customerZone = $this->getZoneByName($customer['address']['region']);
}
$customerAddress['firstname'] = isset($customer['patronymic']) ? $customer['firstName'] . ' ' . $customer['patronymic'] : $customer['firstName'];
$customerAddress['lastname'] = isset($customer['lastName']) ? $customer['lastName'] : '';
$customerAddress['address_1'] = $customer['address']['text'];
$customerAddress['city'] = $customer['address']['city'];
$customerAddress['postcode'] = isset($customer['address']['index']) ? $customer['address']['index'] : '';
if (isset($customerCountry)) {
$customerAddress['country_id'] = $customerCountry['country_id'];
}
if (isset($customerZone) && isset($customerZone['zone_id'])) {
$customerAddress['zone_id'] = $customerZone['zone_id'];
}
$customerData['address'] = array($customerAddress);
if (isset($this->customFieldSetting) && $customer['customFields']) {
foreach ($customer['customFields'] as $code => $value) {
if (array_key_exists($code, $this->customFieldSetting)) {
$fieldCode = str_replace('c_', '', $this->customFieldSetting[$code]);
$customFields[$fieldCode] = $value;
}
}
$customerData['custom_field'] = isset($customFields) ? $customFields : '';
}
$this->model_customer_customer->editCustomer($customer_id, $customerData);
} }
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

@ -1,827 +0,0 @@
<?php
require_once __DIR__ . '/../history.php';
class ModelExtensionRetailcrmHistoryV45 extends ModelExtensionRetailcrmHistory
{
protected $createResult;
protected $settings;
protected $moduleTitle;
protected $opencartApiClient;
private $customFieldSetting;
public function __construct($registry)
{
parent::__construct($registry);
$this->load->library('retailcrm/retailcrm');
$this->moduleTitle = $this->retailcrm->getModuleTitle();
$this->opencartApiClient = $this->retailcrm->getOcApiClient($registry);
}
/**
* Getting changes from RetailCRM
* @param \RetailcrmProxy $retailcrmApiClient
*
* @return boolean
*/
public function request($retailcrmApiClient)
{
$this->load->library('retailcrm/retailcrm');
$this->load->model('setting/setting');
$this->load->model('setting/store');
$this->load->model('user/api');
$this->load->model('sale/order');
$this->load->model('customer/customer');
$this->load->model('extension/retailcrm/references');
$this->load->model('catalog/product');
$this->load->model('catalog/option');
$this->load->model('localisation/zone');
$this->load->language('extension/module/retailcrm');
$settings = $this->model_setting_setting->getSetting($this->moduleTitle);
$history = $this->model_setting_setting->getSetting('retailcrm_history');
$settings['domain'] = parse_url(HTTP_SERVER, PHP_URL_HOST);
$url = isset($settings[$this->moduleTitle . '_url']) ? $settings[$this->moduleTitle . '_url'] : null;
$key = isset($settings[$this->moduleTitle . '_apikey']) ? $settings[$this->moduleTitle . '_apikey'] : null;
if (empty($url) || empty($key)) {
$this->log->addNotice('You need to configure retailcrm module first.');
return false;
}
$sinceIdOrders = $history['retailcrm_history_orders'] ? $history['retailcrm_history_orders'] : null;
$sinceIdCustomers = $history['retailcrm_history_customers'] ? $history['retailcrm_history_customers'] : null;
$packsOrders = $retailcrmApiClient->ordersHistory(array(
'sinceId' => $sinceIdOrders ? $sinceIdOrders : 0
), 1, 100);
$packsCustomers = $retailcrmApiClient->customersHistory(array(
'sinceId' => $sinceIdCustomers ? $sinceIdCustomers : 0
), 1, 100);
if(!$packsOrders->isSuccessful() && count($packsOrders->history) <= 0 && !$packsCustomers->isSuccessful() && count($packsCustomers->history) <= 0) {
return false;
}
$generatedAt = $packsOrders['generatedAt'];
$orders = RetailcrmHistoryHelper::assemblyOrder($packsOrders->history);
$customers = RetailcrmHistoryHelper::assemblyCustomer($packsCustomers->history);
$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->settings = $settings;
$this->totalTitle = $this->totalTitles();
$this->subtotalSettings = $this->model_setting_setting->getSetting($this->totalTitle . 'sub_total');
$this->totalSettings = $this->model_setting_setting->getSetting($this->totalTitle . 'total');
$this->shippingSettings = $this->model_setting_setting->getSetting($this->totalTitle . 'shipping');
$this->delivery = array_flip($settings[$this->moduleTitle . '_delivery']);
$this->payment = array_flip($settings[$this->moduleTitle . '_payment']);
$this->status = array_flip($settings[$this->moduleTitle . '_status']);
$this->delivery_default = $settings[$this->moduleTitle . '_default_shipping'];
$this->payment_default = $settings[$this->moduleTitle . '_default_payment'];
$this->ocPayment = $this->model_extension_retailcrm_references
->getOpercartPaymentTypes();
$this->ocDelivery = $this->model_extension_retailcrm_references
->getOpercartDeliveryTypes();
$this->zones = $this->model_localisation_zone->getZones();
if (isset($settings[$this->moduleTitle . '_custom_field'])) {
$this->customFieldSetting = array_flip($settings[$this->moduleTitle . '_custom_field']);
}
$updatedOrders = array();
$newOrders = array();
foreach ($orders as $order) {
if (isset($order['deleted'])) {
continue;
}
if (isset($order['externalId'])) {
$updatedOrders[] = $order['id'];
} else {
$newOrders[] = $order['id'];
}
}
unset($orders);
$updateCustomers = array();
foreach ($customers as $customer) {
if (isset($customer['deleted'])) {
continue;
}
if (isset($customer['externalId'])) {
$updateCustomers[] = $customer['id'];
}
}
unset($customers);
if (!empty($updateCustomers)) {
$customers = $retailcrmApiClient->customersList($filter = array('ids' => $updateCustomers));
if ($customers) {
$this->updateCustomers($customers['customers']);
}
}
if (!empty($newOrders)) {
$orders = $retailcrmApiClient->ordersList($filter = array('ids' => $newOrders));
if ($orders) {
$this->createResult = $this->createOrders($orders['orders']);
}
}
if (!empty($updatedOrders)) {
$orders = $retailcrmApiClient->ordersList($filter = array('ids' => $updatedOrders));
if ($orders) {
$this->updateOrders($orders['orders']);
}
}
$this->model_setting_setting->editSetting(
'retailcrm_history',
array(
'retailcrm_history_orders' => $sinceIdOrders,
'retailcrm_history_customers' => $sinceIdCustomers,
'retailcrm_history_datetime' => $generatedAt
)
);
if (!empty($this->createResult['customers'])) {
$retailcrmApiClient->customersFixExternalIds($this->createResult['customers']);
}
if (!empty($this->createResult['orders'])) {
$retailcrmApiClient->ordersFixExternalIds($this->createResult['orders']);
}
return true;
}
/**
* Update orders from history
*
* @param array $orders
*
* @return void
*/
protected function updateOrders($orders)
{
foreach ($orders as $order) {
$ocOrder = $this->model_sale_order->getOrder($order['externalId']);
if (isset($order['payments']) && $order['payments']) {
foreach ($order['payments'] as $orderPayment) {
if (isset($orderPayment['externalId'])) {
$payment = $orderPayment;
}
}
if (!isset($payment) && count($order['payments']) == 1) {
$payment = end($order['payments']);
}
} elseif (isset($order['paymentType'])) {
$payment['type'] = $order['paymentType'];
}
$data = array();
$mail = isset($order['email']) ? $order['email'] : $order['customer']['email'];
$phone = isset($order['phone']) ? $order['phone'] : '';
if (!$phone) {
$data['telephone'] = $order['customer']['phones'] ? $order['customer']['phones'][0]['number'] : '80000000000';
} else {
$data['telephone'] = $phone;
}
if (isset($order['customer']['externalId']) && $order['customer']['externalId']) {
$customer = $this->model_customer_customer->getCustomer($order['customer']['externalId']);
}
$data['customer'] = $order['firstName'];
$data['customer_id'] = (isset($customer)) ? $customer['customer_id'] : 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'];
$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'] = isset($shippingCountry) ? $shippingCountry['country_id'] : $ocOrder['shipping_country_id'];
$data['shipping_country'] = isset($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'] = 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'];
if ($delivery !== null) {
if (isset($this->settings[$this->moduleTitle . '_delivery'][$ocOrder['shipping_code']])
&& isset($this->delivery[$delivery])
) {
$data['shipping'] = $this->delivery[$delivery];
$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[$this->moduleTitle . '_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'] = '';
$data['tax_id'] = '';
$data['product'] = '';
$data['product_id'] = '';
$data['reward'] = '';
$data['affiliate'] = '';
$data['affiliate_id'] = '';
$data['payment_tax_id'] = '';
$data['order_product_id'] = '';
$data['payment_company'] = '';
$data['payment_company_id'] = '';
$data['company'] = '';
$data['company_id'] = '';
$data['order_product'] = array();
$discount = false;
foreach ($order['items'] as $item) {
$productId = $item['offer']['externalId'];
$options = array();
if (isset($item['discountTotal']) && $item['discountTotal'] > 0) {
$discount = true;
}
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);
$rewards = $this->model_catalog_product->getProductRewards($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,
'reward' => $rewards[$data['customer_group_id']]['points'] * $item['quantity']
);
}
if (isset($this->customFieldSetting) && $order['customFields']) {
foreach ($order['customFields'] as $code => $value) {
if (array_key_exists($code, $this->customFieldSetting)) {
$fieldCode = str_replace('o_', '', $this->customFieldSetting[$code]);
$customFields[$fieldCode] = $value;
}
}
$data['custom_field'] = isset($customFields) ? $customFields : '';
} else {
$data['custom_field'] = $ocOrder['custom_field'];
}
$deliveryCost = !empty($order['delivery']['cost']) ? $order['delivery']['cost'] : 0;
$data['total'] = $order['totalSumm'];
$data['order_total'] = array(
array(
'order_total_id' => '',
'code' => 'sub_total',
'title' => $this->language->get('product_summ'),
'value' => $order['summ'],
'text' => $order['summ'],
'sort_order' => $this->subtotalSettings['sub_total_sort_order']
),
array(
'order_total_id' => '',
'code' => 'shipping',
'title' => $data['shipping_method'],
'value' => $deliveryCost,
'text' => $deliveryCost,
'sort_order' => $this->shippingSettings[$this->totalTitle . 'shipping_sort_order']
),
array(
'order_total_id' => '',
'code' => 'total',
'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[$this->totalTitle . 'total_sort_order']
)
);
if ((isset($order['discount'])
&& $order['discount'] > 0)
|| $discount
) {
$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)) {
$data['order_status_id'] = $this->status[$order['status']];
} else {
$tmpOrder = $this->model_sale_order->getOrder($order['externalId']);
$data['order_status_id'] = $tmpOrder['order_status_id'];
}
$this->editOrder($order['externalId'], $data);
$this->opencartApiClient->addHistory($order['externalId'], $data['order_status_id']);
}
}
/**
* Create orders from history
*
* @param array $orders
*
* @return array
*/
protected function createOrders($orders)
{
$customersIdsFix = array();
$ordersIdsFix = array();
foreach ($orders as $order) {
$store = $this->config->get('config_store_id');
if (isset($order['payments']) && $order['payments']) {
$payment = end($order['payments']);
} elseif (isset($order['paymentType'])) {
$payment['type'] = $order['paymentType'];
}
$customer_id = (!empty($order['customer']['externalId']))
? $order['customer']['externalId']
: 0;
$data = array();
if ($customer_id == 0) {
if (isset($order['customer']['address']['countryIso'])) {
$customerCountry = $this->getCountryByIsoCode($order['customer']['address']['countryIso']);
} else {
$customerCountry = $this->getCountryByIsoCode($order['delivery']['address']['countryIso']);
}
if (isset($order['customer']['address']['region'])) {
$customerZone = $this->getZoneByName($order['customer']['address']['region']);
} else {
$customerZone = $this->getZoneByName($order['delivery']['address']['region']);
}
$cData = array(
'store_id' => 0,
'customer_group_id' => '1',
'firstname' => isset($order['patronymic']) ? $order['firstName'] . ' ' . $order['patronymic'] : $order['firstName'],
'lastname' => (!empty($order['customer']['lastName'])) ? $order['customer']['lastName'] : ' ',
'email' => $order['customer']['email'],
'telephone' => $order['customer']['phones'] ? $order['customer']['phones'][0]['number'] : ' ',
'fax' => '',
'newsletter' => 0,
'password' => 'tmppass',
'status' => 1,
'approved' => 1,
'safe' => 0,
'affiliate' => '',
'address' => array(
array(
'firstname' => isset($order['patronymic']) ? $order['firstName'] . ' ' . $order['patronymic'] : $order['firstName'],
'lastname' => (!empty($order['customer']['lastName'])) ? $order['customer']['lastName'] : ' ',
'address_1' => $order['customer']['address']['text'],
'address_2' => ' ',
'city' => !empty($order['customer']['address']['city']) ? $order['customer']['address']['city'] : $order['delivery']['address']['city'],
'postcode' => isset($order['customer']['address']['index']) ? $order['customer']['address']['index'] : $order['delivery']['address']['index'],
'tax_id' => '1',
'company' => '',
'company_id' => '',
'zone_id' => $customerZone ? $customerZone['zone_id'] : 0,
'country_id' => $customerCountry ? $customerCountry['country_id'] : 0,
'default' => '1'
)
),
);
$customer_id = $this->model_customer_customer->addCustomer($cData);
$customersIdsFix[] = array('id' => $order['customer']['id'], 'externalId' => (int)$customer_id);
}
$mail = isset($order['email']) ? $order['email'] : $order['customer']['email'];
$phone = isset($order['phone']) ? $order['phone'] : '';
if (!$phone) {
$data['telephone'] = $order['customer']['phones'] ? $order['customer']['phones'][0]['number'] : '80000000000';
} else {
$data['telephone'] = $phone;
}
$data['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'] = (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'] = (isset($order['lastName'])) ? $order['lastName'] : $order['firstName'];
$data['payment_address_1'] = $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'];
$shippingZone = '';
if (!empty($order['delivery']['address']['region']) && 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'])) {
$shippingCountry = $this->getCountryByIsoCode($order['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'] = isset($shippingCountry) ? $shippingCountry['country_id'] : 0;
$data['shipping_country'] = isset($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'] = (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] : $this->delivery_default;
$data['shipping_code'] = $delivery != null ? $this->delivery[$delivery] : $this->delivery_default;
$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'] = $this->payment_default;
$data['payment_method'] = $this->ocPayment[$data['payment']];
$data['payment_code'] = $this->payment_default;
}
// this data will not retrive from crm for now
$data['tax'] = '';
$data['tax_id'] = '';
$data['product'] = '';
$data['product_id'] = '';
$data['reward'] = '';
$data['affiliate'] = '';
$data['affiliate_id'] = 0;
$data['payment_tax_id'] = '';
$data['order_product_id'] = '';
$data['payment_company'] = '';
$data['payment_company_id'] = '';
$data['company'] = '';
$data['company_id'] = '';
$data['order_product'] = array();
foreach ($order['items'] as $item) {
$productId = $item['offer']['externalId'];
$options = array();
if(mb_strpos($item['offer']['externalId'], '#') > 1) {
$offer = explode('#', $item['offer']['externalId']);
$productId = $offer[0];
$optionsFromCRM = explode('_', $offer[1]);
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);
$rewards = $this->model_catalog_product->getProductRewards($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,
'reward' => $rewards[$data['customer_group_id']]['points'] * $item['quantity']
);
}
if (isset($this->customFieldSetting) && $order['customFields']) {
foreach ($order['customFields'] as $code => $value) {
if (array_key_exists($code, $this->customFieldSetting)) {
$fieldCode = str_replace('o_', '', $this->customFieldSetting[$code]);
$customFields[$fieldCode] = $value;
}
}
$data['custom_field'] = isset($customFields) ? $customFields : '';
}
$deliveryCost = !empty($order['delivery']['cost']) ? $order['delivery']['cost'] : 0;
$data['total'] = $order['totalSumm'];
$data['order_total'] = array(
array(
'order_total_id' => '',
'code' => 'sub_total',
'title' => $this->language->get('product_summ'),
'value' => $order['summ'],
'text' => $order['summ'],
'sort_order' => $this->subtotalSettings['sub_total_sort_order']
),
array(
'order_total_id' => '',
'code' => 'shipping',
'title' => $data['shipping_method'],
'value' => $deliveryCost,
'text' => $deliveryCost,
'sort_order' => $this->shippingSettings[$this->totalTitle . 'shipping_sort_order']
),
array(
'order_total_id' => '',
'code' => 'total',
'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[$this->totalTitle . 'total_sort_order']
)
);
$data['fromApi'] = true;
$data['order_status_id'] = 1;
$order_id = $this->addOrder($data);
$ordersIdsFix[] = array('id' => $order['id'], 'externalId' => (int) $order_id);
}
return array('customers' => $customersIdsFix, 'orders' => $ordersIdsFix);
}
protected function updateCustomers($customers)
{
foreach ($customers as $customer) {
$customer_id = $customer['externalId'];
$customerData = $this->model_customer_customer->getCustomer($customer_id);
$customerData['password'] = false;
$customerData['firstname'] = $customer['firstName'];
$customerData['lastname'] = isset($customer['lastName']) ? $customer['lastName'] : '';
$customerData['email'] = $customer['email'];
$customerData['telephone'] = $customer['phones'] ? $customer['phones'][0]['number'] : '';
$customerAddress = $this->model_customer_customer->getAddress($customerData['address_id']);
if (isset($customer['address']['countryIso'])) {
$customerCountry = $this->getCountryByIsoCode($customer['address']['countryIso']);
}
if (isset($customer['address']['region'])) {
$customerZone = $this->getZoneByName($customer['address']['region']);
}
$customerAddress['firstname'] = isset($customer['patronymic']) ? $customer['firstName'] . ' ' . $customer['patronymic'] : $customer['firstName'];
$customerAddress['lastname'] = isset($customer['lastName']) ? $customer['lastName'] : '';
$customerAddress['address_1'] = $customer['address']['text'];
$customerAddress['city'] = $customer['address']['city'];
$customerAddress['postcode'] = isset($customer['address']['index']) ? $customer['address']['index'] : '';
if (isset($customerCountry)) {
$customerAddress['country_id'] = $customerCountry['country_id'];
}
if (isset($customerZone) && isset($customerZone['zone_id'])) {
$customerAddress['zone_id'] = $customerZone['zone_id'];
}
$customerData['address'] = array($customerAddress);
if (isset($this->customFieldSetting) && $customer['customFields']) {
foreach ($customer['customFields'] as $code => $value) {
if (array_key_exists($code, $this->customFieldSetting)) {
$fieldCode = str_replace('c_', '', $this->customFieldSetting[$code]);
$customFields[$fieldCode] = $value;
}
}
$customerData['custom_field'] = isset($customFields) ? $customFields : '';
}
$this->model_customer_customer->editCustomer($customer_id, $customerData);
}
}
}

View File

@ -1,305 +1,194 @@
<?php <?php
class ModelExtensionRetailcrmOrder extends Model { class ModelExtensionRetailcrmOrder extends Model
protected $settings; {
protected $moduleTitle; /**
protected $retailcrmApiClient; * Create order in OC
*
protected static $lastRepsonse = null; * @param array $order
*
public function __construct($registry) * @return int $order_id
*/
public function addOrder($order)
{ {
parent::__construct($registry); $this->db->query("INSERT INTO `" . DB_PREFIX . "order` SET 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()");
$this->load->model('setting/setting');
$this->load->library('retailcrm/retailcrm');
$this->moduleTitle = $this->retailcrm->getModuleTitle(); $order_id = $this->db->getLastId();
$this->settings = $this->model_setting_setting->getSetting($this->moduleTitle);
// 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;
} }
/** /**
* Upload orders to CRM * Edit order in OC
* *
* @param array $orders * @param int $order_id
* @param \RetailcrmProxy $retailcrmApiClient * @param array $order
* *
* @return mixed * @return void
*/ */
public function uploadToCrm($orders, $retailcrmApiClient) public function editOrder($order_id, $order)
{ {
if ($retailcrmApiClient === false) { $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 . "'");
return false;
$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']);
} }
$ordersToCrm = array(); // Totals
$this->db->query("DELETE FROM " . DB_PREFIX . "order_total WHERE order_id = '" . (int)$order_id . "'");
foreach ($orders as $order) { if (isset($order['order_total'])) {
$ordersToCrm[] = $this->process($order); $this->addOrderTotals($order_id, $order['order_total']);
} }
$chunkedOrders = array_chunk($ordersToCrm, 50);
foreach($chunkedOrders as $ordersPart) {
$retailcrmApiClient->ordersUpload($ordersPart);
}
return $chunkedOrders;
} }
/** /**
* Send one order by id * Add order products
* *
* @param array $order_data * @param int $order_id
* @param \RetailcrmProxy $retailcrmApiClient * @param array $products
* *
* @return mixed * @return void
*/ */
public function uploadOrder($order_data, $retailcrmApiClient) public function addOrderProducts($order_id, $products)
{ {
if ($retailcrmApiClient === false) { foreach ($products as $product) {
return false; $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'] . "', reward = '" . (float)$product['reward'] . "'");
$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']) . "'");
}
} }
}
if (isset($this->request->post['fromApi'])) { /**
return false; * 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'] . "'");
} }
}
$order = $this->process($order_data); /**
* Get total titles
if (isset($order['customer']['externalId'])) { *
$this->load->model('extension/retailcrm/customer'); * @return string $title
$this->load->model('customer/customer'); */
$customer = $this->model_customer_customer->getCustomer($order['customer']['externalId']); protected function totalTitles()
$this->model_extension_retailcrm_customer->sendToCrm($customer, $retailcrmApiClient); {
if (version_compare(VERSION, '3.0', '<')) {
$title = '';
} else { } else {
$customers = $retailcrmApiClient->customersList( $title = 'total_';
array(
'name' => $order_data['telephone'],
'email' => $order_data['email']
),
1,
100
);
if ($customers) {
foreach ($customers['customers'] as $customer) {
$order['customer']['id'] = $customer['id'];
}
}
unset($customers);
} }
self::$lastRepsonse = $retailcrmApiClient->ordersCreate($order); return $title;
return $order;
} }
/** /**
* Process order * Get country by iso code 2
* *
* @param array $order_data * @param string $isoCode
* *
* @return array $order * @return array
*/ */
private function process($order_data) { public function getCountryByIsoCode($isoCode)
$order = array();
$this->load->model('catalog/product');
if (!empty($order_data['payment_code']) && isset($this->settings[$this->moduleTitle . '_payment'][$order_data['payment_code']])) {
$payment_code = $this->settings[$this->moduleTitle . '_payment'][$order_data['payment_code']];
} else {
$payment_code = '';
}
if (!empty($order_data['shipping_code'])) {
$shippingCode = explode('.', $order_data['shipping_code']);
$shippingModule = $shippingCode[0];
if (isset($this->settings[$this->moduleTitle . '_delivery'][$order_data['shipping_code']])) {
$delivery_code = $this->settings[$this->moduleTitle . '_delivery'][$order_data['shipping_code']];
} elseif (isset($this->settings[$this->moduleTitle . '_delivery'][$shippingModule])) {
$delivery_code = $this->settings[$this->moduleTitle . '_delivery'][$shippingModule];
}
}
if (!isset($delivery_code) && isset($shippingModule)) {
if (isset($this->settings[$this->moduleTitle . '_delivery'])
&& $this->settings[$this->moduleTitle . '_delivery']
) {
$deliveries = array_keys($this->settings[$this->moduleTitle . '_delivery']);
$shipping_code = '';
array_walk($deliveries, function($item, $key) use ($shippingModule, &$shipping_code) {
if (strripos($item, $shippingModule) !== false) {
$shipping_code = $item;
}
});
$delivery_code = $this->settings[$this->moduleTitle . '_delivery'][$shipping_code];
}
}
if (!empty($order_data['payment_iso_code_2'])) {
$order['countryIso'] = $order_data['payment_iso_code_2'];
}
if (isset($this->settings[$this->moduleTitle . '_order_number'])
&& $this->settings[$this->moduleTitle . '_order_number'] == 1
) {
$order['number'] = $order_data['order_id'];
}
$order['externalId'] = $order_data['order_id'];
$order['firstName'] = $order_data['firstname'];
$order['lastName'] = $order_data['lastname'];
$order['phone'] = $order_data['telephone'];
$order['customerComment'] = $order_data['comment'];
if (!empty($order_data['email'])) {
$order['email'] = $order_data['email'];
}
if ($order_data['customer_id']) {
$order['customer']['externalId'] = $order_data['customer_id'];
}
$deliveryCost = 0;
$orderTotals = isset($order_data['totals']) ? $order_data['totals'] : $order_data['order_total'] ;
foreach ($orderTotals as $totals) {
if ($totals['code'] == 'shipping') {
$deliveryCost = $totals['value'];
}
}
$order['createdAt'] = $order_data['date_added'];
if ($this->settings[$this->moduleTitle . '_apiversion'] != 'v5') {
$order['paymentType'] = $payment_code;
}
$country = (isset($order_data['shipping_country'])) ? $order_data['shipping_country'] : '' ;
$order['delivery'] = array(
'code' => isset($delivery_code) ? $delivery_code : '',
'cost' => $deliveryCost,
'address' => array(
'countryIso' => $order_data['shipping_iso_code_2'],
'index' => $order_data['shipping_postcode'],
'city' => $order_data['shipping_city'],
'region' => $order_data['shipping_zone'],
'text' => implode(', ', array(
$order_data['shipping_postcode'],
$country,
$order_data['shipping_city'],
$order_data['shipping_address_1'],
$order_data['shipping_address_2']
))
)
);
$orderProducts = isset($order_data['products']) ? $order_data['products'] : $order_data['order_product'];
$offerOptions = array('select', 'radio');
foreach ($orderProducts as $product) {
$offerId = '';
if (!empty($product['option'])) {
$options = array();
$productOptions = $this->model_catalog_product->getProductOptions($product['product_id']);
foreach ($product['option'] as $option) {
if ($option['type'] == 'checkbox') {
$properties[] = array(
'code' => $option['product_option_value_id'],
'name' => $option['name'],
'value' => $option['value']
);
}
if (!in_array($option['type'], $offerOptions)) continue;
foreach($productOptions as $productOption) {
if($productOption['product_option_id'] = $option['product_option_id']) {
foreach($productOption['product_option_value'] as $productOptionValue) {
if($productOptionValue['product_option_value_id'] == $option['product_option_value_id']) {
$options[$option['product_option_id']] = $productOptionValue['option_value_id'];
}
}
}
}
}
ksort($options);
$offerId = array();
foreach($options as $optionKey => $optionValue) {
$offerId[] = $optionKey.'-'.$optionValue;
}
$offerId = implode('_', $offerId);
}
if ($this->settings[$this->moduleTitle . '_apiversion'] != 'v3') {
$item = array(
'offer' => array(
'externalId' => !empty($offerId) ? $product['product_id'].'#'.$offerId : $product['product_id']
),
'productName' => $product['name'],
'initialPrice' => $product['price'],
'quantity' => $product['quantity'],
);
} else {
$item = array(
'productName' => $product['name'],
'initialPrice' => $product['price'],
'quantity' => $product['quantity'],
'productId' => !empty($offerId) ? $product['product_id'].'#'.$offerId : $product['product_id']
);
}
if (isset($properties)) $item['properties'] = $properties;
$order['items'][] = $item;
}
if (isset($order_data['order_status_id']) && $order_data['order_status_id'] > 0) {
$order['status'] = $this->settings[$this->moduleTitle . '_status'][$order_data['order_status_id']];
}
if ($this->settings[$this->moduleTitle . '_apiversion'] == 'v5') {
if ($payment_code) {
$payment = array(
'externalId' => $order_data['order_id'],
'type' => $payment_code
);
$order['payments'][] = $payment;
}
}
if (isset($this->settings[$this->moduleTitle . '_custom_field']) && $order_data['custom_field']) {
$customFields = json_decode($order_data['custom_field']);
foreach ($customFields as $key => $value) {
if (isset($this->settings[$this->moduleTitle . '_custom_field']['o_' . $key])) {
$customFieldsToCrm[$this->settings[$this->moduleTitle . '_custom_field']['o_' . $key]] = $value;
}
}
if (isset($customFieldsToCrm)) {
$order['customFields'] = $customFieldsToCrm;
}
}
return $order;
}
/**
* @return mixed
*/
public static function getLastResponse()
{ {
return self::$lastRepsonse; $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

@ -0,0 +1,9 @@
<?php
class ModelExtensionRetailcrmProducts extends Model {
public function getProductOptions($product_id) {
$this->load->model('catalog/product_option');
return $this->model_catalog_product_option->getProductOptionsByProductId($product_id);
}
}

View File

@ -1,5 +1,5 @@
.retailcrm_unit {margin-bottom: 10px;} .retailcrm_unit {margin-bottom: 10px;}
.retailcrm_unit input {width: 30%;} .retailcrm_unit input {width: 60%;}
.checkbox input{width: auto;} .checkbox input{width: auto;}
.retailcrm_unit input[type=checkbox] {width: 13px;} .retailcrm_unit input[type=checkbox] {width: 13px;}
.retailcrm_unit select {max-width: 500px;} .retailcrm_unit select {max-width: 500px;}

View File

@ -2,19 +2,19 @@
<div id="content"> <div id="content">
<div class="page-header"> <div class="page-header">
<div class="container-fluid"> <div class="container-fluid">
<div class="pull-right"> <div class="float-right">
{% if export_file %} {% if export_file %}
<button type="button" id="export" data-toggle="tooltip" title="{{ text_button_export }}" class="btn btn-success"><i class="fa fa-download"></i></button> <button type="button" id="export" data-toggle="tooltip" title="{{ text_button_export }}" class="btn btn-success"><i class="fa fa-download"></i></button>
{% endif %} {% endif %}
<button type="button" id="icml" data-toggle="tooltip" title="{{ text_button_catalog }}" class="btn btn-success"><i class="fa fa-file-text-o"></i></button> <button type="button" id="icml" data-toggle="tooltip" title="{{ text_button_catalog }}" class="btn btn-success"><i class="fa fa-file"></i></button>
<button type="submit" form="form-module" data-toggle="tooltip" title="{{ button_save }}" class="btn btn-primary"><i class="fa fa-save"></i></button> <button type="submit" form="form-module" data-toggle="tooltip" title="{{ button_save }}" class="btn btn-primary"><i class="fa fa-save"></i></button>
<a href="{{ cancel }}" data-toggle="tooltip" title="{{ button_cancel }}" class="btn btn-default"><i class="fa fa-reply"></i></a></div> <a href="{{ cancel }}" data-toggle="tooltip" title="{{ button_cancel }}" class="btn btn-light"><i class="fa fa-reply"></i></a></div>
<h1>{{ heading_title }}</h1> <h1>{{ heading_title }}</h1>
<ul class="breadcrumb"> <ol class="breadcrumb">
{% for breadcrumb in breadcrumbs %} {% for breadcrumb in breadcrumbs %}
<li><a href="{{ breadcrumb.href }}">{{ breadcrumb.text }}</a></li> <li class="breadcrumb-item"><a href="{{ breadcrumb.href }}">{{ breadcrumb.text }}</a></li>
{% endfor %} {% endfor %}
</ul> </ol>
</div> </div>
</div> </div>
<div class="container-fluid"> <div class="container-fluid">
@ -35,14 +35,14 @@
<div class="panel-body"> <div class="panel-body">
<form action="{{ action }}" method="post" enctype="multipart/form-data" id="form-module" class="form-horizontal"> <form action="{{ action }}" method="post" enctype="multipart/form-data" id="form-module" class="form-horizontal">
<ul class="nav nav-tabs"> <ul class="nav nav-tabs">
<li class="active"><a href="#tab-general" data-toggle="tab">{{ general_tab_text }}</a></li> <li class="nav-item"><a href="#tab-general" data-toggle="tab" class="nav-link active show">{{ general_tab_text }}</a></li>
{% if saved_settings.module_retailcrm_apikey is defined and saved_settings.module_retailcrm_apikey and saved_settings.module_retailcrm_url is defined and saved_settings.module_retailcrm_url %} {% if saved_settings.module_retailcrm_apikey is defined and saved_settings.module_retailcrm_apikey and saved_settings.module_retailcrm_url is defined and saved_settings.module_retailcrm_url %}
<li><a href="#tab-references" data-toggle="tab">{{ references_tab_text }}</a></li> <li class="nav-item"><a href="#tab-references" data-toggle="tab" class="nav-link">{{ references_tab_text }}</a></li>
<li><a href="#tab-collector" data-toggle="tab">{{ collector_tab_text }}</a></li> <li class="nav-item"><a href="#tab-collector" data-toggle="tab" class="nav-link">{{ collector_tab_text }}</a></li>
{% if saved_settings.module_retailcrm_apiversion == 'v5' %} {% if saved_settings.module_retailcrm_apiversion == 'v5' %}
<li><a href="#tab-custom_fields" data-toggle="tab"> {{ custom_fields_tab_text }} </a></li> <li><a href="#tab-custom_fields" data-toggle="tab" class="nav-link"> {{ custom_fields_tab_text }} </a></li>
{% endif %} {% endif %}
<li><a href="#tab-logs" data-toggle="tab">{{ logs_tab_text }}</a></li> <li class="nav-item"><a href="#tab-logs" data-toggle="tab" class="nav-link">{{ logs_tab_text }}</a></li>
{% endif %} {% endif %}
</ul> </ul>
<div class="tab-content"> <div class="tab-content">
@ -50,8 +50,8 @@
<input type="hidden" name="module_retailcrm_status" value="1"> <input type="hidden" name="module_retailcrm_status" value="1">
<fieldset> <fieldset>
<legend>{{ retailcrm_base_settings }}</legend> <legend>{{ retailcrm_base_settings }}</legend>
<div class="form-group retailcrm_unit"> <div class="row form-group retailcrm_unit">
<label class="col-sm-2 control-label" for="retailcrm_url">{{ retailcrm_apiversion }}</label> <label class="col-sm-2 col-form-label" for="retailcrm_url">{{ retailcrm_apiversion }}</label>
<div class="col-lg-1 col-md-2 col-sm-2"> <div class="col-lg-1 col-md-2 col-sm-2">
<select name="module_retailcrm_apiversion" class="form-control"> <select name="module_retailcrm_apiversion" class="form-control">
{% for version in api_versions %} {% for version in api_versions %}
@ -60,14 +60,14 @@
</select> </select>
</div> </div>
</div> </div>
<div class="form-group retailcrm_unit"> <div class="row form-group retailcrm_unit">
<label class="col-sm-2 control-label" for="retailcrm_url">{{ retailcrm_url }}</label> <label class="col-sm-2 col-form-label" for="retailcrm_url">{{ retailcrm_url }}</label>
<div class="col-lg-4 col-md-6 col-sm-10"> <div class="col-lg-4 col-md-6 col-sm-10">
<input class="form-control" id="retailcrm_url" type="text" name="module_retailcrm_url" value="{% if saved_settings.module_retailcrm_url is defined %}{{ saved_settings.module_retailcrm_url }}{% endif %}"> <input class="form-control" id="retailcrm_url" type="text" name="module_retailcrm_url" value="{% if saved_settings.module_retailcrm_url is defined %}{{ saved_settings.module_retailcrm_url }}{% endif %}">
</div> </div>
</div> </div>
<div class="form-group retailcrm_unit"> <div class="row form-group retailcrm_unit">
<label class="col-sm-2 control-label" for="retailcrm_apikey">{{ retailcrm_apikey }}</label> <label class="col-sm-2 col-form-label" for="retailcrm_apikey">{{ retailcrm_apikey }}</label>
<div class="col-lg-4 col-md-6 col-sm-10"> <div class="col-lg-4 col-md-6 col-sm-10">
<input class="form-control" id="retailcrm_apikey" type="text" name="module_retailcrm_apikey" value="{% if saved_settings.module_retailcrm_apikey is defined %}{{ saved_settings.module_retailcrm_apikey }}{% endif %}"> <input class="form-control" id="retailcrm_apikey" type="text" name="module_retailcrm_apikey" value="{% if saved_settings.module_retailcrm_apikey is defined %}{{ saved_settings.module_retailcrm_apikey }}{% endif %}">
</div> </div>
@ -75,10 +75,10 @@
</fieldset> </fieldset>
<fieldset> <fieldset>
<legend>{{ retailcrm_countries_settings }}</legend> <legend>{{ retailcrm_countries_settings }}</legend>
<div class="form-group retailcrm_unit"> <div class="row form-group retailcrm_unit">
<label class="col-sm-2 control-label"></label> <label class="col-sm-2 col-form-label">{{ retailcrm_countries_settings }}</label>
<div class="col-lg-4 col-md-6 col-sm-10"> <div class="col-lg-4 col-md-6 col-sm-10">
<div class="well well-sm" style="height: 150px; overflow: auto;"> <div class="form-control well well-sm" style="height: 150px; overflow: auto;">
{% for country in countries %} {% for country in countries %}
<div class="checkbox"> <div class="checkbox">
<label> <label>
@ -99,8 +99,8 @@
{% else %} {% else %}
<fieldset> <fieldset>
<legend>{{ retailcrm_upload_order }}</legend> <legend>{{ retailcrm_upload_order }}</legend>
<div class="form-group retailcrm_unit"> <div class="row form-group retailcrm_unit">
<label class="col-sm-2 control-label">{{ text_button_export_order }} № </label> <label class="col-sm-2 col-form-label">{{ text_button_export_order }} № </label>
<div class="col-sm-10"> <div class="col-sm-10">
<div class="row"> <div class="row">
<div class="col-lg-3 col-md-6 col-sm-6"> <div class="col-lg-3 col-md-6 col-sm-6">
@ -116,8 +116,8 @@
{% if saved_settings.module_retailcrm_apiversion is defined and saved_settings.module_retailcrm_apiversion != 'v3' %} {% if saved_settings.module_retailcrm_apiversion is defined and saved_settings.module_retailcrm_apiversion != 'v3' %}
<fieldset> <fieldset>
<legend>{{ special_price_settings }}</legend> <legend>{{ special_price_settings }}</legend>
<div class="form-group retailcrm_unit"> <div class="row form-group retailcrm_unit">
<label class="col-sm-2 control-label">{{ special_price_settings }}</label> <label class="col-sm-2 col-form-label" for="module_retailcrm_special">{{ special_price_settings }}</label>
<div class="col-md-4 col-sm-10"> <div class="col-md-4 col-sm-10">
<select id="module_retailcrm_special" name="module_retailcrm_special" class="form-control"> <select id="module_retailcrm_special" name="module_retailcrm_special" class="form-control">
{% for priceType in priceTypes %} {% for priceType in priceTypes %}
@ -134,23 +134,49 @@
{% endif %} {% endif %}
<fieldset> <fieldset>
<legend>{{ order_number }}</legend> <legend>{{ order_number }}</legend>
<div class="form-group"> <div class="row form-group">
<label class="col-sm-2 control-label" class="col-sm-2 control-label" for="module_retailcrm_order_number">{{ text_order_number }}</label> <label class="col-sm-2 col-form-label" class="col-sm-2 col-form-label" for="module_retailcrm_order_number">{{ text_order_number }}</label>
<div class="col-sm-10"> <div class="col-sm-10">
<label class="control-label" class="radio-inline"> <div class="btn-group btn-group-toggle" data-toggle="buttons">
<input type="radio" name="module_retailcrm_order_number" value="1" {% if saved_settings.module_retailcrm_order_number is defined and saved_settings.module_retailcrm_order_number == 1 %}
{% if saved_settings.module_retailcrm_order_number is defined and saved_settings.module_retailcrm_order_number == 1 %} {% set check_order_number = true %}
checked {% endif %}
{% endif %} /> <label class="btn btn-outline-secondary{% if check_order_number == true %} active{% endif %}">
{{ text_yes }} <input type="radio" name="module_retailcrm_order_number" value="1" {% if check_order_number == true %}checked{% endif %}/>
</label> {{ text_yes }}
<label class="control-label" class="radio-inline"> </label>
<input type="radio" name="module_retailcrm_order_number" value="0" {% if saved_settings.module_retailcrm_order_number is not defined or saved_settings.module_retailcrm_order_number == 0 %}
{% if saved_settings.module_retailcrm_order_number is not defined or saved_settings.module_retailcrm_order_number == 0 %} {%set check_order_number = false %}
checked {% endif %}
{% endif %} /> <label class="btn btn-outline-secondary{% if check_order_number == false %} active{% endif %}">
{{ text_no }} <input type="radio" name="module_retailcrm_order_number" value="0" {% if check_order_number == false %}checked{% endif %}/>
</label> {{ text_no }}
</label>
</div>
</div>
</div>
</fieldset>
<fieldset>
<legend>{{ debug }}</legend>
<div class="row form-group">
<label class="col-sm-2 col-form-label" class="col-sm-2 col-form-label" for="module_retailcrm_debug_mode">{{ text_debug }}</label>
<div class="col-sm-10">
<div class="btn-group btn-group-toggle" data-toggle="buttons">
{% if saved_settings.module_retailcrm_debug_mode is defined and saved_settings.module_retailcrm_debug_mode == 1 %}
{% set debug_mode = true %}
{% endif %}
<label class="btn btn-outline-secondary{% if debug_mode == true %} active{% endif %}">
<input type="radio" name="module_retailcrm_debug_mode" value="1"{% if debug_mode == true %} checked{% endif %}>
{{ text_yes }}
</label>
{% if saved_settings.module_retailcrm_debug_mode is not defined or saved_settings.module_retailcrm_debug_mode == 0 %}
{% set debug_mode = false %}
{% endif %}
<label class="btn btn-outline-secondary{% if debug_mode == false %} active{% endif %}">
<input type="radio" name="module_retailcrm_debug_mode" value="0"{% if debug_mode == false %} checked{% endif %}>
{{ text_no }}
</label>
</div>
</div> </div>
</div> </div>
</fieldset> </fieldset>
@ -158,8 +184,8 @@
<div class="tab-pane" id="tab-references"> <div class="tab-pane" id="tab-references">
<fieldset> <fieldset>
<legend>{{ retailcrm_dict_settings }}</legend> <legend>{{ retailcrm_dict_settings }}</legend>
<div class="form-group"> <div class="row form-group">
<label class="col-sm-2 control-label"> {{ retailcrm_dict_delivery }}</label> <label class="col-sm-2 col-form-label"> {{ retailcrm_dict_delivery }}</label>
<div class="col-sm-10"> <div class="col-sm-10">
<div class="row"> <div class="row">
{% if delivery.opencart is not empty %} {% if delivery.opencart is not empty %}
@ -168,9 +194,9 @@
<div class="pm">{{ value.title ~ ':' }}</div> <div class="pm">{{ value.title ~ ':' }}</div>
{% for key, val in value %} {% for key, val in value %}
{% if key != 'title' %} {% if key != 'title' %}
<div class="form-group retailcrm_unit"> <div class="row form-group retailcrm_unit">
<div class="col-lg-4 col-md-6 col-sm-6"> <div class="col-lg-4 col-md-6 col-sm-6">
<select id="retailcrm_delivery_{{ val.code }}" name="module_retailcrm_delivery[{{ val.code }}]" > <select id="retailcrm_delivery_{{ val.code }}" name="module_retailcrm_delivery[{{ val.code }}]" class="form-control">
{% for k, v in delivery.retailcrm %} {% for k, v in delivery.retailcrm %}
<option value="{{ v.code }}" {% if saved_settings.module_retailcrm_delivery[key] is defined and v.code == saved_settings.module_retailcrm_delivery[key] %} selected="selected" {% endif %}> <option value="{{ v.code }}" {% if saved_settings.module_retailcrm_delivery[key] is defined and v.code == saved_settings.module_retailcrm_delivery[key] %} selected="selected" {% endif %}>
{{ v.name }} {{ v.name }}
@ -179,7 +205,7 @@
</select> </select>
</div> </div>
<div class="col-lg-4 col-md-6 col-sm-6"> <div class="col-lg-4 col-md-6 col-sm-6">
<label class="col-sm-2 control-label" for="retailcrm_pm_{{ val.code }}">{{ val.title }}</label> <label class="col-form-label" for="retailcrm_pm_{{ val.code }}">{{ val.title }}</label>
</div> </div>
</div> </div>
{% endif %} {% endif %}
@ -195,8 +221,8 @@
</div> </div>
</div> </div>
</div> </div>
<div class="form-group"> <div class="row form-group">
<label class="col-sm-2 control-label">{{ retailcrm_dict_status }}</label> <label class="col-sm-2 col-form-label">{{ retailcrm_dict_status }}</label>
<div class="col-sm-10"> <div class="col-sm-10">
{% for status in statuses.opencart %} {% for status in statuses.opencart %}
{% set uid = status.order_status_id %} {% set uid = status.order_status_id %}
@ -211,14 +237,14 @@
</select> </select>
</div> </div>
<div class="col-lg-4 col-md-6 col-sm-6"> <div class="col-lg-4 col-md-6 col-sm-6">
<label class="control-label" for="retailcrm_status_{{ status.order_status_id }} ">{{ status.name }}</label> <label class="col-form-label" for="retailcrm_status_{{ status.order_status_id }} ">{{ status.name }}</label>
</div> </div>
</div> </div>
{% endfor %} {% endfor %}
</div> </div>
</div> </div>
<div class="form-group"> <div class="row form-group">
<label class="col-sm-2 control-label">{{ retailcrm_dict_payment }}</label> <label class="col-sm-2 col-form-label">{{ retailcrm_dict_payment }}</label>
<div class="col-sm-10"> <div class="col-sm-10">
{% for key, value in payments.opencart %} {% for key, value in payments.opencart %}
<div class="row retailcrm_unit"> <div class="row retailcrm_unit">
@ -232,14 +258,14 @@
</select> </select>
</div> </div>
<div class="col-lg-4 col-md-6 col-sm-6"> <div class="col-lg-4 col-md-6 col-sm-6">
<label class="control-label" for="retailcrm_payment_{{ key }}">{{ value }}</label> <label class="col-form-label" for="retailcrm_payment_{{ key }}">{{ value }}</label>
</div> </div>
</div> </div>
{% endfor %} {% endfor %}
</div> </div>
</div> </div>
<div class="form-group"> <div class="row form-group">
<label class="col-sm-2 control-label">{{ retailcrm_dict_default }}</label> <label class="col-sm-2 col-form-label">{{ retailcrm_dict_default }}</label>
<div class="col-sm-10"> <div class="col-sm-10">
<div class="row"> <div class="row">
<div class="retailcrm_unit col-sm-12"> <div class="retailcrm_unit col-sm-12">
@ -254,7 +280,7 @@
</select> </select>
</div> </div>
<div class="col-lg-4 col-md-6 col-sm-6"> <div class="col-lg-4 col-md-6 col-sm-6">
<label class="col-sm-2 control-label" for="module_retailcrm_default_payment">{{ text_payment }}</label> <label class="col-sm-2 col-form-label" for="module_retailcrm_default_payment">{{ text_payment }}</label>
</div> </div>
</div> </div>
</div> </div>
@ -276,15 +302,15 @@
</select> </select>
</div> </div>
<div class="col-lg-4 col-md-6 col-sm-6"> <div class="col-lg-4 col-md-6 col-sm-6">
<label class="col-sm-2 control-label" for="module_retailcrm_default_shipping">{{ text_shipping }}</label> <label class="col-sm-2 col-form-label" for="module_retailcrm_default_shipping">{{ text_shipping }}</label>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
<div class="form-group"> <div class="row form-group">
<label class="col-sm-2 control-label">{{ retailcrm_missing_status }}</label> <label class="col-sm-2 col-form-label">{{ retailcrm_missing_status }}</label>
<div class="col-sm-10"> <div class="col-sm-10">
<div class="row"> <div class="row">
<div class="col-lg-4 col-md-6 col-sm-6"> <div class="col-lg-4 col-md-6 col-sm-6">
@ -307,84 +333,102 @@
<div class="tab-pane" id="tab-collector"> <div class="tab-pane" id="tab-collector">
<fieldset> <fieldset>
<legend>{{ daemon_collector }}</legend> <legend>{{ daemon_collector }}</legend>
<div class="form-group"> <div class="row form-group">
<label class="col-sm-2 control-label" for="retailcrm_collector_active" class="col-md-4">{{ text_collector_activity }}</label> <label class="col-sm-2 col-form-label" for="retailcrm_collector_active" class="col-md-4">{{ text_collector_activity }}</label>
<div class="col-sm-10"> <div class="col-sm-10">
<label class="control-label" class="radio-inline"> <div class="btn-group btn-group-toggle" data-toggle="buttons">
<input type="radio" name="module_retailcrm_collector_active" value="1" {% if saved_settings.module_retailcrm_collector_active is defined and {% if saved_settings.module_retailcrm_collector_active is defined
saved_settings.module_retailcrm_collector_active == 1 %} {{ 'checked' }} and saved_settings.module_retailcrm_collector_active == 1 %}
{% endif %}> {% set collector_active = true %}
{{ text_yes }} {% endif %}
</label> <label class="btn btn-outline-secondary{% if collector_active == true %} active{% endif %}">
<label class="control-label" class="radio-inline"> <input type="radio" name="module_retailcrm_collector_active" value="1"{% if collector_active == true %} checked{% endif %}>
<input type="radio" name="module_retailcrm_collector_active" value="0" {% if not saved_settings.module_retailcrm_collector_active or {{ text_yes }}
saved_settings.module_retailcrm_collector_active == 0 %} {{ 'checked' }} </label>
{% endif %}> {% if not saved_settings.module_retailcrm_collector_active
{{ text_no }} or saved_settings.module_retailcrm_collector_active == 0 %}
</label> {% set collector_active = false %}
{% endif %}
<label class="btn btn-outline-secondary{% if collector_active == false %} active{% endif %}">
<input type="radio" name="module_retailcrm_collector_active" value="0"{% if collector_active == false %} checked{% endif %}>
{{ text_no }}
</label>
</div>
</div> </div>
</div> </div>
<div class="form-group"> <div class="row form-group">
<label class="col-sm-2 control-label" for="retailcrm_collector" class="col-md-4">{{ collector_site_key }}</label> <label class="col-sm-2 col-form-label" for="retailcrm_collector" class="col-md-4">{{ collector_site_key }}</label>
<div class="col-sm-4"> <div class="col-sm-4">
<input class="form-control" id="retailcrm_collector_site_key" type="text" name="module_retailcrm_collector[site_key]" value="{% if saved_settings.module_retailcrm_collector.site_key is defined %}{{ saved_settings.module_retailcrm_collector.site_key }}{% endif %}"> <input class="form-control" id="retailcrm_collector_site_key" type="text" name="module_retailcrm_collector[site_key]" value="{% if saved_settings.module_retailcrm_collector.site_key is defined %}{{ saved_settings.module_retailcrm_collector.site_key }}{% endif %}">
</div> </div>
</div> </div>
<div class="form-group"> <div class="row form-group">
<label class="col-sm-2 control-label" for="retailcrm_collector" class="col-md-4">{{ text_collector_form_capture }}</label> <label class="col-sm-2 col-form-label" for="retailcrm_collector" class="col-md-4">{{ text_collector_form_capture }}</label>
<div class="col-sm-10"> <div class="col-sm-10">
<label class="control-label" class="radio-inline"> <div class="btn-group btn-group-toggle" data-toggle="buttons">
<input type="radio" name="module_retailcrm_collector[form_capture]" value="1" {% if saved_settings.module_retailcrm_collector.form_capture is defined and {% if saved_settings.module_retailcrm_collector.form_capture is defined
saved_settings.module_retailcrm_collector.form_capture == 1 %} {{ 'checked' }} and saved_settings.module_retailcrm_collector.form_capture == 1 %}
{% endif %}> {% set form_capture = true %}
{{ text_yes }} {% endif %}
</label> <label class="btn btn-outline-secondary{% if form_capture == true %} active{% endif %}">
<label class="control-label" class="radio-inline"> <input type="radio" name="module_retailcrm_collector[form_capture]" value="1"{% if form_capture == true %} checked{% endif %}>
<input type="radio" name="module_retailcrm_collector[form_capture]" value="0" {% if saved_settings.module_retailcrm_collector.form_capture is not defined or {{ text_yes }}
saved_settings.module_retailcrm_collector.form_capture == 0 %} {{ 'checked' }} </label>
{% endif %}> {% if saved_settings.module_retailcrm_collector.form_capture is not defined
{{ text_no }} or saved_settings.module_retailcrm_collector.form_capture == 0 %}
</label> {% set form_capture = false %}
{% endif %}
<label class="btn btn-outline-secondary{% if form_capture == false %} active{% endif %}">
<input type="radio" name="module_retailcrm_collector[form_capture]" value="0"{% if form_capture == false %} checked{% endif %}>
{{ text_no }}
</label>
</div>
</div> </div>
</div> </div>
<div class="form-group"> <div class="row form-group">
<label class="col-sm-2 control-label" for="module_retailcrm_collector" class="col-md-4">{{ text_collector_period }}</label> <label class="col-sm-2 col-form-label" for="module_retailcrm_collector" class="col-md-4">{{ text_collector_period }}</label>
<div class="col-sm-2"> <div class="col-sm-2">
<input class="form-control" id="module_retailcrm_collector_period" type="text" name="module_retailcrm_collector[period]" value="{% if saved_settings.module_retailcrm_collector.period is defined %}{{ saved_settings.module_retailcrm_collector.period }}{% endif %}"> <input class="form-control" id="module_retailcrm_collector_period" type="text" name="module_retailcrm_collector[period]" value="{% if saved_settings.module_retailcrm_collector.period is defined %}{{ saved_settings.module_retailcrm_collector.period }}{% endif %}">
</div> </div>
</div> </div>
<div class="form-group"> <div class="row form-group">
<label class="col-sm-2 control-label" for="module_retailcrm_collector" class="col-md-4">{{ text_label_promo }}</label> <label class="col-sm-2 col-form-label" for="module_retailcrm_collector" class="col-md-4">{{ text_label_promo }}</label>
<div class="col-sm-4"> <div class="col-sm-4">
<input class="form-control" id="module_retailcrm_collector[]" type="text" name="module_retailcrm_collector[label_promo]" value="{% if saved_settings.module_retailcrm_collector.label_promo is defined %}{{ saved_settings.module_retailcrm_collector.label_promo }}{% endif %}"> <input class="form-control" id="module_retailcrm_collector[]" type="text" name="module_retailcrm_collector[label_promo]" value="{% if saved_settings.module_retailcrm_collector.label_promo is defined %}{{ saved_settings.module_retailcrm_collector.label_promo }}{% endif %}">
</div> </div>
</div> </div>
<div class="form-group"> <div class="row form-group">
<label class="col-sm-2 control-label" for="module_retailcrm_collector" class="col-md-4">{{ text_label_send }}</label> <label class="col-sm-2 col-form-label" for="module_retailcrm_collector" class="col-md-4">{{ text_label_send }}</label>
<div class="col-sm-4"> <div class="col-sm-4">
<input class="form-control" id="module_retailcrm_collector_label_send" type="text" name="module_retailcrm_collector[label_send]" value="{% if saved_settings.module_retailcrm_collector.label_send is defined %}{{ saved_settings.module_retailcrm_collector.label_send }}{% endif %}"> <input class="form-control" id="module_retailcrm_collector_label_send" type="text" name="module_retailcrm_collector[label_send]" value="{% if saved_settings.module_retailcrm_collector.label_send is defined %}{{ saved_settings.module_retailcrm_collector.label_send }}{% endif %}">
</div> </div>
</div> </div>
<div class="form-group"> <div class="row form-group">
<label class="col-sm-2 control-label" for="module_retailcrm_collector" class="col-md-4">{{ collector_custom_text }}</label> <label class="col-sm-2 col-form-label" for="module_retailcrm_collector" class="col-md-4">{{ collector_custom_text }}</label>
<div class="col-sm-10"> <div class="col-sm-10">
<label class="radio-inline"> <div class="btn-group btn-group-toggle" data-toggle="buttons">
<input type="radio" name="module_retailcrm_collector[custom_form]" value="1" {% if saved_settings.module_retailcrm_collector.custom_form is defined and {% if saved_settings.module_retailcrm_collector.custom_form is defined
saved_settings.module_retailcrm_collector.custom_form == 1 %} {{ 'checked' }} and saved_settings.module_retailcrm_collector.custom_form == 1 %}
{% endif %}> {% set custom_form = true %}
{{ text_yes }} {% endif %}
</label> <label class="btn btn-outline-secondary{% if custom_form == true %} active{% endif %}">
<label class="radio-inline"> <input type="radio" name="module_retailcrm_collector[custom_form]" value="1"{% if custom_form == true %} checked{% endif %}>
<input type="radio" name="module_retailcrm_collector[custom_form]" value="0" {% if saved_settings.module_retailcrm_collector.custom_form is not defined or {{ text_yes }}
saved_settings.module_retailcrm_collector.custom_form == 0 %} {{ 'checked' }} </label>
{% endif %}> {% if saved_settings.module_retailcrm_collector.custom_form is not defined
{{ text_no }} or saved_settings.module_retailcrm_collector.custom_form == 0 %}
</label> {% set custom_form = false %}
{% endif %}
<label class="btn btn-outline-secondary{% if custom_form == false %} active{% endif %}">
<input type="radio" name="module_retailcrm_collector[custom_form]" value="0"{% if custom_form == false %} checked{% endif %}>
{{ text_no }}
</label>
</div>
</div> </div>
</div> </div>
{% for field, label in collectorFields %} {% for field, label in collectorFields %}
<div class="form-group"> <div class="row form-group">
<label class="col-sm-2 control-label" for="retailcrm_collector">{{ label }}</label> <label class="col-sm-2 col-form-label" for="retailcrm_collector">{{ label }}</label>
<div class="col-sm-10"> <div class="col-sm-10">
<div class="row"> <div class="row">
<div class="col-md-4 col-sm-6"> <div class="col-md-4 col-sm-6">
@ -405,25 +449,31 @@
<fieldset> <fieldset>
<legend>{{ retailcrm_dict_custom_fields }}</legend> <legend>{{ retailcrm_dict_custom_fields }}</legend>
{% if customFields.retailcrm is not empty and customFields.opencart is not empty %} {% if customFields.retailcrm is not empty and customFields.opencart is not empty %}
<div class="form-group"> <div class="row form-group">
<label class="col-sm-2 control-label" for="retailcrm_custom_field_active">{{ text_custom_field_activity }}</label> <label class="col-sm-2 col-form-label" for="retailcrm_custom_field_active">{{ text_custom_field_activity }}</label>
<div class="col-sm-10"> <div class="col-sm-10">
<label class="radio-inline"> <div class="btn-group btn-group-toggle" data-toggle="buttons">
<input type="radio" name="module_retailcrm_custom_field_active" value="1" {% if saved_settings.module_retailcrm_custom_field_active is defined and {% if saved_settings.module_retailcrm_custom_field_active is defined
saved_settings.module_retailcrm_custom_field_active == 1 %} and saved_settings.module_retailcrm_custom_field_active == 1 %}
checked {% endif %} > {% set custom_field_active = true %}
{{ text_yes }} {% endif %}
</label> <label class="btn btn-outline-secondary{% if custom_field_active == true %} active{% endif %}">
<label class="radio-inline"> <input type="radio" name="module_retailcrm_custom_field_active" value="1"{% if custom_field_active == true %} checked{% endif %}>
<input type="radio" name="module_retailcrm_custom_field_active" value="0" {% if saved_settings.module_retailcrm_custom_field_active is not defined or {{ text_yes }}
saved_settings.module_retailcrm_custom_field_active == 0 %} </label>
checked {% endif %} > {% if saved_settings.module_retailcrm_custom_field_active is not defined
{{ text_no }} or saved_settings.module_retailcrm_custom_field_active == 0 %}
</label> {% set custom_field_active = false %}
{% endif %}
<label class="btn btn-outline-secondary{% if custom_field_active == false %} active{% endif %}">
<input type="radio" name="module_retailcrm_custom_field_active" value="0"{% if custom_field_active == false %} checked{% endif %}>
{{ text_no }}
</label>
</div>
</div> </div>
</div> </div>
<div class="form-group"> <div class="row form-group">
<label class="col-sm-2 control-label">{{ text_customers_custom_fields }}</label> <label class="col-sm-2 col-form-label">{{ text_customers_custom_fields }}</label>
<div class="col-sm-10"> <div class="col-sm-10">
<div class="row"> <div class="row">
{% for customField in customFields.opencart %} {% for customField in customFields.opencart %}
@ -446,8 +496,8 @@
</div> </div>
</div> </div>
</div> </div>
<div class="form-group"> <div class="row form-group">
<label class="col-sm-2 control-label">{{ text_orders_custom_fields }}</label> <label class="col-sm-2 col-form-label">{{ text_orders_custom_fields }}</label>
<div class="col-sm-10"> <div class="col-sm-10">
<div class="row"> <div class="row">
{% for customField in customFields.opencart %} {% for customField in customFields.opencart %}

View File

@ -12,12 +12,14 @@ class ControllerApiRetailcrm extends Controller
$this->load->model('localisation/country'); $this->load->model('localisation/country');
$this->load->model('setting/setting'); $this->load->model('setting/setting');
$this->load->library('retailcrm/retailcrm'); $this->load->library('retailcrm/retailcrm');
$moduleTitle = $this->retailcrm->getModuleTitle(); $setting = $this->model_setting_setting->getSetting(\Retailcrm\Retailcrm::MODULE);
$setting = $this->model_setting_setting->getSetting($moduleTitle);
$response = array(); $response = array();
if (isset($setting[$moduleTitle . '_country']) && $setting[$moduleTitle . '_country']) { if (
foreach ($setting[$moduleTitle . '_country'] as $country) { isset($setting[\Retailcrm\Retailcrm::MODULE . '_country'])
&& $setting[\Retailcrm\Retailcrm::MODULE . '_country']
) {
foreach ($setting[\Retailcrm\Retailcrm::MODULE . '_country'] as $country) {
$response = array_merge($response, $this->getDeliveryTypesByZones($country)); $response = array_merge($response, $this->getDeliveryTypesByZones($country));
} }
} }
@ -139,17 +141,9 @@ class ControllerApiRetailcrm extends Controller
return array('error' => 'Not found api key'); return array('error' => 'Not found api key');
} }
if (isset($this->request->get['key']) if (isset($this->request->get['key']) && !empty($this->request->get['key'])) {
&& !empty($this->request->get['key']) $this->load->model('extension/retailcrm/api');
) { $api = $this->model_extension_retailcrm_api->login($this->request->get['username'], $this->request->get['key']);
$this->load->model('account/api');
if ( version_compare(VERSION, '3.0', '<')) {
$api = $this->model_account_api->getApiByKey($this->request->get['key']);
} else {
$this->load->model('extension/retailcrm/api');
$api = $this->model_extension_retailcrm_api->login($this->request->get['username'], $this->request->get['key']);
}
if (!empty($api)) { if (!empty($api)) {
return $api; return $api;
@ -161,14 +155,7 @@ class ControllerApiRetailcrm extends Controller
private function loadModels() private function loadModels()
{ {
if (version_compare(VERSION, '3.0', '<')) { $this->load->model('setting/extension');
$this->load->model('extension/extension'); $this->modelExtension = 'setting_extension';
$this->modelExtension = 'extension_extension';
} else {
$this->load->model('setting/extension');
$this->modelExtension = 'setting_extension';
}
} }
} }

View File

@ -26,9 +26,11 @@ class ControllerExtensionModuleRetailcrm extends Controller {
} }
$this->load->library('retailcrm/retailcrm'); $this->load->library('retailcrm/retailcrm');
$data = $args[0];
$data['order_id'] = $output;
$retailcrm_order = $this->retailcrm->createObject(\Retailcrm\Order::class);
$retailcrm_order = $this->retailcrm->getObject('Order'); $retailcrm_order->prepare($data);
$retailcrm_order->prepare($args[0]);
$retailcrm_order->setField('externalId', $output); $retailcrm_order->setField('externalId', $output);
$retailcrm_order->create($this->retailcrm->getApiClient()); $retailcrm_order->create($this->retailcrm->getApiClient());
@ -49,47 +51,20 @@ class ControllerExtensionModuleRetailcrm extends Controller {
} }
$order_id = $args[0]; $order_id = $args[0];
$data = $args[1];
$this->load->model('checkout/order');
$this->load->model('account/order');
$this->load->library('retailcrm/retailcrm'); $this->load->library('retailcrm/retailcrm');
$this->load->model('extension/module/retailcrm');
$moduleTitle = $this->retailcrm->getModuleTitle(); $order_status_id = $this->model_extension_module_retailcrm->getOrderStatusId($order_id);
$data = $this->model_checkout_order->getOrder($order_id); $data['order_status_id'] = $order_status_id;
$retailcrm_order = $this->retailcrm->createObject(\Retailcrm\Order::class);
if ($data['order_status_id'] == 0) { $retailcrm_order->prepare($data);
return; $retailcrm_order->setField('externalId', $order_id);
} $retailcrm_order->edit($this->retailcrm->getApiClient());
$data['products'] = $this->model_account_order->getOrderProducts($order_id); return true;
$data['totals'] = $this->model_account_order->getOrderTotals($order_id);
foreach ($data['products'] as $key => $product) {
$productOptions = $this->model_account_order->getOrderOptions($order_id, $product['order_product_id']);
if (!empty($productOptions)) {
$data['products'][$key]['option'] = $productOptions;
}
}
if (!isset($data['fromApi'])) {
$this->load->model('setting/setting');
$status = $this->model_setting_setting->getSetting($moduleTitle);
if ($data['order_status_id'] > 0) {
$data['order_status'] = $status[$moduleTitle . '_status'][$data['order_status_id']];
}
if (file_exists(DIR_APPLICATION . 'model/extension/retailcrm/custom/order.php')) {
$this->load->model('extension/retailcrm/custom/order');
$order = $this->model_extension_retailcrm_custom_order->processOrder($data, false);
$this->model_extension_retailcrm_custom_order->sendToCrm($order, $this->retailcrmApiClient, false);
} else {
$this->load->model('extension/retailcrm/order');
$order = $this->model_extension_retailcrm_order->processOrder($data, false);
$this->model_extension_retailcrm_order->sendToCrm($order, $this->retailcrmApiClient, false);
}
}
} }
/** /**
@ -107,10 +82,11 @@ class ControllerExtensionModuleRetailcrm extends Controller {
} }
$this->load->library('retailcrm/retailcrm'); $this->load->library('retailcrm/retailcrm');
$retailcrm_customer = $this->retailcrm->createObject('Customer'); $retailcrm_customer = $this->retailcrm->createObject(\Retailcrm\Customer::class);
$retailcrm_customer->prepare($args[0]); $retailcrm_customer->prepare($args[0]);
$retailcrm_customer->setField('externalId', $output); $retailcrm_customer->setField('externalId', $output);
$retailcrm_customer->create(); $retailcrm_customer->create($this->retailcrm->getApiClient());
return true; return true;
} }
@ -130,10 +106,12 @@ class ControllerExtensionModuleRetailcrm extends Controller {
$customer_id = $args[0]; $customer_id = $args[0];
$data = $args[1]; $data = $args[1];
$this->load->library('retailcrm/customer'); $this->load->library('retailcrm/retailcrm');
$this->retailcrm->process($data); $retailcrm_customer = $this->retailcrm->createObject(\Retailcrm\Customer::class);
$this->retailcrm->setField('externalId', $customer_id);
$this->retailcrm->edit(); $retailcrm_customer->process($data);
$retailcrm_customer->setField('externalId', $customer_id);
$retailcrm_customer->edit($this->retailcrm->getApiClient());
return true; return true;
} }

View File

@ -1,350 +1,9 @@
<?php <?php
class ModelExtensionRetailcrmOrder extends Model { class ModelExtensionRetailcrmOrder extends Model {
protected $settings; public function getOrderStatusId($order_id) {
protected $moduleTitle; $query = $this->db->query("SELECT order_status_id FROM " . DB_PREFIX . "order WHERE order_id = '" . (int)$order_id . "'");
public function __construct($registry) { return $query->rows;
parent::__construct($registry);
$this->load->model('setting/setting');
$this->load->library('retailcrm/retailcrm');
$this->moduleTitle = $this->retailcrm->getModuleTitle();
$this->settings = $this->model_setting_setting->getSetting($this->moduleTitle);
}
/**
* Create order in CRM
*
* @param array $order
* @param \RetailcrmProxy $retailcrmApiClient
* @param bool $create (default = true)
*
* @return mixed
*/
public function sendToCrm($order, $retailcrmApiClient, $create = true) {
if (isset($this->request->post['fromApi']) || $retailcrmApiClient === false) {
return false;
}
if (!isset($order['customer']['externalId'])) {
$customer = $this->searchCustomer($order['phone'], $order['email'], $retailcrmApiClient);
if ($customer) {
$order['customer']['id'] = $customer['id'];
}
}
if ($create) {
$retailcrmApiClient->ordersCreate($order);
} else {
$order_payment = reset($order['payments']);
unset($order['payments']);
$response = $retailcrmApiClient->ordersEdit($order);
if ($this->settings[$this->moduleTitle . '_apiversion'] == 'v5' && $response->isSuccessful()) {
$this->updatePayment($order_payment, $order['externalId'], $retailcrmApiClient);
}
}
return $order;
}
/**
* Process order
*
* @param array $order_data
* @param bool $create (default = true)
*
* @return array $order
*/
public function processOrder($order_data, $create = true) {
$this->load->model('setting/setting');
$this->load->model('catalog/product');
$this->settings = $this->model_setting_setting->getSetting($this->moduleTitle);
$order_id = $order_data['order_id'];
if (!empty($order_data['payment_code']) && isset($this->settings[$this->moduleTitle . '_payment'][$order_data['payment_code']])) {
$payment_code = $this->settings[$this->moduleTitle . '_payment'][$order_data['payment_code']];
} else {
$payment_code = '';
}
if (!empty($order_data['shipping_code'])) {
$shippingCode = explode('.', $order_data['shipping_code']);
$shippingModule = $shippingCode[0];
if (isset($this->settings[$this->moduleTitle . '_delivery'][$order_data['shipping_code']])) {
$delivery_code = $this->settings[$this->moduleTitle . '_delivery'][$order_data['shipping_code']];
} elseif (isset($this->settings[$this->moduleTitle . '_delivery'][$shippingModule])) {
$delivery_code = $this->settings[$this->moduleTitle . '_delivery'][$shippingModule];
}
}
if (!isset($delivery_code) && isset($shippingModule)) {
if (isset($this->settings[$this->moduleTitle . '_delivery'])
&& $this->settings[$this->moduleTitle . '_delivery']
) {
$deliveries = array_keys($this->settings[$this->moduleTitle . '_delivery']);
$shipping_code = '';
array_walk($deliveries, function ($item, $key) use ($shippingModule, &$shipping_code) {
if (strripos($item, $shippingModule) !== false) {
$shipping_code = $item;
}
});
$delivery_code = $this->settings[$this->moduleTitle . '_delivery'][$shipping_code];
}
}
if (!empty($order_data['payment_iso_code_2'])) {
$order['countryIso'] = $order_data['payment_iso_code_2'];
}
if (isset($this->settings[$this->moduleTitle . '_order_number'])
&& $this->settings[$this->moduleTitle . '_order_number'] == 1
) {
$order['number'] = $order_data['order_id'];
}
$order['externalId'] = $order_id;
$order['firstName'] = $order_data['firstname'];
$order['lastName'] = $order_data['lastname'];
$order['phone'] = $order_data['telephone'];
$order['customerComment'] = $order_data['comment'];
if ($order_data['customer_id']) {
$order['customer']['externalId'] = $order_data['customer_id'];
}
if (!empty($order_data['email'])) {
$order['email'] = $order_data['email'];
}
$deliveryCost = 0;
$couponTotal = 0;
$orderTotals = isset($order_data['totals']) ? $order_data['totals'] : $order_data['order_total'] ;
$totals = $this->explodeTotals($orderTotals);
if (isset($totals['shipping'])) {
$deliveryCost = $totals['shipping'];
}
if (isset($totals['coupon'])) {
$couponTotal += abs($totals['coupon']);
}
if (isset($totals['reward'])) {
$couponTotal += abs($totals['reward']);
}
$order['createdAt'] = $order_data['date_added'];
if ($this->settings[$this->moduleTitle . '_apiversion'] != 'v5') {
$order['paymentType'] = $payment_code;
if ($couponTotal > 0) {
$order['discount'] = $couponTotal;
}
} else {
if ($couponTotal > 0) {
$order['discountManualAmount'] = $couponTotal;
}
}
$country = isset($order_data['shipping_country']) ? $order_data['shipping_country'] : '' ;
$order['delivery'] = array(
'code' => isset($delivery_code) ? $delivery_code : '',
'address' => array(
'index' => $order_data['shipping_postcode'],
'city' => $order_data['shipping_city'],
'countryIso' => $order_data['shipping_iso_code_2'],
'region' => $order_data['shipping_zone'],
'text' => implode(', ', array(
$order_data['shipping_postcode'],
$country,
$order_data['shipping_city'],
$order_data['shipping_address_1'],
$order_data['shipping_address_2']
))
)
);
if (!empty($deliveryCost)){
$order['delivery']['cost'] = $deliveryCost;
}
$orderProducts = isset($order_data['products']) ? $order_data['products'] : $order_data['order_product'];
$offerOptions = array('select', 'radio');
foreach ($orderProducts as $product) {
$offerId = '';
if (!empty($product['option'])) {
$options = array();
$productOptions = $this->model_catalog_product->getProductOptions($product['product_id']);
foreach ($product['option'] as $option) {
if ($option['type'] == 'checkbox') {
$properties[] = array(
'code' => $option['product_option_value_id'],
'name' => $option['name'],
'value' => $option['value']
);
}
if (!in_array($option['type'], $offerOptions)) continue;
foreach($productOptions as $productOption) {
if($productOption['product_option_id'] = $option['product_option_id']) {
foreach($productOption['product_option_value'] as $productOptionValue) {
if($productOptionValue['product_option_value_id'] == $option['product_option_value_id']) {
$options[$option['product_option_id']] = $productOptionValue['option_value_id'];
}
}
}
}
}
ksort($options);
$offerId = array();
foreach ($options as $optionKey => $optionValue) {
$offerId[] = $optionKey.'-'.$optionValue;
}
$offerId = implode('_', $offerId);
}
if ($this->settings[$this->moduleTitle . '_apiversion'] != 'v3') {
$item = array(
'offer' => array(
'externalId' => !empty($offerId) ? $product['product_id'].'#'.$offerId : $product['product_id']
),
'productName' => $product['name'],
'initialPrice' => $product['price'],
'quantity' => $product['quantity'],
);
} else {
$item = array(
'productName' => $product['name'],
'initialPrice' => $product['price'],
'quantity' => $product['quantity'],
'productId' => !empty($offerId) ? $product['product_id'].'#'.$offerId : $product['product_id']
);
}
if (isset($properties)) $item['properties'] = $properties;
$order['items'][] = $item;
if (isset($order_data['order_status_id']) && $order_data['order_status_id'] > 0) {
$order['status'] = $this->settings[$this->moduleTitle . '_status'][$order_data['order_status_id']];
} elseif (isset($order_data['order_status_id']) && $order_data['order_status_id'] == 0) {
$order['status'] = $this->settings[$this->moduleTitle . '_missing_status'];
}
if (isset($this->settings[$this->moduleTitle . '_custom_field']) && $order_data['custom_field']) {
$customFields = $order_data['custom_field'];
foreach ($customFields as $key => $value) {
if (isset($this->settings[$this->moduleTitle . '_custom_field']['o_' . $key])) {
$customFieldsToCrm[$this->settings[$this->moduleTitle . '_custom_field']['o_' . $key]] = $value;
}
}
if (isset($customFieldsToCrm)) {
$order['customFields'] = $customFieldsToCrm;
}
}
}
$payment = array(
'externalId' => $order_id,
'type' => $payment_code,
'amount' => $totals['total']
);
if (!$create) {
$payment['order'] = array(
'externalId' => $order_id
);
}
$order['payments'][] = $payment;
return $order;
}
/**
* Update payment in CRM
*
* @param array $order_payment
* @param int $orderId
*
* @return void
*/
private function updatePayment($order_payment, $orderId, $retailcrmApiClient) {
$response_order = $retailcrmApiClient->ordersGet($orderId);
if ($response_order->isSuccessful()) {
$order_info = $response_order['order'];
}
foreach ($order_info['payments'] as $payment_data) {
if (isset($payment_data['externalId']) && $payment_data['externalId'] == $orderId) {
$payment = $payment_data;
}
}
if (isset($payment) && $payment['type'] != $order_payment['type']) {
$response = $retailcrmApiClient->ordersPaymentDelete($payment['id']);
if ($response->isSuccessful()) {
$retailcrmApiClient->ordersPaymentCreate($order_payment);
}
} elseif (isset($payment) && $payment['type'] == $order_payment['type']) {
$retailcrmApiClient->ordersPaymentEdit($order_payment);
}
}
private function searchCustomer($phone, $email, $retailcrmApiClient) {
$customer = array();
$response = $retailcrmApiClient->customersList(
array(
'name' => $phone,
'email' => $email
),
1,
100
);
if ($response->isSuccessful() && isset($response['customers'])) {
$customers = $response['customers'];
if ($customers) {
$customer = end($customers);
}
}
return $customer;
}
/**
* @param $totals
*
* @return array
*/
private function explodeTotals($totals)
{
$resultTotals = array();
foreach ($totals as $total) {
$resultTotals[$total['code']] = $total['value'];
}
return $resultTotals;
} }
} }

View File

@ -0,0 +1,9 @@
<?php
class ModelExtensionRetailcrmProducts extends Model {
public function getProductOptions($product_id) {
$this->load->model('catalog/product');
return $this->model_catalog_product->getProductOptions($product_id);
}
}

View File

@ -11,7 +11,7 @@ if (!isset($cli_action)) {
} }
// Version // Version
$version = '2.3.0'; $version = '3.1';
$indexFile = file_get_contents(realpath(dirname(__FILE__)) . '/../../index.php'); $indexFile = file_get_contents(realpath(dirname(__FILE__)) . '/../../index.php');
preg_match("/define\([\s]*['\"]VERSION['\"][\s]*,[\s]*['\"](.*)['\"][\s]*\)[\s]*;/mi", $indexFile, $versionMatches); preg_match("/define\([\s]*['\"]VERSION['\"][\s]*,[\s]*['\"](.*)['\"][\s]*\)[\s]*;/mi", $indexFile, $versionMatches);
@ -132,16 +132,13 @@ $registry->set('cache', $cache);
$registry->set('response', $response); $registry->set('response', $response);
if (version_compare(VERSION, '3.0', '<')) { $session = new Session($config->get('session_engine'), $registry);
$session = new Session();
} else {
$session = new Session($config->get('session_engine'), $registry);
}
$registry->set('session', $session); $registry->set('session', $session);
$languages = array(); $languages = array();
$query = $db->query("SELECT * FROM " . DB_PREFIX . "language"); $query = $db->query("SELECT * FROM " . DB_PREFIX . "language");
foreach ($query->rows as $result) { foreach ($query->rows as $result) {
$languages[$result['code']] = $result; $languages[$result['code']] = $result;
} }
@ -149,33 +146,24 @@ foreach ($query->rows as $result) {
$adminLanguageCode = $config->get('config_admin_language'); $adminLanguageCode = $config->get('config_admin_language');
$config->set('config_language_id', $languages[$adminLanguageCode]['language_id']); $config->set('config_language_id', $languages[$adminLanguageCode]['language_id']);
if (version_compare(VERSION, '2.3', '<')) { $language = new Language($languages[$adminLanguageCode]['directory']);
$language = new Language($languages[$adminLanguageCode]['directory']);
} else {
$language = new Language($adminLanguageCode);
}
if(isset($languages[$adminLanguageCode]['filename'])) { if(isset($languages[$adminLanguageCode]['filename'])) {
$language->load($languages[$adminLanguageCode]['filename']); $language->load($languages[$adminLanguageCode]['filename']);
} else { } else {
$language->load($languages[$adminLanguageCode]['directory']); $language->load($languages[$adminLanguageCode]['directory']);
} }
$registry->set('language', $language); $registry->set('language', $language);
$document = new Document(); $document = new Document();
$registry->set('document', $document); $registry->set('document', $document);
$registry->set('currency', new Cart\Currency($registry)); $registry->set('currency', new Cart\Currency($registry));
$registry->set('weight', new Cart\Weight($registry)); $registry->set('weight', new Cart\Weight($registry));
$registry->set('length', new Cart\Length($registry)); $registry->set('length', new Cart\Length($registry));
$registry->set('user', new Cart\User($registry)); $registry->set('user', new Cart\User($registry));
if (version_compare(VERSION, '3.0', '<')) { $controller = new Router($registry);
$controller = new Front($registry);
} else {
$controller = new Router($registry);
}
$action = new Action($cli_action); $action = new Action($cli_action);
$controller->dispatch($action, new Action('error/not_found')); $controller->dispatch($action, new Action('error/not_found'));

View File

@ -1,3 +0,0 @@
<?php
$cli_action = 'extension/module/retailcrm/icml';
require_once('dispatch.php');

View File

@ -1,4 +0,0 @@
<?php
$cli_action = 'extension/module/retailcrm/prices';
require_once('dispatch.php');

View File

@ -14,9 +14,11 @@ class OpencartApiClient {
public function __construct(Registry &$registry) { public function __construct(Registry &$registry) {
$this->registry = $registry; $this->registry = $registry;
$moduleTitle = $this->getModuleTitle(); $settings = $this->model_setting_setting->getSetting(\Retailcrm\Retailcrm::MODULE);
$settings = $this->model_setting_setting->getSetting($moduleTitle);
$this->cookieFileName = $settings[$moduleTitle . '_apikey']; if (isset($settings[\Retailcrm\Retailcrm::MODULE . '_apikey'])) {
$this->cookieFileName = $settings[\Retailcrm\Retailcrm::MODULE . '_apikey'];
}
$this->auth(); $this->auth();
} }

View File

@ -8,16 +8,22 @@ class RetailcrmProxy
{ {
private $api; private $api;
private $log; private $log;
private $debug;
public function __construct($url, $key, $log, $version = null) public function __construct($url, $key, $log, $version = null, $debug = false)
{ {
switch ($version) { switch ($version) {
case 'v5': case 'v5':
$this->api = new RetailcrmApiClient5($url, $key, $version); $this->api = new RetailcrmApiClient5($url, $key, $version);
break; break;
default:
$this->api = new RetailcrmApiClient5($url, $key, $version);
break;
} }
$this->log = $log; $this->log = $log;
$this->debug = $debug;
} }
public function __call($method, $arguments) public function __call($method, $arguments)
@ -27,6 +33,16 @@ class RetailcrmProxy
try { try {
$response = call_user_func_array(array($this->api, $method), $arguments); $response = call_user_func_array(array($this->api, $method), $arguments);
if ($this->debug) {
$logger = new Log($method);
$logger->write(
array(
'data' => $arguments,
'response' => $response
)
);
}
if (!$response->isSuccessful()) { if (!$response->isSuccessful()) {
error_log($date . " [$method] " . $response->getErrorMsg() . "\n", 3, $this->log); error_log($date . " [$method] " . $response->getErrorMsg() . "\n", 3, $this->log);
if (isset($response['errors'])) { if (isset($response['errors'])) {

View File

@ -33,7 +33,7 @@ abstract class Base
* @return bool * @return bool
*/ */
public function setField($field, $value) { public function setField($field, $value) {
if (!isset($this->data[$field])) { if (!array_key_exists($field, $this->data)) {
return false; return false;
} }
@ -46,8 +46,8 @@ abstract class Base
* @param $fields * @param $fields
*/ */
public function setFields($fields) { public function setFields($fields) {
foreach ($fields as $field) { foreach ($fields as $field => $value) {
$this->setField($field['field'], $field['value']); $this->setField($field, $value);
} }
} }
@ -114,27 +114,93 @@ abstract class Base
/** /**
* Prepare data array * Prepare data array
* *
* @param $data * @param array $data
* *
* @return void * @return void
*/ */
abstract function prepare($data); public function prepare($data)
{
unset($data);
Retailcrm::filterRecursive($this->data);
}
/** /**
* Send to crm * Send to crm
* *
* @param $retailcrm_api_client * @param $retailcrm_api_client
* *
* @return void * @return mixed
*/ */
abstract function create($retailcrm_api_client); abstract public function create($retailcrm_api_client);
/** /**
* Edit in crm * Edit in crm
* *
* @param $retailcrm_api_client * @param $retailcrm_api_client
* *
* @return void * @return mixed
*/ */
abstract function edit($retailcrm_api_client); abstract public function edit($retailcrm_api_client);
/**
* Upload to CRM
*
* @param $retailcrm_api_client
* @param array $data
* @param string $method
*
* @return boolean
*/
public function upload($retailcrm_api_client, $data = array(), $method = 'orders')
{
if (!$data) {
return false;
}
$upload = array();
$countOrders = count($data);
$countIterations = (int) ($countOrders / 50);
foreach ($data as $key => $entity) {
$this->prepare($entity);
$upload[] = $this->data;
$this->resetData();
if ($countIterations > 0) {
unset($data[$key]);
}
if (($countIterations == 0 && count($data) == count($upload))
|| count($upload) == 50
) {
/** @var \RetailcrmApiClient5 $retailcrm_api_client */
$retailcrm_api_client->{$method . 'Upload'}($upload);
$upload = array();
$countIterations--;
}
}
return true;
}
/**
* Reset data on default
*/
private function resetData()
{
$numericValues = array(
'externalId',
'discountManualAmount'
);
foreach ($this->data as $field => $value) {
if (in_array($field, $numericValues)) {
$this->data[$field] = 0;
} elseif (is_array($value)) {
$this->data[$field] = array();
} else {
$this->data[$field] = null;
}
}
}
} }

View File

@ -0,0 +1,13 @@
<?php
namespace Retailcrm\Custom;
interface Base
{
/**
* @param array $data
*
* @return array
*/
public function prepare(array $data);
}

View File

@ -18,9 +18,9 @@ class Customer extends Base
); );
public function prepare($customer) { public function prepare($customer) {
if (file_exists(DIR_SYSTEM . 'library/retailcrm/custom.php')) { if (file_exists(DIR_SYSTEM . 'library/retailcrm/custom/customer.php')) {
$custom = new \Retailcrm\Custom($this->registry); $custom = new \Retailcrm\Custom\Customer($this->registry);
$this->data = $custom->processCustomer($customer); $this->data = $custom->prepare($customer);
} else { } else {
$this->load->model('setting/setting'); $this->load->model('setting/setting');
$setting = $this->model_setting_setting->getSetting(\Retailcrm\Retailcrm::MODULE); $setting = $this->model_setting_setting->getSetting(\Retailcrm\Retailcrm::MODULE);
@ -45,6 +45,10 @@ class Customer extends Base
$this->setField('email', $customer['email']); $this->setField('email', $customer['email']);
$this->setField('createdAt', date('Y-m-d H:i:s')); $this->setField('createdAt', date('Y-m-d H:i:s'));
if (isset($customer['customer_id']) && !$this->data['externalId']) {
$this->setField('externalId', $customer['customer_id']);
}
if (isset($settings[\Retailcrm\Retailcrm::MODULE . '_custom_field']) && $customer['custom_field']) { if (isset($settings[\Retailcrm\Retailcrm::MODULE . '_custom_field']) && $customer['custom_field']) {
$custom_fields = $this->prepareCustomFields($customer['custom_field'], $setting, 'c_'); $custom_fields = $this->prepareCustomFields($customer['custom_field'], $setting, 'c_');
@ -53,13 +57,37 @@ class Customer extends Base
} }
} }
} }
parent::prepare($customer);
} }
public function create($retailctm_api_client) { /**
$retailctm_api_client->customersCreate($this->data); * @param $retailcrm_api_client
*
* @return mixed
*/
public function create($retailcrm_api_client) {
if ($retailcrm_api_client === false) {
return false;
}
$response = $retailcrm_api_client->customersCreate($this->data);
return $response;
} }
public function edit($retailctm_api_client) { /**
$retailctm_api_client->customersEdit($this->data); * @param $retailcrm_api_client
*
* @return mixed
*/
public function edit($retailcrm_api_client) {
if ($retailcrm_api_client === false) {
return false;
}
$response = $retailcrm_api_client->customersEdit($this->data);
return $response;
} }
} }

View File

@ -24,16 +24,24 @@ class Order extends Base
); );
public function prepare($order) { public function prepare($order) {
if (file_exists(DIR_SYSTEM . 'library/retailcrm/custom.php')) { if (file_exists(DIR_SYSTEM . 'library/retailcrm/custom/order.php')) {
$custom = new \Retailcrm\Custom($this->registry); $custom = new \Retailcrm\Custom\Order($this->registry);
$this->data = $custom->processOrder($order); $this->data = $custom->prepare($order);
} else { } else {
$this->load->model('setting/setting'); $this->load->model('setting/setting');
$this->load->model('catalog/product'); $this->load->model('catalog/product');
$this->load->model('extension/retailcrm/products');
$settings = $this->model_setting_setting->getSetting(\Retailcrm\Retailcrm::MODULE); $settings = $this->model_setting_setting->getSetting(\Retailcrm\Retailcrm::MODULE);
$delivery_settings = $settings[\Retailcrm\Retailcrm::MODULE . '_delivery']; $delivery_settings = isset($settings[\Retailcrm\Retailcrm::MODULE . '_delivery'])
$payments_settings = $settings[\Retailcrm\Retailcrm::MODULE . '_payment']; ? $settings[\Retailcrm\Retailcrm::MODULE . '_delivery']
$status_settings = $settings[\Retailcrm\Retailcrm::MODULE . '_status']; : array();
$payments_settings = isset($settings[\Retailcrm\Retailcrm::MODULE . '_payment'])
? $settings[\Retailcrm\Retailcrm::MODULE . '_payment']
: array();
$status_settings = isset($settings[\Retailcrm\Retailcrm::MODULE . '_status'])
? $settings[\Retailcrm\Retailcrm::MODULE . '_status']
: array();
$totals = $this->explodeTotals($order['totals']); $totals = $this->explodeTotals($order['totals']);
$coupon_total = 0; $coupon_total = 0;
@ -53,22 +61,33 @@ class Order extends Base
if (isset($order['order_status_id']) && $order['order_status_id'] > 0) { if (isset($order['order_status_id']) && $order['order_status_id'] > 0) {
$status = $status_settings[$order['order_status_id']]; $status = $status_settings[$order['order_status_id']];
} elseif (isset($order['order_status_id']) && $order['order_status_id'] == 0) { } elseif (!isset($order['order_status_id'])) {
$status = $settings[\Retailcrm\Retailcrm::MODULE . '_missing_status']; $status = $settings[\Retailcrm\Retailcrm::MODULE . '_missing_status'];
} }
if (isset($settings[\Retailcrm\Retailcrm::MODULE . '_order_number'])
&& $settings[\Retailcrm\Retailcrm::MODULE . '_order_number'] == 1
) {
$this->setField('number', $order['order_id']);
}
$fields = array( $fields = array(
'firstName' => $order['firstname'], 'firstName' => $order['firstname'],
'lastName' => $order['lastname'], 'lastName' => $order['lastname'],
'email' => $order['email'], 'email' => $order['email'],
'phone' => $order['telephone'], 'phone' => $order['telephone'],
'customerComment' => $order['comment'], 'customerComment' => $order['comment'],
'createdAt' => $order['date_added'], 'createdAt' => isset($order['date_added']) ? $order['date_added'] : date('Y-m-d H:i:s'),
'discountManualAmount' => $coupon_total, 'discountManualAmount' => $coupon_total,
'status' => $status 'status' => $status
); );
if (isset($order['order_id']) && !$this->data['externalId']) {
$fields['externalId'] = $order['order_id'];
}
$this->setFields($fields); $this->setFields($fields);
if (isset($order['shipping_code'])) { if (isset($order['shipping_code'])) {
$delivery_code = $this->getDeliveryMethod($order['shipping_code'], $delivery_settings); $delivery_code = $this->getDeliveryMethod($order['shipping_code'], $delivery_settings);
} }
@ -123,14 +142,38 @@ class Order extends Base
} }
} }
} }
parent::prepare($order);
} }
/**
* @param $retailcrm_api_client
*
* @return bool|mixed
*/
public function create($retailcrm_api_client) { public function create($retailcrm_api_client) {
$retailcrm_api_client->ordersCreate($this->data); if ($retailcrm_api_client === false) {
return false;
}
$response = $retailcrm_api_client->ordersCreate($this->data);
return $response;
} }
/**
* @param $retailcrm_api_client
*
* @return bool|mixed
*/
public function edit($retailcrm_api_client) { public function edit($retailcrm_api_client) {
$retailcrm_api_client->ordersEdit($this->data); if ($retailcrm_api_client === false) {
return false;
}
$response = $retailcrm_api_client->ordersEdit($this->data);
return $response;
} }
/** /**
@ -163,7 +206,7 @@ class Order extends Base
$delivery_code = $deliveries[$delivery]; $delivery_code = $deliveries[$delivery];
} }
return $delivery_code; return isset($delivery_code) ? $delivery_code : null;
} }
/** /**
@ -194,7 +237,17 @@ class Order extends Base
continue; continue;
} }
$options[$option['product_option_id']] = $option['option_value_id']; $productOptions = $this->model_extension_retailcrm_products->getProductOptions($product['product_id']);
foreach ($productOptions as $productOption) {
if ($productOption['product_option_id'] == $option['product_option_id']) {
foreach ($productOption['product_option_value'] as $productOptionValue) {
if ($productOptionValue['product_option_value_id'] == $option['product_option_value_id']) {
$options[$option['product_option_id']] = $productOptionValue['option_value_id'];
}
}
}
}
} }
ksort($options); ksort($options);

View File

@ -46,8 +46,14 @@ class Retailcrm {
? $setting[self::MODULE . '_apiversion'] : ''; ? $setting[self::MODULE . '_apiversion'] : '';
} }
$debug = false;
if (isset($setting[self::MODULE . '_debug_mode']) && $setting[self::MODULE . '_debug_mode']) {
$debug = true;
}
if ($apiUrl && $apiKey) { if ($apiUrl && $apiKey) {
return new \RetailcrmProxy($apiUrl, $apiKey, DIR_LOGS . 'retailcrm.log', $apiVersion); return new \RetailcrmProxy($apiUrl, $apiKey, DIR_LOGS . 'retailcrm.log', $apiVersion, $debug);
} }
return false; return false;
@ -67,8 +73,9 @@ class Retailcrm {
public function getOffers($product) public function getOffers($product)
{ {
$this->load->model('extension/retailcrm/products');
// Формируем офферы отнсительно доступных опций // Формируем офферы отнсительно доступных опций
$options = $this->model_catalog_product->getProductOptions($product['product_id']); $options = $this->model_extension_retailcrm_products->getProductOptions($product['product_id']);
$offerOptions = array('select', 'radio'); $offerOptions = array('select', 'radio');
$requiredOptions = array(); $requiredOptions = array();
$notRequiredOptions = array(); $notRequiredOptions = array();
@ -138,4 +145,29 @@ class Retailcrm {
return $offers; return $offers;
} }
/**
* Filter result array
*
* @param $haystack
*
* @return mixed
*/
public static function filterRecursive($haystack)
{
foreach ($haystack as $key => $value) {
if (is_array($value)) {
$haystack[$key] = self::filterRecursive($haystack[$key]);
}
if (is_null($haystack[$key])
|| $haystack[$key] === ''
|| (is_array($haystack[$key]) && count($haystack[$key]) == 0)
) {
unset($haystack[$key]);
} elseif (!is_array($value)) {
$haystack[$key] = trim($value);
}
}
return $haystack;
}
} }