Compare commits

..

24 commits

Author SHA1 Message Date
ellynoize
b1d013dd30
Added option to round order amount (#269) 2025-01-20 10:26:45 +03:00
ellynoize
c5916fc8f2
Fix constant (#268)
Co-authored-by: ellynoize <a.kolesnikov@retailcrm.ru>
2024-11-14 12:10:15 +03:00
ellynoize
2c6cccc3b1
Добавлена передача дополнительных параметров в GET запросах (#267) 2024-10-14 17:26:34 +03:00
Uryvskiy Dima
c893cf24fb
ref #95381 Support for services in ICML (#265) 2024-05-06 09:07:38 +03:00
Kocmonavtik
d5f29dc5fe
ref #92633 Display module version (#263) 2023-11-23 11:10:52 +03:00
Uryvskiy Dima
3a30986e4b
ref #92124 Added currency validation (#260) 2023-10-06 14:00:10 +03:00
Uryvskiy Dima
571263ca2c
ref #90809 Changed the logic of customer subscriptions to promotional newsletters (#259) 2023-07-24 10:43:13 +03:00
Uryvskiy Dima
a375804086
Added query escaping in method for getting zone 2023-07-10 10:09:36 +03:00
KMityai
a56ce789ed version bump 2023-07-07 16:13:20 +03:00
KMityai
f5f55dd449 added escaping for db query in method for getting zone 2023-07-07 15:58:04 +03:00
KMityai
62605b11ed updated test testGetZoneByName 2023-07-07 15:48:53 +03:00
Uryvskiy Dima
22a9c2d819
ref #73045 Fixed the transfer of the weight of offers 2023-07-04 15:03:31 +03:00
Ivan Chaplygin
a2a4eca8c7 ref #73045 fix code 2023-07-04 14:38:35 +03:00
Ivan Chaplygin
63f625b329 ref #73045 Changing the weight transfer when generating a catalog 2023-07-03 17:15:00 +03:00
Uryvskiy Dima
6a7f395116
ref #90088 Types of deliveries and payments are displayed only active status and available stores 2023-06-07 14:41:33 +03:00
Ivan Chaplygin
792546d007 ref #90088 fix code 2023-06-07 13:39:01 +03:00
Ivan Chaplygin
7d3390bc02 ref #90088 fix style code
edit test
Edit getting site
2023-06-07 13:01:59 +03:00
Ivan Chaplygin
ef6d09c03a ref #90088 fix test
update Dockerfile
2023-06-05 17:18:10 +03:00
Ivan Chaplygin
e4cfdd8c9f ref #90088 create test 2023-06-02 16:27:31 +03:00
Ivan Chaplygin
8b7522ca6c ref #90088 update version 2023-06-02 14:55:21 +03:00
Ivan Chaplygin
b6181ab426 ref #90088 editing handler function 2023-06-02 14:43:54 +03:00
Ivan Chaplygin
3e1c19fd8d ref #90088 Types of deliveries and payments are displayed only active status and available stores 2023-06-02 13:55:00 +03:00
Uryvskiy Dima
090a5783c5
Optimization of the history processing algorithm (#254) 2023-04-28 11:44:38 +03:00
Vlad
feaeca458f
Fix customer create externalId (#251) 2022-09-05 12:58:12 +03:00
30 changed files with 603 additions and 342 deletions

View file

@ -2,7 +2,7 @@ FROM php:7.1-apache
RUN apt-get update RUN apt-get update
RUN apt-get install -y netcat zlib1g-dev libpq-dev git libicu-dev libxml2-dev libpng-dev libjpeg-dev libmcrypt-dev libxslt-dev libfreetype6-dev \ RUN apt-get install -y netcat zlib1g-dev libpq-dev git libicu-dev libxml2-dev libpng-dev libjpeg-dev libmcrypt-dev libxslt-dev libfreetype6-dev unzip \
&& docker-php-ext-configure intl \ && docker-php-ext-configure intl \
&& docker-php-ext-install intl \ && docker-php-ext-install intl \
&& docker-php-ext-configure pgsql -with-pgsql=/usr/local/pgsql \ && docker-php-ext-configure pgsql -with-pgsql=/usr/local/pgsql \

View file

@ -26,15 +26,6 @@ jobs:
strategy: strategy:
matrix: matrix:
include: include:
- php-version: '7.3'
test-suite: '3'
oc: '3.0.0.0'
- php-version: '7.3'
test-suite: '3'
oc: '3.0.0.2'
- php-version: '7.3'
test-suite: '3'
oc: '3.0.1.0'
- php-version: '7.3' - php-version: '7.3'
test-suite: '3' test-suite: '3'
oc: '3.0.1.1' oc: '3.0.1.1'
@ -71,15 +62,6 @@ jobs:
- php-version: '7.3' - php-version: '7.3'
test-suite: '3' test-suite: '3'
oc: '3.0.3.8' oc: '3.0.3.8'
- php-version: '7.4'
test-suite: '3'
oc: '3.0.0.0'
- php-version: '7.4'
test-suite: '3'
oc: '3.0.0.2'
- php-version: '7.4'
test-suite: '3'
oc: '3.0.1.0'
- php-version: '7.4' - php-version: '7.4'
test-suite: '3' test-suite: '3'
oc: '3.0.1.1' oc: '3.0.1.1'

View file

@ -1,3 +1,39 @@
## v4.1.19
* Added option to round order amount
## v4.1.18
* Fixed constant with version of module.
## v4.1.17
* Added additional parameters to GET requests.
## v4.1.16
* Support for services in ICML
## v4.1.15
* Display module version
## v4.1.14
* Added currency validation when configuring the module
## v4.1.13
* Changed the logic of customer subscriptions to promotional newsletters
## v4.1.12
* Added escaping for db query in method for getting zone
## v4.1.11
* Fixed the transfer of the weight offers
## v4.1.10
* Types of deliveries and payments are displayed only active status and available stores
## v4.1.9
* Optimization of the history processing algorithm
## v4.1.8
* Fixed customer externalId when creating a customer and sending it to RetailCRM
## v4.1.7 ## v4.1.7
* Fixed notices in ICML generation and while setting delivery type * Fixed notices in ICML generation and while setting delivery type
* Fixed incorrect data check before setting payment data * Fixed incorrect data check before setting payment data

View file

@ -1 +1 @@
4.1.7 4.1.19

6
doc/Update module.md Normal file
View file

@ -0,0 +1,6 @@
### Обновление версии модуля
Для обновления версии модуля необходимо обновить следующие файлы:
* VERSION
* CHANGELOG.md
* src/upload/admin/controller/extension/module/retailcrm.php

View file

@ -1,8 +1,10 @@
<?php <?php
use retailcrm\Retailcrm;
class ControllerExtensionModuleRetailcrm extends Controller class ControllerExtensionModuleRetailcrm extends Controller
{ {
private $_error = array(); private $_error = [];
protected $log, $statuses, $payments, $deliveryTypes, $retailcrmApiClient, $moduleTitle, $tokenTitle; protected $log, $statuses, $payments, $deliveryTypes, $retailcrmApiClient, $moduleTitle, $tokenTitle;
public $children, $template; public $children, $template;
@ -25,10 +27,10 @@ class ControllerExtensionModuleRetailcrm extends Controller
$this->model_setting_setting->editSetting( $this->model_setting_setting->editSetting(
$this->moduleTitle, $this->moduleTitle,
array( [
$this->moduleTitle . '_status' => 1, $this->moduleTitle . '_status' => 1,
$this->moduleTitle . '_country' => array($this->config->get('config_country_id')) $this->moduleTitle . '_country' => [$this->config->get('config_country_id')]
) ]
); );
$this->addEvents(); $this->addEvents();
@ -59,7 +61,7 @@ class ControllerExtensionModuleRetailcrm extends Controller
$this->uninstall_collector(); $this->uninstall_collector();
$this->model_setting_setting->editSetting( $this->model_setting_setting->editSetting(
$this->moduleTitle, $this->moduleTitle,
array($this->moduleTitle . '_status' => 0) [$this->moduleTitle . '_status' => 0]
); );
} }
@ -79,7 +81,7 @@ class ControllerExtensionModuleRetailcrm extends Controller
$this->loadModels(); $this->loadModels();
$this->load->model('setting/setting'); $this->load->model('setting/setting');
$this->{'model_' . $this->modelExtension}->install('analytics', 'daemon_collector'); $this->{'model_' . $this->modelExtension}->install('analytics', 'daemon_collector');
$this->model_setting_setting->editSetting($collector, array($collector . '_status' => 1)); $this->model_setting_setting->editSetting($collector, [$collector . '_status' => 1]);
} }
/** /**
@ -92,7 +94,7 @@ class ControllerExtensionModuleRetailcrm extends Controller
$collector = $this->getCollectorTitle(); $collector = $this->getCollectorTitle();
$this->loadModels(); $this->loadModels();
$this->load->model('setting/setting'); $this->load->model('setting/setting');
$this->model_setting_setting->editSetting($collector, array($collector . '_status' => 0)); $this->model_setting_setting->editSetting($collector, [$collector . '_status' => 0]);
$this->{'model_' . $this->modelExtension}->uninstall('analytics', 'daemon_collector'); $this->{'model_' . $this->modelExtension}->uninstall('analytics', 'daemon_collector');
} }
@ -107,7 +109,7 @@ class ControllerExtensionModuleRetailcrm extends Controller
$this->loadModels(); $this->loadModels();
$this->load->model('setting/setting'); $this->load->model('setting/setting');
$this->{'model_' . $this->modelExtension}->install('analytics', 'online_consultant'); $this->{'model_' . $this->modelExtension}->install('analytics', 'online_consultant');
$this->model_setting_setting->editSetting($consultant, array($consultant . '_status' => 1)); $this->model_setting_setting->editSetting($consultant, [$consultant . '_status' => 1]);
} }
/** /**
@ -120,7 +122,7 @@ class ControllerExtensionModuleRetailcrm extends Controller
$consultant = $this->getConsultantTitle(); $consultant = $this->getConsultantTitle();
$this->loadModels(); $this->loadModels();
$this->load->model('setting/setting'); $this->load->model('setting/setting');
$this->model_setting_setting->editSetting($consultant, array($consultant . '_status' => 0)); $this->model_setting_setting->editSetting($consultant, [$consultant . '_status' => 0]);
$this->{'model_' . $this->modelExtension}->uninstall('analytics', 'online_consultant'); $this->{'model_' . $this->modelExtension}->uninstall('analytics', 'online_consultant');
} }
@ -186,42 +188,21 @@ class ControllerExtensionModuleRetailcrm extends Controller
$this->request->post $this->request->post
); );
if (!isset($history_setting['retailcrm_history_orders']) && !isset($history_setting['retailcrm_history_customers'])) { if (
!isset($history_setting['retailcrm_history_orders'])
&& !isset($history_setting['retailcrm_history_customers'])
) {
$api = $this->retailcrm->getApiClient( $api = $this->retailcrm->getApiClient(
$this->request->post[$this->moduleTitle . '_url'], $this->request->post[$this->moduleTitle . '_url'],
$this->request->post[$this->moduleTitle . '_apikey'] $this->request->post[$this->moduleTitle . '_apikey']
); );
$ordersHistory = $api->ordersHistory();
if ($ordersHistory && $ordersHistory->isSuccessful() && !empty($ordersHistory['history'])) {
$ordersHistory = $api->ordersHistory(array(), $ordersHistory['pagination']['totalPageCount']);
if ($ordersHistory && $ordersHistory->isSuccessful()) {
$ordersHistoryArr = $ordersHistory['history'];
$lastChangeOrders = end($ordersHistoryArr);
$sinceIdOrders = $lastChangeOrders['id'];
}
}
$customersHistory = $api->customersHistory();
if ($customersHistory && $customersHistory->isSuccessful() && !empty($customersHistory['history'])) {
$customersHistory = $api->customersHistory(array(), $customersHistory['pagination']['totalPageCount']);
if ($customersHistory && $customersHistory->isSuccessful()) {
$customersHistoryArr = $customersHistory['history'];
$lastChangeCustomers = end($customersHistoryArr);
$sinceIdCustomers = $lastChangeCustomers['id'];
}
}
$this->model_setting_setting->editSetting( $this->model_setting_setting->editSetting(
'retailcrm_history', 'retailcrm_history',
array( [
'retailcrm_history_orders' => isset($sinceIdOrders) ? $sinceIdOrders : 1, 'retailcrm_history_orders' => $this->getHistorySinceId($api, 'ordersHistory'),
'retailcrm_history_customers' => isset($sinceIdCustomers) ? $sinceIdCustomers : 1 'retailcrm_history_customers' => $this->getHistorySinceId($api, 'customersHistory'),
) ]
); );
} }
@ -242,12 +223,12 @@ class ControllerExtensionModuleRetailcrm extends Controller
if ($result === true) { if ($result === true) {
$this->model_setting_setting->editSetting( $this->model_setting_setting->editSetting(
'retailcrm_setting', 'retailcrm_setting',
array( [
'retailcrm_setting_active_in_crm' => true, 'retailcrm_setting_active_in_crm' => true,
'retailcrm_setting_client_id' => $clientId, 'retailcrm_setting_client_id' => $clientId,
'retailcrm_setting_url' => $this->request->post[$this->moduleTitle . '_url'], 'retailcrm_setting_url' => $this->request->post[$this->moduleTitle . '_url'],
'retailcrm_setting_key' => $this->request->post[$this->moduleTitle . '_apikey'] 'retailcrm_setting_key' => $this->request->post[$this->moduleTitle . '_apikey']
) ]
); );
} }
} }
@ -261,7 +242,7 @@ class ControllerExtensionModuleRetailcrm extends Controller
$this->response->redirect($redirect); $this->response->redirect($redirect);
} }
$text_strings = array( $text_strings = [
'heading_title', 'heading_title',
'text_enabled', 'text_enabled',
'text_disabled', 'text_disabled',
@ -320,7 +301,11 @@ class ControllerExtensionModuleRetailcrm extends Controller
'special_price', 'special_price',
'order_number', 'order_number',
'text_order_number', 'text_order_number',
'text_currency', 'summ_around',
'text_summ_around',
'icml_settings',
'icml_service_enabled_label',
'icml_service_description',
'text_currency_label', 'text_currency_label',
'status_changes', 'status_changes',
'text_status_changes', 'text_status_changes',
@ -333,35 +318,39 @@ class ControllerExtensionModuleRetailcrm extends Controller
'text_retailcrm_label_discount', 'text_retailcrm_label_discount',
'default_retailcrm_label_discount', 'default_retailcrm_label_discount',
'sum_payment', 'sum_payment',
'text_sum_payment' 'text_sum_payment',
); ];
$_data = &$data; $_data = &$data;
$_data['module_version'] = Retailcrm::VERSION_MODULE;
foreach ($text_strings as $text) { foreach ($text_strings as $text) {
$_data[$text] = $this->language->get($text); $_data[$text] = $this->language->get($text);
} }
$_data['currencies'] = $this->model_localisation_currency->getCurrencies(0); $_data['currencies'] = $this->model_localisation_currency->getCurrencies(0);
$_data['retailcrm_errors'] = array(); $_data['retailcrm_errors'] = [];
$_data['saved_settings'] = $this->model_setting_setting $_data['saved_settings'] = $this->model_setting_setting
->getSetting($this->moduleTitle); ->getSetting($this->moduleTitle);
$url = isset($_data['saved_settings'][$this->moduleTitle . '_url']) $url = $_data['saved_settings'][$this->moduleTitle . '_url'] ?? null;
? $_data['saved_settings'][$this->moduleTitle . '_url'] $key = $_data['saved_settings'][$this->moduleTitle . '_apikey'] ?? null;
: null;
$key = isset($_data['saved_settings'][$this->moduleTitle . '_apikey'])
? $_data['saved_settings'][$this->moduleTitle . '_apikey']
: null;
if (!empty($url) && !empty($key)) { if (!empty($url) && !empty($key)) {
$this->validate($url, $key);
$_data['delivery'] = $this->model_extension_retailcrm_references $site = $this->model_extension_retailcrm_references->getApiSite();
->getDeliveryTypes(); $_data['delivery'] = $this->getAvailableTypes(
$site,
$this->model_extension_retailcrm_references->getDeliveryTypes()
);
$_data['payments'] = $this->getAvailableTypes(
$site,
$this->model_extension_retailcrm_references->getPaymentTypes()
);
$_data['statuses'] = $this->model_extension_retailcrm_references $_data['statuses'] = $this->model_extension_retailcrm_references
->getOrderStatuses(); ->getOrderStatuses();
$_data['payments'] = $this->model_extension_retailcrm_references
->getPaymentTypes();
$_data['customFields'] = $this->model_extension_retailcrm_references $_data['customFields'] = $this->model_extension_retailcrm_references
->getCustomFields(); ->getCustomFields();
@ -371,9 +360,7 @@ class ControllerExtensionModuleRetailcrm extends Controller
$_data['customerGroups'] = $this->model_customer_customer_group->getCustomerGroups(); $_data['customerGroups'] = $this->model_customer_customer_group->getCustomerGroups();
} }
$config_data = array( $config_data = [$this->moduleTitle . '_status'];
$this->moduleTitle . '_status'
);
foreach ($config_data as $conf) { foreach ($config_data as $conf) {
if (isset($this->request->post[$conf])) { if (isset($this->request->post[$conf])) {
@ -383,40 +370,35 @@ class ControllerExtensionModuleRetailcrm extends Controller
} }
} }
if (isset($this->_error['warning'])) { $_data['error_warning'] = $this->_error['warning'] ?? '';
$_data['error_warning'] = $this->_error['warning']; $_data['breadcrumbs'] = [];
} else {
$_data['error_warning'] = '';
}
$_data['breadcrumbs'] = array(); $_data['breadcrumbs'][] = [
$_data['breadcrumbs'][] = array(
'text' => $this->language->get('text_home'), 'text' => $this->language->get('text_home'),
'href' => $this->url->link( 'href' => $this->url->link(
'common/dashboard', 'common/dashboard',
$this->tokenTitle . '=' . $this->session->data[$this->tokenTitle], 'SSL' $this->tokenTitle . '=' . $this->session->data[$this->tokenTitle], 'SSL'
), ),
'separator' => false 'separator' => false
); ];
$_data['breadcrumbs'][] = array( $_data['breadcrumbs'][] = [
'text' => $this->language->get('text_module'), 'text' => $this->language->get('text_module'),
'href' => $this->url->link( 'href' => $this->url->link(
'extension/extension', 'extension/extension',
$this->tokenTitle . '=' . $this->session->data[$this->tokenTitle], 'SSL' $this->tokenTitle . '=' . $this->session->data[$this->tokenTitle], 'SSL'
), ),
'separator' => ' :: ' 'separator' => ' :: '
); ];
$_data['breadcrumbs'][] = array( $_data['breadcrumbs'][] = [
'text' => $this->language->get('retailcrm_title'), 'text' => $this->language->get('retailcrm_title'),
'href' => $this->url->link( 'href' => $this->url->link(
'extension/module/retailcrm', 'extension/module/retailcrm',
$this->tokenTitle . '=' . $this->session->data[$this->tokenTitle], 'SSL' $this->tokenTitle . '=' . $this->session->data[$this->tokenTitle], 'SSL'
), ),
'separator' => ' :: ' 'separator' => ' :: '
); ];
$_data['action'] = $this->url->link( $_data['action'] = $this->url->link(
'extension/module/retailcrm', 'extension/module/retailcrm',
@ -428,7 +410,7 @@ class ControllerExtensionModuleRetailcrm extends Controller
$this->tokenTitle . '=' . $this->session->data[$this->tokenTitle], 'SSL' $this->tokenTitle . '=' . $this->session->data[$this->tokenTitle], 'SSL'
); );
$_data['modules'] = array(); $_data['modules'] = [];
if (isset($this->request->post['retailcrm_module'])) { if (isset($this->request->post['retailcrm_module'])) {
$_data['modules'] = $this->request->post['retailcrm_module']; $_data['modules'] = $this->request->post['retailcrm_module'];
@ -452,11 +434,11 @@ class ControllerExtensionModuleRetailcrm extends Controller
$_data['export_file'] = true; $_data['export_file'] = true;
} }
$collectorFields = array( $collectorFields = [
'name' => $this->language->get('field_name'), 'name' => $this->language->get('field_name'),
'email' => $this->language->get('field_email'), 'email' => $this->language->get('field_email'),
'phone' => $this->language->get('field_phone') 'phone' => $this->language->get('field_phone')
); ];
$_data['collectorFields'] = $collectorFields; $_data['collectorFields'] = $collectorFields;
@ -575,20 +557,12 @@ class ControllerExtensionModuleRetailcrm extends Controller
$this->response->setOutput( $this->response->setOutput(
json_encode( json_encode(
array( ['status_code' => $response->getStatusCode(), 'error_msg' => $error],
'status_code' => $response->getStatusCode(), JSON_THROW_ON_ERROR
'error_msg' => $error
)
) )
); );
} else { } else {
$this->response->setOutput( $this->response->setOutput(json_encode(['status_code' => $response->getStatusCode()]));
json_encode(
array(
'status_code' => $response->getStatusCode()
)
)
);
} }
} }
} }
@ -608,7 +582,7 @@ class ControllerExtensionModuleRetailcrm extends Controller
$this->model_extension_retailcrm_customer->uploadToCrm($customers, $this->retailcrm->getApiClient()); $this->model_extension_retailcrm_customer->uploadToCrm($customers, $this->retailcrm->getApiClient());
$orders = $this->model_sale_order->getOrders(); $orders = $this->model_sale_order->getOrders();
$fullOrders = array(); $fullOrders = [];
foreach ($orders as $order) { foreach ($orders as $order) {
$fullOrder = $this->model_sale_order->getOrder($order['order_id']); $fullOrder = $this->model_sale_order->getOrder($order['order_id']);
@ -651,39 +625,57 @@ class ControllerExtensionModuleRetailcrm extends Controller
* *
* @return bool * @return bool
*/ */
private function validate() private function validate($apiUrl = null, $apiKey = null)
{ {
if (!empty($this->request->post[$this->moduleTitle . '_url']) && !empty($this->request->post[$this->moduleTitle . '_apikey'])) { $warningMessage = '';
$apiClient = $this->retailcrm->getApiClient(
$this->request->post[$this->moduleTitle . '_url'], $apiUrl = $this->request->post[$this->moduleTitle . '_url'] ?? $apiUrl;
$this->request->post[$this->moduleTitle . '_apikey'] $apiKey = $this->request->post[$this->moduleTitle . '_apikey'] ?? $apiKey;
try {
if ( !empty($apiUrl) && !empty($apiKey)) {
$apiClient = $this->retailcrm->getApiClient($apiUrl, $apiKey);
$response = $apiClient->sitesList();
if (empty($response['sites']) || !$response->isSuccessful()) {
$warningMessage = 'text_error_api_key';
} elseif (count($response['sites']) > 1) {
$warningMessage = 'text_error_api_key_site';
} else {
$site = current($response['sites']);
if ($this->config->get('config_currency') !== $site['currency']) {
$warningMessage = 'text_error_api_key_currency';
}
}
if (!$this->user->hasPermission('modify', 'extension/module/retailcrm')) {
$this->_error['warning'] = $this->language->get('error_permission');
}
if (isset($this->request->post[$this->moduleTitle . '_collector']['custom']) &&
$this->request->post[$this->moduleTitle . '_collector']['custom_form'] == 1) {
$customField = $this->request->post[$this->moduleTitle . '_collector']['custom'];
if (empty($customField['name']) && empty($customField['email']) && empty($customField['phone'])) {
$this->_error['fields'] = $this->language->get('text_error_collector_fields');
}
}
} else {
$warningMessage = 'text_error_api_empty';
}
} catch (Throwable $exception) {
$warningMessage = sprintf(
'An error has occurred! In file: %s, on line: %s. Error message: %s',
$exception->getFile(), $exception->getLine(), $exception->getMessage()
); );
} }
$response = $apiClient->apiVersions(); if ('' !== $warningMessage) {
$this->_error['warning'] = $this->language->get($warningMessage);
if (!$response || !$response->isSuccessful()) {
$this->_error['warning'] = $this->language->get('text_error_api');
} }
if (!$this->user->hasPermission('modify', 'extension/module/retailcrm')) { return empty($this->_error);
$this->_error['warning'] = $this->language->get('error_permission');
}
if (isset($this->request->post[$this->moduleTitle . '_collector']['custom']) &&
$this->request->post[$this->moduleTitle . '_collector']['custom_form'] == 1) {
$customField = $this->request->post[$this->moduleTitle . '_collector']['custom'];
if (empty($customField['name']) && empty($customField['email']) && empty($customField['phone'])) {
$this->_error['fields'] = $this->language->get('text_error_collector_fields');
}
}
if (!$this->_error) {
return true;
} else {
return false;
}
} }
/** /**
@ -839,6 +831,13 @@ class ControllerExtensionModuleRetailcrm extends Controller
'extension/module/retailcrm/customer_edit' 'extension/module/retailcrm/customer_edit'
); );
$this->{'model_' . $this->modelEvent}
->addEvent(
$this->moduleTitle,
'catalog/model/account/customer/editNewsletter/after',
'extension/module/retailcrm/customer_edit_newsletter'
);
$this->{'model_' . $this->modelEvent} $this->{'model_' . $this->modelEvent}
->addEvent( ->addEvent(
$this->moduleTitle, $this->moduleTitle,
@ -912,15 +911,15 @@ class ControllerExtensionModuleRetailcrm extends Controller
$name = 'Opencart'; $name = 'Opencart';
$accountUrl = $scheme . $this->request->server['HTTP_HOST'] . '/admin'; $accountUrl = $scheme . $this->request->server['HTTP_HOST'] . '/admin';
$configuration = array( $configuration = [
'clientId' => $clientId, 'clientId' => $clientId,
'code' => $integrationCode . '-' . $clientId, 'code' => $integrationCode . '-' . $clientId,
'integrationCode' => $integrationCode, 'integrationCode' => $integrationCode,
'active' => $active, 'active' => $active,
'name' => $name, 'name' => $name,
'logo' => $logo, 'logo' => $logo,
'accountUrl' => $accountUrl 'accountUrl' => $accountUrl,
); ];
$response = $apiClient->integrationModulesEdit($configuration); $response = $apiClient->integrationModulesEdit($configuration);
@ -934,4 +933,57 @@ class ControllerExtensionModuleRetailcrm extends Controller
return false; return false;
} }
private function getHistorySinceId($api, $method)
{
$lastSinceId = 0;
$startDate = new DateTime('-1 days');
$historyResponse = $api->$method(['startDate' => $startDate->format('Y-m-d H:i:s')]);
if (
!$historyResponse instanceof ApiResponse
|| !$historyResponse->isSuccessful()
|| empty($historyResponse['history'])
|| empty($historyResponse['pagination'])
) {
return $lastSinceId;
}
$startPage = $historyResponse['pagination']['currentPage'];
$lastPage = $historyResponse['pagination']['totalPageCount'];
for ($startPage; $startPage <= $lastPage; ++$startPage) {
if ($historyResponse instanceof ApiResponse && !empty($historyResponse['history'])) {
$history = $historyResponse['history'];
$lastSinceId = end($history)['id'];
$historyResponse = $api->$method(['sinceId' => $lastSinceId]);
}
}
return $lastSinceId;
}
private function getAvailableTypes($availableSite, $types)
{
$result['opencart'] = $types['opencart'];
$result['retailcrm'] = [];
if (empty($availableSite)) {
return $result;
}
foreach ($types['retailcrm'] as $codeKey => $type) {
if ($type['active'] !== true) {
continue;
}
if (!empty($type['sites']) && !in_array($availableSite['code'], $type['sites'])) {
continue;
}
$result['retailcrm'][$codeKey] = $type;
}
return $result;
}
} }

View file

@ -50,8 +50,11 @@ $_['text_payment'] = 'Payment';
$_['text_shipping'] = 'Delivery'; $_['text_shipping'] = 'Delivery';
$_['text_orders_custom_fields'] = 'Custom fields of orders'; $_['text_orders_custom_fields'] = 'Custom fields of orders';
$_['text_customers_custom_fields'] = 'Custom fields of customers'; $_['text_customers_custom_fields'] = 'Custom fields of customers';
$_['text_error_collector_fields']= 'Fill in the names of fields of Demon Collector form'; $_['text_error_collector_fields'] = 'Fill in the names of fields of Demon Collector form';
$_['text_error_api'] = 'The selected API version is not available.'; $_['text_error_api_empty'] = 'The "RetailCRM URL" and "RetailCRM API key" fields cannot be empty, enter the correct value';
$_['text_error_api_key'] = 'Invalid API key';
$_['text_error_api_key_site'] = 'API key with one-shop access required';
$_['text_error_api_key_currency'] = 'The currency of the site differs from the currency of the store in CRM. For the integration to work correctly, the currencies in CRM and CMS must match';
$_['text_error_custom_field'] = 'Create custom fields on a customer page in Opencart and RetailCRM in order to set up their transfer'; $_['text_error_custom_field'] = 'Create custom fields on a customer page in Opencart and RetailCRM in order to set up their transfer';
$_['text_error_cf_opencart'] = 'There are no custom fields in Opencart'; $_['text_error_cf_opencart'] = 'There are no custom fields in Opencart';
$_['text_error_cf_retailcrm'] = 'There are no custom fields in RetailCRM'; $_['text_error_cf_retailcrm'] = 'There are no custom fields in RetailCRM';
@ -69,10 +72,14 @@ $_['retailcrm_missing_status'] = 'Status of lost orders';
$_['order_number'] = 'Order number'; $_['order_number'] = 'Order number';
$_['text_order_number'] = 'Upload the order number to RetailCRM'; $_['text_order_number'] = 'Upload the order number to RetailCRM';
$_['text_currency'] = 'Currency setting'; $_['summ_around'] = 'Around total summ';
$_['text_currency_label'] = 'Currency in ICML'; $_['text_summ_around'] = 'Around the order total summ';
$_['icml_settings'] = 'ICML settings';
$_['icml_service_enabled_label'] = 'Upload services in ICML';
$_['icml_service_description'] = 'When the option is enabled, all products for which delivery is disabled will be considered as services and uploaded to CRM as services';
$_['text_currency_label'] = 'Currency of goods';
$_['text_lenght'] = 'Setting of the unit of measurement'; $_['text_lenght'] = 'Setting of the unit of measurement';
$_['text_lenght_label'] = 'Unit of measurement in ICML'; $_['text_lenght_label'] = 'Unit of measurement of goods';
$_['status_changes'] = 'History of changes'; $_['status_changes'] = 'History of changes';
$_['text_status_changes'] = 'Record changes to the order history of Opencart'; $_['text_status_changes'] = 'Record changes to the order history of Opencart';

View file

@ -51,7 +51,10 @@ $_['text_shipping'] = 'Envío';
$_['text_orders_custom_fields'] = 'Los campos de pedidos personalizados'; $_['text_orders_custom_fields'] = 'Los campos de pedidos personalizados';
$_['text_customers_custom_fields'] = 'Los campos de clientes personalizados'; $_['text_customers_custom_fields'] = 'Los campos de clientes personalizados';
$_['text_error_collector_fields']= 'Rellene los nombres de los campos del formulario Daemon Collector'; $_['text_error_collector_fields']= 'Rellene los nombres de los campos del formulario Daemon Collector';
$_['text_error_api'] = 'La versión seleccionada de la API no está disponible.'; $_['text_error_api_empty'] = 'Los campos "URL de RetailCRM" y "Clave de API de RetailCRM" no pueden estar vacíos, ingrese el valor correcto';
$_['text_error_api_key'] = 'Clave API del CRM no válida';
$_['text_error_api_key_site'] = 'Se requiere clave API con acceso a una tienda';
$_['text_error_api_key_currency'] = 'La moneda del sitio web es distinto a la tienda del CRM. Para el funcionamiento correcto de la integración, las monedas del CMS y CRM deben coincid';
$_['text_error_custom_field'] = 'Cree campos personalizados en la ficha del cliente en Opencart y RetailCRM para configurar sus transmisión.'; $_['text_error_custom_field'] = 'Cree campos personalizados en la ficha del cliente en Opencart y RetailCRM para configurar sus transmisión.';
$_['text_error_cf_opencart'] = 'Faltan campos personalizados en Opencart'; $_['text_error_cf_opencart'] = 'Faltan campos personalizados en Opencart';
$_['text_error_cf_retailcrm'] = 'Faltan campos personalizados en RetailCRM'; $_['text_error_cf_retailcrm'] = 'Faltan campos personalizados en RetailCRM';
@ -69,10 +72,15 @@ $_['retailcrm_missing_status'] = 'Estado de pedidos perdidos';
$_['order_number'] = 'Número de pedido'; $_['order_number'] = 'Número de pedido';
$_['text_order_number'] = 'Transferir número de pedido a RetailCRM'; $_['text_order_number'] = 'Transferir número de pedido a RetailCRM';
$_['text_currency'] = 'Ajustes de moneda'; $_['summ_around'] = 'Redondeo del costo del pedido';
$_['text_currency_label'] = 'Moneda en ICML'; $_['text_summ_around'] = 'Redondear los costos del pedido a RetailCRM';
$_['icml_settings'] = 'Ajustes de ICML';
$_['icml_service_enabled_label'] = 'Subir servicios de ICML';
$_['icml_service_description'] = 'Si habilita la opción, todos los productos para los que la entrega está desactivada se tratarán como servicios y se cargarán en CRM como servicios';
$_['text_currency_label'] = 'Moneda de bienes';
$_['text_lenght'] = 'Ajustar unidad de medida'; $_['text_lenght'] = 'Ajustar unidad de medida';
$_['text_lenght_label'] = 'Unidad de medida en ICML'; $_['text_lenght_label'] = 'Unidad de medida de bienes';
$_['status_changes'] = 'Historial de cambios'; $_['status_changes'] = 'Historial de cambios';
$_['text_status_changes'] = 'Registrar los cambios en el historial de pedidos de Opencart'; $_['text_status_changes'] = 'Registrar los cambios en el historial de pedidos de Opencart';

View file

@ -50,8 +50,11 @@ $_['text_payment'] = 'Оплата';
$_['text_shipping'] = 'Доставка'; $_['text_shipping'] = 'Доставка';
$_['text_orders_custom_fields'] = 'Кастомные поля заказов'; $_['text_orders_custom_fields'] = 'Кастомные поля заказов';
$_['text_customers_custom_fields'] = 'Кастомные поля клиентов'; $_['text_customers_custom_fields'] = 'Кастомные поля клиентов';
$_['text_error_collector_fields']= 'Заполните названия полей формы Демон Collector'; $_['text_error_collector_fields'] = 'Заполните названия полей формы Демон Collector';
$_['text_error_api'] = 'Недоступна выбранная версия API.'; $_['text_error_api_empty'] = 'Поля "URL RetailCRM" и "Ключ API RetailCRM" не могут быть пустыми, введите корректное значение';
$_['text_error_api_key'] = 'Неверный API ключ';
$_['text_error_api_key_site'] = 'Требуется API ключ с доступом к одному магазину';
$_['text_error_api_key_currency'] = 'Валюта сайта отличается от валюты магазина в CRM. Для корректной работы интеграции, валюты в CRM и CMS должны совпадать';
$_['text_error_custom_field'] = 'Создайте пользовательские поля в карточке клиента в Opencart и RetailCRM, чтобы настроить их передачу'; $_['text_error_custom_field'] = 'Создайте пользовательские поля в карточке клиента в Opencart и RetailCRM, чтобы настроить их передачу';
$_['text_error_cf_opencart'] = 'Отсутствуют пользовательские поля в Opencart'; $_['text_error_cf_opencart'] = 'Отсутствуют пользовательские поля в Opencart';
$_['text_error_cf_retailcrm'] = 'Отсутствуют пользовательские поля в RetailCRM'; $_['text_error_cf_retailcrm'] = 'Отсутствуют пользовательские поля в RetailCRM';
@ -69,10 +72,14 @@ $_['retailcrm_missing_status'] = 'Статус пропавших заказо
$_['order_number'] = 'Номер заказа'; $_['order_number'] = 'Номер заказа';
$_['text_order_number'] = 'Передавать номер заказа в RetailCRM'; $_['text_order_number'] = 'Передавать номер заказа в RetailCRM';
$_['text_currency'] = 'Настройка валюты'; $_['summ_around'] = 'Округление суммы заказа';
$_['text_currency_label'] = 'Валюта в ICML'; $_['text_summ_around'] = 'Округлять сумму заказа';
$_['icml_settings'] = 'Настройки ICML';
$_['icml_service_enabled_label'] = 'Выгружать услуги в ICML';
$_['icml_service_description'] = 'При включении опции все товары, для которых отключена доставка, будут рассматриваться как услуги и загружаться в CRM как услуги';
$_['text_currency_label'] = 'Валюта товаров';
$_['text_lenght'] = 'Настройка единицы измерения'; $_['text_lenght'] = 'Настройка единицы измерения';
$_['text_lenght_label'] = 'Единица измерения в ICML'; $_['text_lenght_label'] = 'Единица измерения товаров';
$_['status_changes'] = 'История изменений'; $_['status_changes'] = 'История изменений';
$_['text_status_changes'] = 'Фиксировать изменения в истории заказа Opencart'; $_['text_status_changes'] = 'Фиксировать изменения в истории заказа Opencart';

View file

@ -72,15 +72,10 @@ class ModelExtensionRetailcrmHistory extends Model {
return false; return false;
} }
$sinceIdOrders = $history['retailcrm_history_orders'] ? $history['retailcrm_history_orders'] : null; $sinceIdOrders = $history['retailcrm_history_orders'] ?? 0;
$sinceIdCustomers = $history['retailcrm_history_customers'] ? $history['retailcrm_history_customers'] : null; $sinceIdCustomers = $history['retailcrm_history_customers'] ?? 0;
$packsOrders = $retailcrmApiClient->ordersHistory(['sinceId' => $sinceIdOrders]);
$packsOrders = $retailcrmApiClient->ordersHistory(array( $packsCustomers = $retailcrmApiClient->customersHistory(['sinceId' => $sinceIdCustomers]);
'sinceId' => $sinceIdOrders ? $sinceIdOrders : 0
), 1, 100);
$packsCustomers = $retailcrmApiClient->customersHistory(array(
'sinceId' => $sinceIdCustomers ? $sinceIdCustomers : 0
), 1, 100);
if (!$packsOrders->isSuccessful() && count($packsOrders->history) <= 0 if (!$packsOrders->isSuccessful() && count($packsOrders->history) <= 0
&& !$packsCustomers->isSuccessful() && count($packsCustomers->history) <= 0 && !$packsCustomers->isSuccessful() && count($packsCustomers->history) <= 0
@ -88,30 +83,28 @@ class ModelExtensionRetailcrmHistory extends Model {
return false; return false;
} }
$orders = RetailcrmHistoryHelper::assemblyOrder($packsOrders->history);
$customers = RetailcrmHistoryHelper::assemblyCustomer($packsCustomers->history);
$ordersHistory = $packsOrders->history; $ordersHistory = $packsOrders->history;
$customersHistory = $packsCustomers->history; $customersHistory = $packsCustomers->history;
$lastChangeOrders = $ordersHistory ? end($ordersHistory) : null; $lastChangeOrders = $ordersHistory ? end($ordersHistory) : null;
$lastChangeCustomers = $customersHistory ? end($customersHistory) : null; $lastChangeCustomers = $customersHistory ? end($customersHistory) : null;
if ($lastChangeOrders !== null) { if ($lastChangeOrders !== null && $lastChangeCustomers !== null) {
$sinceIdOrders = $lastChangeOrders['id']; $this->model_setting_setting->editSetting(
} 'retailcrm_history',
[
if ($lastChangeCustomers !== null) { 'retailcrm_history_orders' => $lastChangeOrders['id'],
$sinceIdCustomers = $lastChangeCustomers['id']; 'retailcrm_history_customers' => $lastChangeCustomers['id']
]
);
} }
$orders = RetailcrmHistoryHelper::assemblyOrder($ordersHistory);
$customers = RetailcrmHistoryHelper::assemblyCustomer($customersHistory);
$newOrders = [];
$updatedOrders = [];
$this->settings = $settings; $this->settings = $settings;
$this->status = array_flip($settings[$this->moduleTitle . '_status']); $this->status = array_flip($settings[$this->moduleTitle . '_status']);
$updatedOrders = array();
$newOrders = array();
foreach ($orders as $order) { foreach ($orders as $order) {
if (isset($order['deleted'])) { if (isset($order['deleted'])) {
continue; continue;
@ -126,7 +119,7 @@ class ModelExtensionRetailcrmHistory extends Model {
unset($orders); unset($orders);
$updateCustomers = array(); $updateCustomers = [];
foreach ($customers as $customer) { foreach ($customers as $customer) {
if (isset($customer['deleted'])) { if (isset($customer['deleted'])) {
@ -141,34 +134,27 @@ class ModelExtensionRetailcrmHistory extends Model {
unset($customers); unset($customers);
if (!empty($updateCustomers)) { if (!empty($updateCustomers)) {
$customers = $retailcrmApiClient->customersList(array('ids' => $updateCustomers)); $customers = $retailcrmApiClient->customersList(['ids' => $updateCustomers]);
if ($customers) { if ($customers) {
$this->updateCustomers($customers['customers']); $this->updateCustomers($customers['customers']);
} }
} }
if (!empty($newOrders)) { if (!empty($newOrders)) {
$orders = $retailcrmApiClient->ordersList(array('ids' => $newOrders)); $orders = $retailcrmApiClient->ordersList(['ids' => $newOrders]);
if ($orders) { if ($orders) {
$this->createResult = $this->createOrders($orders['orders'], $retailcrmApiClient); $this->createResult = $this->createOrders($orders['orders'], $retailcrmApiClient);
} }
} }
if (!empty($updatedOrders)) { if (!empty($updatedOrders)) {
$orders = $retailcrmApiClient->ordersList(array('ids' => $updatedOrders)); $orders = $retailcrmApiClient->ordersList(['ids' => $updatedOrders]);
if ($orders) { if ($orders) {
$this->updateOrders($orders['orders'], $retailcrmApiClient); $this->updateOrders($orders['orders'], $retailcrmApiClient);
} }
} }
$this->model_setting_setting->editSetting(
'retailcrm_history',
array(
'retailcrm_history_orders' => $sinceIdOrders,
'retailcrm_history_customers' => $sinceIdCustomers
)
);
if (!empty($this->createResult['customers'])) { if (!empty($this->createResult['customers'])) {
$retailcrmApiClient->customersFixExternalIds($this->createResult['customers']); $retailcrmApiClient->customersFixExternalIds($this->createResult['customers']);
} }

View file

@ -15,13 +15,14 @@ class ModelExtensionRetailcrmIcml extends Model
/** /**
* Constructor * Constructor
* *
* @param Registry $registry * @param Registry $registry
*/ */
public function __construct($registry) public function __construct($registry)
{ {
parent::__construct($registry); parent::__construct($registry);
$this->load->library('retailcrm/retailcrm'); $this->load->library('retailcrm/retailcrm');
$this->load->model('localisation/weight_class');
} }
public function generateICML() public function generateICML()
@ -77,7 +78,7 @@ class ModelExtensionRetailcrmIcml extends Model
*/ */
private function addCategories() private function addCategories()
{ {
$categories = $this->model_catalog_category->getCategories(array()); $categories = $this->model_catalog_category->getCategories([]);
foreach ($categories as $category) { foreach ($categories as $category) {
$category = $this->model_catalog_category->getCategory($category['category_id']); $category = $this->model_catalog_category->getCategory($category['category_id']);
@ -102,11 +103,18 @@ class ModelExtensionRetailcrmIcml extends Model
} }
private function addOffers() { private function addOffers() {
$offerManufacturers = array(); $offerManufacturers = [];
$servicesForIcml = $this->retailcrm->useServicesForIcml();
$currencyForIcml = $this->retailcrm->getCurrencyForIcml(); $currencyForIcml = $this->retailcrm->getCurrencyForIcml();
$defaultCurrency = $this->getDefaultCurrency(); $defaultCurrency = $this->getDefaultCurrency();
$settingLenght = $this->retailcrm->getLenghtForIcml(); $settingLenght = $this->retailcrm->getLenghtForIcml();
$leghtsArray = $this->model_localisation_length_class->getLengthClasses(); $leghtsArray = $this->model_localisation_length_class->getLengthClasses();
$weightClassesMas = $this->model_localisation_weight_class->getWeightClasses();
$weightClasses = [];
foreach ($weightClassesMas as $weightClass) {
$weightClasses[$weightClass['weight_class_id']]['value'] = $weightClass['value'];
}
foreach ($leghtsArray as $lenght) { foreach ($leghtsArray as $lenght) {
if ($lenght['value'] == 1) { if ($lenght['value'] == 1) {
@ -115,20 +123,20 @@ class ModelExtensionRetailcrmIcml extends Model
} }
$manufacturers = $this->model_catalog_manufacturer $manufacturers = $this->model_catalog_manufacturer
->getManufacturers(array()); ->getManufacturers([]);
foreach ($manufacturers as $manufacturer) { foreach ($manufacturers as $manufacturer) {
$offerManufacturers[$manufacturer['manufacturer_id']] = $manufacturer['name']; $offerManufacturers[$manufacturer['manufacturer_id']] = $manufacturer['name'];
} }
$products = $this->model_catalog_product->getProducts(array()); $products = $this->model_catalog_product->getProducts([]);
foreach ($products as $product) { foreach ($products as $product) {
$offers = $this->retailcrm->getOffers($product); $offers = $this->retailcrm->getOffers($product);
foreach ($offers as $optionsString => $optionsValues) { foreach ($offers as $optionsString => $optionsValues) {
$optionsString = explode('_', $optionsString); $optionsString = explode('_', $optionsString);
$options = array(); $options = [];
foreach($optionsString as $optionString) { foreach($optionsString as $optionString) {
$option = explode('-', $optionString); $option = explode('-', $optionString);
@ -143,35 +151,43 @@ class ModelExtensionRetailcrmIcml extends Model
'value_id' => $option[1], 'value_id' => $option[1],
'option_id' => $optionIds[1] 'option_id' => $optionIds[1]
); );
} }
} }
} }
ksort($options); ksort($options);
$offerId = array(); $offerId = [];
foreach($options as $optionKey => $optionData) { foreach($options as $optionKey => $optionData) {
$offerId[] = $optionKey.'-'.$optionData['value_id']; $offerId[] = $optionKey.'-'.$optionData['value_id'];
} }
$offerId = implode('_', $offerId); $offerId = implode('_', $offerId);
$e = $this->eOffers->appendChild($this->dd->createElement('offer')); $catalog = $this->eOffers->appendChild($this->dd->createElement('offer'));
if (!empty($offerId)) { if (!empty($offerId)) {
$e->setAttribute('id', $product['product_id'] . '#' . $offerId); $catalog->setAttribute('id', $product['product_id'] . '#' . $offerId);
$e->setAttribute('productId', $product['product_id']); $catalog->setAttribute('productId', $product['product_id']);
$e->setAttribute('quantity', $optionsValues['qty']); $catalog->setAttribute('quantity', $optionsValues['qty']);
} else { } else {
$e->setAttribute('id', $product['product_id']); $catalog->setAttribute('id', $product['product_id']);
$e->setAttribute('productId', $product['product_id']); $catalog->setAttribute('productId', $product['product_id']);
$e->setAttribute('quantity', $product['quantity']); $catalog->setAttribute('quantity', $product['quantity']);
} }
/**
* Set type for offers
*/
$useServices = $servicesForIcml && isset($product['shipping']) && $product['shipping'] == 0;
$catalog->setAttribute('type', $useServices ? 'service' : 'product');
/** /**
* Offer activity * Offer activity
*/ */
$activity = $product['status'] == 1 ? 'Y' : 'N'; $activity = $product['status'] == 1 ? 'Y' : 'N';
$e->appendChild( $catalog->appendChild(
$this->dd->createElement('productActivity') $this->dd->createElement('productActivity')
)->appendChild( )->appendChild(
$this->dd->createTextNode($activity) $this->dd->createTextNode($activity)
@ -183,7 +199,7 @@ class ModelExtensionRetailcrmIcml extends Model
->getProductCategories($product['product_id']); ->getProductCategories($product['product_id']);
if (!empty($categories)) { if (!empty($categories)) {
foreach ($categories as $category) { foreach ($categories as $category) {
$e->appendChild($this->dd->createElement('categoryId')) $catalog->appendChild($this->dd->createElement('categoryId'))
->appendChild( ->appendChild(
$this->dd->createTextNode($category) $this->dd->createTextNode($category)
); );
@ -192,18 +208,18 @@ class ModelExtensionRetailcrmIcml extends Model
/** /**
* Name & price * Name & price
*/ */
$e->appendChild($this->dd->createElement('productName')) $catalog->appendChild($this->dd->createElement('productName'))
->appendChild($this->dd->createTextNode($product['name'])); ->appendChild($this->dd->createTextNode($product['name']));
if (!empty($options)) { if (!empty($options)) {
$optionsString = array(); $optionsString = [];
foreach($options as $option) { foreach($options as $option) {
$optionsString[] = $option['name'].': '.$option['value']; $optionsString[] = $option['name'].': '.$option['value'];
} }
$optionsString = ' ('.implode(', ', $optionsString).')'; $optionsString = ' ('.implode(', ', $optionsString).')';
$e->appendChild($this->dd->createElement('name')) $catalog->appendChild($this->dd->createElement('name'))
->appendChild($this->dd->createTextNode($product['name'].$optionsString)); ->appendChild($this->dd->createTextNode($product['name'].$optionsString));
} else { } else {
$e->appendChild($this->dd->createElement('name')) $catalog->appendChild($this->dd->createElement('name'))
->appendChild($this->dd->createTextNode($product['name'])); ->appendChild($this->dd->createTextNode($product['name']));
} }
@ -217,13 +233,13 @@ class ModelExtensionRetailcrmIcml extends Model
$price = $product['price'] + $optionsValues['price']; $price = $product['price'] + $optionsValues['price'];
} }
$e->appendChild($this->dd->createElement('price')) $catalog->appendChild($this->dd->createElement('price'))
->appendChild($this->dd->createTextNode($price)); ->appendChild($this->dd->createTextNode($price));
/** /**
* Vendor * Vendor
*/ */
if ($product['manufacturer_id'] != 0) { if ($product['manufacturer_id'] != 0) {
$e->appendChild($this->dd->createElement('vendor')) $catalog->appendChild($this->dd->createElement('vendor'))
->appendChild( ->appendChild(
$this->dd->createTextNode( $this->dd->createTextNode(
$offerManufacturers[$product['manufacturer_id']] $offerManufacturers[$product['manufacturer_id']]
@ -264,7 +280,7 @@ class ModelExtensionRetailcrmIcml extends Model
$productHeight $productHeight
); );
$e->appendChild($this->dd->createElement('dimensions')) $catalog->appendChild($this->dd->createElement('dimensions'))
->appendChild($this->dd->createTextNode($dimensions)); ->appendChild($this->dd->createTextNode($dimensions));
} }
@ -273,14 +289,14 @@ class ModelExtensionRetailcrmIcml extends Model
*/ */
if ($product['image']) { if ($product['image']) {
$image = $this->generateImage($product['image']); $image = $this->generateImage($product['image']);
$e->appendChild($this->dd->createElement('picture')) $catalog->appendChild($this->dd->createElement('picture'))
->appendChild($this->dd->createTextNode($image)); ->appendChild($this->dd->createTextNode($image));
} }
/** /**
* Url * Url
*/ */
$this->url = new Url(HTTP_CATALOG, HTTPS_CATALOG); $this->url = new Url(HTTP_CATALOG, HTTPS_CATALOG);
$e->appendChild($this->dd->createElement('url')) $catalog->appendChild($this->dd->createElement('url'))
->appendChild( ->appendChild(
$this->dd->createTextNode( $this->dd->createTextNode(
$this->url->link( $this->url->link(
@ -298,7 +314,7 @@ class ModelExtensionRetailcrmIcml extends Model
$param->setAttribute('code', $optionData['option_id']); $param->setAttribute('code', $optionData['option_id']);
$param->setAttribute('name', $optionData['name']); $param->setAttribute('name', $optionData['name']);
$param->appendChild($this->dd->createTextNode($optionData['value'])); $param->appendChild($this->dd->createTextNode($optionData['value']));
$e->appendChild($param); $catalog->appendChild($param);
} }
} }
if ($product['sku']) { if ($product['sku']) {
@ -306,24 +322,24 @@ class ModelExtensionRetailcrmIcml extends Model
$sku->setAttribute('code', 'article'); $sku->setAttribute('code', 'article');
$sku->setAttribute('name', $this->language->get('article')); $sku->setAttribute('name', $this->language->get('article'));
$sku->appendChild($this->dd->createTextNode($product['sku'])); $sku->appendChild($this->dd->createTextNode($product['sku']));
$e->appendChild($sku); $catalog->appendChild($sku);
} }
if ($product['weight'] != '') { if ($product['weight'] != '') {
$weight = $this->dd->createElement('param'); $weight = $this->dd->createElement('weight');
$weight->setAttribute('code', 'weight'); $coeffWeight = 1;
$weight->setAttribute('name', $this->language->get('weight'));
if (!empty($optionsValues['weight'])) { if (!empty($weightClasses[$product['weight_class_id']]['value'])) {
$weightValue = round($product['weight'] + $optionsValues['weight'], 3); $coeffWeight = $weightClasses[$product['weight_class_id']]['value'];
} else {
$weightValue = round($product['weight'], 3);
} }
if (isset($product['weight_class'])) { $weightValue = !empty($optionsValues['weight'])
$weightValue = $weightValue . ' ' . $product['weight_class']; ? $product['weight'] + $optionsValues['weight']
} : $product['weight']
;
$weightValue = round($weightValue / $coeffWeight, 6);
$weight->appendChild($this->dd->createTextNode($weightValue)); $weight->appendChild($this->dd->createTextNode($weightValue));
$e->appendChild($weight); $catalog->appendChild($weight);
} }
} }
} }
@ -336,7 +352,7 @@ class ModelExtensionRetailcrmIcml extends Model
private function generateImage($image) private function generateImage($image)
{ {
$this->load->model('tool/image'); $this->load->model('tool/image');
$currentTheme = $this->config->get('config_theme'); $currentTheme = $this->config->get('config_theme');
$width = $this->config->get($currentTheme . '_image_related_width') ? $this->config->get($currentTheme . '_image_related_width') : 200; $width = $this->config->get($currentTheme . '_image_related_width') ? $this->config->get($currentTheme . '_image_related_width') : 200;
$height = $this->config->get($currentTheme . '_image_related_height') ? $this->config->get($currentTheme . '_image_related_height') : 200; $height = $this->config->get($currentTheme . '_image_related_height') ? $this->config->get($currentTheme . '_image_related_height') : 200;

View file

@ -158,6 +158,22 @@ class ModelExtensionRetailcrmReferences extends Model
return (!$response->isSuccessful()) ? array() : $response->deliveryTypes; return (!$response->isSuccessful()) ? array() : $response->deliveryTypes;
} }
/**
* Get RetailCRM available sites list
*/
public function getApiSite()
{
$response = $this->retailcrmApiClient->sitesList();
if (!$response || !$response->isSuccessful()) {
return [];
}
$sites = $response->sites;
return end($sites);
}
/** /**
* Get RetailCRM order statuses * Get RetailCRM order statuses
* *

View file

@ -1,5 +1,11 @@
.retailcrm_unit {margin-bottom: 10px;} .retailcrm_unit {margin-bottom: 10px;}
.retailcrm_disable_border {border: none !important;}
.retailcrm_unit input {width: 30%;} .retailcrm_unit input {width: 30%;}
.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;}
.question-mark {
cursor: help;
position: relative;
}

View file

@ -97,7 +97,22 @@
</div> </div>
</fieldset> </fieldset>
<fieldset> <fieldset>
<legend><?php echo $text_currency; ?></legend> <legend><?php echo $icml_settings; ?></legend>
<div class="form-group retailcrm_unit">
<label class="col-sm-2 control-label question-mark" for="retailcrm_icml_service_enabled" title="When the option is enabled, all products for which delivery is disabled will be considered as services and uploaded to CRM as services"><?php echo $icml_service_enabled_label; ?></label>
<div class="col-sm-10">
<label class="radio-inline">
<input type="radio" name="retailcrm_icml_service_enabled value="1"
<?php if(isset($saved_settings['retailcrm_icml_service_enabled']) && $saved_settings['retailcrm_icml_service_enabled'] == 1): echo 'checked'; endif;?>/>
<?php echo $text_yes; ?>
</label>
<label class="radio-inline">
<input type="radio" name="retailcrm_icml_service_enabled" value="0"
<?php if(!isset($saved_settings['retailcrm_icml_service_enabled']) || $saved_settings['retailcrm_icml_service_enabled'] == 0): echo 'checked'; endif;?>/>
<?php echo $text_no; ?>
</label>
</div>
</div
<div class="form-group retailcrm_unit"> <div class="form-group retailcrm_unit">
<label class="col-sm-2 control-label"><?php echo $text_currency; ?></label> <label class="col-sm-2 control-label"><?php echo $text_currency; ?></label>
<div class="col-md-4 col-sm-10"> <div class="col-md-4 col-sm-10">
@ -112,9 +127,6 @@
</select> </select>
</div> </div>
</div> </div>
</fieldset>
<fieldset>
<legend><?php echo $text_lenght; ?></legend>
<div class="form-group retailcrm_unit"> <div class="form-group retailcrm_unit">
<label class="col-sm-2 control-label"><?php echo $text_lenght_label; ?></label> <label class="col-sm-2 control-label"><?php echo $text_lenght_label; ?></label>
<div class="col-md-4 col-sm-10"> <div class="col-md-4 col-sm-10">
@ -213,6 +225,26 @@
</div> </div>
</div> </div>
</fieldset> </fieldset>
<fieldset>
<legend><?php echo $summ_around; ?></legend>
<div class="form-group">
<label class="col-sm-2 control-label" for="retailcrm_summ_around"><?php echo $text_summ_around; ?></label>
<div class="col-sm-10">
<label class="radio-inline">
<input type="radio" name="retailcrm_summ_around" value="1" <?php if (isset($saved_settings['retailcrm_summ_around']) &&
$saved_settings['retailcrm_summ_around'] == 1) :
echo 'checked'; endif; ?> />
<?php echo $text_yes; ?>
</label>
<label class="radio-inline">
<input type="radio" name="retailcrm_summ_around" value="0" <?php if (!isset($saved_settings['retailcrm_summ_around']) ||
$saved_settings['retailcrm_summ_around'] == 0) :
echo 'checked'; endif; ?> />
<?php echo $text_no; ?>
</label>
</div>
</div>
</fieldset>
<fieldset> <fieldset>
<legend><?php echo $text_retailcrm_discount; ?></legend> <legend><?php echo $text_retailcrm_discount; ?></legend>
<div class="form-group"> <div class="form-group">

View file

@ -9,7 +9,7 @@
<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-text-o"></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-default"><i class="fa fa-reply"></i></a></div>
<h1>{{ heading_title }}</h1> <h1>{{ heading_title }} {{ module_version }}</h1>
<ul class="breadcrumb"> <ul class="breadcrumb">
{% for breadcrumb in breadcrumbs %} {% for breadcrumb in breadcrumbs %}
<li><a href="{{ breadcrumb.href }}">{{ breadcrumb.text }}</a></li> <li><a href="{{ breadcrumb.href }}">{{ breadcrumb.text }}</a></li>
@ -55,7 +55,7 @@
<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="form-group retailcrm_unit retailcrm_disable_border">
<label class="col-sm-2 control-label" for="retailcrm_apikey">{{ retailcrm_apikey }}</label> <label class="col-sm-2 control-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 %}">
@ -100,8 +100,27 @@
</div> </div>
</fieldset> </fieldset>
<fieldset> <fieldset>
<legend>{{ text_currency }}</legend> <legend>{{ icml_settings }}</legend>
<div class="form-group retailcrm_unit"> <div class="form-group retailcrm_unit retailcrm_disable_border">
<label class="col-sm-2 control-label question-mark" for="module_retailcrm_icml_service_enabled" title="{{ icml_service_description }}">{{ icml_service_enabled_label }}</label>
<div class="col-sm-10">
<label class="radio-inline">
<input type="radio" name="module_retailcrm_icml_service_enabled" value="1"
{% if saved_settings.module_retailcrm_icml_service_enabled is defined and saved_settings.module_retailcrm_icml_service_enabled == 1 %}
checked
{% endif %} />
{{ text_yes }}
</label>
<label class="radio-inline">
<input type="radio" name="module_retailcrm_icml_service_enabled" value="0"
{% if saved_settings.module_retailcrm_icml_service_enabled is not defined or saved_settings.module_retailcrm_icml_service_enabled == 0 %}
checked
{% endif %} />
{{ text_no }}
</label>
</div>
</div>
<div class="form-group retailcrm_unit retailcrm_disable_border">
<label class="col-sm-2 control-label">{{ text_currency_label }}</label> <label class="col-sm-2 control-label">{{ text_currency_label }}</label>
<div class="col-md-4 col-sm-10"> <div class="col-md-4 col-sm-10">
<select id="module_retailcrm_currency" name="module_retailcrm_currency" class="form-control"> <select id="module_retailcrm_currency" name="module_retailcrm_currency" class="form-control">
@ -115,17 +134,14 @@
</select> </select>
</div> </div>
</div> </div>
</fieldset> <div class="form-group retailcrm_unit retailcrm_disable_border">
<fieldset>
<legend>{{ text_lenght }}</legend>
<div class="form-group retailcrm_unit">
<label class="col-sm-2 control-label">{{ text_lenght_label }}</label> <label class="col-sm-2 control-label">{{ text_lenght_label }}</label>
<div class="col-md-4 col-sm-10"> <div class="col-md-4 col-sm-10">
<select id="module_retailcrm_lenght" name="module_retailcrm_lenght" class="form-control"> <select id="module_retailcrm_lenght" name="module_retailcrm_lenght" class="form-control">
{% for lenght in lenghts %} {% for lenght in lenghts %}
<option value="{{ lenght.length_class_id }}" {% if saved_settings.module_retailcrm_lenght is defined and saved_settings.module_retailcrm_lenght == lenght.length_class_id %} selected="selected" {% endif %}> <option value="{{ lenght.length_class_id }}" {% if saved_settings.module_retailcrm_lenght is defined and saved_settings.module_retailcrm_lenght == lenght.length_class_id %} selected="selected" {% endif %}>
{{ lenght.title }} {{ lenght.title }}
</option> </option>
{% endfor %} {% endfor %}
</select> </select>
</div> </div>
@ -220,6 +236,28 @@
</div> </div>
</div> </div>
</fieldset> </fieldset>
<fieldset>
<legend>{{ summ_around }}</legend>
<div class="form-group">
<label class="col-sm-2 control-label" class="col-sm-2 control-label" for="module_retailcrm_summ_around">{{ text_summ_around }}</label>
<div class="col-sm-10">
<label class="control-label" class="radio-inline">
<input type="radio" name="module_retailcrm_summ_around" value="1"
{% if saved_settings.module_retailcrm_summ_around is defined and saved_settings.module_retailcrm_summ_around == 1 %}
checked
{% endif %} />
{{ text_yes }}
</label>
<label class="control-label" class="radio-inline">
<input type="radio" name="module_retailcrm_summ_around" value="0"
{% if saved_settings.module_retailcrm_summ_around is not defined or saved_settings.module_retailcrm_summ_around == 0 %}
checked
{% endif %} />
{{ text_no }}
</label>
</div>
</div>
</fieldset>
<fieldset> <fieldset>
<legend>{{ text_retailcrm_discount }}</legend> <legend>{{ text_retailcrm_discount }}</legend>
<div class="form-group"> <div class="form-group">

View file

@ -138,6 +138,20 @@ class ControllerExtensionModuleRetailcrm extends Controller {
} }
} }
public function customer_edit_newsletter($parameter1, $parameter2, $parameter3)
{
$customerId = $this->customer->getId();
$customer = $this->model_account_customer->getCustomer($customerId);
if (file_exists(DIR_APPLICATION . 'model/extension/retailcrm/custom/customer.php')) {
$this->load->model('extension/retailcrm/custom/customer');
$this->model_extension_retailcrm_custom_customer->changeInCrm($customer, $this->retailcrmApiClient);
} else {
$customer_manager = $this->retailcrm->getCustomerManager();
$customer_manager->editCustomerNewsLetter($customer);
}
}
/** /**
* Update customer on event * Update customer on event
* *

View file

@ -136,6 +136,12 @@ class ModelExtensionRetailcrmOrder extends Model {
$order['number'] = $order_data['order_id']; $order['number'] = $order_data['order_id'];
} }
if (isset($this->settings[$this->moduleTitle . '_summ_around'])
&& $this->settings[$this->moduleTitle . '_summ_around'] == 1
) {
$order['applyRound'] = true;
}
$order['externalId'] = $order_id; $order['externalId'] = $order_id;
$order['firstName'] = $order_data['shipping_firstname']; $order['firstName'] = $order_data['shipping_firstname'];
$order['lastName'] = $order_data['shipping_lastname']; $order['lastName'] = $order_data['shipping_lastname'];
@ -420,6 +426,7 @@ class ModelExtensionRetailcrmOrder extends Model {
'lastName' => $data['lastname'], 'lastName' => $data['lastname'],
'email' => $data['email'], 'email' => $data['email'],
'createdAt' => $data['date_added'], 'createdAt' => $data['date_added'],
'externalId' => $data['customer_id'],
'address' => array( 'address' => array(
'countryIso' => $data['payment_iso_code_2'], 'countryIso' => $data['payment_iso_code_2'],
'index' => $data['payment_postcode'], 'index' => $data['payment_postcode'],

View file

@ -584,30 +584,18 @@ class RetailcrmApiClient5
/** /**
* Get orders history * Get orders history
*
* @param array $filter * @param array $filter
* @param null $page * @param int|null $limit
* @param null $limit
* *
* @return ApiResponse * @return ApiResponse
*/ */
public function ordersHistory(array $filter = array(), $page = null, $limit = null) public function ordersHistory(array $filter = [], ?int $limit = 100)
{ {
$parameters = array();
if (count($filter)) {
$parameters['filter'] = $filter;
}
if (null !== $page) {
$parameters['page'] = (int) $page;
}
if (null !== $limit) {
$parameters['limit'] = (int) $limit;
}
return $this->client->makeRequest( return $this->client->makeRequest(
'/orders/history', '/orders/history',
RetailcrmHttpClient::METHOD_GET, RetailcrmHttpClient::METHOD_GET,
$parameters ['filter' => $filter, 'limit' => $limit]
); );
} }
@ -908,30 +896,18 @@ class RetailcrmApiClient5
/** /**
* Get customers history * Get customers history
*
* @param array $filter * @param array $filter
* @param null $page * @param int|null $limit
* @param null $limit
* *
* @return ApiResponse * @return ApiResponse
*/ */
public function customersHistory(array $filter = array(), $page = null, $limit = null) public function customersHistory(array $filter = [], ?int $limit = 100)
{ {
$parameters = array();
if (count($filter)) {
$parameters['filter'] = $filter;
}
if (null !== $page) {
$parameters['page'] = (int) $page;
}
if (null !== $limit) {
$parameters['limit'] = (int) $limit;
}
return $this->client->makeRequest( return $this->client->makeRequest(
'/customers/history', '/customers/history',
RetailcrmHttpClient::METHOD_GET, RetailcrmHttpClient::METHOD_GET,
$parameters ['filter' => $filter, 'limit' => $limit]
); );
} }
@ -1108,34 +1084,17 @@ class RetailcrmApiClient5
/** /**
* Get orders assembly history * Get orders assembly history
* *
* @param array $filter (default: array()) * @param array $filter
* @param int $page (default: null) * @param int|null $limit
* @param int $limit (default: null)
*
* @throws \InvalidArgumentException
* @throws \RetailCrm\Exception\CurlException
* @throws \RetailCrm\Exception\InvalidJsonException
* *
* @return ApiResponse * @return ApiResponse
*/ */
public function ordersPacksHistory(array $filter = array(), $page = null, $limit = null) public function ordersPacksHistory(array $filter = [], ?int $limit = 100)
{ {
$parameters = array();
if (count($filter)) {
$parameters['filter'] = $filter;
}
if (null !== $page) {
$parameters['page'] = (int) $page;
}
if (null !== $limit) {
$parameters['limit'] = (int) $limit;
}
return $this->client->makeRequest( return $this->client->makeRequest(
'/orders/packs/history', '/orders/packs/history',
RetailcrmHttpClient::METHOD_GET, RetailcrmHttpClient::METHOD_GET,
$parameters ['filter' => $filter, 'limit' => $limit]
); );
} }
@ -2452,30 +2411,18 @@ class RetailcrmApiClient5
/** /**
* Get corporate customers history * Get corporate customers history
* @param array $filter
* @param null $page
* @param null $limit
* *
* @return \ApiResponse * @param array $filter
* @param int|null $limit
*
* @return ApiResponse
*/ */
public function customersCorporateHistory(array $filter = [], $page = null, $limit = null) public function customersCorporateHistory(array $filter = [], ?int $limit = 100)
{ {
$parameters = [];
if (count($filter)) {
$parameters['filter'] = $filter;
}
if (null !== $page) {
$parameters['page'] = (int) $page;
}
if (null !== $limit) {
$parameters['limit'] = (int) $limit;
}
return $this->client->makeRequest( return $this->client->makeRequest(
'/customers-corporate/history', '/customers-corporate/history',
RetailcrmHttpClient::METHOD_GET, RetailcrmHttpClient::METHOD_GET,
$parameters ['filter' => $filter, 'limit' => $limit]
); );
} }

View file

@ -1,5 +1,7 @@
<?php <?php
use retailcrm\Retailcrm;
class RetailcrmHttpClient class RetailcrmHttpClient
{ {
const METHOD_GET = 'GET'; const METHOD_GET = 'GET';
@ -46,9 +48,9 @@ class RetailcrmHttpClient
public function makeRequest( public function makeRequest(
$path, $path,
$method, $method,
array $parameters = array() array $parameters = []
) { ) {
$allowedMethods = array(self::METHOD_GET, self::METHOD_POST); $allowedMethods = [self::METHOD_GET, self::METHOD_POST];
if (!in_array($method, $allowedMethods, false)) { if (!in_array($method, $allowedMethods, false)) {
throw new \InvalidArgumentException( throw new \InvalidArgumentException(
@ -60,7 +62,16 @@ class RetailcrmHttpClient
); );
} }
$parameters = array_merge($this->defaultParameters, $parameters);
$parameters = self::METHOD_GET === $method
? array_merge($this->defaultParameters, $parameters, [
'cms_source' => 'OpenCart',
'cms_version' => VERSION,
'php_version' => function_exists('phpversion') ? phpversion() : '',
'module_version' => Retailcrm::VERSION_MODULE,
])
: $parameters = array_merge($this->defaultParameters, $parameters);
$url = $this->url . $path; $url = $this->url . $path;

View file

@ -6,7 +6,7 @@
* @method ordersCreate($order, $site = null) * @method ordersCreate($order, $site = null)
* @method ordersEdit($order, $by = 'externalId', $site = null) * @method ordersEdit($order, $by = 'externalId', $site = null)
* @method ordersGet($order, $by = 'externalId', $site = null) * @method ordersGet($order, $by = 'externalId', $site = null)
* @method ordersList($filter, $page, $limit) * @method ordersList(array $filter = [], $page = null, $limit = null)
* @method customersCreate($customer, $site = null) * @method customersCreate($customer, $site = null)
* @method customersEdit($customer, $by = 'externalId', $site = null) * @method customersEdit($customer, $by = 'externalId', $site = null)
* @method customersList(array $filter = [], $page = null, $limit = null) * @method customersList(array $filter = [], $page = null, $limit = null)
@ -27,16 +27,16 @@ class RetailcrmProxy {
public function __construct($url, $key) { public function __construct($url, $key) {
$this->api = new RetailcrmApiClient5($url, $key); $this->api = new RetailcrmApiClient5($url, $key);
$this->log = new \Log('retailcrm.log'); $this->log = new \Log('retailcrm.log');
} }
public function __call($method, $arguments) { public function __call($method, $arguments) {
try { try {
$response = call_user_func_array(array($this->api, $method), $arguments); $response = call_user_func_array([$this->api, $method], $arguments);
if (!$response->isSuccessful()) { if (!$response->isSuccessful()) {
$this->log->write(sprintf("[%s] %s", $method, $response->getErrorMsg())); $this->log->write(sprintf("[%s] %s", $method, $response->getErrorMsg()));
if (isset($response['errors'])) { if (isset($response['errors'])) {
$error = implode("\n", $response['errors']); $error = implode("\n", $response['errors']);
$this->log->write($error . "\n"); $this->log->write($error . "\n");

View file

@ -38,10 +38,14 @@ class Customer {
} }
$customer_data['firstname'] = $customer['firstName']; $customer_data['firstname'] = $customer['firstName'];
$customer_data['lastname'] = isset($customer['lastName']) ? $customer['lastName'] : ''; $customer_data['lastname'] = $customer['lastName'] ?? '';
$customer_data['email'] = $customer['email']; $customer_data['email'] = $customer['email'];
$customer_data['telephone'] = $customer['phones'] ? $customer['phones'][0]['number'] : ''; $customer_data['telephone'] = $customer['phones'] ? $customer['phones'][0]['number'] : '';
if (!empty($customer['emailMarketingUnsubscribedAt'])) {
$customer_data['newsletter'] = 0;
}
$customer_data['affiliate'] = false; $customer_data['affiliate'] = false;
} }
@ -109,7 +113,7 @@ class Customer {
} }
} }
$customer_data['custom_field'] = isset($custom_fields) ? $custom_fields : ''; $customer_data['custom_field'] = $custom_fields ?? [];
} }
} }
} }

View file

@ -124,6 +124,7 @@ class DataRepository extends \retailcrm\Base {
* @return array * @return array
*/ */
public function getZoneByName($name) { public function getZoneByName($name) {
$name = $this->db->escape($name);
$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "zone` WHERE name = '" . $name . "'"); $query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "zone` WHERE name = '" . $name . "'");
return $query->row; return $query->row;

View file

@ -12,7 +12,7 @@ class CustomerManager {
} }
public function createCustomer($customer_data, $address) { public function createCustomer($customer_data, $address) {
$customer = $this->prepareCustomer($customer_data, $address); $customer = $this->prepareCustomer($customer_data, $address, !empty($customer_data['newsletter']));
$this->api->customersCreate($customer); $this->api->customersCreate($customer);
} }
@ -23,13 +23,22 @@ class CustomerManager {
$this->api->customersEdit($customer); $this->api->customersEdit($customer);
} }
public function editCustomerNewsLetter($customer_data) {
$this->api->customersEdit(
[
'externalId' => $customer_data['customer_id'],
'subscribed' => !empty($customer_data['newsletter']),
]
);
}
public function uploadCustomers($customers) { public function uploadCustomers($customers) {
$this->api->customersUpload($customers); $this->api->customersUpload($customers);
} }
public function prepareCustomer($customer_data, $address) { public function prepareCustomer($customer_data, $address, $isSubscribed = null) {
return $this->customer_converter return $this->customer_converter
->initCustomerData($customer_data, $address) ->initCustomerData($customer_data, $address, $isSubscribed)
->setCustomerData() ->setCustomerData()
->setAddress() ->setAddress()
->setCustomFields() ->setCustomFields()

View file

@ -4,9 +4,9 @@ namespace retailcrm\service;
class RetailcrmCustomerConverter { class RetailcrmCustomerConverter {
protected $data; protected $data;
protected $customer_data = array(); protected $customer_data = [];
protected $address = array(); protected $address = [];
protected $isSubscribed;
protected $settingsManager; protected $settingsManager;
public function __construct( public function __construct(
@ -19,10 +19,11 @@ class RetailcrmCustomerConverter {
return $this->data; return $this->data;
} }
public function initCustomerData($customer_data, $address) { public function initCustomerData($customer_data, $address, $isSubscribed) {
$this->data = array(); $this->data = [];
$this->customer_data = $customer_data; $this->customer_data = $customer_data;
$this->address = $address; $this->address = $address;
$this->isSubscribed = $isSubscribed;
return $this; return $this;
} }
@ -34,12 +35,12 @@ class RetailcrmCustomerConverter {
$this->data['email'] = $this->customer_data['email']; $this->data['email'] = $this->customer_data['email'];
$this->data['createdAt'] = $this->customer_data['date_added']; $this->data['createdAt'] = $this->customer_data['date_added'];
if ($this->isSubscribed !== null) {
$this->data['subscribed'] = $this->isSubscribed;
}
if (!empty($this->customer_data['telephone'])) { if (!empty($this->customer_data['telephone'])) {
$this->data['phones'] = array( $this->data['phones'] = [['number' => $this->customer_data['telephone']]];
array(
'number' => $this->customer_data['telephone']
)
);
} }
return $this; return $this;
@ -47,13 +48,13 @@ class RetailcrmCustomerConverter {
public function setAddress() { public function setAddress() {
if (!empty($this->address)) { if (!empty($this->address)) {
$this->data['address'] = array( $this->data['address'] = [
'index' => $this->address['postcode'], 'index' => $this->address['postcode'],
'countryIso' => $this->address['iso_code_2'], 'countryIso' => $this->address['iso_code_2'],
'region' => $this->address['zone'], 'region' => $this->address['zone'],
'city' => $this->address['city'], 'city' => $this->address['city'],
'text' => $this->address['address_1'] . ' ' . $this->address['address_2'] 'text' => $this->address['address_1'] . ' ' . $this->address['address_2']
); ];
} }
return $this; return $this;

View file

@ -43,12 +43,14 @@ class RetailcrmOrderConverter {
$this->data['countryIso'] = $this->order_data['shipping_iso_code_2']; $this->data['countryIso'] = $this->order_data['shipping_iso_code_2'];
} }
if ($this->settingsManager->getSetting('order_number') if ($this->settingsManager->getSetting('order_number') == 1) {
&& $this->settingsManager->getSetting('order_number') == 1
) {
$this->data['number'] = $this->order_data['order_id']; $this->data['number'] = $this->order_data['order_id'];
} }
if ($this->settingsManager->getSetting('summ_around') == 1) {
$this->data['applyRound'] = true;
}
$this->data['externalId'] = $this->order_data['order_id']; $this->data['externalId'] = $this->order_data['order_id'];
$this->data['firstName'] = $this->order_data['shipping_firstname']; $this->data['firstName'] = $this->order_data['shipping_firstname'];
$this->data['lastName'] = $this->order_data['shipping_lastname']; $this->data['lastName'] = $this->order_data['shipping_lastname'];

View file

@ -14,6 +14,7 @@
<field id="cumulative_discount" group="customer">cumulativeDiscount</field> <field id="cumulative_discount" group="customer">cumulativeDiscount</field>
<field id="personal_discount" group="customer">personalDiscount</field> <field id="personal_discount" group="customer">personalDiscount</field>
<field id="discount_card_number" group="customer">discountCardNumber</field> <field id="discount_card_number" group="customer">discountCardNumber</field>
<field id="email_marketing_unsubscribed_at" group="customer">emailMarketingUnsubscribedAt</field>
<field id="address.index" group="customerAddress">index</field> <field id="address.index" group="customerAddress">index</field>
<field id="address.country" group="customerAddress">country</field> <field id="address.country" group="customerAddress">country</field>

View file

@ -16,6 +16,7 @@ class Retailcrm {
const RETAILCRM_DISCOUNT = 'retailcrm_discount'; const RETAILCRM_DISCOUNT = 'retailcrm_discount';
const RETAILCRM_DISCOUNT_SORT_ORDER = 8; const RETAILCRM_DISCOUNT_SORT_ORDER = 8;
const VERSION_MODULE = '4.1.19';
protected $registry; protected $registry;
@ -242,6 +243,15 @@ class Retailcrm {
return false; return false;
} }
public function useServicesForIcml()
{
$this->load->model('setting/setting');
$setting = $this->model_setting_setting->getSetting($this->getModuleTitle());
return $setting['module_retailcrm_icml_service_enabled'] ?? false;
}
/** /**
* @return mixed * @return mixed
*/ */

View file

@ -41,4 +41,63 @@ class ControllerRetailcrmAdminTest extends TestCase
$response = $this->dispatchAction('extension/module/retailcrm/uninstall_collector'); $response = $this->dispatchAction('extension/module/retailcrm/uninstall_collector');
$this->assertRegExp('/Connection settings/', $response->getOutput()); $this->assertRegExp('/Connection settings/', $response->getOutput());
} }
public function testGetAvailableTypes()
{
$data = $this->getDataForTestAvailableTypes();
$sites = end($data['site']);
$types = $data['types'];
$retailCrm = new ControllerExtensionModuleRetailcrm(self::$registry);
$class = new ReflectionClass($retailCrm);
$method = $class->getMethod('getAvailableTypes');
$method->setAccessible(true);
$result = $method->invokeArgs($retailCrm, [$sites, $types]);
$this->assertNotEmpty($result['opencart']);
$this->assertNotEmpty($result['retailcrm']);
$this->assertCount(2, $result['retailcrm']);
$this->assertNotEmpty($result['retailcrm']['test1']['code']);
$this->assertNotEmpty($result['retailcrm']['test4']['code']);
}
private function getDataForTestAvailableTypes(): array
{
return [
'site' => [
'opencart' => [
'code' => 'opencart',
'name' => 'OpenCart'
]
],
'types' => [
'opencart' => [
'test'
],
'retailcrm' => [
'test1' => [
'active' => true,
'sites' => [],
'code' => 'test1'
],
'test2' => [
'active' => false,
'sites' => [],
'code' => 'test2'
],
'test3' => [
'active' => true,
'sites' => ['otherSite'],
'code' => 'test3'
],
'test4' => [
'active' => true,
'sites' => ['cms1', 'cms2', 'opencart'],
'code' => 'test4'
]
]
]
];
}
} }

View file

@ -19,6 +19,8 @@ class DataRepositoryAdminTest extends TestCase {
$this->assertNotEmpty($zone); $this->assertNotEmpty($zone);
$this->assertNotEmpty($zone['zone_id']); $this->assertNotEmpty($zone['zone_id']);
$repository->getZoneByName('Rostov-na-Do\'nu');
} }
public function testGetCurrencyByCode() { public function testGetCurrencyByCode() {

View file

@ -11,7 +11,7 @@ class RetailcrmCustomerConverterTest extends TestCase {
$customer_data = $model->getCustomer(1); $customer_data = $model->getCustomer(1);
$customer = $converter $customer = $converter
->initCustomerData($customer_data, array()) ->initCustomerData($customer_data, [], true)
->setCustomerData() ->setCustomerData()
->getCustomer(); ->getCustomer();
@ -20,23 +20,24 @@ class RetailcrmCustomerConverterTest extends TestCase {
$this->assertEquals($customer_data['lastname'], $customer['lastName']); $this->assertEquals($customer_data['lastname'], $customer['lastName']);
$this->assertEquals($customer_data['email'], $customer['email']); $this->assertEquals($customer_data['email'], $customer['email']);
$this->assertEquals($customer_data['date_added'], $customer['createdAt']); $this->assertEquals($customer_data['date_added'], $customer['createdAt']);
$this->assertTrue($customer['subscribed']);
} }
public function testSetAddress() { public function testSetAddress() {
$converter = \retailcrm\factory\CustomerConverterFactory::create(static::$registry); $converter = \retailcrm\factory\CustomerConverterFactory::create(static::$registry);
$model = $this->loadModel('account/customer'); $model = $this->loadModel('account/customer');
$customer_data = $model->getCustomer(static::CUSTOMER_ID); $customer_data = $model->getCustomer(static::CUSTOMER_ID);
$address = array( $address = [
'postcode' => '111111', 'postcode' => '111111',
'iso_code_2' => 'EN', 'iso_code_2' => 'EN',
'zone' => 'Zone', 'zone' => 'Zone',
'city' => 'City', 'city' => 'City',
'address_1' => 'Address', 'address_1' => 'Address',
'address_2' => '' 'address_2' => ''
); ];
$customer = $converter $customer = $converter
->initCustomerData($customer_data, $address) ->initCustomerData($customer_data, $address, null)
->setAddress() ->setAddress()
->getCustomer(); ->getCustomer();