diff --git a/Block/Adminhtml/System/Config/Button.php b/Block/Adminhtml/System/Config/Button.php
index 872c540..b472340 100644
--- a/Block/Adminhtml/System/Config/Button.php
+++ b/Block/Adminhtml/System/Config/Button.php
@@ -72,4 +72,4 @@ class Button extends \Magento\Config\Block\System\Config\Form\Field
return $button->toHtml();
}
-}
\ No newline at end of file
+}
diff --git a/Block/Adminhtml/System/Config/Form/Field/Attributes.php b/Block/Adminhtml/System/Config/Form/Field/Attributes.php
index d7c933e..0b872e7 100644
--- a/Block/Adminhtml/System/Config/Form/Field/Attributes.php
+++ b/Block/Adminhtml/System/Config/Form/Field/Attributes.php
@@ -1,61 +1,63 @@
getValues();
- $html = '
';
- $html .= '';
- $html .= '';
-
- $selected = explode(',', $element->getValue());
- foreach ($selected as $value) {
- if ($key = array_search($value, array_column($values, 'value'))) {
- $html .= '- ';
- $html .= isset($values[$key]['label'])?$values[$key]['label']:'n/a';
- $html .= '
';
- $values[$key]['selected'] = TRUE;
- }
- }
-
- $html .= ' | ';
- $html .= '';
- if ($values) {
- foreach ($values as $option) {
- if (!isset($option['selected'])) {
- $html .= '- ';
- $html .= isset($option['label'])?$option['label']:'n/a';
- $html .= '
';
- }
- }
- }
-
- $html .= ' |
';
- $html .= '' . $element->getElementHtml() . '
';
- $html .= '';
-
- return $html;
- }
-
-}
\ No newline at end of file
+ protected function _getElementHtml(AbstractElement $element)
+ {
+ $values = $element->getValues();
+ $html = '';
+ $html .= '';
+ $html .= '';
+
+ $selected = explode(',', $element->getValue());
+
+ foreach ($selected as $value) {
+ if ($key = array_search($value, array_column($values, 'value'))) {
+ $html .= '- ';
+ $html .= isset($values[$key]['label'])?$values[$key]['label']:'n/a';
+ $html .= '
';
+ $values[$key]['selected'] = TRUE;
+ }
+ }
+
+ $html .= ' | ';
+ $html .= '';
+
+ if ($values) {
+ foreach ($values as $option) {
+ if (!isset($option['selected'])) {
+ $html .= '- ';
+ $html .= isset($option['label'])?$option['label']:'n/a';
+ $html .= '
';
+ }
+ }
+ }
+
+ $html .= ' |
';
+ $html .= '' . $element->getElementHtml() . '
';
+ $html .= '';
+
+ return $html;
+ }
+}
diff --git a/Block/Adminhtml/System/Config/Form/Field/ListMode.php b/Block/Adminhtml/System/Config/Form/Field/ListMode.php
new file mode 100644
index 0000000..4f36103
--- /dev/null
+++ b/Block/Adminhtml/System/Config/Form/Field/ListMode.php
@@ -0,0 +1,16 @@
+ 'grid', 'label' => __('Grid Only')],
+ ['value' => 'list', 'label' => __('List Only')],
+ ['value' => 'grid-list', 'label' => __('Grid (default) / List')],
+ ['value' => 'list-grid', 'label' => __('List (default) / Grid')]
+ ];
+ }
+}
\ No newline at end of file
diff --git a/Block/Adminhtml/System/Config/Form/Field/Payment.php b/Block/Adminhtml/System/Config/Form/Field/Payment.php
index 567af4d..bc1c6f9 100644
--- a/Block/Adminhtml/System/Config/Form/Field/Payment.php
+++ b/Block/Adminhtml/System/Config/Form/Field/Payment.php
@@ -1,96 +1,87 @@
get('\Psr\Log\LoggerInterface');
- $this->_logger = $logger;
-
- $base = new Base;
-
- $this->_apiUrl = $base->_apiUrl;
- $this->_apiKey = $base->_apiKey;
-
- $this->_systemStore = $systemStore;
- $this->_formFactory = $formFactory;
-
- }
-
- public function render(AbstractElement $element)
- {
- $values = $element->getValues();
- $html = '';
-
- if((!empty($this->_apiUrl))&&(!empty($this->_apiKey))){
-
- $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
- $paymentConfig = $objectManager->get('Magento\Payment\Model\Config');
- $activePaymentMethods = $paymentConfig->getActiveMethods();
-
- $client = new \Retailcrm\Retailcrm\Model\ApiClient\ApiClient($this->_apiUrl,$this->_apiKey);
-
- try {
- $response = $client->paymentTypesList();
- if ($response->isSuccessful()&&200 === $response->getStatusCode()) {
- $paymentTypes = $response['paymentTypes'];
- }
- } catch (Retailcrm\Retailcrm\Model\ApiClient\Exception\CurlException $e) {
- $this->_logger->addDebug($e->getMessage());
- }
-
- $config = \Magento\Framework\App\ObjectManager::getInstance()->get(
- 'Magento\Framework\App\Config\ScopeConfigInterface'
- );
-
- foreach (array_keys($activePaymentMethods) as $k=>$payment){
- $html .='';
- $html .='';
- $html .=''.$payment.' | ';
- $html .='';
- $html .='';
- $html .=' | ';
- $html .='
';
- $html .='
';
-
- }
-
- return $html;
- }else{
- $html = 'Please check your API Url & API Key
';
-
- return $html;
- }
- }
-
-
-}
\ No newline at end of file
+ protected $_apiUrl;
+ protected $_apiKey;
+ protected $_systemStore;
+ protected $_formFactory;
+ protected $_logger;
+
+ public function __construct(
+ \Magento\Framework\Data\FormFactory $formFactory,
+ \Magento\Store\Model\System\Store $systemStore
+ ) {
+ $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
+ $config = $objectManager->get('\Magento\Framework\App\Config\ScopeConfigInterface');
+ $this->_apiUrl = $config->getValue('retailcrm/general/api_url');
+ $this->_apiKey = $config->getValue('retailcrm/general/api_key');
+ $this->_apiVersion = $config->getValue('retailcrm/general/api_version');
+ $this->_systemStore = $systemStore;
+ $this->_formFactory = $formFactory;
+ }
+
+ public function render(AbstractElement $element)
+ {
+ $html = '';
+ $htmlError = 'Please check your API Url & API Key
';
+
+ if ((!empty($this->_apiUrl)) && (!empty($this->_apiKey))) {
+ $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
+ $paymentConfig = $objectManager->get('Magento\Payment\Model\Config');
+ $activePaymentMethods = $paymentConfig->getActiveMethods();
+
+ $client = new ApiClient($this->_apiUrl, $this->_apiKey, $this->_apiVersion);
+
+ $response = $client->paymentTypesList();
+
+ if ($response === false) {
+ return $htmlError;
+ }
+
+ if ($response->isSuccessful()) {
+ $paymentTypes = $response['paymentTypes'];
+ } else {
+ return $htmlError;
+ }
+
+ $config = \Magento\Framework\App\ObjectManager::getInstance()->get(
+ 'Magento\Framework\App\Config\ScopeConfigInterface'
+ );
+
+ foreach (array_keys($activePaymentMethods) as $k=>$payment){
+ $html .='';
+ $html .='';
+ $html .=''.$payment.' | ';
+ $html .='';
+ $html .='';
+ $html .= ' | ';
+ $html .= '
';
+ $html .= '
';
+ }
+
+ return $html;
+ } else {
+ return $htmlError;
+ }
+ }
+}
diff --git a/Block/Adminhtml/System/Config/Form/Field/Shipping.php b/Block/Adminhtml/System/Config/Form/Field/Shipping.php
index 7fd896b..6cdb525 100644
--- a/Block/Adminhtml/System/Config/Form/Field/Shipping.php
+++ b/Block/Adminhtml/System/Config/Form/Field/Shipping.php
@@ -1,99 +1,88 @@
get('\Psr\Log\LoggerInterface');
- $this->_logger = $logger;
-
- $base = new Base;
-
- $this->_apiUrl = $base->_apiUrl;
- $this->_apiKey = $base->_apiKey;
-
- $this->_systemStore = $systemStore;
- $this->_formFactory = $formFactory;
-
- }
-
- public function render(AbstractElement $element)
- {
- $values = $element->getValues();
- $html = '';
-
- if(!empty($this->_apiUrl) && !empty($this->_apiKey)) {
-
- $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
- $shipConfig = $objectManager->get('Magento\Shipping\Model\Config');
- $deliveryMethods = $shipConfig->getActiveCarriers();
-
- $client = new \Retailcrm\Retailcrm\Model\ApiClient\ApiClient($this->_apiUrl,$this->_apiKey);
-
- try {
- $response = $client->deliveryTypesList();
- if ($response->isSuccessful()&&200 === $response->getStatusCode()) {
- $deliveryTypes = $response['deliveryTypes'];
- }
- } catch (Retailcrm\Retailcrm\Model\ApiClient\Exception\CurlException $e) {
- $this->_logger->addDebug($e->getMessage());
- }
-
- $config = \Magento\Framework\App\ObjectManager::getInstance()->get(
- 'Magento\Framework\App\Config\ScopeConfigInterface'
- );
-
- foreach (array_keys($deliveryMethods) as $k=>$delivery){
- $html .='';
- $html .='';
- $html .=''.$delivery.' | ';
- $html .='';
- $html .='';
- $html .=' | ';
- $html .='
';
- $html .='
';
-
- }
-
- return $html;
-
- } else {
- $html .= 'Please check your API Url & API Key
';
- }
-
- $html = '';
-
- return $html;
-
- }
-
-
-}
\ No newline at end of file
+ protected $_apiUrl;
+ protected $_apiKey;
+ protected $_systemStore;
+ protected $_formFactory;
+ protected $_logger;
+ protected $_objectManager;
+
+ public function __construct(
+ \Magento\Framework\Data\FormFactory $formFactory,
+ \Magento\Store\Model\System\Store $systemStore
+ ) {
+ $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
+ $config = $objectManager->get('\Magento\Framework\App\Config\ScopeConfigInterface');
+ $this->_apiUrl = $config->getValue('retailcrm/general/api_url');
+ $this->_apiKey = $config->getValue('retailcrm/general/api_key');
+ $this->_apiVersion = $config->getValue('retailcrm/general/api_version');
+ $this->_systemStore = $systemStore;
+ $this->_formFactory = $formFactory;
+ $this->_objectManager = $objectManager;
+ }
+
+ public function render(AbstractElement $element)
+ {
+ $html = '';
+ $htmlError = 'Please check your API Url & API Key
';
+
+ if (!empty($this->_apiUrl) && !empty($this->_apiKey)) {
+ $shipConfig = $this->_objectManager->get('Magento\Shipping\Model\Config');
+ $deliveryMethods = $shipConfig->getActiveCarriers();
+
+ $client = new ApiClient($this->_apiUrl, $this->_apiKey, $this->_apiVersion);
+
+ $response = $client->deliveryTypesList();
+
+ if ($response === false) {
+ return $htmlError;
+ }
+
+ if ($response->isSuccessful()) {
+ $deliveryTypes = $response['deliveryTypes'];
+ } else {
+ return $htmlError;
+ }
+
+ $config = \Magento\Framework\App\ObjectManager::getInstance()->get(
+ 'Magento\Framework\App\Config\ScopeConfigInterface'
+ );
+
+ foreach (array_keys($deliveryMethods) as $k => $delivery) {
+ $html .='';
+ $html .='';
+ $html .=''.$delivery.' | ';
+ $html .='';
+ $html .='';
+ $html .=' | ';
+ $html .='
';
+ $html .='
';
+ }
+
+ return $html;
+ } else {
+ return $htmlError;
+ }
+ }
+}
diff --git a/Block/Adminhtml/System/Config/Form/Field/Status.php b/Block/Adminhtml/System/Config/Form/Field/Status.php
index 803a4f5..f02d7f3 100644
--- a/Block/Adminhtml/System/Config/Form/Field/Status.php
+++ b/Block/Adminhtml/System/Config/Form/Field/Status.php
@@ -1,96 +1,91 @@
get('\Psr\Log\LoggerInterface');
- $this->_logger = $logger;
-
- $base = new Base;
-
- $this->_apiUrl = $base->_apiUrl;
- $this->_apiKey = $base->_apiKey;
-
- $this->_systemStore = $systemStore;
- $this->_formFactory = $formFactory;
-
- }
-
- public function render(AbstractElement $element)
- {
- $values = $element->getValues();
- $html = '';
-
- if((!empty($this->_apiUrl))&&(!empty($this->_apiKey))){
- $manager = \Magento\Framework\App\ObjectManager::getInstance();
- $obj = $manager->create('Magento\Sales\Model\ResourceModel\Order\Status\Collection');
- $statuses = $obj->toOptionArray();
-
- $client = new \Retailcrm\Retailcrm\Model\ApiClient\ApiClient($this->_apiUrl,$this->_apiKey);
-
- try {
- $response = $client->statusesList();
- if ($response->isSuccessful()&&200 === $response->getStatusCode()) {
- $statusTypes = $response['statuses'];
- }
- } catch (Retailcrm\Retailcrm\Model\ApiClient\Exception\CurlException $e) {
- $this->_logger->addDebug($e->getMessage());
- }
-
- $config = \Magento\Framework\App\ObjectManager::getInstance()->get(
- 'Magento\Framework\App\Config\ScopeConfigInterface'
- );
-
- foreach ($statuses as $k => $status){
- $html .='';
- $html .='';
- $html .=''.$status['label'].' | ';
- $html .='';
- $html .='';
- $html .=' | ';
- $html .='
';
- $html .='
';
-
- }
-
- return $html;
-
- }else{
- $html = 'Please check your API Url & API Key
';
-
- return $html;
- }
- }
-
-
-}
\ No newline at end of file
+ protected $_apiUrl;
+ protected $_apiKey;
+ protected $_systemStore;
+ protected $_formFactory;
+ protected $_logger;
+ protected $_objectManager;
+
+ public function __construct(
+ \Magento\Framework\Data\FormFactory $formFactory,
+ \Magento\Store\Model\System\Store $systemStore
+ ) {
+ $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
+ $config = $objectManager->get('\Magento\Framework\App\Config\ScopeConfigInterface');
+ $this->_apiUrl = $config->getValue('retailcrm/general/api_url');
+ $this->_apiKey = $config->getValue('retailcrm/general/api_key');
+ $this->_apiVersion = $config->getValue('retailcrm/general/api_version');
+ $this->_systemStore = $systemStore;
+ $this->_formFactory = $formFactory;
+ $this->_objectManager = $objectManager;
+ }
+
+ public function render(AbstractElement $element)
+ {
+ $html = '';
+ $htmlError = 'Please check your API Url & API Key
';
+
+ if ((!empty($this->_apiUrl)) && (!empty($this->_apiKey))) {
+ $statusCollection = $this->_objectManager->create('Magento\Sales\Model\ResourceModel\Order\Status\Collection');
+ $statuses = $statusCollection->toOptionArray();
+
+ $client = new ApiClient($this->_apiUrl, $this->_apiKey, $this->_apiVersion);
+
+ $response = $client->statusesList();
+
+ if ($response === false) {
+ return $htmlError;
+ }
+
+ if ($response->isSuccessful()) {
+ $statusTypes = $response['statuses'];
+ } else {
+ return $htmlError;
+ }
+
+ $config = $this->_objectManager->get('Magento\Framework\App\Config\ScopeConfigInterface');
+
+ foreach ($statuses as $k => $status){
+ $html .= '';
+ $html .= '';
+ $html .= '' . $status['label'] . ' | ';
+ $html .= '';
+ $html .= '';
+ $html .= ' | ';
+ $html .= '
';
+ $html .= '
';
+ }
+
+ return $html;
+ } else {
+ return $htmlError;
+ }
+ }
+}
diff --git a/Block/Display.php b/Block/Display.php
index 02d3588..507ce62 100644
--- a/Block/Display.php
+++ b/Block/Display.php
@@ -1,17 +1,16 @@
_pageFactory = $pageFactory;
- return parent::__construct($context);
- }
+ protected $_pageFactory;
- public function execute()
- {
- return $this->_pageFactory->create();
- }
+ public function __construct(
+ \Magento\Framework\App\Action\Context $context,
+ \Magento\Framework\View\Result\PageFactory $pageFactory
+ ) {
+ $this->_pageFactory = $pageFactory;
+ return parent::__construct($context);
+ }
+
+ public function execute()
+ {
+ return $this->_pageFactory->create();
+ }
}
\ No newline at end of file
diff --git a/Controller/Index/Test.php b/Controller/Index/Test.php
index 5d46c4e..9ef79ef 100644
--- a/Controller/Index/Test.php
+++ b/Controller/Index/Test.php
@@ -7,25 +7,24 @@ use Psr\Log\LoggerInterface;
class Test extends \Magento\Framework\App\Action\Action
{
- protected $logger;
+ protected $logger;
public function __construct(
- LoggerInterface $logger
- ,\Magento\Framework\App\Action\Context $context
- ,\Magento\Framework\View\Page\Config $pageConfig
- ,\Magento\Framework\App\Config\ScopeConfigInterface $config
- )
- {
- $this->logger = $logger;
-
- $api_url = $config->getValue('retailcrm/general/api_url');
- $api_key = $config->getValue('retailcrm/general/api_key');
-
- var_dump($api_key);
- var_dump($api_url);
-
- //$this->logger->debug($api_url);
-
+ LoggerInterface $logger,
+ \Magento\Framework\App\Action\Context $context,
+ \Magento\Framework\View\Page\Config $pageConfig,
+ \Magento\Framework\App\Config\ScopeConfigInterface $config
+ ) {
+ $this->logger = $logger;
+
+ $api_url = $config->getValue('retailcrm/general/api_url');
+ $api_key = $config->getValue('retailcrm/general/api_key');
+
+ var_dump($api_key);
+ var_dump($api_url);
+
+ //$this->logger->debug($api_url);
+
parent::__construct($context);
}
@@ -33,6 +32,5 @@ class Test extends \Magento\Framework\App\Action\Action
{
//
exit;
- }
-
-}
\ No newline at end of file
+ }
+}
diff --git a/Cron/Icml.php b/Cron/Icml.php
index cac587f..c526cef 100644
--- a/Cron/Icml.php
+++ b/Cron/Icml.php
@@ -1,20 +1,19 @@
get('\Psr\Log\LoggerInterface');
- $this->_logger = $logger;
+ $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
+ $logger = new \Retailcrm\Retailcrm\Model\Logger\Logger($objectManager);
+ $this->_logger = $logger;
}
- public function execute() {
- $Icml = new \Retailcrm\Retailcrm\Model\Icml\Icml();
- $Icml->generate();
-
- $this->_logger->addDebug('Cron Works: create icml');
+ public function execute()
+ {
+ $Icml = new \Retailcrm\Retailcrm\Model\Icml\Icml();
+ $Icml->generate();
}
-
}
diff --git a/Cron/OrderHistory.php b/Cron/OrderHistory.php
index b2d1229..f46615f 100644
--- a/Cron/OrderHistory.php
+++ b/Cron/OrderHistory.php
@@ -1,20 +1,23 @@
get('\Psr\Log\LoggerInterface');
- $this->_logger = $logger;
- }
-
- public function execute() {
- $history = new \Retailcrm\Retailcrm\Model\History\Exchange();
- $history->ordersHistory();
-
- $this->_logger->addDebug('Cron Works: OrderHistory');
+ $logger = new \Retailcrm\Retailcrm\Model\Logger\Logger($om);
+ $this->_logger = $logger;
}
-}
\ No newline at end of file
+ public function execute()
+ {
+ $history = new \Retailcrm\Retailcrm\Model\History\Exchange();
+ $history->ordersHistory();
+
+ $this->_logger->writeRow('Cron Works: OrderHistory');
+ }
+}
diff --git a/Helper/Data.php b/Helper/Data.php
index d94655c..d3e27ea 100644
--- a/Helper/Data.php
+++ b/Helper/Data.php
@@ -1,4 +1,5 @@
$value) {
- if (is_array($value)) {
- $haystack[$key] = self::filterRecursive($haystack[$key]);
- }
-
- if (is_null($haystack[$key])
- || $haystack[$key] === ''
- || count($haystack[$key]) == 0
- ) {
- unset($haystack[$key]);
- } elseif (!is_array($value)) {
- $haystack[$key] = trim($value);
- }
- }
-
- return $haystack;
+ foreach ($haystack as $key => $value) {
+ if (is_array($value)) {
+ $haystack[$key] = self::filterRecursive($haystack[$key]);
+ }
+
+ if (is_null($haystack[$key])
+ || $haystack[$key] === ''
+ || count($haystack[$key]) == 0
+ ) {
+ unset($haystack[$key]);
+ } elseif (!is_array($value)) {
+ $haystack[$key] = trim($value);
+ }
+ }
+
+ return $haystack;
}
}
\ No newline at end of file
diff --git a/Helper/Proxy.php b/Helper/Proxy.php
new file mode 100644
index 0000000..0ab24e0
--- /dev/null
+++ b/Helper/Proxy.php
@@ -0,0 +1,81 @@
+logger = new Logger($objectManager);
+ $this->apiClient = new ApiClient($url, $key, $apiVersion);
+ }
+
+ public function __call($method, $arguments)
+ {
+ try {
+ $response = call_user_func_array([$this->apiClient->request, $method], $arguments);
+
+ if (!$response->isSuccessful()) {
+ $this->logger->writeRow(
+ sprintf(
+ "[HTTP status %s] %s",
+ $response->getStatusCode(),
+ $response->getErrorMsg()
+ )
+ );
+
+ if (isset($response['errors'])) {
+ $this->logger->writeRow(implode(' :: ', $response['errors']));
+ }
+ }
+ } catch (\RetailCrm\Exception\CurlException $exception) {
+ $this->logger->writeRow($exception->getMessage());
+ return false;
+ } catch (\RetailCrm\Exception\InvalidJsonException $exception) {
+ $this->logger->writeRow($exception->getMessage());
+ return false;
+ } catch (\InvalidArgumentException $exception) {
+ $this->logger->writeRow($exception->getMessage());
+ }
+
+ return $response;
+ }
+
+ /**
+ * Get API version
+ *
+ * @return string
+ */
+ public function getVersion()
+ {
+ if (!is_object($this->apiClient)) {
+ return false;
+ }
+
+ return $this->apiClient->getVersion();
+ }
+
+ /**
+ * Get error text message
+ *
+ * @param string $property
+ *
+ * @return string
+ */
+ public function getErrorText($property)
+ {
+ return $this->{$property};
+ }
+}
diff --git a/Model/Config/Backend/ApiUrl.php b/Model/Config/Backend/ApiUrl.php
new file mode 100644
index 0000000..e5e8b73
--- /dev/null
+++ b/Model/Config/Backend/ApiUrl.php
@@ -0,0 +1,138 @@
+getValue();
+ $apiKey = $this->getFieldsetDataValue('api_key');
+ $apiVersion = $this->getFieldsetDataValue('api_version');
+
+ if (!$this->isUrl($apiUrl)) {
+ throw new \Magento\Framework\Exception\ValidatorException(__('Invalid CRM url'));
+ }
+
+ if (!$this->isHttps($apiUrl)) {
+ $this->schemeEdit($apiUrl);
+ }
+
+ $api = new ApiClient($apiUrl, $apiKey, $apiVersion);
+
+ if ($this->validateApiUrl($api)) {
+ $this->setValue($apiUrl);
+ }
+
+ parent::beforeSave();
+ }
+
+ /**
+ * Call after save api url
+ *
+ * @return void
+ */
+ public function afterSave()
+ {
+ return parent::afterSave();
+ }
+
+ /**
+ * Validate selected api url
+ *
+ * @param ApiClient $api
+ * @param string $apiVersion
+ *
+ * @throws \Magento\Framework\Exception\ValidatorException
+ *
+ * @return boolean
+ */
+ protected function validateApiUrl(ApiClient $api)
+ {
+ $response = $api->availableVersions();
+
+ if ($response === false) {
+ throw new \Magento\Framework\Exception\ValidatorException(__('Verify that the data entered is correct'));
+ } elseif (!$response->isSuccessful() && $response['errorMsg'] == $api->getErrorText ('errorApiKey')) {
+ throw new \Magento\Framework\Exception\ValidatorException(__('Invalid CRM api key'));
+ } elseif (isset($response['errorMsg']) && $response['errorMsg'] == $api->getErrorText('errorAccount')) {
+ throw new \Magento\Framework\Exception\ValidatorException(__('Invalid CRM api url'));
+ }
+
+ return true;
+ }
+
+ /**
+ * Check url scheme
+ *
+ * @param string $url
+ *
+ * @return boolean
+ */
+ protected function isHttps($url)
+ {
+ $url_array = parse_url($url);
+
+ if ($url_array['scheme'] === 'https') {
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ /**
+ * Edit scheme from http to https
+ *
+ * @param string $url
+ *
+ * @return string
+ */
+ protected function schemeEdit(&$url)
+ {
+ $url_array = parse_url($url);
+
+ $url = 'https://' . $url_array['host'];
+ }
+
+ /**
+ * Check url
+ *
+ * @param string $url
+ *
+ * @return type
+ */
+ public function isUrl($url)
+ {
+ return preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $url);
+ }
+}
diff --git a/Model/Config/Backend/ApiVersion.php b/Model/Config/Backend/ApiVersion.php
new file mode 100644
index 0000000..d294f63
--- /dev/null
+++ b/Model/Config/Backend/ApiVersion.php
@@ -0,0 +1,93 @@
+getFieldsetDataValue('api_url');
+ $apiKey = $this->getFieldsetDataValue('api_key');
+ $apiVersion = $this->getValue();
+
+ $api = new ApiClient($apiUrl, $apiKey, $apiVersion);
+
+ $this->validateApiVersion($api, $apiVersion);
+
+ parent::beforeSave();
+ }
+
+ /**
+ * Call after save api version
+ *
+ * @return void
+ */
+ public function afterSave()
+ {
+ return parent::afterSave();
+ }
+
+ /**
+ * Validate selected api version
+ *
+ * @param ApiClient $api
+ * @param string $apiVersion
+ *
+ * @throws \Magento\Framework\Exception\ValidatorException
+ *
+ * @return void
+ */
+ protected function validateApiVersion(ApiClient $api, $apiVersion)
+ {
+ $apiVersions = [
+ 'v4' => '4.0',
+ 'v5' => '5.0'
+ ];
+
+ $response = $api->availableVersions();
+
+ if ($response->isSuccessful()) {
+ $availableVersions = $response['versions'];
+ } else {
+ throw new \Magento\Framework\Exception\ValidatorException(__('Invalid CRM url or api key'));
+ }
+
+ if (isset($availableVersions)) {
+ if (in_array($apiVersions[$apiVersion], $availableVersions)) {
+ $this->setValue($this->getValue());
+ } else {
+ throw new \Magento\Framework\Exception\ValidatorException(__('Selected api version forbidden'));
+ }
+ }
+ }
+}
diff --git a/Model/History/Exchange.php b/Model/History/Exchange.php
index e80ec3d..2a7da17 100644
--- a/Model/History/Exchange.php
+++ b/Model/History/Exchange.php
@@ -1,762 +1,765 @@
get('\Retailcrm\Retailcrm\Helper\Data');
- $logger = $om->get('\Psr\Log\LoggerInterface');
- $config = $om->get('\Magento\Framework\App\Config\ScopeConfigInterface');
- $resourceConfig = $om->get('Magento\Config\Model\ResourceModel\Config');
- $customerFactory = $om->get('\Magento\Customer\Model\CustomerFactory');
- $quote = $om->get('\Magento\Quote\Model\QuoteFactory');
- $customerRepository = $om->get('\Magento\Customer\Api\CustomerRepositoryInterface');
- $product = $om->get('\Magento\Catalog\Model\Product');
- $shipconfig = $om->get('\Magento\Shipping\Model\Config');
- $quoteManagement = $om->get('\Magento\Quote\Model\QuoteManagement');
- $registry = $om->get('\Magento\Framework\Registry');
- $cacheTypeList = $om->get('\Magento\Framework\App\Cache\TypeListInterface');
- $order = $om->get('\Magento\Sales\Api\Data\OrderInterface');
- $orderManagement = $om->get('\Magento\Sales\Api\OrderManagementInterface');
- //$invoiceService = $om->get('\Magento\Sales\Model\Service\InvoiceService');
- //$transaction = $om->get('\Magento\Framework\DB\Transaction');
- $eventManager = $om->get('\Magento\Framework\Event\Manager');
-
-
- $this->_shipconfig = $shipconfig;
- $this->_logger = $logger;
- $this->_helper = $helper;
- $this->_config = $config;
- $this->_resourceConfig = $resourceConfig;
- $this->_customerFactory = $customerFactory;
- $this->_quote = $quote;
- $this->_customerRepository = $customerRepository;
- $this->_product = $product;
- $this->_quoteManagement = $quoteManagement;
- $this->_registry = $registry;
- $this->_cacheTypeList = $cacheTypeList;
- $this->_order = $order;
- $this->_orderManagement = $orderManagement;
- //$this->_transaction = $transaction;
- //$this->_invoiceService = $invoiceService;
- $this->_eventManager = $eventManager;
-
- $url = $config->getValue('retailcrm/general/api_url');
- $key = $config->getValue('retailcrm/general/api_key');
-
- if(!empty($url) && !empty($key)) {
- $this->_api = new \Retailcrm\Retailcrm\Model\ApiClient\ApiClient($url,$key);
- }
- }
-
- public function ordersHistory()
- {
- $historyFilter = array();
- $historiOrder = array();
-
- $historyStart = $this->_config->getValue('retailcrm/general/filter_history');
- if($historyStart && $historyStart > 0) {
- $historyFilter['sinceId'] = $historyStart;
- }
-
- while(true) {
- try {
- $response = $this->_api->ordersHistory($historyFilter);
- if ($response->isSuccessful()&&200 === $response->getStatusCode()) {
- $nowTime = $response->getGeneratedAt();
-
- } else {
- $this->_logger->addDebug(
- sprintf("Orders history error: [HTTP status %s] %s", $response->getStatusCode(), $response->getErrorMsg())
- );
-
- if (isset($response['errors'])) {
- $this->_logger->addDebug(implode(' :: ', $response['errors']));
- }
-
- return false;
- }
- } catch (\Retailcrm\Retailcrm\Model\ApiClient\Exception\CurlException $e) {
-
- $this->_logger->addDebug($e->getMessage());
-
- return false;
- }
-
- $orderH = isset($response['history']) ? $response['history'] : array();
- if(count($orderH) == 0) {
- return true;
- }
-
- $historiOrder = array_merge($historiOrder, $orderH);
- $end = array_pop($response->history);
- $historyFilter['sinceId'] = $end['id'];
-
- if($response['pagination']['totalPageCount'] == 1) {
-
- $this->_resourceConfig->saveConfig('retailcrm/general/filter_history', $historyFilter['sinceId'], 'default', 0);
- $this->_cacheTypeList->cleanType('config');
-
- $orders = self::assemblyOrder($historiOrder);
-
- $logger = new \Retailcrm\Retailcrm\Model\Logger\Logger();
- $logger->write($orders,'OrderHistory');
-
- $this->processOrders($orders, $nowTime);
-
- return true;
- }
- }//endwhile
-
- }
-
- /**
- * @param array $orders
- */
- private function processOrders($orders, $time)
- {
- $logger = new \Retailcrm\Retailcrm\Model\Logger\Logger();
- $logger->write($orders,'processOrders');
-
- if(!empty($orders)) {
-
- foreach ($orders as $order) {
- if(!empty($order['externalId'])) {
- $this->doUpdate($order);
- } else {
- $this->doCreate($order);
- }
- }
-
- die();
- }
- }
-
- /**
- * @param array $order
- */
- private function doCreate($order)
- {
- $logger = new \Retailcrm\Retailcrm\Model\Logger\Logger();
- $logger->write($order,'doCreate');
-
- $payments = $this->_config->getValue('retailcrm/Payment');
- $shippings = $this->_config->getValue('retailcrm/Shipping');
-
- $om = \Magento\Framework\App\ObjectManager::getInstance();
- $manager = $om->get('Magento\Store\Model\StoreManagerInterface');
- $store = $manager->getStore();
- $websiteId = $manager->getStore()->getWebsiteId();
-
- $customer = $this->_customerFactory->create();
- $customer->setWebsiteId($websiteId);
- $customer->loadByEmail($order['email']);// load customet by email address
-
- if(!$customer->getEntityId()){
- //If not avilable then create this customer
- $customer->setWebsiteId($websiteId)
- ->setStore($store)
- ->setFirstname($order['firstName'])
- ->setLastname($order['lastName'])
- ->setEmail($order['email'])
- ->setPassword($order['email']);
- try {
- $customer->save();
- } catch (Exception $e) {
- $this->_logger->addDebug($e->getMessage());
- }
- }
-
- //Create object of quote
- $quote = $this->_quote->create();
-
- //set store for which you create quote
- $quote->setStore($store);
-
- // if you have allready buyer id then you can load customer directly
- $customer = $this->_customerRepository->getById($customer->getEntityId());
- $quote->setCurrency();
- $quote->assignCustomer($customer); //Assign quote to customer
-
- //add items in quote
- foreach($order['items'] as $item){
- $product = $this->_product->load($item['offer']['externalId']);
- $product->setPrice($item['initialPrice']);
- $quote->addProduct(
- $product,
- intval($item['quantity'])
- );
- }
-
- $products = array();
- foreach ($order['items'] as $item) {
- $products[$item['offer']['externalId']] = array('qty' => $item['quantity']);
- }
-
- $orderData = array(
- 'currency_id' => 'USD',
- 'email' => $order['email'],
- 'shipping_address' =>array(
- 'firstname' => $order['firstName'],
- 'lastname' => $order['lastName'],
- 'street' => $order['delivery']['address']['street'],
- 'city' => $order['delivery']['address']['city'],
- 'country_id' => $order['delivery']['address']['countryIso'],//US
- 'region' => $order['delivery']['address']['region'],
- 'postcode' => $order['delivery']['address']['index'],
- 'telephone' => $order['phone'],
- 'save_in_address_book' => 1
- ),
- 'items'=> $products
- );
-
- $shippings = array_flip(array_filter($shippings));
- $payments = array_flip(array_filter($payments));
-
- $ShippingMethods = $this->getAllShippingMethodsCode($shippings[$order['delivery']['code']]);
-
- //Set Address to quote
- $quote->getBillingAddress()->addData($orderData['shipping_address']);
- $quote->getShippingAddress()->addData($orderData['shipping_address']);
-
- $shippingAddress=$quote->getShippingAddress();
- $shippingAddress->setCollectShippingRates(true)
- ->collectShippingRates()
- ->setShippingMethod($ShippingMethods);
-
- $quote->setPaymentMethod($payments[$order['paymentType']]);
- $quote->setInventoryProcessed(false);
+ protected $_api;
+ protected $_config;
+ protected $_helper;
+ protected $_logger;
+ protected $_resourceConfig;
+ protected $_customerFactory;
+ protected $_quote;
+ protected $_customerRepository;
+ protected $_product;
+ protected $_shipconfig;
+ protected $_quoteManagement;
+ protected $_registry;
+ protected $_cacheTypeList;
+ protected $_order;
+ protected $_orderManagement;
+ //protected $_transaction;
+ //protected $_invoiceService;
+ protected $_eventManager;
+ protected $_objectManager;
+
+ public function __construct()
+ {
+ $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
+ $helper = $objectManager->get('\Retailcrm\Retailcrm\Helper\Data');
+ $config = $objectManager->get('\Magento\Framework\App\Config\ScopeConfigInterface');
+ $resourceConfig = $objectManager->get('Magento\Config\Model\ResourceModel\Config');
+ $customerFactory = $objectManager->get('\Magento\Customer\Model\CustomerFactory');
+ $quote = $objectManager->get('\Magento\Quote\Model\QuoteFactory');
+ $customerRepository = $objectManager->get('\Magento\Customer\Api\CustomerRepositoryInterface');
+ $product = $objectManager->get('\Magento\Catalog\Model\Product');
+ $shipconfig = $objectManager->get('\Magento\Shipping\Model\Config');
+ $quoteManagement = $objectManager->get('\Magento\Quote\Model\QuoteManagement');
+ $registry = $objectManager->get('\Magento\Framework\Registry');
+ $cacheTypeList = $objectManager->get('\Magento\Framework\App\Cache\TypeListInterface');
+ $order = $objectManager->get('\Magento\Sales\Api\Data\OrderInterface');
+ $orderManagement = $objectManager->get('\Magento\Sales\Api\OrderManagementInterface');
+ //$invoiceService = $objectManager->get('\Magento\Sales\Model\Service\InvoiceService');
+ //$transaction = $objectManager->get('\Magento\Framework\DB\Transaction');
+ $eventManager = $objectManager->get('\Magento\Framework\Event\Manager');
+ $logger = new \Retailcrm\Retailcrm\Model\Logger\Logger($objectManager);
+
+ $this->_shipconfig = $shipconfig;
+ $this->_logger = $logger;
+ $this->_helper = $helper;
+ $this->_config = $config;
+ $this->_resourceConfig = $resourceConfig;
+ $this->_customerFactory = $customerFactory;
+ $this->_quote = $quote;
+ $this->_customerRepository = $customerRepository;
+ $this->_product = $product;
+ $this->_quoteManagement = $quoteManagement;
+ $this->_registry = $registry;
+ $this->_cacheTypeList = $cacheTypeList;
+ $this->_order = $order;
+ $this->_orderManagement = $orderManagement;
+ //$this->_transaction = $transaction;
+ //$this->_invoiceService = $invoiceService;
+ $this->_eventManager = $eventManager;
+ $this->_objectManager = $objectManager;
+
+ $url = $config->getValue('retailcrm/general/api_url');
+ $key = $config->getValue('retailcrm/general/api_key');
+ $version = $config->getValue('retailcrm/general/api_version');
+
+ if (!empty($url) && !empty($key)) {
+ $this->_api = new ApiClient($url, $key, $version);
+ }
+ }
+
+ /**
+ * Get orders history from CRM
+ *
+ * @return boolean
+ */
+ public function ordersHistory()
+ {
+ $this->_registry->register('RETAILCRM_HISTORY', true);
+
+ $historyFilter = [];
+ $historyOrder = [];
+
+ $historyStart = $this->_config->getValue('retailcrm/general/filter_history');
+
+ if ($historyStart && $historyStart > 0) {
+ $historyFilter['sinceId'] = $historyStart;
+ }
+
+ while (true) {
+ $response = $this->_api->ordersHistory($historyFilter);
+
+ if ($response === false) {
+ return;
+ }
+
+ if (!$response->isSuccessful()) {
+ return true;
+ }
+
+ $orderH = isset($response['history']) ? $response['history'] : [];
+
+ if (count($orderH) == 0) {
+ return true;
+ }
+
+ $historyOrder = array_merge($historyOrder, $orderH);
+ $end = array_pop($orderH);
+ $historyFilter['sinceId'] = $end['id'];
+
+ if ($response['pagination']['totalPageCount'] == 1) {
+ $this->_resourceConfig->saveConfig('retailcrm/general/filter_history', $historyFilter['sinceId'], 'default', 0);
+ $this->_cacheTypeList->cleanType('config');
+
+ $orders = self::assemblyOrder($historyOrder);
+
+ $this->_logger->writeDump($orders,'OrderHistory');
+
+ $this->processOrders($orders);
+
+ return true;
+ }
+ }//endwhile
+
+ $this->_registry->register('RETAILCRM_HISTORY', false);
+ }
+
+ /**
+ * Process orders
+ *
+ * @param array $orders
+ *
+ * @return void
+ */
+ private function processOrders($orders)
+ {
+ $this->_logger->writeDump($orders,'processOrders');
+
+ if (!empty($orders)) {
+ foreach ($orders as $order) {
+ if (isset($order['externalId']) && !empty($order['externalId'])) {
+ $this->doUpdate($order);
+ } else {
+ $this->doCreate($order);
+ }
+ }
+ }
+ }
+
+ /**
+ * Create new order from CRM
+ *
+ * @param array $order
+ *
+ * @return void
+ */
+ private function doCreate($order)
+ {
+ $this->_logger->writeDump($order,'doCreate');
+
+ $payments = $this->_config->getValue('retailcrm/Payment');
+ $shippings = $this->_config->getValue('retailcrm/Shipping');
+
+ $manager = $this->_objectManager->get('Magento\Store\Model\StoreManagerInterface');
+ $region = $this->_objectManager->get('Magento\Directory\Model\RegionFactory')->create();
+ $store = $manager->getStore();
+ $websiteId = $manager->getStore()->getWebsiteId();
+
+ $customer = $this->_customerFactory->create();
+ $customer->setWebsiteId($websiteId);
+
+ if (isset($order['customer']['externalId'])) {
+ $customer->load($order['customer']['externalId']);
+ }
+
+ if (!$customer->getId()) {
+ //If not avilable then create this customer
+ $customer->setWebsiteId($websiteId)
+ ->setStore($store)
+ ->setFirstname($order['firstName'])
+ ->setLastname($order['lastName'])
+ ->setEmail($order['email'])
+ ->setPassword($order['email']);
+ try {
+ $customer->save();
+ } catch (\Exception $exception) {
+ $this->_logger->writeRow($exception->getMessage());
+ }
+
+ $this->_api->customersFixExternalIds(
+ [
+ [
+ 'id' => $order['customer']['id'],
+ 'externalId' => $customer->getId()
+ ]
+ ]
+ );
+ }
+
+ //Create object of quote
+ $quote = $this->_quote->create();
+
+ //set store for which you create quote
+ $quote->setStore($store);
+
+ // if you have allready buyer id then you can load customer directly
+ $customer = $this->_customerRepository->getById($customer->getId());
+ $quote->setCurrency();
+ $quote->assignCustomer($customer); //Assign quote to customer
+
+ //add items in quote
+ foreach($order['items'] as $item){
+ $product = $this->_product->load($item['offer']['externalId']);
+ $product->setPrice($item['initialPrice']);
+ $quote->addProduct(
+ $product,
+ intval($item['quantity'])
+ );
+ }
+
+ $products = [];
+
+ foreach ($order['items'] as $item) {
+ $products[$item['offer']['externalId']] = ['qty' => $item['quantity']];
+ }
+
+ $orderData = [
+ 'currency_id' => $manager->getStore()->getCurrentCurrency()->getCode(),
+ 'email' => $order['email'],
+ 'shipping_address' => [
+ 'firstname' => $order['firstName'],
+ 'lastname' => $order['lastName'],
+ 'street' => $order['delivery']['address']['street'],
+ 'city' => $order['delivery']['address']['city'],
+ 'country_id' => $order['countryIso'],
+ 'region' => $order['delivery']['address']['region'],
+ 'postcode' => $order['delivery']['address']['index'],
+ 'telephone' => $order['phone'],
+ 'save_in_address_book' => 1
+ ],
+ 'items'=> $products
+ ];
+
+ $region->loadByName($order['delivery']['address']['region'], $order['countryIso']);
+
+ if ($region->getId()) {
+ $orderData['shipping_address']['region_id'] = $region->getId();
+ }
+
+ $shippings = array_flip(array_filter($shippings));
+ $payments = array_flip(array_filter($payments));
+
+ $ShippingMethods = $this->getAllShippingMethodsCode($shippings[$order['delivery']['code']]);
+
+ //Set Address to quote
+ $quote->getBillingAddress()->addData($orderData['shipping_address']);
+ $quote->getShippingAddress()->addData($orderData['shipping_address']);
+
+ $shippingAddress = $quote->getShippingAddress();
+ $shippingAddress->setCollectShippingRates(true)
+ ->collectShippingRates()
+ ->setShippingMethod($ShippingMethods);
+
+ if ($this->_api->getVersion() == 'v4') {
+ $paymentType = $order['paymentType'];
+ } elseif ($this->_api->getVersion() == 'v5') {
+ if ($order['payments']) {
+ $paymentType = $this->getPaymentMethod($order['payments']);
+ }
+ }
+
+ $quote->setPaymentMethod($payments[$paymentType]);
+ $quote->setInventoryProcessed(false);
+
+ $quote->save();
+
+ // Set Sales Order Payment
+ $quote->getPayment()->importData(['method' => $payments[$paymentType]]);
+
+ // Collect Totals & Save Quote
+ $quote->collectTotals()->save();
+
+ // Create Order From Quote
+ $magentoOrder = $this->_quoteManagement->submit($quote);
+
+ $increment_id = $magentoOrder->getId();
+
+ $this->_api->ordersFixExternalIds(
+ [
+ [
+ 'id' => $order['id'],
+ 'externalId' => $increment_id
+ ]
+ ]
+ );
+ }
+
+ /**
+ * Create old edited order
+ *
+ * @param array $order
+ *
+ * @return void
+ */
+ private function doCreateUp($order)
+ {
+ $this->_logger->writeDump($order,'doCreateUp');
+
+ $response = $this->_api->ordersGet($order['id'], $by = 'id');
+
+ if (!$response->isSuccessful()) {
+ return;
+ }
+
+ if (isset($response['order'])) {
+ $order = $response['order'];
+ }
+
+ $payments = $this->_config->getValue('retailcrm/Payment');
+ $shippings = $this->_config->getValue('retailcrm/Shipping');
+
+ $manager = $this->_objectManager->get('Magento\Store\Model\StoreManagerInterface');
+ $region = $this->_objectManager->get('Magento\Directory\Model\RegionFactory')->create();
+ $store = $manager->getStore();
+ $websiteId = $manager->getStore()->getWebsiteId();
+
+ $customer = $this->_customerFactory->create();
+ $customer->setWebsiteId($websiteId);
+
+ if (isset($order['customer']['externalId'])) {
+ $customer->load($order['customer']['externalId']); // load customet by external id
+ }
+
+ //Create object of quote
+ $quote = $this->_quote->create();
+
+ //set store for which you create quote
+ $quote->setStore($store);
+ $quote->setCurrency();
+
+ // if you have allready buyer id then you can load customer directly
+ if ($customer->getId()) {
+ $customer = $this->_customerRepository->getById($customer->getId());
+ $quote->assignCustomer($customer); //Assign quote to customer
+ } else {
+ $quote->setCustomerEmail($order['email']);
+ $quote->setCustomerIsGuest(1);
+ }
+
+ //add items in quote
+ foreach($order['items'] as $item){
+ $product = $this->_product->load($item['offer']['externalId']);
+ $product->setPrice($item['initialPrice']);
+ $quote->addProduct(
+ $product,
+ intval($item['quantity'])
+ );
+ }
+
+ $products = [];
+
+ foreach ($order['items'] as $item) {
+ $products[$item['offer']['externalId']] = ['qty' => $item['quantity']];
+ }
+
+ $orderData = [
+ 'currency_id' => $manager->getStore()->getCurrentCurrency()->getCode(),
+ 'email' => $order['email'],
+ 'shipping_address' =>array(
+ 'firstname' => $order['firstName'],
+ 'lastname' => $order['lastName'],
+ 'street' => $order['delivery']['address']['street'],
+ 'city' => $order['delivery']['address']['city'],
+ 'country_id' => $order['countryIso'],//US
+ 'region' => $order['delivery']['address']['region'],
+ 'postcode' => $order['delivery']['address']['index'],
+ 'telephone' => $order['phone'],
+ 'save_in_address_book' => 1
+ ),
+ 'items'=> $products
+ ];
+
+ $region->loadByName($order['delivery']['address']['region'], $order['countryIso']);
+
+ if ($region->getId()) {
+ $orderData['shipping_address']['region_id'] = $region->getId();
+ }
+
+ $shippings = array_flip(array_filter($shippings));
+ $payments = array_flip(array_filter($payments));
+
+ $ShippingMethods = $this->getAllShippingMethodsCode($shippings[$order['delivery']['code']]);
+
+ //Set Address to quote
+ $quote->getBillingAddress()->addData($orderData['shipping_address']);
+ $quote->getShippingAddress()->addData($orderData['shipping_address']);
+
+ $shippingAddress = $quote->getShippingAddress();
+ $shippingAddress->setCollectShippingRates(true)
+ ->collectShippingRates()
+ ->setShippingMethod($ShippingMethods);
+
+ if ($this->_api->getVersion() == 'v4') {
+ $paymentType = $order['paymentType'];
+ } elseif ($this->_api->getVersion() == 'v5') {
+ $paymentType = $this->getPaymentMethod($order['payments'], false);
+ }
+
+ $quote->setPaymentMethod($payments[$paymentType]);
+ $quote->setInventoryProcessed(false);
+
+
+ $originalId = $order['externalId'];
+ $oldOrder = $this->_order->load($originalId);
+
+ $orderDataUp = [
+ 'original_increment_id' => $oldOrder->getIncrementId(),
+ 'relation_parent_id' => $oldOrder->getId(),
+ 'relation_parent_real_id' => $oldOrder->getIncrementId(),
+ 'edit_increment' => $oldOrder->getEditIncrement() + 1,
+ 'increment_id' => $oldOrder->getIncrementId() . '-' . ($oldOrder->getEditIncrement() + 1)
+ ];
- $quote->save();
-
- // Set Sales Order Payment
- $quote->getPayment()->importData(['method' => $payments[$order['paymentType']]]);
-
- // Collect Totals & Save Quote
- $quote->collectTotals()->save();
-
- // Create Order From Quote
- $magentoOrder = $this->_quoteManagement->submit($quote);
-
- try {
- $increment_id = $magentoOrder->getRealOrderId();
- } catch (\Retailcrm\Retailcrm\Model\ApiClient\Exception\CurlException $e) {
- $this->_logger->addDebug($e->getMessage());
- }
-
-
-
- try {
- $response = $this->_api->ordersFixExternalIds(
- array(
- array(
- 'id' => $order['id'],
- 'externalId' =>$increment_id
- )
- )
- );
-
- if (!$response->isSuccessful() || 200 !== $response->getStatusCode()) {
- $this->_logger->addDebug(
- sprintf(
- "Orders fix error: [HTTP status %s] %s",
- $response->getStatusCode(),
- $response->getErrorMsg()
- )
- );
-
- if (isset($response['errors'])) {
- $this->_logger->addDebug(implode(' :: ', $response['errors']));
- }
- }
- } catch (\Retailcrm\Retailcrm\Model\ApiClient\Exception\CurlException $e) {
- $this->_logger->addDebug($e->getMessage());
- }
-
- }
-
- /**
- * @param array $order
- */
- private function doCreateUp($order)
- {
- $logger = new \Retailcrm\Retailcrm\Model\Logger\Logger();
- $logger->write($order,'doCreateUp');
-
- try {
- $response = $this->_api->ordersGet($order['id'], $by = 'id');
-
- if ($response->isSuccessful() && 200 === $response->getStatusCode()) {
- $order = $response->order;
- } else {
- $this->_logger->addDebug(
- sprintf(
- "Orders get error: [HTTP status %s] %s",
- $response->getStatusCode(),
- $response->getErrorMsg()
- )
- );
-
- if (isset($response['errors'])) {
- $this->_logger->addDebug(implode(' :: ', $response['errors']));
- }
- }
- } catch (Retailcrm_Retailcrm_Model_Exception_CurlException $e) {
- $this->_logger->addDebug($e->getMessage());
- }
-
-
- $payments = $this->_config->getValue('retailcrm/Payment');
- $shippings = $this->_config->getValue('retailcrm/Shipping');
-
- $om = \Magento\Framework\App\ObjectManager::getInstance();
- $manager = $om->get('Magento\Store\Model\StoreManagerInterface');
- $store = $manager->getStore();
- $websiteId = $manager->getStore()->getWebsiteId();
-
- $customer = $this->_customerFactory->create();
- $customer->setWebsiteId($websiteId);
- $customer->loadByEmail($order['email']);// load customet by email address
-
- if(!$customer->getEntityId()){
- //If not avilable then create this customer
- $customer->setWebsiteId($websiteId)
- ->setStore($store)
- ->setFirstname($order['firstName'])
- ->setLastname($order['lastName'])
- ->setEmail($order['email'])
- ->setPassword($order['email']);
- try {
- $customer->save();
- } catch (Exception $e) {
- $this->_logger->addDebug($e->getMessage());
- }
- }
-
- //Create object of quote
- $quote = $this->_quote->create();
-
- //set store for which you create quote
- $quote->setStore($store);
-
- // if you have allready buyer id then you can load customer directly
- $customer = $this->_customerRepository->getById($customer->getEntityId());
- $quote->setCurrency();
- $quote->assignCustomer($customer); //Assign quote to customer
-
- //add items in quote
- foreach($order['items'] as $item){
- $product = $this->_product->load($item['offer']['externalId']);
- $product->setPrice($item['initialPrice']);
- $quote->addProduct(
- $product,
- intval($item['quantity'])
- );
- }
-
- $products = array();
- foreach ($order['items'] as $item) {
- $products[$item['offer']['externalId']] = array('qty' => $item['quantity']);
- }
-
- $orderData = array(
- 'currency_id' => 'USD',
- 'email' => $order['email'],
- 'shipping_address' =>array(
- 'firstname' => $order['firstName'],
- 'lastname' => $order['lastName'],
- 'street' => $order['delivery']['address']['street'],
- 'city' => $order['delivery']['address']['city'],
- 'country_id' => $order['delivery']['address']['countryIso'],//US
- 'region' => $order['delivery']['address']['region'],
- 'postcode' => $order['delivery']['address']['index'],
- 'telephone' => $order['phone'],
- 'save_in_address_book' => 1
- ),
- 'items'=> $products
- );
-
- $shippings = array_flip(array_filter($shippings));
- $payments = array_flip(array_filter($payments));
-
- $ShippingMethods = $this->getAllShippingMethodsCode($shippings[$order['delivery']['code']]);
-
- //Set Address to quote
- $quote->getBillingAddress()->addData($orderData['shipping_address']);
- $quote->getShippingAddress()->addData($orderData['shipping_address']);
-
- $shippingAddress=$quote->getShippingAddress();
- $shippingAddress->setCollectShippingRates(true)
- ->collectShippingRates()
- ->setShippingMethod($ShippingMethods);
-
- $quote->setPaymentMethod($payments[$order['paymentType']]);
- $quote->setInventoryProcessed(false);
-
-
- $originalId = $order['externalId'];
- $oldOrder = $this->_order->loadByIncrementId($originalId);
- $oldOrderArr = $oldOrder->getData();
-
- if(!empty($oldOrderArr['original_increment_id'])) {
- $originalId = $oldOrderArr['original_increment_id'];
- }
-
- $orderDataUp = array(
- 'original_increment_id' => $originalId,
- 'relation_parent_id' => $oldOrder->getId(),
- 'relation_parent_real_id' => $oldOrder->getIncrementId(),
- 'edit_increment' => $oldOrder->getEditIncrement()+1,
- 'increment_id' => $originalId.'-'.($oldOrder->getEditIncrement()+1)
- );
-
- print_r($orderDataUp);
-
$quote->setReservedOrderId($orderDataUp['increment_id']);
- $quote->save();
-
- // Set Sales Order Payment
- $quote->getPayment()->importData(['method' => $payments[$order['paymentType']]]);
-
- // Collect Totals & Save Quote
- $quote->collectTotals()->save();
-
- // Create Order From Quote
- $magentoOrder = $this->_quoteManagement->submit($quote,$orderDataUp);
-
- try {
- $increment_id = $magentoOrder->getRealOrderId();
-
- } catch (\Retailcrm\Retailcrm\Model\ApiClient\Exception\CurlException $e) {
- $this->_logger->addDebug($e->getMessage());
- }
-
- try {
- $response = $this->_api->ordersFixExternalIds(
- array(
- array(
- 'id' => $order['id'],
- 'externalId' =>$increment_id
- )
- )
- );
-
- if (!$response->isSuccessful() || 200 !== $response->getStatusCode()) {
- $this->_logger->addDebug(
- sprintf(
- "Orders fix error: [HTTP status %s] %s",
- $response->getStatusCode(),
- $response->getErrorMsg()
- )
- );
-
- if (isset($response['errors'])) {
- $this->_logger->addDebug(implode(' :: ', $response['errors']));
- }
- }
- } catch (\Retailcrm\Retailcrm\Model\ApiClient\Exception\CurlException $e) {
- $this->_logger->addDebug($e->getMessage());
- }
-
-
-
-
- }
-
- /**
- * @param array $order
- */
- private function doUpdate($order)
- {
- $logger = new \Retailcrm\Retailcrm\Model\Logger\Logger();
- $logger->write($order,'doUpdate');
-
- $Status = $this->_config->getValue('retailcrm/Status');
- $Status = array_flip(array_filter($Status));
-
- $magentoOrder = $this->_order->loadByIncrementId($order['externalId']);
- $magentoOrderArr = $magentoOrder->getData();
-
- $logger->write($magentoOrderArr,'magentoOrderArr');
- $logger->write($Status,'status');
-
- if((!empty($order['order_edit']))&&($order['order_edit'] == 1)) {
- $this->doCreateUp($order);
- }
-
- if (!empty($order['status'])) {
- $change = $Status[$order['status']];
-
- if($change == 'canceled'){
- $this->_orderManagement->cancel($magentoOrderArr['entity_id']);
- }
-
- if($change == 'holded'){
- $om = \Magento\Framework\App\ObjectManager::getInstance();
- $order_status = $om->get('Magento\Sales\Model\Order')->load($magentoOrder->getId());
- $order_status->setStatus('holded');
- $order_status->save();
- }
-
- if(($change == 'complete')||($order['status']== 'complete')){
- $om = \Magento\Framework\App\ObjectManager::getInstance();
- $order_status = $om->get('Magento\Sales\Model\Order')->load($magentoOrder->getId());
- $order_status->setStatus('complete');
- $order_status->save();
- }
-
- if($change == 'closed'){
- $om = \Magento\Framework\App\ObjectManager::getInstance();
- $order_status = $om->get('Magento\Sales\Model\Order')->load($magentoOrder->getId());
- $order_status->setStatus('closed');
- $order_status->save();
- }
-
- if($change == 'processing'){
- $om = \Magento\Framework\App\ObjectManager::getInstance();
- $order_status = $om->get('Magento\Sales\Model\Order')->load($magentoOrder->getId());
- $order_status->setStatus('processing');
- $order_status->save();
-
- }
-
- if($change == 'fraud'){
- $om = \Magento\Framework\App\ObjectManager::getInstance();
- $order_status = $om->get('Magento\Sales\Model\Order')->load($magentoOrder->getId());
- $order_status->setStatus('fraud');
- $order_status->save();
- }
-
- if($change == 'payment_review'){
- $om = \Magento\Framework\App\ObjectManager::getInstance();
- $order_status = $om->get('Magento\Sales\Model\Order')->load($magentoOrder->getId());
- $order_status->setStatus('payment_review');
- $order_status->save();
- }
-
- if($change == 'paypal_canceled_reversal'){
- $om = \Magento\Framework\App\ObjectManager::getInstance();
- $order_status = $om->get('Magento\Sales\Model\Order')->load($magentoOrder->getId());
- $order_status->setStatus('paypal_canceled_reversal');
- $order_status->save();
- }
-
- if($change == 'paypal_reversed'){
- $om = \Magento\Framework\App\ObjectManager::getInstance();
- $order_status = $om->get('Magento\Sales\Model\Order')->load($magentoOrder->getId());
- $order_status->setStatus('paypal_reversed');
- $order_status->save();
- }
-
- if($change == 'pending_payment'){
- $om = \Magento\Framework\App\ObjectManager::getInstance();
- $order_status = $om->get('Magento\Sales\Model\Order')->load($magentoOrder->getId());
- $order_status->setStatus('pending_payment');
- $order_status->save();
- }
-
- if($change == 'pending_paypal'){
- $om = \Magento\Framework\App\ObjectManager::getInstance();
- $order_status = $om->get('Magento\Sales\Model\Order')->load($magentoOrder->getId());
- $order_status->setStatus('pending_paypal');
- $order_status->save();
- }
-
-
-
-
-
- }
-
-
-
-
-
-
-
-
- }
-
-
- public static function assemblyOrder($orderHistory)
- {
- $orders = array();
- foreach ($orderHistory as $change) {
- $change['order'] = self::removeEmpty($change['order']);
- if(isset($change['order']['items'])) {
- $items = array();
- foreach($change['order']['items'] as $item) {
- if(isset($change['created'])) {
- $item['create'] = 1;
- }
-
- $items[$item['id']] = $item;
- }
-
- $change['order']['items'] = $items;
- }
-
- $logger = new \Retailcrm\Retailcrm\Model\Logger\Logger();
- $logger->write($change,'retailcrmHistoryAssemblyOrder');
-
-
- if(isset($change['order']['contragent']['contragentType'])) {
- $change['order']['contragentType'] = self::newValue($change['order']['contragent']['contragentType']);
- unset($change['order']['contragent']);
- }
-
- if(isset($orders[$change['order']['id']])) {
- $orders[$change['order']['id']] = array_merge($orders[$change['order']['id']], $change['order']);
- }
- else {
- $orders[$change['order']['id']] = $change['order'];
- }
-
- if($change['field'] == 'manager_comment'){
- $orders[$change['order']['id']][$change['field']] = $change['newValue'];
- }
-
- if(($change['field'] != 'status')&&
- ($change['field'] != 'country')&&
- ($change['field'] != 'manager_comment')&&
- ($change['field'] != 'order_product.status')&&
- ($change['field'] != 'payment_status')&&
- ($change['field'] != 'prepay_sum')
- ) {
- $orders[$change['order']['id']]['order_edit'] = 1;
- }
-
- if(isset($change['item'])) {
- if($orders[$change['order']['id']]['items'][$change['item']['id']]) {
- $orders[$change['order']['id']]['items'][$change['item']['id']] = array_merge($orders[$change['order']['id']]['items'][$change['item']['id']], $change['item']);
- }
-
- else{
- $orders[$change['order']['id']]['items'][$change['item']['id']] = $change['item'];
- }
-
- if(empty($change['oldValue']) && $change['field'] == 'order_product') {
- $orders[$change['order']['id']]['items'][$change['item']['id']]['create'] = 1;
- $orders[$change['order']['id']]['order_edit'] = 1;
- unset($orders[$change['order']['id']]['items'][$change['item']['id']]['delete']);
- }
-
- if(empty($change['newValue']) && $change['field'] == 'order_product') {
- $orders[$change['order']['id']]['items'][$change['item']['id']]['delete'] = 1;
- $orders[$change['order']['id']]['order_edit'] = 1;
- }
-
- if(!empty($change['newValue']) && $change['field'] == 'order_product.quantity') {
- $orders[$change['order']['id']]['order_edit'] = 1;
- }
-
- if(!$orders[$change['order']['id']]['items'][$change['item']['id']]['create'] && $fields['item'][$change['field']]) {
- $orders[$change['order']['id']]['items'][$change['item']['id']][$fields['item'][$change['field']]] = $change['newValue'];
- }
- }
- else {
- if((isset($fields['delivery'][$change['field']]))&&($fields['delivery'][$change['field']] == 'service')) {
- $orders[$change['order']['id']]['delivery']['service']['code'] = self::newValue($change['newValue']);
- }
- elseif(isset($fields['delivery'][$change['field']])) {
- $orders[$change['order']['id']]['delivery'][$fields['delivery'][$change['field']]] = self::newValue($change['newValue']);
- }
- elseif(isset($fields['orderAddress'][$change['field']])) {
- $orders[$change['order']['id']]['delivery']['address'][$fields['orderAddress'][$change['field']]] = $change['newValue'];
- }
- elseif(isset($fields['integrationDelivery'][$change['field']])) {
- $orders[$change['order']['id']]['delivery']['service'][$fields['integrationDelivery'][$change['field']]] = self::newValue($change['newValue']);
- }
- elseif(isset($fields['customerContragent'][$change['field']])) {
- $orders[$change['order']['id']][$fields['customerContragent'][$change['field']]] = self::newValue($change['newValue']);
- }
- elseif(strripos($change['field'], 'custom_') !== false) {
- $orders[$change['order']['id']]['customFields'][str_replace('custom_', '', $change['field'])] = self::newValue($change['newValue']);
- }
- elseif(isset($fields['order'][$change['field']])) {
- $orders[$change['order']['id']][$fields['order'][$change['field']]] = self::newValue($change['newValue']);
- }
-
- if(isset($change['created'])) {
- $orders[$change['order']['id']]['create'] = 1;
- }
-
- if(isset($change['deleted'])) {
- $orders[$change['order']['id']]['deleted'] = 1;
- }
- }
- }
-
- return $orders;
- }
-
- public static function removeEmpty($inputArray)
- {
- $outputArray = array();
- if (!empty($inputArray)) {
- foreach ($inputArray as $key => $element) {
- if(!empty($element) || $element === 0 || $element === '0') {
- if (is_array($element)) {
- $element = self::removeEmpty($element);
- }
-
- $outputArray[$key] = $element;
- }
- }
- }
-
- return $outputArray;
- }
-
- public static function newValue($value)
- {
- if(isset($value['code'])) {
- return $value['code'];
- } else{
- return $value;
- }
- }
-
- public function getAllShippingMethodsCode($mcode)
- {
- $activeCarriers = $this->_shipconfig->getActiveCarriers();
- $storeScope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE;
- foreach($activeCarriers as $carrierCode => $carrierModel)
- {
- $options = array();
- if( $carrierMethods = $carrierModel->getAllowedMethods()) {
- foreach ($carrierMethods as $methodCode => $method) {
- $code= $carrierCode.'_'.$methodCode;
- if($mcode == $carrierCode){
- $methods[$mcode] = $code;
- }
- }
- }
- }
-
- return $methods[$mcode];
- }
-
-}
\ No newline at end of file
+ $quote->save();
+
+ // Set Sales Order Payment
+ $quote->getPayment()->importData(['method' => $payments[$paymentType]]);
+
+ // Collect Totals & Save Quote
+ $quote->collectTotals()->save();
+
+ // Create Order From Quote
+ $magentoOrder = $this->_quoteManagement->submit($quote,$orderDataUp);
+ $oldOrder->setStatus('canceled')->save();
+ $increment_id = $magentoOrder->getId();
+
+ $this->_api->ordersFixExternalIds(
+ [
+ [
+ 'id' => $order['id'],
+ 'externalId' => $increment_id
+ ]
+ ]
+ );
+ }
+
+ /**
+ * Edit order
+ *
+ * @param array $order
+ *
+ * @return void
+ */
+ private function doUpdate($order)
+ {
+ $this->_logger->writeDump($order,'doUpdate');
+
+ $Status = $this->_config->getValue('retailcrm/Status');
+ $Status = array_flip(array_filter($Status));
+
+ $magentoOrder = $this->_order->load($order['externalId']);
+ $magentoOrderArr = $magentoOrder->getData();
+
+ $this->_logger->writeDump($magentoOrderArr, 'magentoOrderArr');
+ $this->_logger->writeDump($Status, 'status');
+
+ if ((!empty($order['order_edit'])) && ($order['order_edit'] == 1)) {
+ $this->doCreateUp($order);
+ }
+
+ if (!empty($order['status'])) {
+ $change = $Status[$order['status']];
+
+ if($change == 'canceled'){
+ $this->_orderManagement->cancel($magentoOrderArr['entity_id']);
+ }
+
+ if($change == 'holded'){
+ $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
+ $order_status = $objectManager->get('Magento\Sales\Model\Order')->load($magentoOrder->getId());
+ $order_status->setStatus('holded');
+ $order_status->save();
+ }
+
+ if(($change == 'complete')||($order['status']== 'complete')){
+ $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
+ $order_status = $objectManager->get('Magento\Sales\Model\Order')->load($magentoOrder->getId());
+ $order_status->setStatus('complete');
+ $order_status->save();
+ }
+
+ if($change == 'closed'){
+ $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
+ $order_status = $objectManager->get('Magento\Sales\Model\Order')->load($magentoOrder->getId());
+ $order_status->setStatus('closed');
+ $order_status->save();
+ }
+
+ if($change == 'processing'){
+ $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
+ $order_status = $objectManager->get('Magento\Sales\Model\Order')->load($magentoOrder->getId());
+ $order_status->setStatus('processing');
+ $order_status->save();
+
+ }
+
+ if($change == 'fraud'){
+ $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
+ $order_status = $objectManager->get('Magento\Sales\Model\Order')->load($magentoOrder->getId());
+ $order_status->setStatus('fraud');
+ $order_status->save();
+ }
+
+ if($change == 'payment_review'){
+ $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
+ $order_status = $objectManager->get('Magento\Sales\Model\Order')->load($magentoOrder->getId());
+ $order_status->setStatus('payment_review');
+ $order_status->save();
+ }
+
+ if($change == 'paypal_canceled_reversal'){
+ $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
+ $order_status = $objectManager->get('Magento\Sales\Model\Order')->load($magentoOrder->getId());
+ $order_status->setStatus('paypal_canceled_reversal');
+ $order_status->save();
+ }
+
+ if($change == 'paypal_reversed'){
+ $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
+ $order_status = $objectManager->get('Magento\Sales\Model\Order')->load($magentoOrder->getId());
+ $order_status->setStatus('paypal_reversed');
+ $order_status->save();
+ }
+
+ if($change == 'pending_payment'){
+ $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
+ $order_status = $objectManager->get('Magento\Sales\Model\Order')->load($magentoOrder->getId());
+ $order_status->setStatus('pending_payment');
+ $order_status->save();
+ }
+
+ if($change == 'pending_paypal'){
+ $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
+ $order_status = $objectManager->get('Magento\Sales\Model\Order')->load($magentoOrder->getId());
+ $order_status->setStatus('pending_paypal');
+ $order_status->save();
+ }
+ }
+ }
+
+ /**
+ * Assembly orders from history
+ *
+ * @param array $orderHistory
+ *
+ * @return array $orders
+ */
+ public static function assemblyOrder($orderHistory)
+ {
+ $orders = [];
+
+ foreach ($orderHistory as $change) {
+ $change['order'] = self::removeEmpty($change['order']);
+
+ if (isset($change['order']['items'])) {
+ $items = [];
+
+ foreach ($change['order']['items'] as $item) {
+ if (isset($change['created'])) {
+ $item['create'] = 1;
+ }
+
+ $items[$item['id']] = $item;
+ }
+
+ $change['order']['items'] = $items;
+ }
+
+ if (isset($change['order']['contragent']['contragentType'])) {
+ $change['order']['contragentType'] = self::newValue($change['order']['contragent']['contragentType']);
+ unset($change['order']['contragent']);
+ }
+
+ if (isset($orders[$change['order']['id']])) {
+ $orders[$change['order']['id']] = array_merge($orders[$change['order']['id']], $change['order']);
+ } else {
+ $orders[$change['order']['id']] = $change['order'];
+ }
+
+ if ($change['field'] == 'manager_comment') {
+ $orders[$change['order']['id']][$change['field']] = $change['newValue'];
+ }
+
+ if (($change['field'] != 'status')
+ && ($change['field'] != 'country')
+ && ($change['field'] != 'manager_comment')
+ && ($change['field'] != 'order_product.status')
+ && ($change['field'] != 'payment_status')
+ && ($change['field'] != 'prepay_sum')
+ ) {
+ $orders[$change['order']['id']]['order_edit'] = 1;
+ }
+
+ if (isset($change['item'])) {
+ if (isset($orders[$change['order']['id']]['items'])
+ && $orders[$change['order']['id']]['items'][$change['item']['id']]
+ ) {
+ $orders[$change['order']['id']]['items'][$change['item']['id']] = array_merge($orders[$change['order']['id']]['items'][$change['item']['id']], $change['item']);
+ } else{
+ $orders[$change['order']['id']]['items'][$change['item']['id']] = $change['item'];
+ }
+
+ if (empty($change['oldValue']) && $change['field'] == 'order_product') {
+ $orders[$change['order']['id']]['items'][$change['item']['id']]['create'] = 1;
+ $orders[$change['order']['id']]['order_edit'] = 1;
+ unset($orders[$change['order']['id']]['items'][$change['item']['id']]['delete']);
+ }
+
+ if (empty($change['newValue']) && $change['field'] == 'order_product') {
+ $orders[$change['order']['id']]['items'][$change['item']['id']]['delete'] = 1;
+ $orders[$change['order']['id']]['order_edit'] = 1;
+ }
+
+ if (!empty($change['newValue']) && $change['field'] == 'order_product.quantity') {
+ $orders[$change['order']['id']]['order_edit'] = 1;
+ }
+
+ if (!$orders[$change['order']['id']]['items'][$change['item']['id']]['create'] && $fields['item'][$change['field']]) {
+ $orders[$change['order']['id']]['items'][$change['item']['id']][$fields['item'][$change['field']]] = $change['newValue'];
+ }
+ } else {
+ if ((isset($fields['delivery'][$change['field']]))&&($fields['delivery'][$change['field']] == 'service')) {
+ $orders[$change['order']['id']]['delivery']['service']['code'] = self::newValue($change['newValue']);
+ } elseif (isset($fields['delivery'][$change['field']])) {
+ $orders[$change['order']['id']]['delivery'][$fields['delivery'][$change['field']]] = self::newValue($change['newValue']);
+ } elseif (isset($fields['orderAddress'][$change['field']])) {
+ $orders[$change['order']['id']]['delivery']['address'][$fields['orderAddress'][$change['field']]] = $change['newValue'];
+ } elseif (isset($fields['integrationDelivery'][$change['field']])) {
+ $orders[$change['order']['id']]['delivery']['service'][$fields['integrationDelivery'][$change['field']]] = self::newValue($change['newValue']);
+ } elseif (isset($fields['customerContragent'][$change['field']])) {
+ $orders[$change['order']['id']][$fields['customerContragent'][$change['field']]] = self::newValue($change['newValue']);
+ } elseif (strripos($change['field'], 'custom_') !== false) {
+ $orders[$change['order']['id']]['customFields'][str_replace('custom_', '', $change['field'])] = self::newValue($change['newValue']);
+ } elseif (isset($fields['order'][$change['field']])) {
+ $orders[$change['order']['id']][$fields['order'][$change['field']]] = self::newValue($change['newValue']);
+ }
+
+ if (isset($change['created'])) {
+ $orders[$change['order']['id']]['create'] = 1;
+ }
+
+ if (isset($change['deleted'])) {
+ $orders[$change['order']['id']]['deleted'] = 1;
+ }
+ }
+ }
+
+ return $orders;
+ }
+
+ /**
+ * Remove empty elements
+ *
+ * @param array $inputArray
+ *
+ * @return array $outputArray
+ */
+ public static function removeEmpty($inputArray)
+ {
+ $outputArray = [];
+
+ if (!empty($inputArray)) {
+ foreach ($inputArray as $key => $element) {
+ if(!empty($element) || $element === 0 || $element === '0') {
+ if (is_array($element)) {
+ $element = self::removeEmpty($element);
+ }
+
+ $outputArray[$key] = $element;
+ }
+ }
+ }
+
+ return $outputArray;
+ }
+
+ /**
+ * Set new value
+ *
+ * @param mixed $value
+ *
+ * @return string $value
+ */
+ public static function newValue($value)
+ {
+ if(isset($value['code'])) {
+ return $value['code'];
+ } else{
+ return $value;
+ }
+ }
+
+ /**
+ * Get shipping methods
+ *
+ * @param string $mcode
+ *
+ * @return string
+ */
+ public function getAllShippingMethodsCode($mcode)
+ {
+ $activeCarriers = $this->_shipconfig->getActiveCarriers();
+ $storeScope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE;
+
+ foreach($activeCarriers as $carrierCode => $carrierModel) {
+ $options = [];
+
+ if ($carrierMethods = $carrierModel->getAllowedMethods()) {
+ foreach ($carrierMethods as $methodCode => $method) {
+ $code = $carrierCode . '_'. $methodCode;
+
+ if ($mcode == $carrierCode) {
+ $methods[$mcode] = $code;
+ }
+ }
+ }
+ }
+
+ return $methods[$mcode];
+ }
+
+ /**
+ * Get payment type for api v5
+ *
+ * @param array $payments
+ * @param boolean $newOrder
+ *
+ * @return mixed
+ */
+ protected function getPaymentMethod($payments, $newOrder = true)
+ {
+ if (count($payments) == 1 || $newOrder) {
+ $payment = reset($payments);
+ } elseif (count($payments) > 1 && !$newOrder) {
+ foreach ($payments as $paymentCrm) {
+ if (isset($paymentCrm['externalId'])) {
+ $payment = $paymentCrm;
+ }
+ }
+ }
+
+ if (isset($payment)) {
+ return $payment['type'];
+ }
+
+ return false;
+ }
+}
diff --git a/Model/Icml/Icml.php b/Model/Icml/Icml.php
index ebb79bb..c16adc2 100644
--- a/Model/Icml/Icml.php
+++ b/Model/Icml/Icml.php
@@ -1,4 +1,5 @@
get('Magento\Store\Model\StoreManagerInterface');
- $categoryCollectionFactory = $om->get('\Magento\Catalog\Model\ResourceModel\Category\CollectionFactory');
- $product = $om->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
- $storeManager = $om->get('\Magento\Store\Model\StoreManagerInterface');
- $StockState = $om->get('\Magento\CatalogInventory\Api\StockStateInterface');
- $configurable = $om->get('Magento\ConfigurableProduct\Model\Product\Type\Configurable');
- $config = $om->get('\Magento\Framework\App\Config\ScopeConfigInterface');
-
- $this->_configurable = $configurable;
- $this->_StockState = $StockState;
- $this->_storeManager = $storeManager;
- $this->_product = $product;
- $this->_category = $categoryCollectionFactory;
- $this->_manager = $manager;
- $this->_config = $config;
+ $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
+ $manager = $objectManager->get('Magento\Store\Model\StoreManagerInterface');
+ $categoryCollectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Category\CollectionFactory');
+ $product = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
+ $storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface');
+ $StockState = $objectManager->get('\Magento\CatalogInventory\Api\StockStateInterface');
+ $configurable = $objectManager->get('Magento\ConfigurableProduct\Model\Product\Type\Configurable');
+ $config = $objectManager->get('\Magento\Framework\App\Config\ScopeConfigInterface');
+
+ $this->_configurable = $configurable;
+ $this->_StockState = $StockState;
+ $this->_storeManager = $storeManager;
+ $this->_product = $product;
+ $this->_category = $categoryCollectionFactory;
+ $this->_manager = $manager;
+ $this->_config = $config;
}
- public function generate()
- {
+ public function generate()
+ {
$this->_shop = $this->_manager->getStore()->getId();
$string = '
@@ -71,222 +72,241 @@ class Icml
$dirlist = new \Magento\Framework\Filesystem\DirectoryList('');
$baseDir = $dirlist->getRoot();
$shopCode = $this->_manager->getStore()->getCode();
- $this->_dd->save($baseDir . 'retailcrm_' . $shopCode . '.xml');
-
+ $this->_dd->save($baseDir . 'retailcrm_' . $shopCode . '.xml');
}
-
+
private function addCategories()
{
- $collection = $this->_category->create();
- $collection->addAttributeToSelect('*');
-
- foreach ($collection as $category) {
- if($category->getId()>1){
- $e = $this->_eCategories->appendChild(
- $this->_dd->createElement('category')
- );
- $e->appendChild($this->_dd->createTextNode($category->getName()));
- $e->setAttribute('id', $category->getId());
-
- if ($category->getParentId() > 1) {
- $e->setAttribute('parentId', $category->getParentId());
- }
- }
- }
+ $collection = $this->_category->create();
+ $collection->addAttributeToSelect('*');
+
+ foreach ($collection as $category) {
+ if ($category->getId() > 1){
+ $e = $this->_eCategories->appendChild(
+ $this->_dd->createElement('category')
+ );
+ $e->appendChild($this->_dd->createTextNode($category->getName()));
+ $e->setAttribute('id', $category->getId());
+
+ if ($category->getParentId() > 1) {
+ $e->setAttribute('parentId', $category->getParentId());
+ }
+ }
+ }
}
-
+
private function addOffers()
{
- $offers = array();
-
+ $offers = [];
+
$collection = $this->_product->create();
$collection->addFieldToFilter('visibility', 4);//catalog, search visible
- $collection->addAttributeToSelect('*');
-
- $picUrl = $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);;
- $baseUrl = $this->_storeManager->getStore()->getBaseUrl();
-
- $customAdditionalAttributes = array();
- $customAdditionalAttributes = $this->_config->getValue('retailcrm/Misc/attributes_to_export_into_icml');
-
- foreach ($collection as $product) {
-
- if($product->getTypeId() == 'simple') {
- $offer['id'] = $product->getId();
- $offer['productId'] = $product->getId();
- $offer['productActivity'] = $product->isAvailable() ? 'Y' : 'N';
- $offer['name'] = $product->getName();
- $offer['productName'] = $product->getName();
- $offer['initialPrice'] = $product->getFinalPrice();
- $offer['url'] = $product->getProductUrl();
- $offer['picture'] = $picUrl.'catalog/product'.$product->getImage();
- $offer['quantity'] = $this->_StockState->getStockQty($product->getId(), $product->getStore()->getWebsiteId());
- $offer['categoryId'] = $product->getCategoryIds();
- $offer['vendor'] = $product->getAttributeText('manufacturer');
- $offer['params'] = array();
-
-
- $article = $product->getSku();
- if(!empty($article)) {
- $offer['params'][] = array(
- 'name' => 'Article',
- 'code' => 'article',
- 'value' => $article
- );
- }
-
- $weight = $product->getWeight();
- if(!empty($weight)) {
- $offer['params'][] = array(
- 'name' => 'Weight',
- 'code' => 'weight',
- 'value' => $weight
- );
- }
-
- if(!empty($customAdditionalAttributes)) {
- //var_dump($customAdditionalAttributes);
- }
-
-
- $offers[] = $offer;
-
- }
-
- if($product->getTypeId() == 'configurable') {
-
- $associated_products = $this->_configurable
- ->getUsedProductCollection($product)
- ->addAttributeToSelect('*')
- ->addFilterByRequiredOptions();
-
- foreach ($associated_products as $associatedProduct) {
- $offer['id'] = $associatedProduct->getId();
- $offer['productId'] = $product->getId();
- $offer['productActivity'] = $associatedProduct->isAvailable() ? 'Y' : 'N';
- $offer['name'] = $associatedProduct->getName();
- $offer['productName'] = $product->getName();
- $offer['initialPrice'] = $associatedProduct->getFinalPrice();
- $offer['url'] = $product->getProductUrl();
- $offer['picture'] = $picUrl.'catalog/product'.$associatedProduct->getImage();
- $offer['quantity'] = $this->_StockState->getStockQty($associatedProduct->getId(), $associatedProduct->getStore()->getWebsiteId());
- $offer['categoryId'] = $associatedProduct->getCategoryIds();
- $offer['vendor'] = $associatedProduct->getAttributeText('manufacturer');
- $offer['params'] = array();
-
- $article = $associatedProduct->getSku();
- if(!empty($article)) {
- $offer['params'][] = array(
- 'name' => 'Article',
- 'code' => 'article',
- 'value' => $article
- );
- }
-
- $weight = $associatedProduct->getWeight();
- if(!empty($weight)) {
- $offer['params'][] = array(
- 'name' => 'Weight',
- 'code' => 'weight',
- 'value' => $weight
- );
- }
-
- $offers[] = $offer;
- }
-
-
- }
- }
-
-
- foreach ($offers as $offer) {
- $e = $this->_eOffers->appendChild(
- $this->_dd->createElement('offer')
- );
-
- $e->setAttribute('id', $offer['id']);
- $e->setAttribute('productId', $offer['productId']);
-
- if (!empty($offer['quantity'])) {
- $e->setAttribute('quantity', (int) $offer['quantity']);
- } else {
- $e->setAttribute('quantity', 0);
- }
-
- if (!empty($offer['categoryId'])) {
- foreach ($offer['categoryId'] as $categoryId) {
- $e->appendChild(
- $this->_dd->createElement('categoryId')
- )->appendChild(
- $this->_dd->createTextNode($categoryId)
- );
- }
- } else {
- $e->appendChild($this->_dd->createElement('categoryId', 1));
- }
-
- $e->appendChild($this->_dd->createElement('productActivity'))
- ->appendChild(
- $this->_dd->createTextNode($offer['productActivity'])
- );
-
- $e->appendChild($this->_dd->createElement('name'))
- ->appendChild(
- $this->_dd->createTextNode($offer['name'])
- );
-
- $e->appendChild($this->_dd->createElement('productName'))
- ->appendChild(
- $this->_dd->createTextNode($offer['productName'])
- );
-
- $e->appendChild($this->_dd->createElement('price'))
- ->appendChild(
- $this->_dd->createTextNode($offer['initialPrice'])
- );
-
- if (!empty($offer['purchasePrice'])) {
- $e->appendChild($this->_dd->createElement('purchasePrice'))
- ->appendChild(
- $this->_dd->createTextNode($offer['purchasePrice'])
- );
- }
-
- if (!empty($offer['picture'])) {
- $e->appendChild($this->_dd->createElement('picture'))
- ->appendChild(
- $this->_dd->createTextNode($offer['picture'])
- );
- }
-
- if (!empty($offer['url'])) {
- $e->appendChild($this->_dd->createElement('url'))
- ->appendChild(
- $this->_dd->createTextNode($offer['url'])
- );
- }
-
- if (!empty($offer['vendor'])) {
- $e->appendChild($this->_dd->createElement('vendor'))
- ->appendChild(
- $this->_dd->createTextNode($offer['vendor'])
- );
- }
-
- if(!empty($offer['params'])) {
- foreach($offer['params'] as $param) {
- $paramNode = $this->_dd->createElement('param');
- $paramNode->setAttribute('name', $param['name']);
- $paramNode->setAttribute('code', $param['code']);
- $paramNode->appendChild(
- $this->_dd->createTextNode($param['value'])
- );
- $e->appendChild($paramNode);
- }
- }
- }
-
- }
-
-}
\ No newline at end of file
+ $collection->addAttributeToSelect('*');
+
+ $picUrl = $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
+ $baseUrl = $this->_storeManager->getStore()->getBaseUrl();
+
+ $customAdditionalAttributes = [];
+ $customAdditionalAttributes = $this->_config->getValue('retailcrm/Misc/attributes_to_export_into_icml');
+
+ foreach ($collection as $product) {
+ if ($product->getTypeId() == 'simple') {
+ $offer['id'] = $product->getId();
+ $offer['productId'] = $product->getId();
+ $offer['productActivity'] = $product->isAvailable() ? 'Y' : 'N';
+ $offer['name'] = $product->getName();
+ $offer['productName'] = $product->getName();
+ $offer['initialPrice'] = $product->getFinalPrice();
+ $offer['url'] = $product->getProductUrl();
+ $offer['picture'] = $picUrl.'catalog/product'.$product->getImage();
+ $offer['quantity'] = $this->_StockState->getStockQty($product->getId(), $product->getStore()->getWebsiteId());
+ $offer['categoryId'] = $product->getCategoryIds();
+ $offer['vendor'] = $product->getAttributeText('manufacturer');
+ $offer['params'] = [];
+
+ $article = $product->getSku();
+
+ if(!empty($article)) {
+ $offer['params'][] = [
+ 'name' => 'Article',
+ 'code' => 'article',
+ 'value' => $article
+ ];
+ }
+
+ $weight = $product->getWeight();
+
+ if(!empty($weight)) {
+ $offer['params'][] = [
+ 'name' => 'Weight',
+ 'code' => 'weight',
+ 'value' => $weight
+ ];
+ }
+
+ if(!empty($customAdditionalAttributes)) {
+ //var_dump($customAdditionalAttributes);
+ }
+
+ $offers[] = $offer;
+ }
+
+ if ($product->getTypeId() == 'configurable') {
+ $associated_products = $this->_configurable
+ ->getUsedProductCollection($product)
+ ->addAttributeToSelect('*')
+ ->addFilterByRequiredOptions();
+
+ foreach ($associated_products as $associatedProduct) {
+ $offer['id'] = $associatedProduct->getId();
+ $offer['productId'] = $product->getId();
+ $offer['productActivity'] = $associatedProduct->isAvailable() ? 'Y' : 'N';
+ $offer['name'] = $associatedProduct->getName();
+ $offer['productName'] = $product->getName();
+ $offer['initialPrice'] = $associatedProduct->getFinalPrice();
+ $offer['url'] = $product->getProductUrl();
+ $offer['picture'] = $picUrl.'catalog/product'.$associatedProduct->getImage();
+ $offer['quantity'] = $this->_StockState->getStockQty($associatedProduct->getId(), $associatedProduct->getStore()->getWebsiteId());
+ $offer['categoryId'] = $associatedProduct->getCategoryIds();
+ $offer['vendor'] = $associatedProduct->getAttributeText('manufacturer');
+ $offer['params'] = [];
+
+ $article = $associatedProduct->getSku();
+
+ if ($associatedProduct->getResource()->getAttribute('color')) {
+ $colorAttribute = $associatedProduct->getResource()->getAttribute('color');
+ $color = $colorAttribute->getSource()->getOptionText($associatedProduct->getColor());
+ }
+
+ if (isset($color)) {
+ $offer['params'][] = [
+ 'name' => 'Color',
+ 'code' => 'color',
+ 'value' => $color
+ ];
+ }
+
+ if ($associatedProduct->getResource()->getAttribute('size')) {
+ $sizeAttribute = $associatedProduct->getResource()->getAttribute('size');
+ $size = $sizeAttribute->getSource()->getOptionText($associatedProduct->getSize());
+ }
+
+ if (isset($size)) {
+ $offer['params'][] = [
+ 'name' => 'Size',
+ 'code' => 'size',
+ 'value' => $size
+ ];
+ }
+
+ if (!empty($article)) {
+ $offer['params'][] = [
+ 'name' => 'Article',
+ 'code' => 'article',
+ 'value' => $article
+ ];
+ }
+
+ $weight = $associatedProduct->getWeight();
+
+ if(!empty($weight)) {
+ $offer['params'][] = [
+ 'name' => 'Weight',
+ 'code' => 'weight',
+ 'value' => $weight
+ ];
+ }
+
+ $offers[] = $offer;
+ }
+ }
+ }
+
+ foreach ($offers as $offer) {
+ $e = $this->_eOffers->appendChild(
+ $this->_dd->createElement('offer')
+ );
+
+ $e->setAttribute('id', $offer['id']);
+ $e->setAttribute('productId', $offer['productId']);
+
+ if (!empty($offer['quantity'])) {
+ $e->setAttribute('quantity', (int) $offer['quantity']);
+ } else {
+ $e->setAttribute('quantity', 0);
+ }
+
+ if (!empty($offer['categoryId'])) {
+ foreach ($offer['categoryId'] as $categoryId) {
+ $e->appendChild(
+ $this->_dd->createElement('categoryId')
+ )->appendChild(
+ $this->_dd->createTextNode($categoryId)
+ );
+ }
+ } else {
+ $e->appendChild($this->_dd->createElement('categoryId', 1));
+ }
+
+ $e->appendChild($this->_dd->createElement('productActivity'))
+ ->appendChild(
+ $this->_dd->createTextNode($offer['productActivity'])
+ );
+
+ $e->appendChild($this->_dd->createElement('name'))
+ ->appendChild(
+ $this->_dd->createTextNode($offer['name'])
+ );
+
+ $e->appendChild($this->_dd->createElement('productName'))
+ ->appendChild(
+ $this->_dd->createTextNode($offer['productName'])
+ );
+
+ $e->appendChild($this->_dd->createElement('price'))
+ ->appendChild(
+ $this->_dd->createTextNode($offer['initialPrice'])
+ );
+
+ if (!empty($offer['purchasePrice'])) {
+ $e->appendChild($this->_dd->createElement('purchasePrice'))
+ ->appendChild(
+ $this->_dd->createTextNode($offer['purchasePrice'])
+ );
+ }
+
+ if (!empty($offer['picture'])) {
+ $e->appendChild($this->_dd->createElement('picture'))
+ ->appendChild(
+ $this->_dd->createTextNode($offer['picture'])
+ );
+ }
+
+ if (!empty($offer['url'])) {
+ $e->appendChild($this->_dd->createElement('url'))
+ ->appendChild(
+ $this->_dd->createTextNode($offer['url'])
+ );
+ }
+
+ if (!empty($offer['vendor'])) {
+ $e->appendChild($this->_dd->createElement('vendor'))
+ ->appendChild(
+ $this->_dd->createTextNode($offer['vendor'])
+ );
+ }
+
+ if(!empty($offer['params'])) {
+ foreach($offer['params'] as $param) {
+ $paramNode = $this->_dd->createElement('param');
+ $paramNode->setAttribute('name', $param['name']);
+ $paramNode->setAttribute('code', $param['code']);
+ $paramNode->appendChild(
+ $this->_dd->createTextNode($param['value'])
+ );
+ $e->appendChild($paramNode);
+ }
+ }
+ }
+ }
+}
diff --git a/Model/Logger/Logger.php b/Model/Logger/Logger.php
index 98058cf..a89c4e5 100644
--- a/Model/Logger/Logger.php
+++ b/Model/Logger/Logger.php
@@ -1,29 +1,94 @@
logPath = $logPath;
-
- }
-
- public function write($dump, $file)
- {
- $path =$this->logPath . $file.'.txt';
-
- $f = fopen($_SERVER["DOCUMENT_ROOT"].$path, "a+");
- fwrite($f, print_r(array(date('Y-m-d H:i:s'), array(
- $dump
- )),true));
- fclose($f);
-
+ $directory = $objectManager->get('\Magento\Framework\Filesystem\DirectoryList');
+ $this->logDir = $directory->getPath('log');
}
+ /**
+ * Write data in log file
+ *
+ * @param array $data
+ * @param str $fileName
+ *
+ * @return void
+ */
+ public function writeDump($data, $fileName)
+ {
+ $filePath = $this->logDir . '/' . $fileName . '.log';
+
+ if (!$this->checkSize($filePath)) {
+ $this->clear($filePath);
+ }
+
+ $logData = [
+ 'date' => date('Y-m-d H:i:s'),
+ 'data' => $data
+ ];
+
+ $file = fopen($filePath, "a+");
+ fwrite($file, print_r($logData, true));
+ fclose($file);
+ }
+
+ /**
+ * Write data in log file
+ *
+ * @param str $data
+ * @param str $fileName
+ *
+ * @return void
+ */
+ public function writeRow($data, $fileName = 'retailcrm')
+ {
+ $filePath = $this->logDir . '/' . $fileName . '.log';
+
+ if (!$this->checkSize($filePath)) {
+ $this->clear($filePath);
+ }
+
+ $nowDate = date('Y-m-d H:i:s');
+ $logData = "[$nowDate] @ " . $data . "\n";
+
+ $file = fopen($filePath, "a+");
+ fwrite($file, $logData);
+ fclose($file);
+ }
+
+ /**
+ * Clear file
+ *
+ * @param str $file
+ *
+ * @return void
+ */
+ protected function clear($file)
+ {
+ file_put_contents($file, '');
+ }
+
+ /**
+ * Check file size
+ *
+ * @param str $file
+ *
+ * @return boolean
+ */
+ protected function checkSize($file)
+ {
+ if (!file_exists($file)) {
+ return true;
+ } elseif (filesize($file) > 10485760) {
+ return false;
+ }
+
+ return true;
+ }
}
diff --git a/Model/Observer/Customer.php b/Model/Observer/Customer.php
index 4e07dca..0ec8209 100644
--- a/Model/Observer/Customer.php
+++ b/Model/Observer/Customer.php
@@ -1,59 +1,66 @@
get('\Retailcrm\Retailcrm\Helper\Data');
- $logger = $om->get('\Psr\Log\LoggerInterface');
- $config = $om->get('\Magento\Framework\App\Config\ScopeConfigInterface');
-
- $this->_logger = $logger;
- $this->_helper = $helper;
- $this->_config = $config;
-
- $url = $config->getValue('retailcrm/general/api_url');
- $key = $config->getValue('retailcrm/general/api_key');
-
- if(!empty($url) && !empty($key)) {
- $this->_api = new \Retailcrm\Retailcrm\Model\ApiClient\ApiClient($url,$key);
- }
-
- }
-
- public function execute(\Magento\Framework\Event\Observer $observer)
- {
- $data = $observer->getEvent()->getCustomer();
-
- $customer = array(
- 'externalId' => $data->getId(),
- 'email' => $data->getEmail(),
- 'firstName' => $data->getFirstname(),
- 'patronymic' => $data->getMiddlename(),
- 'lastName' => $data->getLastname(),
- 'createdAt' => date('Y-m-d H:i:s', strtotime($data->getCreatedAt()))
- );
-
- $response = $this->_api->customersEdit($customer);
-
- if ((404 === $response->getStatusCode()) &&($response['errorMsg']==='Not found')) {
- $this->_api->customersCreate($customer);
- }
-
- //$logger = new \Retailcrm\Retailcrm\Model\Logger\Logger();
- //$logger->write($customer,'Customer');
-
- }
-
-
+ public function __construct(
+ \Magento\Framework\ObjectManagerInterface $objectManager,
+ \Magento\Framework\App\Config\ScopeConfigInterface $config,
+ \Magento\Framework\Registry $registry
+ ) {
+ $helper = $objectManager->get('\Retailcrm\Retailcrm\Helper\Data');
+ $logger = $objectManager->get('\Retailcrm\Retailcrm\Model\Logger\Logger');
-}
\ No newline at end of file
+ $this->_logger = $logger;
+ $this->_helper = $helper;
+ $this->_config = $config;
+ $this->_objectManager = $objectManager;
+ $this->registry = $registry;
+
+ $url = $config->getValue('retailcrm/general/api_url');
+ $key = $config->getValue('retailcrm/general/api_key');
+ $version = $config->getValue('retailcrm/general/api_version');
+
+ if (!empty($url) && !empty($key)) {
+ $this->_api = new ApiClient($url, $key, $version);
+ }
+ }
+
+ public function execute(\Magento\Framework\Event\Observer $observer)
+ {
+ if ($this->registry->registry('RETAILCRM_HISTORY') === true) {
+ return;
+ }
+
+ $data = $observer->getEvent()->getCustomer();
+
+ $customer = [
+ 'externalId' => $data->getId(),
+ 'email' => $data->getEmail(),
+ 'firstName' => $data->getFirstname(),
+ 'patronymic' => $data->getMiddlename(),
+ 'lastName' => $data->getLastname(),
+ 'createdAt' => date('Y-m-d H:i:s', strtotime($data->getCreatedAt()))
+ ];
+
+ $response = $this->_api->customersEdit($customer);
+
+ if ($response === false) {
+ return;
+ }
+
+ if (!$response->isSuccessful() && $response->errorMsg == $this->_api->getErrorText('errorNotFound')) {
+ $this->_api->customersCreate($customer);
+ }
+ }
+}
diff --git a/Model/Observer/OrderCreate.php b/Model/Observer/OrderCreate.php
index e4e99e7..fe8b597 100644
--- a/Model/Observer/OrderCreate.php
+++ b/Model/Observer/OrderCreate.php
@@ -1,180 +1,268 @@
get('\Retailcrm\Retailcrm\Helper\Data');
- $logger = $om->get('\Psr\Log\LoggerInterface');
- $configurable = $om->get('Magento\ConfigurableProduct\Model\Product\Type\Configurable');
-
- $this->_configurable = $configurable;
- $this->_logger = $logger;
- $this->_helper = $helper;
- $this->_objectManager = $ObjectManager;
- $this->_config = $config;
-
- $url = $config->getValue('retailcrm/general/api_url');
- $key = $config->getValue('retailcrm/general/api_key');
-
- if(!empty($url) && !empty($key)) {
- $this->_api = new \Retailcrm\Retailcrm\Model\ApiClient\ApiClient($url,$key);
- }
-
- }
-
- public function execute(\Magento\Framework\Event\Observer $observer)
- {
- $order = $observer->getEvent()->getOrder();
- $items = array();
- $addressObj = $order->getBillingAddress();
-
-
- foreach ($order->getAllItems() as $item) {
- if ($item->getProductType() == "simple") {
-
- $price = $item->getPrice();
-
- if($price == 0){
- $om = \Magento\Framework\App\ObjectManager::getInstance();
- $omproduct = $om->get('Magento\Catalog\Model\ProductRepository')
- ->getById($item->getProductId());
- $price = $omproduct->getPrice();
- }
-
- $product = array(
- 'productId' => $item->getProductId(),
+ /**
+ * Constructor
+ *
+ * @param \Magento\Framework\ObjectManagerInterface $objectManager
+ * @param \Magento\Framework\App\Config\ScopeConfigInterface $config
+ * @param \Retailcrm\Retailcrm\Model\Logger\Logger $logger
+ * @param \Magento\Framework\Registry $registry
+ */
+ public function __construct(
+ \Magento\Framework\ObjectManagerInterface $objectManager,
+ \Magento\Framework\App\Config\ScopeConfigInterface $config,
+ \Magento\Framework\Registry $registry
+ ) {
+ $helper = $objectManager->get('\Retailcrm\Retailcrm\Helper\Data');
+ $this->_logger = $objectManager->get('\Retailcrm\Retailcrm\Model\Logger\Logger');
+ $this->_helper = $helper;
+ $this->_objectManager = $objectManager;
+ $this->_config = $config;
+ $this->_registry = $registry;
+
+ $url = $config->getValue('retailcrm/general/api_url');
+ $key = $config->getValue('retailcrm/general/api_key');
+ $apiVersion = $config->getValue('retailcrm/general/api_version');
+
+ if (!empty($url) && !empty($key)) {
+ $this->_api = new ApiClient($url, $key, $apiVersion);
+ }
+ }
+
+ /**
+ * Execute send order in CRM
+ *
+ * @param Observer $observer
+ *
+ * @return $this
+ */
+ public function execute(Observer $observer)
+ {
+ if ($this->_registry->registry('RETAILCRM_HISTORY') === true) {
+ return;
+ }
+
+ $order = $observer->getEvent()->getOrder();
+
+ if ($this->existsInCrm($order->getId()) === true) {
+ return;
+ }
+
+ $items = [];
+ $addressObj = $order->getBillingAddress();
+
+ foreach ($order->getAllItems() as $item) {
+ if ($item->getProductType() == "simple") {
+ $price = $item->getPrice();
+
+ if ($price == 0) {
+ $omproduct = $this->_objectManager->get('Magento\Catalog\Model\ProductRepository')
+ ->getById($item->getProductId());
+ $price = $omproduct->getPrice();
+ }
+
+ $product = [
+ 'productId' => $item->getProductId(),
'productName' => $item->getName(),
'quantity' => $item->getQtyOrdered(),
'initialPrice' => $price,
- 'offer'=>array(
- 'externalId'=>$item->getProductId()
- )
- );
-
- unset($om);
- unset($omproduct);
- unset($price);
-
- $items[] = $product;
- }
- }
-
- $ship = $this->getShippingCode($order->getShippingMethod());
-
- $preparedOrder = array(
- 'site' => $order->getStore()->getCode(),
- 'externalId' => $order->getRealOrderId(),
- 'number' => $order->getRealOrderId(),
- 'createdAt' => date('Y-m-d H:i:s'),
- 'lastName' => $order->getCustomerLastname(),
- 'firstName' => $order->getCustomerFirstname(),
- 'patronymic' => $order->getCustomerMiddlename(),
- 'email' => $order->getCustomerEmail(),
- 'phone' => $addressObj->getTelephone(),
- 'paymentType' => $this->_config->getValue('retailcrm/Payment/'.$order->getPayment()->getMethodInstance()->getCode()),
- 'status' => $this->_config->getValue('retailcrm/Status/'.$order->getStatus()),
- 'discount' => abs($order->getDiscountAmount()),
- 'items' => $items,
- 'delivery' => array(
- 'code' => $this->_config->getValue('retailcrm/Shipping/'.$ship),
- 'cost' => $order->getShippingAmount(),
- 'address' => array(
- 'index' => $addressObj->getData('postcode'),
- 'city' => $addressObj->getData('city'),
- 'country' => $addressObj->getData('country_id'),
- 'street' => $addressObj->getData('street'),
- 'region' => $addressObj->getData('region'),
- 'text' => trim(
- ',',
- implode(
- ',',
- array(
- $addressObj->getData('postcode'),
- $addressObj->getData('city'),
- $addressObj->getData('street'),
- )
- )
- )
- )
- )
- );
-
-
- if(trim($preparedOrder['delivery']['code']) == ''){
- unset($preparedOrder['delivery']['code']);
- }
-
- if(trim($preparedOrder['paymentType']) == ''){
- unset($preparedOrder['paymentType']);
- }
-
- if(trim($preparedOrder['status']) == ''){
- unset($preparedOrder['status']);
- }
-
- if ($order->getCustomerIsGuest() == 0) {
- $preparedCustomer = array(
- 'externalId' => $order->getCustomerId()
- );
-
- if ($this->_api->customersCreate($preparedCustomer)) {
- $preparedOrder['customer']['externalId'] = $order->getCustomerId();
- }
- }
-
- $this->_helper->filterRecursive($preparedOrder);
-
- $logger = new \Retailcrm\Retailcrm\Model\Logger\Logger();
- $logger->write($preparedOrder,'CreateOrder');
-
- try {
- $response = $this->_api->ordersCreate($preparedOrder);
- if ($response->isSuccessful() && 201 === $response->getStatusCode()) {
- $this->_logger->addDebug($response->id);
-
- } else {
- $this->_logger->addDebug(
- sprintf(
- "Order create error: [HTTP status %s] %s",
- $response->getStatusCode(),
- $response->getErrorMsg()
- )
- );
-
- if (isset($response['errors'])) {
- $this->_logger->addDebug(implode(' :: ', $response['errors']));
- }
- }
- } catch (\Retailcrm\Retailcrm\Model\ApiClient\Exception\CurlException $e) {
- $this->_logger->addDebug($e->getMessage());
-
- }
-
-
- return $this;
- }
+ 'offer' => [
+ 'externalId' => $item->getProductId()
+ ]
+ ];
- protected function getShippingCode($string)
- {
- $split = array_values(explode('_', $string));
- $length = count($split);
- $prepare = array_slice($split, 0, $length/2);
-
- return implode('_', $prepare);
- }
+ unset($omproduct);
+ unset($price);
+
+ $items[] = $product;
+ }
+ }
+
+ $shippingCode = $this->getShippingCode($order->getShippingMethod());
+
+ $preparedOrder = [
+ 'site' => $order->getStore()->getCode(),
+ 'externalId' => $order->getId(),
+ 'number' => $order->getRealOrderId(),
+ 'createdAt' => $order->getCreatedAt(),
+ 'lastName' => $order->getCustomerLastname() ? $order->getCustomerLastname() : $addressObj->getLastname(),
+ 'firstName' => $order->getCustomerFirstname() ? $order->getCustomerFirstname() : $addressObj->getFirstname(),
+ 'patronymic' => $order->getCustomerMiddlename() ? $order->getCustomerMiddlename() : $addressObj->getMiddlename(),
+ 'email' => $order->getCustomerEmail(),
+ 'phone' => $addressObj->getTelephone(),
+ 'status' => $this->_config->getValue('retailcrm/Status/' . $order->getStatus()),
+ 'items' => $items,
+ 'delivery' => [
+ 'code' => $this->_config->getValue('retailcrm/Shipping/' . $shippingCode),
+ 'cost' => $order->getShippingAmount(),
+ 'address' => [
+ 'index' => $addressObj->getData('postcode'),
+ 'city' => $addressObj->getData('city'),
+ 'street' => $addressObj->getData('street'),
+ 'region' => $addressObj->getData('region'),
+ 'text' => trim(
+ ',',
+ implode(
+ ',',
+ [
+ $addressObj->getData('postcode'),
+ $addressObj->getData('city'),
+ $addressObj->getData('street'),
+ ]
+ )
+ )
+ ]
+ ]
+ ];
+
+ if ($addressObj->getData('country_id')) {
+ $preparedOrder['countryIso'] = $addressObj->getData('country_id');
+ }
+
+ if ($this->_api->getVersion() == 'v4') {
+ $preparedOrder['paymentType'] = $this->_config->getValue('retailcrm/Payment/'.$order->getPayment()->getMethodInstance()->getCode());
+ $preparedOrder['discount'] = abs($order->getDiscountAmount());
+ } elseif ($this->_api->getVersion() == 'v5') {
+ $preparedOrder['discountManualAmount'] = abs($order->getDiscountAmount());
+
+ $payment = [
+ 'type' => $this->_config->getValue('retailcrm/Payment/' . $order->getPayment()->getMethodInstance()->getCode()),
+ 'externalId' => $order->getId(),
+ 'order' => [
+ 'externalId' => $order->getId(),
+ ]
+ ];
+
+ if ($order->getBaseTotalDue() == 0) {
+ $payment['status'] = 'paid';
+ }
+
+ $preparedOrder['payments'][] = $payment;
+ }
+
+ if (trim($preparedOrder['delivery']['code']) == '') {
+ unset($preparedOrder['delivery']['code']);
+ }
+
+ if (isset($preparedOrder['paymentType']) && trim($preparedOrder['paymentType']) == '') {
+ unset($preparedOrder['paymentType']);
+ }
+
+ if (trim($preparedOrder['status']) == '') {
+ unset($preparedOrder['status']);
+ }
+
+ if ($order->getCustomerIsGuest() == 1) {
+ $customer = $this->getCustomerByEmail($order->getCustomerEmail());
+
+ if ($customer !== false) {
+ $preparedOrder['customer']['id'] = $customer['id'];
+ }
+ } elseif ($order->getCustomerIsGuest() == 0) {
+ if ($this->existsInCrm($order->getCustomerId(), 'customersGet')) {
+ $preparedOrder['customer']['externalId'] = $order->getCustomerId();
+ } else {
+ $preparedCustomer = [
+ 'externalId' => $order->getCustomerId(),
+ 'firstName' => $order->getCustomerFirstname(),
+ 'lastName' => $order->getCustomerLastname(),
+ 'email' => $order->getCustomerEmail()
+ ];
+
+ if ($addressObj->getTelephone()) {
+ $preparedCustomer['phones'][] = [
+ 'number' => $addressObj->getTelephone()
+ ];
+ }
+
+ if ($this->_api->customersCreate($preparedCustomer)) {
+ $preparedOrder['customer']['externalId'] = $order->getCustomerId();
+ }
+ }
+ }
+
+ $this->_helper->filterRecursive($preparedOrder);
+
+ $this->_logger->writeDump($preparedOrder,'CreateOrder');
+
+ $this->_api->ordersCreate($preparedOrder);
+
+ return $this;
+ }
+
+ /**
+ * Get shipping code
+ *
+ * @param string $string
+ *
+ * @return string
+ */
+ protected function getShippingCode($string)
+ {
+ $split = array_values(explode('_', $string));
+ $length = count($split);
+ $prepare = array_slice($split, 0, $length/2);
+
+ return implode('_', $prepare);
+ }
+
+ /**
+ * Check exists order or customer in CRM
+ *
+ * @param int $id
+ *
+ * @return boolean
+ */
+ protected function existsInCrm($id, $method = 'ordersGet', $by = 'externalId')
+ {
+ $response = $this->_api->{$method}($id, $by);
+
+ if ($response === false) {
+ return;
+ }
+
+ if (!$response->isSuccessful() && $response->errorMsg == $this->_api->getErrorText('errorNotFound')) {
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * Get customer by email from CRM
+ *
+ * @param string $email
+ *
+ * @return mixed
+ */
+ protected function getCustomerByEmail($email)
+ {
+ $response = $this->_api->customersList(['email' => $email]);
+
+ if ($response === false) {
+ return false;
+ }
+
+ if ($response->isSuccessful() && isset($response['customers'])) {
+ if (!empty($response['customers'])) {
+ return reset($response['customers']);
+ }
+ }
+
+ return false;
+ }
}
diff --git a/Model/Observer/OrderUpdate.php b/Model/Observer/OrderUpdate.php
index 7adb56f..7a45135 100644
--- a/Model/Observer/OrderUpdate.php
+++ b/Model/Observer/OrderUpdate.php
@@ -1,56 +1,79 @@
get('\Retailcrm\Retailcrm\Helper\Data');
- $logger = $om->get('\Psr\Log\LoggerInterface');
- $config = $om->get('\Magento\Framework\App\Config\ScopeConfigInterface');
-
- $this->_logger = $logger;
- $this->_helper = $helper;
- $this->_config = $config;
-
- $url = $config->getValue('retailcrm/general/api_url');
- $key = $config->getValue('retailcrm/general/api_key');
-
- if(!empty($url) && !empty($key)) {
- $this->_api = new \Retailcrm\Retailcrm\Model\ApiClient\ApiClient($url,$key);
- }
-
- }
-
- public function execute(\Magento\Framework\Event\Observer $observer)
- {
- $order = $observer->getEvent()->getOrder();
-
- if(isset($order)){
-
- $preparedOrder = array(
- 'externalId' => $order->getRealOrderId(),
- 'status' => $this->_config->getValue('retailcrm/Status/'.$order->getStatus()),
- );
-
- if((float)$order->getBaseGrandTotal() == (float)$order->getTotalPaid()){
- $preparedOrder['paymentStatus'] = 'paid';
- }
-
- $this->_helper->filterRecursive($preparedOrder);
- $this->_api->ordersEdit($preparedOrder);
-
- }
-
-
- }
+ /**
+ * Constructor
+ *
+ * @param \Magento\Framework\ObjectManagerInterface $objectManager
+ * @param \Magento\Framework\App\Config\ScopeConfigInterface $config
+ */
+ public function __construct(
+ \Magento\Framework\ObjectManagerInterface $objectManager,
+ \Magento\Framework\App\Config\ScopeConfigInterface $config,
+ \Magento\Framework\Registry $registry
+ ) {
+ $this->_helper = $objectManager->get('\Retailcrm\Retailcrm\Helper\Data');
+ $this->_objectManager = $objectManager;
+ $this->_config = $config;
+ $this->registry = $registry;
-}
\ No newline at end of file
+ $url = $config->getValue('retailcrm/general/api_url');
+ $key = $config->getValue('retailcrm/general/api_key');
+ $apiVersion = $config->getValue('retailcrm/general/api_version');
+
+ if (!empty($url) && !empty($key)) {
+ $this->_api = new ApiClient($url, $key, $apiVersion);
+ }
+ }
+
+ /**
+ * Execute update order in CRM
+ *
+ * @param Observer $observer
+ *
+ * @return void
+ */
+ public function execute(Observer $observer)
+ {
+ if ($this->registry->registry('RETAILCRM_HISTORY') === true) {
+ return;
+ }
+
+ $order = $observer->getEvent()->getOrder();
+
+ if ($order) {
+ $preparedOrder = [
+ 'externalId' => $order->getId(),
+ 'status' => $this->_config->getValue('retailcrm/Status/' . $order->getStatus())
+ ];
+
+ if ($order->getBaseTotalDue() == 0) {
+ if ($this->_api->getVersion() == 'v4') {
+ $preparedOrder['paymentStatus'] = 'paid';
+ } elseif ($this->_api->getVersion() == 'v5') {
+ $payment = [
+ 'externalId' => $order->getPayment()->getId(),
+ 'status' => 'paid'
+ ];
+
+ $this->_api->ordersPaymentsEdit($payment);
+ }
+ }
+
+ $this->_helper->filterRecursive($preparedOrder);
+ $this->_api->ordersEdit($preparedOrder);
+ }
+ }
+}
diff --git a/Model/Order/OrderNumber.php b/Model/Order/OrderNumber.php
index 8b7dbbd..ce411b0 100644
--- a/Model/Order/OrderNumber.php
+++ b/Model/Order/OrderNumber.php
@@ -1,168 +1,165 @@
get('Magento\Sales\Model\OrderRepository');
- $searchCriteriaBuilder = $om->get('Magento\Framework\Api\SearchCriteriaBuilder');
- $config = $om->get('Magento\Framework\App\Config\ScopeConfigInterface');
- $filterBuilder = $om->get('Magento\Framework\Api\FilterBuilder');
- $order = $om->get('\Magento\Sales\Api\Data\OrderInterface');
- $helper = $om->get('\Retailcrm\Retailcrm\Helper\Data');
-
- $this->_orderRepository = $orderRepository;
+ protected $_orderRepository;
+ protected $_searchCriteriaBuilder;
+ protected $_config;
+ protected $_filterBuilder;
+ protected $_order;
+ protected $_helper;
+ protected $_api;
+ protected $_logger;
+
+ public function __construct()
+ {
+ $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
+ $orderRepository = $objectManager->get('Magento\Sales\Model\OrderRepository');
+ $searchCriteriaBuilder = $objectManager->get('Magento\Framework\Api\SearchCriteriaBuilder');
+ $config = $objectManager->get('Magento\Framework\App\Config\ScopeConfigInterface');
+ $filterBuilder = $objectManager->get('Magento\Framework\Api\FilterBuilder');
+ $order = $objectManager->get('\Magento\Sales\Api\Data\OrderInterface');
+ $helper = $objectManager->get('\Retailcrm\Retailcrm\Helper\Data');
+
+ $this->_orderRepository = $orderRepository;
$this->_searchCriteriaBuilder = $searchCriteriaBuilder;
$this->_config = $config;
$this->_filterBuilder = $filterBuilder;
$this->_order = $order;
$this->_helper = $helper;
-
+ $this->_logger = $objectManager->get('\Retailcrm\Retailcrm\Model\Logger\Logger');
+
$url = $config->getValue('retailcrm/general/api_url');
$key = $config->getValue('retailcrm/general/api_key');
-
- if(!empty($url) && !empty($key)) {
- $this->_api = new \Retailcrm\Retailcrm\Model\ApiClient\ApiClient($url,$key);
+ $version = $config->getValue('retailcrm/general/api_version');
+
+ if (!empty($url) && !empty($key)) {
+ $this->_api = new ApiClient($url, $key, $version);
}
- }
-
- public function ExportOrderNumber()
- {
- $ordernumber = $this->_config->getValue('retailcrm/Load/number_order');
- $ordersId = explode(",", $ordernumber);
- $orders = array();
-
- foreach ($ordersId as $id) {
- $orders[] = $this->prepareOrder($id);
- }
-
- $chunked = array_chunk($orders, 50);
- unset($orders);
-
- foreach ($chunked as $chunk) {
- $this->_api->ordersUpload($chunk);
- time_nanosleep(0, 250000000);
- }
-
- unset($chunked);
-
- return true;
-
- }
-
- public function prepareOrder($id)
- {
- $magentoOrder = $this->_order->loadByIncrementId($id);
- $magentoOrderArr = $magentoOrder->getData();
-
- $items = array();
- $addressObj = $magentoOrder->getBillingAddress();
-
- foreach ($magentoOrder->getAllItems() as $item) {
- if ($item->getProductType() == "simple") {
-
- $price = $item->getPrice();
-
- if($price == 0){
- $om = \Magento\Framework\App\ObjectManager::getInstance();
- $omproduct = $om->get('Magento\Catalog\Model\ProductRepository')
- ->getById($item->getProductId());
- $price = $omproduct->getPrice();
- }
-
- $product = array(
- 'productId' => $item->getProductId(),
- 'productName' => $item->getName(),
- 'quantity' => $item->getQtyOrdered(),
- 'initialPrice' => $price,
- 'offer'=>array(
- 'externalId'=>$item->getProductId()
- )
- );
-
- unset($om);
- unset($omproduct);
- unset($price);
-
- $items[] = $product;
- }
- }
-
- $ship = $this->getShippingCode($magentoOrder->getShippingMethod());
-
- $preparedOrder = array(
- 'site' => $magentoOrder->getStore()->getCode(),
- 'externalId' => $magentoOrder->getRealOrderId(),
- 'number' => $magentoOrder->getRealOrderId(),
- 'createdAt' => date('Y-m-d H:i:s'),
- 'lastName' => $magentoOrder->getCustomerLastname(),
- 'firstName' => $magentoOrder->getCustomerFirstname(),
- 'patronymic' => $magentoOrder->getCustomerMiddlename(),
- 'email' => $magentoOrder->getCustomerEmail(),
- 'phone' => $addressObj->getTelephone(),
- 'paymentType' => $this->_config->getValue('retailcrm/Payment/'.$magentoOrder->getPayment()->getMethodInstance()->getCode()),
- 'status' => $this->_config->getValue('retailcrm/Status/'.$magentoOrder->getStatus()),
- 'discount' => abs($magentoOrder->getDiscountAmount()),
- 'items' => $items,
- 'delivery' => array(
- 'code' => $this->_config->getValue('retailcrm/Shipping/'.$ship),
- 'cost' => $magentoOrder->getShippingAmount(),
- 'address' => array(
- 'index' => $addressObj->getData('postcode'),
- 'city' => $addressObj->getData('city'),
- 'country' => $addressObj->getData('country_id'),
- 'street' => $addressObj->getData('street'),
- 'region' => $addressObj->getData('region'),
- 'text' => trim(
- ',',
- implode(
- ',',
- array(
- $addressObj->getData('postcode'),
- $addressObj->getData('city'),
- $addressObj->getData('street'),
- )
- )
- )
- )
- )
- );
-
- if(trim($preparedOrder['delivery']['code']) == ''){
- unset($preparedOrder['delivery']['code']);
- }
-
- if(trim($preparedOrder['paymentType']) == ''){
- unset($preparedOrder['paymentType']);
- }
-
- if(trim($preparedOrder['status']) == ''){
- unset($preparedOrder['status']);
- }
-
- if ($magentoOrder->getCustomerIsGuest() == 0) {
- $preparedOrder['customer']['externalId'] = $magentoOrder->getCustomerId();
- }
-
- $logger = new \Retailcrm\Retailcrm\Model\Logger\Logger();
- $logger->write($preparedOrder,'OrderNumber');
-
- return $this->_helper->filterRecursive($preparedOrder);
-
- }
-
-}
\ No newline at end of file
+ }
+
+ public function ExportOrderNumber()
+ {
+ $ordernumber = $this->_config->getValue('retailcrm/Load/number_order');
+ $ordersId = explode(",", $ordernumber);
+ $orders = [];
+
+ foreach ($ordersId as $id) {
+ $orders[] = $this->prepareOrder($id);
+ }
+
+ $chunked = array_chunk($orders, 50);
+ unset($orders);
+
+ foreach ($chunked as $chunk) {
+ $this->_api->ordersUpload($chunk);
+ time_nanosleep(0, 250000000);
+ }
+
+ unset($chunked);
+
+ return true;
+ }
+
+ public function prepareOrder($id)
+ {
+ $magentoOrder = $this->_order->load($id);
+
+ $items = [];
+ $addressObj = $magentoOrder->getBillingAddress();
+
+ foreach ($magentoOrder->getAllItems() as $item) {
+ if ($item->getProductType() == "simple") {
+ $price = $item->getPrice();
+
+ if ($price == 0){
+ $om = \Magento\Framework\App\ObjectManager::getInstance();
+ $omproduct = $om->get('Magento\Catalog\Model\ProductRepository')
+ ->getById($item->getProductId());
+ $price = $omproduct->getPrice();
+ }
+
+ $product = [
+ 'productId' => $item->getProductId(),
+ 'productName' => $item->getName(),
+ 'quantity' => $item->getQtyOrdered(),
+ 'initialPrice' => $price,
+ 'offer' => [
+ 'externalId'=>$item->getProductId()
+ ]
+ ];
+
+ unset($om);
+ unset($omproduct);
+ unset($price);
+
+ $items[] = $product;
+ }
+ }
+
+ $ship = $this->getShippingCode($magentoOrder->getShippingMethod());
+
+ $preparedOrder = [
+ 'site' => $magentoOrder->getStore()->getCode(),
+ 'externalId' => $magentoOrder->getRealOrderId(),
+ 'number' => $magentoOrder->getRealOrderId(),
+ 'createdAt' => date('Y-m-d H:i:s'),
+ 'lastName' => $magentoOrder->getCustomerLastname(),
+ 'firstName' => $magentoOrder->getCustomerFirstname(),
+ 'patronymic' => $magentoOrder->getCustomerMiddlename(),
+ 'email' => $magentoOrder->getCustomerEmail(),
+ 'phone' => $addressObj->getTelephone(),
+ 'paymentType' => $this->_config->getValue('retailcrm/Payment/'.$magentoOrder->getPayment()->getMethodInstance()->getCode()),
+ 'status' => $this->_config->getValue('retailcrm/Status/'.$magentoOrder->getStatus()),
+ 'discount' => abs($magentoOrder->getDiscountAmount()),
+ 'items' => $items,
+ 'delivery' => [
+ 'code' => $this->_config->getValue('retailcrm/Shipping/'.$ship),
+ 'cost' => $magentoOrder->getShippingAmount(),
+ 'address' => [
+ 'index' => $addressObj->getData('postcode'),
+ 'city' => $addressObj->getData('city'),
+ 'country' => $addressObj->getData('country_id'),
+ 'street' => $addressObj->getData('street'),
+ 'region' => $addressObj->getData('region'),
+ 'text' => trim(
+ ',',
+ implode(
+ ',',
+ [
+ $addressObj->getData('postcode'),
+ $addressObj->getData('city'),
+ $addressObj->getData('street'),
+ ]
+ )
+ )
+ ]
+ ]
+ ];
+
+ if (trim($preparedOrder['delivery']['code']) == ''){
+ unset($preparedOrder['delivery']['code']);
+ }
+
+ if (trim($preparedOrder['paymentType']) == ''){
+ unset($preparedOrder['paymentType']);
+ }
+
+ if (trim($preparedOrder['status']) == ''){
+ unset($preparedOrder['status']);
+ }
+
+ if ($magentoOrder->getCustomerIsGuest() == 0) {
+ $preparedOrder['customer']['externalId'] = $magentoOrder->getCustomerId();
+ }
+
+ $this->_logger->writeDump($preparedOrder,'OrderNumber');
+
+ return $this->_helper->filterRecursive($preparedOrder);
+ }
+}
diff --git a/Model/Setting/ApiVersions.php b/Model/Setting/ApiVersions.php
new file mode 100644
index 0000000..8f9011e
--- /dev/null
+++ b/Model/Setting/ApiVersions.php
@@ -0,0 +1,14 @@
+ 'v4', 'label' => 'v4'],
+ ['value' => 'v5', 'label' => 'v5']
+ ];
+ }
+}
diff --git a/Model/Setting/Attribute.php b/Model/Setting/Attribute.php
index ddf39de..f00036f 100644
--- a/Model/Setting/Attribute.php
+++ b/Model/Setting/Attribute.php
@@ -2,36 +2,33 @@
namespace Retailcrm\Retailcrm\Model\Setting;
-//use Psr\Log\LoggerInterface;
-
class Attribute implements \Magento\Framework\Option\ArrayInterface
{
- protected $_entityType;
- protected $_store;
-
- public function __construct(
- \Magento\Store\Model\Store $store,
- \Magento\Eav\Model\Entity\Type $entityType
- ) {
- $this->_store = $store;
- $this->_entityType = $entityType;
- }
-
- public function toOptionArray()
- {
- $types = array('text', 'multiselect', 'decimal');
- $attributes = $this->_entityType->loadByCode('catalog_product')->getAttributeCollection();
- $attributes->addFieldToFilter('frontend_input', $types);
-
- $result = array();
- foreach ($attributes as $attr) {
- if ($attr->getFrontendLabel()) {
- $result[] = array('value' => $attr->getAttributeId(), 'label' => $attr->getFrontendLabel(), 'title' => $attr->getAttributeCode());
- }
- }
-
- return $result;
- }
-
-
+ protected $_entityType;
+ protected $_store;
+
+ public function __construct(
+ \Magento\Store\Model\Store $store,
+ \Magento\Eav\Model\Entity\Type $entityType
+ ) {
+ $this->_store = $store;
+ $this->_entityType = $entityType;
+ }
+
+ public function toOptionArray()
+ {
+ $types = ['text', 'multiselect', 'decimal'];
+ $attributes = $this->_entityType->loadByCode('catalog_product')->getAttributeCollection();
+ $attributes->addFieldToFilter('frontend_input', $types);
+
+ $result = [];
+
+ foreach ($attributes as $attr) {
+ if ($attr->getFrontendLabel()) {
+ $result[] = array('value' => $attr->getAttributeId(), 'label' => $attr->getFrontendLabel(), 'title' => $attr->getAttributeCode());
+ }
+ }
+
+ return $result;
+ }
}
diff --git a/Model/Setting/Shipping.php b/Model/Setting/Shipping.php
index 68c5cb5..7fd266e 100644
--- a/Model/Setting/Shipping.php
+++ b/Model/Setting/Shipping.php
@@ -2,47 +2,49 @@
namespace Retailcrm\Retailcrm\Model\Setting;
-//use Psr\Log\LoggerInterface;
-
class Shipping implements \Magento\Framework\Option\ArrayInterface
{
- protected $_entityType;
- protected $_store;
-
- public function __construct(
- \Magento\Store\Model\Store $store,
- \Magento\Eav\Model\Entity\Type $entityType
- ) {
- $this->_store = $store;
- $this->_entityType = $entityType;
- }
-
- public function toOptionArray()
- {
- $om = \Magento\Framework\App\ObjectManager::getInstance();
- $activeShipping = $om->create('Magento\Shipping\Model\Config')->getActiveCarriers();
-
- $config = \Magento\Framework\App\ObjectManager::getInstance()->get(
- 'Magento\Framework\App\Config\ScopeConfigInterface'
- );
-
- foreach($activeShipping as $carrierCode => $carrierModel)
- {
- $options = array();
- if( $carrierMethods = $carrierModel->getAllowedMethods() )
- {
- foreach ($carrierMethods as $methodCode => $method)
- {
- $code= $carrierCode.'_'.$methodCode;
- $options[]=array('value'=>$code,'label'=>$method);
- }
- $carrierTitle =$config->getValue('carriers/'.$carrierCode.'/title');
-
- }
- $methods[] = array('value'=>$options,'label'=>$carrierTitle);
- }
-
- return $methods;
-
- }
-}
\ No newline at end of file
+ protected $_entityType;
+ protected $_store;
+
+ public function __construct(
+ \Magento\Store\Model\Store $store,
+ \Magento\Eav\Model\Entity\Type $entityType
+ ) {
+ $this->_store = $store;
+ $this->_entityType = $entityType;
+ }
+
+ public function toOptionArray()
+ {
+ $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
+ $activeShipping = $objectManager->create('Magento\Shipping\Model\Config')->getActiveCarriers();
+
+ $config = $objectManager->get('Magento\Framework\App\Config\ScopeConfigInterface');
+
+ foreach ($activeShipping as $carrierCode => $carrierModel) {
+ $options = [];
+
+ if ($carrierModel->getAllowedMethods()) {
+ $carrierMethods = $carrierModel->getAllowedMethods();
+
+ foreach ($carrierMethods as $methodCode => $method) {
+ $code = $carrierCode . '_' . $methodCode;
+ $options[] = [
+ 'value' => $code,
+ 'label' => $method
+ ];
+ }
+
+ $carrierTitle = $config->getValue('carriers/' . $carrierCode . '/title');
+ }
+
+ $methods[] = [
+ 'value' => $options,
+ 'label' => $carrierTitle
+ ];
+ }
+
+ return $methods;
+ }
+}
diff --git a/Model/Setting/Status.php b/Model/Setting/Status.php
index e2f96c4..a7adbcb 100644
--- a/Model/Setting/Status.php
+++ b/Model/Setting/Status.php
@@ -9,12 +9,9 @@ class Status extends \Magento\Config\Model\Config\Backend\Serialized\ArraySerial
// For value validations
$exceptions = $this->getValue();
- // Validations
-
+ // Validations
$this->setValue($exceptions);
return parent::beforeSave();
}
-
-
-}
\ No newline at end of file
+}
diff --git a/README.md b/README.md
index 1d5c5b6..c6ff888 100644
--- a/README.md
+++ b/README.md
@@ -1,16 +1,29 @@
Magento module
==============
-Magento 2 module for interaction with [RetailCRM](http://www.retailcrm.ru) through [REST API](http://www.retailcrm.ru/docs/Developers/Index).
+Magento 2 module for interaction with [retailCRM](http://www.retailcrm.ru).
Module allows:
-* Exchange the orders with retailCRM
-* Configure relations between dictionaries of RetailCRM and Magento (statuses, payments, delivery types and etc)
-* Generate [ICML](http://www.retailcrm.ru/docs/Developers/ICML) (Intaro Markup Language) for catalog loading by RetailCRM
+* Exchange the orders data with retailCRM
+* Configure relations between dictionaries of retailCRM and Magento (statuses, payments, delivery types and etc)
+* Generate [ICML](http://www.retailcrm.ru/docs/Developers/ICML) (Intaro Markup Language) export file for catalog loading by retailCRM
-ICML
+### ICML
-By default ICML file is being generated by module every 4 hours. You can find file in the web root folder with name "retailcrm_{{shop_code}}.xml". For example, http://retailcrm.ru/retailcrm_default.xml
+By default ICML file is being generated by module every 4 hours. You can find file in the web root folder with name "retailcrm_{{shop_code}}.xml". For example, http://example.org/retailcrm_default.xml
-This module is compatible with Magento up to version 2.1.6
+### Manual install
+
+
+1) Run into your project root directory:
+```bash
+composer require retailcrm/api-client-php ~5.0
+```
+
+2) Unpack the archive with the module into the `app/code/Retailcrm/Retailcrm` directory.
+
+3) Change `app/etc/config.php` file by adding `'Retailcrm_Retailcrm' => 1` line into `modules` array
+
+
+This module is compatible with Magento up to version 2.2.3
diff --git a/README.ru.md b/README.ru.md
new file mode 100644
index 0000000..cd5fc51
--- /dev/null
+++ b/README.ru.md
@@ -0,0 +1,31 @@
+Magento module
+==============
+
+Модуль Magento 2 для интеграции с [retailCRM](http://www.retailcrm.ru).
+
+Модуль позволяет:
+
+* Производить обмен заказами с retailCRM
+* Настроить соответствие справочников retailCRM и Magento (статусы, оплаты, типы доставки и т.д.)
+* Создать [ICML](http://www.retailcrm.ru/docs/Developers/ICML) (Intaro Markup Language) для загрузки каталога товаров в retailCRM
+
+### ICML
+
+По умолчанию ICML-файл генерируется модулем каждые 4 часа. Вы можете найти файл в корневой директории с именем «retailcrm_{{shop_code}}.xml". Например, http://example.org/retailcrm_default.xml
+
+### Ручная установка
+
+1) Находясь в корневой директории проекта выполните команду:
+
+```bash
+composer require retailcrm/api-client-php ~5.0
+```
+
+2) Распакуйте архив с модулем в директорию "app/code/Retailcrm/Retailcrm".
+
+3) В файле "app/etc/config.php" в массив `modules` добавьте элемент `'Retailcrm_Retailcrm' => 1`
+
+
+В конфигурационный файл `composer.json` вашего проекта будет добавлена библиотека [retailcrm/api-client-php](https://github.com/retailcrm/api-client-php), которая будет установлена в директорию `vendor/`.
+
+Этот модуль совместим с Magento 2 до версии 2.2.3
diff --git a/Test/Unit/Observer/CustomerTest.php b/Test/Unit/Observer/CustomerTest.php
new file mode 100644
index 0000000..e8ae7da
--- /dev/null
+++ b/Test/Unit/Observer/CustomerTest.php
@@ -0,0 +1,159 @@
+mockApi = $this->getMockBuilder(\Retailcrm\Retailcrm\Helper\Proxy::class)
+ ->disableOriginalConstructor()
+ ->setMethods([
+ 'customersEdit',
+ 'customersCreate'
+ ])
+ ->getMock();
+
+ $this->mockResponse = $this->getMockBuilder(\RetailCrm\Response\ApiResponse::class)
+ ->disableOriginalConstructor()
+ ->setMethods(['isSuccessful'])
+ ->getMock();
+
+ $this->config = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class)
+ ->getMockForAbstractClass();
+
+ $this->registry = $this->getMockBuilder(\Magento\Framework\Registry::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+
+ $this->mockObserver = $this->getMockBuilder(\Magento\Framework\Event\Observer::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+
+ $this->mockEvent = $this->getMockBuilder(\Magento\Framework\Event::class)
+ ->disableOriginalConstructor()
+ ->setMethods(['getCustomer'])
+ ->getMock();
+
+ $this->objectManager = $this->getMockBuilder(\Magento\Framework\ObjectManagerInterface::class)
+ ->getMockForAbstractClass();
+
+ $this->mockCustomer = $this->getMockBuilder(\Magento\Customer\Model\Customer::class)
+ ->disableOriginalConstructor()
+ ->setMethods([
+ 'getId',
+ 'getEmail',
+ 'getFirstname',
+ 'getMiddlename',
+ 'getLastname'
+ ])
+ ->getMock();
+
+ $this->unit = new \Retailcrm\Retailcrm\Model\Observer\Customer(
+ $this->objectManager,
+ $this->config,
+ $this->registry
+ );
+
+ $reflection = new \ReflectionClass($this->unit);
+ $reflection_property = $reflection->getProperty('_api');
+ $reflection_property->setAccessible(true);
+ $reflection_property->setValue($this->unit, $this->mockApi);
+ }
+
+ /**
+ * @param boolean $isSuccessful
+ * @dataProvider dataProviderCustomer
+ */
+ public function testExecute(
+ $isSuccessful
+ ) {
+ $testData = $this->getAfterSaveCustomerTestData();
+
+ // mock Response
+ $this->mockResponse->expects($this->any())
+ ->method('isSuccessful')
+ ->willReturn($isSuccessful);
+
+ $this->mockResponse->errorMsg = 'Not found';
+
+ // mock API
+ $this->mockApi->expects($this->any())
+ ->method('customersEdit')
+ ->willReturn($this->mockResponse);
+
+ $this->mockApi->expects($this->any())
+ ->method('customersCreate')
+ ->willReturn($this->mockResponse);
+
+ // mock Customer
+ $this->mockCustomer->expects($this->once())
+ ->method('getId')
+ ->willReturn($testData['id']);
+
+ $this->mockCustomer->expects($this->once())
+ ->method('getEmail')
+ ->willReturn($testData['email']);
+
+ $this->mockCustomer->expects($this->once())
+ ->method('getFirstname')
+ ->willReturn($testData['firstname']);
+
+ $this->mockCustomer->expects($this->once())
+ ->method('getMiddlename')
+ ->willReturn($testData['middlename']);
+
+ $this->mockCustomer->expects($this->once())
+ ->method('getLastname')
+ ->willReturn($testData['lastname']);
+
+ // mock Event
+ $this->mockEvent->expects($this->once())
+ ->method('getCustomer')
+ ->willReturn($this->mockCustomer);
+
+ // mock Observer
+ $this->mockObserver->expects($this->once())
+ ->method('getEvent')
+ ->willReturn($this->mockEvent);
+
+ $this->unit->execute($this->mockObserver);
+ }
+
+ /**
+ * Get test customer data
+ *
+ * @return array
+ */
+ protected function getAfterSaveCustomerTestData()
+ {
+ return [
+ 'id' => 1,
+ 'email' => 'test@mail.com',
+ 'firstname' => 'TestFirstname',
+ 'lastname' => 'Testlastname',
+ 'middlename' => 'Testmiddlename'
+ ];
+ }
+
+ public function dataProviderCustomer()
+ {
+ return [
+ [
+ 'is_successful' => true
+ ],
+ [
+ 'is_successful' => false
+ ]
+ ];
+ }
+}
diff --git a/Test/Unit/Observer/OrderCreateTest.php b/Test/Unit/Observer/OrderCreateTest.php
new file mode 100644
index 0000000..9be435f
--- /dev/null
+++ b/Test/Unit/Observer/OrderCreateTest.php
@@ -0,0 +1,426 @@
+_mockApi = $this->getMockBuilder(\Retailcrm\Retailcrm\Helper\Proxy::class)
+ ->disableOriginalConstructor()
+ ->setMethods([
+ 'ordersGet',
+ 'ordersCreate',
+ 'customersGet',
+ 'customersCreate',
+ 'customersList',
+ 'getVersion'
+ ])
+ ->getMock();
+
+ $this->_mockObserver = $this->getMockBuilder(\Magento\Framework\Event\Observer::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+
+ $this->_mockEvent = $this->getMockBuilder(\Magento\Framework\Event::class)
+ ->disableOriginalConstructor()
+ ->setMethods(['getOrder'])
+ ->getMock();
+
+ $this->objectManager = $this->getMockBuilder(\Magento\Framework\ObjectManagerInterface::class)
+ ->getMockForAbstractClass();
+
+ // mock Object Manager
+ $this->objectManager->expects($this->any())
+ ->method('get')
+ ->with($this->logicalOr(
+ $this->equalTo('\Retailcrm\Retailcrm\Helper\Data'),
+ $this->equalTo('\Retailcrm\Retailcrm\Model\Logger\Logger')
+ ))
+ ->will($this->returnCallback([$this, 'getCallbackDataClasses']));
+
+ $this->_config = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class)
+ ->getMockForAbstractClass();
+
+ $this->_logger = $this->getMockBuilder(\Retailcrm\Retailcrm\Model\Logger\Logger::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+
+ $this->_registry = $this->getMockBuilder(\Magento\Framework\Registry::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+
+ $this->_mockOrder = $this->getMockBuilder(\Magento\Sales\Order::class)
+ ->setMethods([
+ 'getId',
+ 'getRealOrderId',
+ 'getCreatedAt',
+ 'getStore',
+ 'getBillingAddress',
+ 'getShippingMethod',
+ 'getCustomerId',
+ 'getCustomerLastname',
+ 'getCustomerFirstname',
+ 'getCustomerMiddlename',
+ 'getCustomerEmail',
+ 'getShippingAmount',
+ 'getDiscountAmount',
+ 'getPayment',
+ 'getBaseTotalDue',
+ 'getCustomerIsGuest',
+ 'getAllItems',
+ 'getStatus'
+ ])
+ ->getMock();
+
+ $this->_mockPayment = $this->getMockBuilder(\Magento\Sales\Model\Order\Payment::class)
+ ->setMethods(['getMethodInstance'])
+ ->disableOriginalConstructor()
+ ->getMock();
+
+ $this->_mockPaymentMethod = $this->getMockBuilder(\Magento\Payment\Model\MethodInterface::class)
+ ->disableOriginalConstructor()
+ ->getMockForAbstractClass();
+
+ $this->_mockItem = $this->getMockBuilder(\Magento\Sales\Model\Order\Item::class)
+ ->disableOriginalConstructor()
+ ->setMethods([
+ 'getPrice',
+ 'getProductId',
+ 'getName',
+ 'getQtyOrdered',
+ 'getProductType'
+ ])
+ ->getMock();
+
+ $this->_mockStore = $this->getMockBuilder(\Magento\Store\Model\Store::class)
+ ->disableOriginalConstructor()
+ ->setMethods(['getCode'])
+ ->getMock();
+
+ $this->_mockBillingAddress = $this->getMockBuilder(\Magento\Customer\Model\Address\AddressModelInterface::class)
+ ->disableOriginalConstructor()
+ ->setMethods(['getTelephone', 'getData'])
+ ->getMockForAbstractClass();
+
+ $this->_mockResponse = $this->getMockBuilder(\RetailCrm\Response\ApiResponse::class)
+ ->disableOriginalConstructor()
+ ->setMethods(['isSuccessful'])
+ ->getMock();
+
+ $this->_unit = new \Retailcrm\Retailcrm\Model\Observer\OrderCreate(
+ $this->objectManager,
+ $this->_config,
+ $this->_registry
+ );
+
+ $reflection = new \ReflectionClass($this->_unit);
+ $reflection_property = $reflection->getProperty('_api');
+ $reflection_property->setAccessible(true);
+ $reflection_property->setValue($this->_unit, $this->_mockApi);
+ }
+
+ /**
+ * @param boolean $isSuccessful
+ * @param string $errorMsg
+ * @param int $customerIsGuest
+ * @param string $apiVersion
+ * @dataProvider dataProviderOrderCreate
+ */
+ public function testExecute(
+ $isSuccessful,
+ $errorMsg,
+ $customerIsGuest,
+ $apiVersion
+ ) {
+ $testData = $this->getAfterSaveOrderTestData();
+
+ // mock Response
+ $this->_mockResponse->expects($this->any())
+ ->method('isSuccessful')
+ ->willReturn($isSuccessful);
+
+ $this->_mockResponse->errorMsg = $errorMsg;
+
+ // mock API
+ $this->_mockApi->expects($this->any())
+ ->method('ordersGet')
+ ->willReturn($this->_mockResponse);
+
+ $this->_mockApi->expects($this->any())
+ ->method('ordersCreate')
+ ->willReturn($this->_mockResponse);
+
+ $this->_mockApi->expects($this->any())
+ ->method('customersGet')
+ ->willReturn($this->_mockResponse);
+
+ $this->_mockApi->expects($this->any())
+ ->method('customersCreate')
+ ->willReturn($this->_mockResponse);
+
+ $this->_mockApi->expects($this->any())
+ ->method('customersList')
+ ->willReturn($this->_mockResponse);
+
+ $this->_mockApi->expects($this->any())
+ ->method('getVersion')
+ ->willReturn($apiVersion);
+
+ // billing address mock set data
+ $this->_mockBillingAddress->expects($this->any())
+ ->method('getTelephone')
+ ->willReturn($testData['order.billingAddress']['telephone']);
+
+ $this->_mockBillingAddress->expects($this->any())
+ ->method('getData')
+ ->with($this->logicalOr(
+ $this->equalTo('city'),
+ $this->equalTo('region'),
+ $this->equalTo('street'),
+ $this->equalTo('postcode'),
+ $this->equalTo('country_id')
+ ))
+ ->will($this->returnCallback([$this, 'getCallbackDataAddress']));
+
+ // store mock set data
+ $this->_mockStore->expects($this->any())
+ ->method('getCode')
+ ->willReturn(1);
+
+ // order item mock set data
+ $this->_mockItem->expects($this->any())
+ ->method('getProductType')
+ ->willReturn('simple');
+
+ $this->_mockItem->expects($this->any())
+ ->method('getPrice')
+ ->willReturn(999.99);
+
+ $this->_mockItem->expects($this->any())
+ ->method('getProductId')
+ ->willReturn(10);
+
+ $this->_mockItem->expects($this->any())
+ ->method('getName')
+ ->willReturn('Product name');
+
+ $this->_mockItem->expects($this->any())
+ ->method('getQtyOrdered')
+ ->willReturn(3);
+
+ // order mock set data
+ $this->_mockOrder->expects($this->any())
+ ->method('getId')
+ ->willReturn($testData['order.id']);
+
+ $this->_mockOrder->expects($this->any())
+ ->method('getBillingAddress')
+ ->willReturn($this->_mockBillingAddress);
+
+ $this->_mockOrder->expects($this->any())
+ ->method('getShippingMethod')
+ ->willReturn($testData['order.shippingMethod']);
+
+ $this->_mockOrder->expects($this->any())
+ ->method('getStore')
+ ->willReturn($this->_mockStore);
+
+ $this->_mockOrder->expects($this->any())
+ ->method('getRealOrderId')
+ ->willReturn($testData['order.realOrderId']);
+
+ $this->_mockOrder->expects($this->any())
+ ->method('getCreatedAt')
+ ->willReturn(date('Y-m-d H:i:s'));
+
+ $this->_mockOrder->expects($this->any())
+ ->method('getCustomerLastname')
+ ->willReturn($testData['order.customerLastname']);
+
+ $this->_mockOrder->expects($this->any())
+ ->method('getCustomerFirstname')
+ ->willReturn($testData['order.customerFirstname']);
+
+ $this->_mockOrder->expects($this->any())
+ ->method('getCustomerMiddlename')
+ ->willReturn($testData['order.customerMiddlename']);
+
+ $this->_mockOrder->expects($this->any())
+ ->method('getCustomerEmail')
+ ->willReturn($testData['order.customerEmail']);
+
+ $this->_mockOrder->expects($this->any())
+ ->method('getAllItems')
+ ->willReturn($testData['order.allItems']);
+
+ $this->_mockOrder->expects($this->any())
+ ->method('getStatus')
+ ->willReturn($testData['order.status']);
+
+ $this->_mockOrder->expects($this->any())
+ ->method('getCustomerIsGuest')
+ ->willReturn($customerIsGuest);
+
+ $this->_mockOrder->expects($this->any())
+ ->method('getCustomerId')
+ ->willReturn(1);
+
+ $this->_mockOrder->expects($this->any())
+ ->method('getPayment')
+ ->willReturn($this->_mockPayment);
+
+ // mock Payment Method
+ $this->_mockPaymentMethod->expects($this->any())
+ ->method('getCode')
+ ->willReturn($testData['order.paymentMethod']);
+
+ // mock Payment
+ $this->_mockPayment->expects($this->any())
+ ->method('getMethodInstance')
+ ->willReturn($this->_mockPaymentMethod);
+
+ // mock Event
+ $this->_mockEvent->expects($this->once())
+ ->method('getOrder')
+ ->willReturn($this->_mockOrder);
+
+ // mock Observer
+ $this->_mockObserver->expects($this->once())
+ ->method('getEvent')
+ ->willReturn($this->_mockEvent);
+
+ $this->_unit->execute($this->_mockObserver);
+ }
+
+ /**
+ * Get test order data
+ *
+ * @return array $testOrderData
+ */
+ protected function getAfterSaveOrderTestData()
+ {
+ $testOrderData = [
+ 'order.id' => 1,
+ 'order.status' => 'processing',
+ 'order.realOrderId' => '000000001',
+ 'order.billingAddress' => [
+ 'telephone' => '890000000000',
+ 'data' => [
+ 'city' => 'Moscow',
+ 'region' => 'Moscow',
+ 'street' => 'TestStreet',
+ 'postcode' => '111111',
+ 'country_id' => 'RU'
+ ]
+ ],
+ 'order.allItems' => [$this->_mockItem],
+ 'order.shippingMethod' => 'flatrate_flatrate',
+ 'order.paymentMethod' => 'checkmo',
+ 'order.customerLastname' => 'Test',
+ 'order.customerFirstname' => 'Test',
+ 'order.customerMiddlename' => 'Test',
+ 'order.customerEmail' => 'test@gmail.com'
+ ];
+
+ return $testOrderData;
+ }
+
+ public function getCallbackDataAddress($dataKey)
+ {
+ $testData = $this->getAfterSaveOrderTestData();
+
+ return $testData['order.billingAddress']['data'][$dataKey];
+ }
+
+ public function getCallbackDataClasses($class)
+ {
+ $helper = $this->getMockBuilder(\Retailcrm\Retailcrm\Helper\Data::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+
+ $logger = $this->getMockBuilder(\Retailcrm\Retailcrm\Model\Logger\Logger::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+
+ if ($class == '\Retailcrm\Retailcrm\Helper\Data') {
+ return $helper;
+ }
+
+ if ($class == '\Retailcrm\Retailcrm\Model\Logger\Logger') {
+ return $logger;
+ }
+ }
+
+ public function dataProviderOrderCreate()
+ {
+ return [
+ [
+ 'is_successful' => true,
+ 'error_msg' => 'Not found',
+ 'customer_is_guest' => 1,
+ 'api_version' => 'v4'
+ ],
+ [
+ 'is_successful' => true,
+ 'error_msg' => 'Not found',
+ 'customer_is_guest' => 0,
+ 'api_version' => 'v4'
+ ],
+ [
+ 'is_successful' => false,
+ 'error_msg' => 'Not found',
+ 'customer_is_guest' => 1,
+ 'api_version' => 'v4'
+ ],
+ [
+ 'is_successful' => false,
+ 'error_msg' => 'Not found',
+ 'customer_is_guest' => 0,
+ 'api_version' => 'v4'
+ ],
+ [
+ 'is_successful' => true,
+ 'error_msg' => 'Not found',
+ 'customer_is_guest' => 1,
+ 'api_version' => 'v5'
+ ],
+ [
+ 'is_successful' => true,
+ 'error_msg' => 'Not found',
+ 'customer_is_guest' => 0,
+ 'api_version' => 'v5'
+ ],
+ [
+ 'is_successful' => false,
+ 'error_msg' => 'Not found',
+ 'customer_is_guest' => 1,
+ 'api_version' => 'v5'
+ ],
+ [
+ 'is_successful' => false,
+ 'error_msg' => 'Not found',
+ 'customer_is_guest' => 0,
+ 'api_version' => 'v5'
+ ]
+ ];
+ }
+}
diff --git a/Test/Unit/Observer/OrderUpdateTest.php b/Test/Unit/Observer/OrderUpdateTest.php
new file mode 100644
index 0000000..1c3709a
--- /dev/null
+++ b/Test/Unit/Observer/OrderUpdateTest.php
@@ -0,0 +1,171 @@
+mockApi = $this->getMockBuilder(\Retailcrm\Retailcrm\Helper\Proxy::class)
+ ->disableOriginalConstructor()
+ ->setMethods([
+ 'ordersEdit',
+ 'ordersPaymentsEdit',
+ 'getVersion'
+ ])
+ ->getMock();
+
+ $this->mockObserver = $this->getMockBuilder(\Magento\Framework\Event\Observer::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+
+ $this->mockEvent = $this->getMockBuilder(\Magento\Framework\Event::class)
+ ->disableOriginalConstructor()
+ ->setMethods(['getOrder'])
+ ->getMock();
+
+ $this->objectManager = $this->getMockBuilder(\Magento\Framework\ObjectManagerInterface::class)
+ ->getMockForAbstractClass();
+
+ $helper = $this->getMockBuilder(\Retailcrm\Retailcrm\Helper\Data::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+
+ $this->mockOrder = $this->getMockBuilder(\Magento\Sales\Order::class)
+ ->setMethods([
+ 'getId',
+ 'getPayment',
+ 'getBaseTotalDue',
+ 'getStatus'
+ ])
+ ->getMock();
+
+ $this->mockPayment = $this->getMockBuilder(\Magento\Sales\Model\Order\Payment::class)
+ ->setMethods(['getId'])
+ ->disableOriginalConstructor()
+ ->getMock();
+
+ // mock Object Manager
+ $this->objectManager->expects($this->any())
+ ->method('get')
+ ->with('\Retailcrm\Retailcrm\Helper\Data')
+ ->willReturn($helper);
+
+ $this->config = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class)
+ ->getMockForAbstractClass();
+
+ $this->registry = $this->getMockBuilder(\Magento\Framework\Registry::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+
+ $this->unit = new \Retailcrm\Retailcrm\Model\Observer\OrderUpdate(
+ $this->objectManager,
+ $this->config,
+ $this->registry
+ );
+
+ $reflection = new \ReflectionClass($this->unit);
+ $reflection_property = $reflection->getProperty('_api');
+ $reflection_property->setAccessible(true);
+ $reflection_property->setValue($this->unit, $this->mockApi);
+ }
+
+ /**
+ * @param int $getBaseTotalDue
+ * @param string $apiVersion
+ * @dataProvider dataProviderOrderUpdate
+ */
+ public function testExecute(
+ $getBaseTotalDue,
+ $apiVersion
+ ) {
+ $testData = $this->getAfterUpdateOrderTestData();
+
+ // mock Payment
+ $this->mockPayment->expects($this->any())
+ ->method('getId')
+ ->willReturn(1);
+
+ // mock Order
+ $this->mockOrder->expects($this->once())
+ ->method('getId')
+ ->willReturn($testData['order.id']);
+
+ $this->mockOrder->expects($this->once())
+ ->method('getStatus')
+ ->willReturn($testData['order.status']);
+
+ $this->mockOrder->expects($this->once())
+ ->method('getBaseTotalDue')
+ ->willReturn($getBaseTotalDue);
+
+ $this->mockOrder->expects($this->any())
+ ->method('getPayment')
+ ->willReturn($this->mockPayment);
+
+ // mock Api
+ $this->mockApi->expects($this->any())
+ ->method('getVersion')
+ ->willReturn($apiVersion);
+
+ // mock Event
+ $this->mockEvent->expects($this->once())
+ ->method('getOrder')
+ ->willReturn($this->mockOrder);
+
+ // mock Observer
+ $this->mockObserver->expects($this->once())
+ ->method('getEvent')
+ ->willReturn($this->mockEvent);
+
+ $this->unit->execute($this->mockObserver);
+ }
+
+ /**
+ * Get test order data
+ *
+ * @return array $testOrderData
+ */
+ protected function getAfterUpdateOrderTestData()
+ {
+ $testOrderData = [
+ 'order.id' => 1,
+ 'order.status' => 'processing',
+ 'order.paymentMethod' => 'checkmo'
+ ];
+
+ return $testOrderData;
+ }
+
+ public function dataProviderOrderUpdate()
+ {
+ return [
+ [
+ 'get_base_total_due' => 0,
+ 'api_version' => 'v4'
+ ],
+ [
+ 'get_base_total_due' => 1,
+ 'api_version' => 'v4'
+ ],
+ [
+ 'get_base_total_due' => 0,
+ 'api_version' => 'v5'
+ ],
+ [
+ 'get_base_total_due' => 1,
+ 'api_version' => 'v5'
+ ]
+ ];
+ }
+}
diff --git a/composer.json b/composer.json
index 012b677..ea887e9 100644
--- a/composer.json
+++ b/composer.json
@@ -2,7 +2,8 @@
"name": "retailcrm/retailcrm",
"description": "Retailcrm",
"require": {
- "php": "~5.5.0|~5.6.0|~7.0.0"
+ "php": "~5.5.0|~5.6.0|~7.0.0",
+ "retailcrm/api-client-php": "~5.0"
},
"type": "magento2-module",
"version": "1.0.0",
diff --git a/etc/adminhtml/system.xml b/etc/adminhtml/system.xml
index 11d8923..657ec96 100644
--- a/etc/adminhtml/system.xml
+++ b/etc/adminhtml/system.xml
@@ -11,16 +11,23 @@
Retailcrm_Retailcrm::retailcrm_configuration
-
-
+
+
https://YourCrmName.retailcrm.ru
+ Retailcrm\Retailcrm\Model\Config\Backend\ApiUrl
-
-
+
+
To generate an API Key, log in to RetailCRM then select Admin > Integration > API Keys
+
+
+
+ Retailcrm\Retailcrm\Model\Setting\ApiVersions
+ Retailcrm\Retailcrm\Model\Config\Backend\ApiVersion
+
diff --git a/etc/config.xml b/etc/config.xml
index 886840b..c35267a 100644
--- a/etc/config.xml
+++ b/etc/config.xml
@@ -3,22 +3,13 @@
-
- test
+ test
-
-
-
-
-
\ No newline at end of file
diff --git a/etc/di.xml b/etc/di.xml
index 53508f4..ec4579e 100644
--- a/etc/di.xml
+++ b/etc/di.xml
@@ -1,5 +1,11 @@
-
-
\ No newline at end of file
+
+
+
+ - Retailcrm\Retailcrm\Console\Command\Command
+
+
+
+
diff --git a/etc/events.xml b/etc/events.xml
index 7a6e8ff..4a826aa 100644
--- a/etc/events.xml
+++ b/etc/events.xml
@@ -1,25 +1,22 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/etc/frontend/events.xml b/etc/frontend/events.xml
index 663136b..f32414d 100644
--- a/etc/frontend/events.xml
+++ b/etc/frontend/events.xml
@@ -4,9 +4,8 @@
-
+
-