1
0
mirror of synced 2024-11-22 13:06:07 +03:00

Refactoring

This commit is contained in:
Akolzin Dmitry 2018-04-28 11:39:23 +03:00
parent dd515492ab
commit 3b6430cf7d
43 changed files with 1230 additions and 3461 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/nbproject/private/

View File

@ -0,0 +1,12 @@
<?php
namespace Retailcrm\Retailcrm\Api;
interface ConfigManagerInterface
{
const URL_PATH = 'retailcrm/general/api_url';
const KEY_PATH = 'retailcrm/general/api_key';
const API_VERSION_PATH = 'retailcrm/general/api_version';
public function getConfigValue($path);
}

View File

@ -0,0 +1,18 @@
<?php
namespace Retailcrm\Retailcrm\ApiClient;
class ApiClientFactory
{
/**
* @param $url
* @param $api_key
* @param null $version
*
* @return \RetailCrm\ApiClient
*/
public function create($url, $api_key, $version = null)
{
return new \RetailCrm\ApiClient($url, $api_key, $version);
}
}

View File

@ -6,18 +6,7 @@ class Button extends \Magento\Config\Block\System\Config\Form\Field
/** /**
* @var string * @var string
*/ */
protected $_template = 'Retailcrm_Retailcrm::system/config/button.phtml'; public $_template = 'Retailcrm_Retailcrm::system/config/button.phtml';
/**
* @param \Magento\Backend\Block\Template\Context $context
* @param array $data
*/
public function __construct(
\Magento\Backend\Block\Template\Context $context,
array $data = []
) {
parent::__construct($context, $data);
}
/** /**
* Remove scope label * Remove scope label
@ -39,7 +28,7 @@ class Button extends \Magento\Config\Block\System\Config\Form\Field
* *
* @SuppressWarnings(PHPMD.UnusedFormalParameter) * @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/ */
protected function _getElementHtml(\Magento\Framework\Data\Form\Element\AbstractElement $element) public function _getElementHtml(\Magento\Framework\Data\Form\Element\AbstractElement $element)
{ {
return $this->_toHtml(); return $this->_toHtml();
} }

View File

@ -6,7 +6,7 @@ use Magento\Framework\Data\Form\Element\AbstractElement;
class Attributes extends \Magento\Config\Block\System\Config\Form\Field class Attributes extends \Magento\Config\Block\System\Config\Form\Field
{ {
protected function _getElementHtml(AbstractElement $element) public function _getElementHtml(AbstractElement $element)
{ {
$values = $element->getValues(); $values = $element->getValues();
$html = '<table id="' . $element->getId() . '_table" class="ui_select_table" cellspacing="0">'; $html = '<table id="' . $element->getId() . '_table" class="ui_select_table" cellspacing="0">';
@ -20,7 +20,7 @@ class Attributes extends \Magento\Config\Block\System\Config\Form\Field
$html .= '<li value="' . $value . '" title="' . $values[$key]['title'] . '">'; $html .= '<li value="' . $value . '" title="' . $values[$key]['title'] . '">';
$html .= isset($values[$key]['label'])?$values[$key]['label']:'n/a'; $html .= isset($values[$key]['label'])?$values[$key]['label']:'n/a';
$html .= '</li>'; $html .= '</li>';
$values[$key]['selected'] = TRUE; $values[$key]['selected'] = true;
} }
} }

View File

@ -1,72 +0,0 @@
<?php
namespace Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Field;
class Base extends \Magento\Framework\Model\AbstractModel
{
public $_apiKey;
public $_apiUrl;
public $_isCredentialCorrect;
protected $logger;
protected $_cacheTypeList;
protected $_resourceConfig;
public function __construct()
{
$om = \Magento\Framework\App\ObjectManager::getInstance();
$config = $om->get('\Magento\Framework\App\Config\ScopeConfigInterface');
$logger = $om->get('\Psr\Log\LoggerInterface');
$cacheTypeList = $om->get('\Magento\Framework\App\Cache\TypeListInterface');
$resourceConfig = $om->get('Magento\Config\Model\ResourceModel\Config');
$this->_resourceConfig = $resourceConfig;
$this->_cacheTypeList = $cacheTypeList;
$this->logger = $logger;
$this->_apiUrl = $config->getValue('retailcrm/general/api_url');
$this->_apiKey = $config->getValue('retailcrm/general/api_key');
$this->_isCredentialCorrect = false;
if (!empty($this->_apiUrl) && !empty($this->_apiKey)) {
if (false === stripos($this->_apiUrl, 'https://')) {
$this->_apiUrl = str_replace("http://", "https://", $this->_apiUrl);
$this->_resourceConfig->saveConfig('retailcrm/general/api_url', $this->_apiUrl, 'default', 0);
$this->_cacheTypeList->cleanType('config');
}
if (!$this->is_url($this->_apiUrl)){
echo 'URL not valid<br>';
echo 'Please check your Url and Reload page<br>';
$this->_resourceConfig->saveConfig('retailcrm/general/api_url', '', 'default', 0);
$this->_cacheTypeList->cleanType('config');
}
$client = new \Retailcrm\Retailcrm\Model\ApiClient\ApiClient(
$this->_apiUrl,
$this->_apiKey
);
try {
$response = $client->sitesList();
} catch (\Retailcrm\Retailcrm\Model\ApiClient\Exception\CurlException $e) {
$this->_logger->addDebug($e->getMessage());
}
if ($response->isSuccessful()) {
$this->_isCredentialCorrect = true;
if($response['success'] != 1) {
$this->_resourceConfig->saveConfig('retailcrm/general/api_url', '', 'default', 0);
$this->_cacheTypeList->cleanType('config');
}
}
}
}
public function is_url($url) {
return preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $url);
}
}

View File

@ -3,27 +3,27 @@
namespace Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Field; namespace Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Field;
use Magento\Framework\Data\Form\Element\AbstractElement; use Magento\Framework\Data\Form\Element\AbstractElement;
use Retailcrm\Retailcrm\Helper\Proxy as ApiClient;
class Payment extends \Magento\Config\Block\System\Config\Form\Field class Payment extends \Magento\Config\Block\System\Config\Form\Field
{ {
protected $_apiUrl; private $systemStore;
protected $_apiKey; private $formFactory;
protected $_systemStore; private $config;
protected $_formFactory; private $paymentConfig;
protected $_logger; private $client;
public function __construct( public function __construct(
\Magento\Framework\Data\FormFactory $formFactory, \Magento\Framework\Data\FormFactory $formFactory,
\Magento\Store\Model\System\Store $systemStore \Magento\Store\Model\System\Store $systemStore,
\Magento\Framework\App\Config\ScopeConfigInterface $config,
\Magento\Payment\Model\Config $paymentConfig,
\Retailcrm\Retailcrm\Helper\Proxy $client
) { ) {
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $this->systemStore = $systemStore;
$config = $objectManager->get('\Magento\Framework\App\Config\ScopeConfigInterface'); $this->formFactory = $formFactory;
$this->_apiUrl = $config->getValue('retailcrm/general/api_url'); $this->config = $config;
$this->_apiKey = $config->getValue('retailcrm/general/api_key'); $this->paymentConfig = $paymentConfig;
$this->_apiVersion = $config->getValue('retailcrm/general/api_version'); $this->client = $client;
$this->_systemStore = $systemStore;
$this->_formFactory = $formFactory;
} }
public function render(AbstractElement $element) public function render(AbstractElement $element)
@ -31,14 +31,9 @@ class Payment extends \Magento\Config\Block\System\Config\Form\Field
$html = ''; $html = '';
$htmlError = '<div style="margin-left: 15px;"><b><i>Please check your API Url & API Key</i></b></div>'; $htmlError = '<div style="margin-left: 15px;"><b><i>Please check your API Url & API Key</i></b></div>';
if ((!empty($this->_apiUrl)) && (!empty($this->_apiKey))) { if ($this->client->isConfigured()) {
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $activePaymentMethods = $this->paymentConfig->getActiveMethods();
$paymentConfig = $objectManager->get('Magento\Payment\Model\Config'); $response = $this->client->paymentTypesList();
$activePaymentMethods = $paymentConfig->getActiveMethods();
$client = new ApiClient($this->_apiUrl, $this->_apiKey, $this->_apiVersion);
$response = $client->paymentTypesList();
if ($response === false) { if ($response === false) {
return $htmlError; return $htmlError;
@ -50,10 +45,6 @@ class Payment extends \Magento\Config\Block\System\Config\Form\Field
return $htmlError; return $htmlError;
} }
$config = \Magento\Framework\App\ObjectManager::getInstance()->get(
'Magento\Framework\App\Config\ScopeConfigInterface'
);
foreach (array_keys($activePaymentMethods) as $k => $payment) { foreach (array_keys($activePaymentMethods) as $k => $payment) {
$html .= '<table id="' . $element->getId() . '_table">'; $html .= '<table id="' . $element->getId() . '_table">';
$html .= '<tr id="row_retailcrm_payment_'.$payment.'">'; $html .= '<tr id="row_retailcrm_payment_'.$payment.'">';
@ -61,10 +52,10 @@ class Payment extends \Magento\Config\Block\System\Config\Form\Field
$html .= '<td>'; $html .= '<td>';
$html .= '<select id="1" name="groups[Payment][fields][' . $payment . '][value]">'; $html .= '<select id="1" name="groups[Payment][fields][' . $payment . '][value]">';
$selected = $config->getValue('retailcrm/Payment/' . $payment); $selected = $this->config->getValue('retailcrm/Payment/' . $payment);
foreach ($paymentTypes as $k => $value) { foreach ($paymentTypes as $k => $value) {
if ((!empty($selected)) && (($selected == $value['code']))) { if (!empty($selected) && $selected == $value['code']) {
$select = 'selected="selected"'; $select = 'selected="selected"';
} else { } else {
$select = ''; $select = '';

View File

@ -3,29 +3,27 @@
namespace Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Field; namespace Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Field;
use Magento\Framework\Data\Form\Element\AbstractElement; use Magento\Framework\Data\Form\Element\AbstractElement;
use Retailcrm\Retailcrm\Helper\Proxy as ApiClient;
class Shipping extends \Magento\Config\Block\System\Config\Form\Field class Shipping extends \Magento\Config\Block\System\Config\Form\Field
{ {
protected $_apiUrl; private $systemStore;
protected $_apiKey; private $formFactory;
protected $_systemStore; private $config;
protected $_formFactory; private $shippingConfig;
protected $_logger; private $client;
protected $_objectManager;
public function __construct( public function __construct(
\Magento\Framework\Data\FormFactory $formFactory, \Magento\Framework\Data\FormFactory $formFactory,
\Magento\Store\Model\System\Store $systemStore \Magento\Store\Model\System\Store $systemStore,
\Magento\Framework\App\Config\ScopeConfigInterface $config,
\Magento\Shipping\Model\Config $shippingConfig,
\Retailcrm\Retailcrm\Helper\Proxy $client
) { ) {
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $this->systemStore = $systemStore;
$config = $objectManager->get('\Magento\Framework\App\Config\ScopeConfigInterface'); $this->formFactory = $formFactory;
$this->_apiUrl = $config->getValue('retailcrm/general/api_url'); $this->config = $config;
$this->_apiKey = $config->getValue('retailcrm/general/api_key'); $this->shippingConfig = $shippingConfig;
$this->_apiVersion = $config->getValue('retailcrm/general/api_version'); $this->client = $client;
$this->_systemStore = $systemStore;
$this->_formFactory = $formFactory;
$this->_objectManager = $objectManager;
} }
public function render(AbstractElement $element) public function render(AbstractElement $element)
@ -33,13 +31,9 @@ class Shipping extends \Magento\Config\Block\System\Config\Form\Field
$html = ''; $html = '';
$htmlError = '<div style="margin-left: 15px;"><b><i>Please check your API Url & API Key</i></b></div>'; $htmlError = '<div style="margin-left: 15px;"><b><i>Please check your API Url & API Key</i></b></div>';
if (!empty($this->_apiUrl) && !empty($this->_apiKey)) { if ($this->client->isConfigured()) {
$shipConfig = $this->_objectManager->get('Magento\Shipping\Model\Config'); $deliveryMethods = $this->shippingConfig->getActiveCarriers();
$deliveryMethods = $shipConfig->getActiveCarriers(); $response = $this->client->deliveryTypesList();
$client = new ApiClient($this->_apiUrl, $this->_apiKey, $this->_apiVersion);
$response = $client->deliveryTypesList();
if ($response === false) { if ($response === false) {
return $htmlError; return $htmlError;
@ -51,10 +45,6 @@ class Shipping extends \Magento\Config\Block\System\Config\Form\Field
return $htmlError; return $htmlError;
} }
$config = \Magento\Framework\App\ObjectManager::getInstance()->get(
'Magento\Framework\App\Config\ScopeConfigInterface'
);
foreach (array_keys($deliveryMethods) as $k => $delivery) { foreach (array_keys($deliveryMethods) as $k => $delivery) {
$html .= '<table id="' . $element->getId() . '_table">'; $html .= '<table id="' . $element->getId() . '_table">';
$html .= '<tr id="row_retailcrm_shipping_'.$delivery.'">'; $html .= '<tr id="row_retailcrm_shipping_'.$delivery.'">';
@ -62,10 +52,10 @@ class Shipping extends \Magento\Config\Block\System\Config\Form\Field
$html .= '<td>'; $html .= '<td>';
$html .= '<select id="1" name="groups[Shipping][fields]['.$delivery.'][value]">'; $html .= '<select id="1" name="groups[Shipping][fields]['.$delivery.'][value]">';
$selected = $config->getValue('retailcrm/Shipping/'.$delivery); $selected = $this->config->getValue('retailcrm/Shipping/'.$delivery);
foreach ($deliveryTypes as $k => $value) { foreach ($deliveryTypes as $k => $value) {
if ((!empty($selected)) && (($selected == $value['code']))) { if (!empty($selected) && $selected == $value['code']) {
$select = 'selected="selected"'; $select = 'selected="selected"';
} else { } else {
$select = ''; $select = '';

View File

@ -3,29 +3,27 @@
namespace Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Field; namespace Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Field;
use Magento\Framework\Data\Form\Element\AbstractElement; use Magento\Framework\Data\Form\Element\AbstractElement;
use Retailcrm\Retailcrm\Helper\Proxy as ApiClient;
class Status extends \Magento\Config\Block\System\Config\Form\Field class Status extends \Magento\Config\Block\System\Config\Form\Field
{ {
protected $_apiUrl; private $systemStore;
protected $_apiKey; private $formFactory;
protected $_systemStore; private $config;
protected $_formFactory; private $statusCollection;
protected $_logger; private $client;
protected $_objectManager;
public function __construct( public function __construct(
\Magento\Framework\Data\FormFactory $formFactory, \Magento\Framework\Data\FormFactory $formFactory,
\Magento\Store\Model\System\Store $systemStore \Magento\Store\Model\System\Store $systemStore,
\Magento\Framework\App\Config\ScopeConfigInterface $config,
\Magento\Sales\Model\ResourceModel\Order\Status\Collection $statusCollection,
\Retailcrm\Retailcrm\Helper\Proxy $client
) { ) {
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $this->systemStore = $systemStore;
$config = $objectManager->get('\Magento\Framework\App\Config\ScopeConfigInterface'); $this->formFactory = $formFactory;
$this->_apiUrl = $config->getValue('retailcrm/general/api_url'); $this->config = $config;
$this->_apiKey = $config->getValue('retailcrm/general/api_key'); $this->statusCollection = $statusCollection;
$this->_apiVersion = $config->getValue('retailcrm/general/api_version'); $this->client = $client;
$this->_systemStore = $systemStore;
$this->_formFactory = $formFactory;
$this->_objectManager = $objectManager;
} }
public function render(AbstractElement $element) public function render(AbstractElement $element)
@ -33,13 +31,9 @@ class Status extends \Magento\Config\Block\System\Config\Form\Field
$html = ''; $html = '';
$htmlError = '<div style="margin-left: 15px;"><b><i>Please check your API Url & API Key</i></b></div>'; $htmlError = '<div style="margin-left: 15px;"><b><i>Please check your API Url & API Key</i></b></div>';
if ((!empty($this->_apiUrl)) && (!empty($this->_apiKey))) { if ($this->client->isConfigured()) {
$statusCollection = $this->_objectManager->create('Magento\Sales\Model\ResourceModel\Order\Status\Collection'); $statuses = $this->statusCollection->toOptionArray();
$statuses = $statusCollection->toOptionArray(); $response = $this->client->statusesList();
$client = new ApiClient($this->_apiUrl, $this->_apiKey, $this->_apiVersion);
$response = $client->statusesList();
if ($response === false) { if ($response === false) {
return $htmlError; return $htmlError;
@ -51,8 +45,6 @@ class Status extends \Magento\Config\Block\System\Config\Form\Field
return $htmlError; return $htmlError;
} }
$config = $this->_objectManager->get('Magento\Framework\App\Config\ScopeConfigInterface');
foreach ($statuses as $k => $status) { foreach ($statuses as $k => $status) {
$html .= '<table id="' . $element->getId() . '_table">'; $html .= '<table id="' . $element->getId() . '_table">';
$html .= '<tr id="row_retailcrm_status_' . $status['label'] . '">'; $html .= '<tr id="row_retailcrm_status_' . $status['label'] . '">';
@ -60,15 +52,14 @@ class Status extends \Magento\Config\Block\System\Config\Form\Field
$html .= '<td>'; $html .= '<td>';
$html .= '<select name="groups[Status][fields][' . $status['value'] . '][value]">'; $html .= '<select name="groups[Status][fields][' . $status['value'] . '][value]">';
$selected = $config->getValue('retailcrm/Status/' . $status['value']); $selected = $this->config->getValue('retailcrm/Status/' . $status['value']);
$html .= '<option value=""> Select status </option>'; $html .= '<option value=""> Select status </option>';
foreach ($statusTypes as $k => $value) { foreach ($statusTypes as $k => $value) {
if ( if ((!empty($selected)
(!empty($selected)) && $selected == $value['name'])
&& (($selected == $value['name'])) || $selected == $value['code']
|| (($selected == $value['code']))
) { ) {
$select = 'selected="selected"'; $select = 'selected="selected"';
} else { } else {

View File

@ -4,11 +4,6 @@ namespace Retailcrm\Retailcrm\Block;
class Display extends \Magento\Framework\View\Element\Template class Display extends \Magento\Framework\View\Element\Template
{ {
public function __construct(\Magento\Framework\View\Element\Template\Context $context)
{
parent::__construct($context);
}
public function sayHello() public function sayHello()
{ {
return __('Hello World'); return __('Hello World');

View File

@ -7,7 +7,8 @@ class Button extends \Magento\Backend\App\Action
/** /**
* @var \Psr\Log\LoggerInterface * @var \Psr\Log\LoggerInterface
*/ */
protected $_logger; private $logger;
private $order;
/** /**
* @param \Magento\Backend\App\Action\Context $context * @param \Magento\Backend\App\Action\Context $context
@ -15,16 +16,16 @@ class Button extends \Magento\Backend\App\Action
*/ */
public function __construct( public function __construct(
\Magento\Backend\App\Action\Context $context, \Magento\Backend\App\Action\Context $context,
\Psr\Log\LoggerInterface $logger \Psr\Log\LoggerInterface $logger,
\Retailcrm\Retailcrm\Model\Order\OrderNumber $order
) { ) {
$this->_logger = $logger; $this->order = $order;
$this->logger = $logger;
parent::__construct($context); parent::__construct($context);
} }
public function execute() public function execute()
{ {
$order = new \Retailcrm\Retailcrm\Model\Order\OrderNumber(); $this->order->exportOrderNumber();
$order->ExportOrderNumber();
} }
} }

View File

@ -4,18 +4,18 @@ namespace Retailcrm\Retailcrm\Controller\Index;
class Display extends \Magento\Framework\App\Action\Action class Display extends \Magento\Framework\App\Action\Action
{ {
protected $_pageFactory; private $pageFactory;
public function __construct( public function __construct(
\Magento\Framework\App\Action\Context $context, \Magento\Framework\App\Action\Context $context,
\Magento\Framework\View\Result\PageFactory $pageFactory \Magento\Framework\View\Result\PageFactory $pageFactory
) { ) {
$this->_pageFactory = $pageFactory; $this->pageFactory = $pageFactory;
return parent::__construct($context); parent::__construct($context);
} }
public function execute() public function execute()
{ {
return $this->_pageFactory->create(); return $this->pageFactory->create();
} }
} }

View File

@ -1,36 +0,0 @@
<?php
namespace Retailcrm\Retailcrm\Controller\Index;
use Magento\Framework\App\Helper\Context;
use Psr\Log\LoggerInterface;
class Test extends \Magento\Framework\App\Action\Action
{
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);
parent::__construct($context);
}
public function execute()
{
//
exit;
}
}

View File

@ -2,18 +2,21 @@
namespace Retailcrm\Retailcrm\Cron; namespace Retailcrm\Retailcrm\Cron;
class Icml { class Icml
protected $_logger; {
private $logger;
private $icml;
public function __construct() { public function __construct(
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); \Retailcrm\Retailcrm\Model\Logger\Logger $logger,
$logger = new \Retailcrm\Retailcrm\Model\Logger\Logger($objectManager); \Retailcrm\Retailcrm\Model\Icml\Icml $icml
$this->_logger = $logger; ) {
$this->logger = $logger;
$this->icml = $icml;
} }
public function execute() public function execute()
{ {
$Icml = new \Retailcrm\Retailcrm\Model\Icml\Icml(); $this->icml->generate();
$Icml->generate();
} }
} }

View File

@ -4,20 +4,20 @@ namespace Retailcrm\Retailcrm\Cron;
class OrderHistory class OrderHistory
{ {
protected $_logger; private $logger;
private $history;
public function __construct() public function __construct(
{ \Retailcrm\Retailcrm\Model\Logger\Logger $logger,
$om = \Magento\Framework\App\ObjectManager::getInstance(); \Retailcrm\Retailcrm\Model\History\Exchange $history
$logger = new \Retailcrm\Retailcrm\Model\Logger\Logger($om); ) {
$this->_logger = $logger; $this->logger = $logger;
$this->history = $history;
} }
public function execute() public function execute()
{ {
$history = new \Retailcrm\Retailcrm\Model\History\Exchange(); $this->history->ordersHistory();
$history->ordersHistory(); $this->logger->writeRow('Cron Works: OrderHistory');
$this->_logger->writeRow('Cron Works: OrderHistory');
} }
} }

View File

@ -10,12 +10,13 @@ use Magento\Store\Model\ScopeInterface;
class Data extends AbstractHelper class Data extends AbstractHelper
{ {
protected $storeManager; private $storeManager;
protected $objectManager; private $objectManager;
const XML_PATH_RETAILCRM = 'retailcrm/'; const XML_PATH_RETAILCRM = 'retailcrm/';
public function __construct(Context $context, public function __construct(
Context $context,
ObjectManagerInterface $objectManager, ObjectManagerInterface $objectManager,
StoreManagerInterface $storeManager StoreManagerInterface $storeManager
) { ) {
@ -27,7 +28,9 @@ class Data extends AbstractHelper
public function getConfigValue($field, $storeId = null) public function getConfigValue($field, $storeId = null)
{ {
return $this->scopeConfig->getValue( return $this->scopeConfig->getValue(
$field, ScopeInterface::SCOPE_STORE, $storeId $field,
ScopeInterface::SCOPE_STORE,
$storeId
); );
} }
@ -46,16 +49,16 @@ class Data extends AbstractHelper
* *
* @return array * @return array
*/ */
public function filterRecursive($haystack) public static function filterRecursive($haystack)
{ {
foreach ($haystack as $key => $value) { foreach ($haystack as $key => $value) {
if (is_array($value)) { if (is_array($value)) {
$haystack[$key] = self::filterRecursive($haystack[$key]); $haystack[$key] = self::filterRecursive($haystack[$key]);
} }
if (is_null($haystack[$key]) if ($haystack[$key] === null
|| $haystack[$key] === '' || $haystack[$key] === ''
|| count($haystack[$key]) == 0 || (is_array($haystack[$key]) && empty($haystack[$key]))
) { ) {
unset($haystack[$key]); unset($haystack[$key]);
} elseif (!is_array($value)) { } elseif (!is_array($value)) {

View File

@ -2,24 +2,48 @@
namespace Retailcrm\Retailcrm\Helper; namespace Retailcrm\Retailcrm\Helper;
use RetailCrm\ApiClient;
use Magento\Framework\App\ObjectManager;
use Retailcrm\Retailcrm\Model\Logger\Logger; use Retailcrm\Retailcrm\Model\Logger\Logger;
use Retailcrm\Retailcrm\Model\Service\ConfigManager;
use Retailcrm\Retailcrm\ApiClient\ApiClientFactory;
class Proxy class Proxy
{ {
protected $logger; private $logger;
protected $apiClient; private $apiClient;
private $url;
private $apiKey;
private $version;
private $apiClientFactory;
private $errorAccount = 'Account does not exist.'; private $errorAccount = 'Account does not exist.';
private $errorNotFound = 'Not found'; private $errorNotFound = 'Not found';
private $errorApiKey = 'Wrong "apiKey" value.'; private $errorApiKey = 'Wrong "apiKey" value.';
public function __construct ($url, $key, $apiVersion) /**
{ * Proxy constructor.
$objectManager = ObjectManager::getInstance(); * @param string $pathUrl
$this->logger = new Logger($objectManager); * @param string $pathKey
$this->apiClient = new ApiClient($url, $key, $apiVersion); * @param string $pathVersion
* @param ConfigManager $config
* @param Logger $logger
* @param ApiClientFactory $apiClientFactory
*/
public function __construct(
$pathUrl,
$pathKey,
$pathVersion,
ConfigManager $config,
Logger $logger,
ApiClientFactory $apiClientFactory
) {
$this->logger = $logger;
$this->url = $config->getConfigValue($pathUrl);
$this->apiKey = $config->getConfigValue($pathKey);
$this->version = $config->getConfigValue($pathVersion);
$this->apiClientFactory = $apiClientFactory;
if ($this->isConfigured()) {
$this->init();
}
} }
public function __call($method, $arguments) public function __call($method, $arguments)
@ -53,6 +77,50 @@ class Proxy
return $response; return $response;
} }
/**
* Init retailcrm api client
*/
public function init()
{
$this->apiClient = $this->apiClientFactory->create(
$this->url,
$this->apiKey,
$this->version
);
}
/**
* @param $url
*/
public function setUrl($url)
{
$this->url = $url;
}
/**
* @param $apiKey
*/
public function setApiKey($apiKey)
{
$this->apiKey = $apiKey;
}
/**
* @param $version
*/
public function setVersion($version)
{
$this->version = $version;
}
/**
* @return bool
*/
public function isConfigured()
{
return $this->url && $this->apiKey;
}
/** /**
* Get API version * Get API version
* *

View File

File diff suppressed because it is too large Load Diff

View File

@ -1,30 +0,0 @@
<?php
/**
* PHP version 5.3
*
* Class CurlException
*
* @category RetailCrm
* @package RetailCrm
* @author RetailCrm <integration@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
* @link http://www.retailcrm.ru/docs/Developers/ApiVersion4
*/
namespace Retailcrm\Retailcrm\Model\ApiClient\Exception;
/**
* PHP version 5.3
*
* Class CurlException
*
* @category RetailCrm
* @package RetailCrm
* @author RetailCrm <integration@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
* @link http://www.retailcrm.ru/docs/Developers/ApiVersion4
*/
class CurlException extends \RuntimeException
{
}

View File

@ -1,30 +0,0 @@
<?php
/**
* PHP version 5.3
*
* Class InvalidJsonException
*
* @category RetailCrm
* @package RetailCrm
* @author RetailCrm <integration@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
* @link http://www.retailcrm.ru/docs/Developers/ApiVersion4
*/
namespace Retailcrm\Retailcrm\Model\ApiClient\Exception;
/**
* PHP version 5.3
*
* Class InvalidJsonException
*
* @category RetailCrm
* @package RetailCrm
* @author RetailCrm <integration@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
* @link http://www.retailcrm.ru/docs/Developers/ApiVersion4
*/
class InvalidJsonException extends \DomainException
{
}

View File

@ -1,128 +0,0 @@
<?php
/**
* PHP version 5.3
*
* HTTP client
*
* @category RetailCrm
* @package RetailCrm
* @author RetailCrm <integration@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
* @link http://www.retailcrm.ru/docs/Developers/ApiVersion4
*/
namespace Retailcrm\Retailcrm\Model\ApiClient\Http;
use Retailcrm\Retailcrm\Model\ApiClient\Exception\CurlException;
use Retailcrm\Retailcrm\Model\ApiClient\Exception\InvalidJsonException;
use Retailcrm\Retailcrm\Model\ApiClient\Response\ApiResponse;
/**
* PHP version 5.3
*
* HTTP client
*
* @category RetailCrm
* @package RetailCrm
* @author RetailCrm <integration@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
* @link http://www.retailcrm.ru/docs/Developers/ApiVersion4
*/
class Client
{
const METHOD_GET = 'GET';
const METHOD_POST = 'POST';
protected $url;
protected $defaultParameters;
/**
* Client constructor.
*
* @param string $url api url
* @param array $defaultParameters array of parameters
*
* @throws \InvalidArgumentException
*/
public function __construct($url, array $defaultParameters = array())
{
if (false === stripos($url, 'https://')) {
throw new \InvalidArgumentException(
'API schema requires HTTPS protocol'
);
}
$this->url = $url;
$this->defaultParameters = $defaultParameters;
}
/**
* Make HTTP request
*
* @param string $path request url
* @param string $method (default: 'GET')
* @param array $parameters (default: array())
*
* @SuppressWarnings(PHPMD.ExcessiveParameterList)
*
* @throws \InvalidArgumentException
* @throws CurlException
* @throws InvalidJsonException
*
* @return ApiResponse
*/
public function makeRequest(
$path,
$method,
array $parameters = array()
) {
$allowedMethods = array(self::METHOD_GET, self::METHOD_POST);
if (!in_array($method, $allowedMethods, false)) {
throw new \InvalidArgumentException(
sprintf(
'Method "%s" is not valid. Allowed methods are %s',
$method,
implode(', ', $allowedMethods)
)
);
}
$parameters = array_merge($this->defaultParameters, $parameters);
$url = $this->url . $path;
if (self::METHOD_GET === $method && count($parameters)) {
$url .= '?' . http_build_query($parameters, '', '&');
}
$curlHandler = curl_init();
curl_setopt($curlHandler, CURLOPT_URL, $url);
curl_setopt($curlHandler, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curlHandler, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curlHandler, CURLOPT_FAILONERROR, false);
curl_setopt($curlHandler, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curlHandler, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curlHandler, CURLOPT_TIMEOUT, 30);
curl_setopt($curlHandler, CURLOPT_CONNECTTIMEOUT, 30);
if (self::METHOD_POST === $method) {
curl_setopt($curlHandler, CURLOPT_POST, true);
curl_setopt($curlHandler, CURLOPT_POSTFIELDS, $parameters);
}
$responseBody = curl_exec($curlHandler);
$statusCode = curl_getinfo($curlHandler, CURLINFO_HTTP_CODE);
$errno = curl_errno($curlHandler);
$error = curl_error($curlHandler);
curl_close($curlHandler);
if ($errno) {
throw new CurlException($error, $errno);
}
return new ApiResponse($statusCode, $responseBody);
}
}

View File

@ -1,180 +0,0 @@
<?php
/**
* PHP version 5.3
*
* Response from retailCRM API
*
* @category RetailCrm
* @package RetailCrm
* @author RetailCrm <integration@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
* @link http://www.retailcrm.ru/docs/Developers/ApiVersion4
*/
namespace Retailcrm\Retailcrm\Model\ApiClient\Response;
use Retailcrm\Retailcrm\Model\ApiClient\Exception\InvalidJsonException;
/**
* PHP version 5.3
*
* Response from retailCRM API
*
* @category RetailCrm
* @package RetailCrm
* @author RetailCrm <integration@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
* @link http://www.retailcrm.ru/docs/Developers/ApiVersion4
*/
class ApiResponse implements \ArrayAccess
{
// HTTP response status code
protected $statusCode;
// response assoc array
protected $response;
/**
* ApiResponse constructor.
*
* @param int $statusCode HTTP status code
* @param mixed $responseBody HTTP body
*
* @throws InvalidJsonException
*/
public function __construct($statusCode, $responseBody = null)
{
$this->statusCode = (int) $statusCode;
if (!empty($responseBody)) {
$response = json_decode($responseBody, true);
if (!$response && JSON_ERROR_NONE !== ($error = json_last_error())) {
throw new InvalidJsonException(
"Invalid JSON in the API response body. Error code #$error",
$error
);
}
$this->response = $response;
}
}
/**
* Return HTTP response status code
*
* @return int
*/
public function getStatusCode()
{
return $this->statusCode;
}
/**
* HTTP request was successful
*
* @return bool
*/
public function isSuccessful()
{
return $this->statusCode < 400;
}
/**
* Allow to access for the property throw class method
*
* @param string $name method name
* @param mixed $arguments method parameters
*
* @throws \InvalidArgumentException
*
* @return mixed
*/
public function __call($name, $arguments)
{
// convert getSomeProperty to someProperty
$propertyName = strtolower(substr($name, 3, 1)) . substr($name, 4);
if (!isset($this->response[$propertyName])) {
throw new \InvalidArgumentException("Method \"$name\" not found");
}
return $this->response[$propertyName];
}
/**
* Allow to access for the property throw object property
*
* @param string $name property name
*
* @throws \InvalidArgumentException
*
* @return mixed
*/
public function __get($name)
{
if (!isset($this->response[$name])) {
throw new \InvalidArgumentException("Property \"$name\" not found");
}
return $this->response[$name];
}
/**
* Offset set
*
* @param mixed $offset offset
* @param mixed $value value
*
* @throws \BadMethodCallException
* @return void
*/
public function offsetSet($offset, $value)
{
throw new \BadMethodCallException('This activity not allowed');
}
/**
* Offset unset
*
* @param mixed $offset offset
*
* @throws \BadMethodCallException
* @return void
*/
public function offsetUnset($offset)
{
throw new \BadMethodCallException('This call not allowed');
}
/**
* Check offset
*
* @param mixed $offset offset
*
* @return bool
*/
public function offsetExists($offset)
{
return isset($this->response[$offset]);
}
/**
* Get offset
*
* @param mixed $offset offset
*
* @throws \InvalidArgumentException
*
* @return mixed
*/
public function offsetGet($offset)
{
if (!isset($this->response[$offset])) {
throw new \InvalidArgumentException("Property \"$offset\" not found");
}
return $this->response[$offset];
}
}

View File

@ -6,15 +6,17 @@ use Retailcrm\Retailcrm\Helper\Proxy as ApiClient;
class ApiUrl extends \Magento\Framework\App\Config\Value class ApiUrl extends \Magento\Framework\App\Config\Value
{ {
private $api;
/** /**
* ApiUrl constructor.
* @param \Magento\Framework\Model\Context $context * @param \Magento\Framework\Model\Context $context
* @param \Magento\Framework\Registry $registry * @param \Magento\Framework\Registry $registry
* @param \Magento\Framework\App\Config\ScopeConfigInterface $config * @param \Magento\Framework\App\Config\ScopeConfigInterface $config
* @param \Magento\Framework\App\Cache\TypeListInterface $cacheTypeList * @param \Magento\Framework\App\Cache\TypeListInterface $cacheTypeList
* @param \Magento\Framework\App\Config\ValueFactory $configValueFactory * @param \Magento\Framework\Model\ResourceModel\AbstractResource|null $resource
* @param \Magento\Framework\Model\ResourceModel\AbstractResource $resource * @param \Magento\Framework\Data\Collection\AbstractDb|null $resourceCollection
* @param \Magento\Framework\Data\Collection\AbstractDb $resourceCollection * @param ApiClient $api
* @param string $runModelPath
* @param array $data * @param array $data
*/ */
public function __construct( public function __construct(
@ -22,51 +24,45 @@ class ApiUrl extends \Magento\Framework\App\Config\Value
\Magento\Framework\Registry $registry, \Magento\Framework\Registry $registry,
\Magento\Framework\App\Config\ScopeConfigInterface $config, \Magento\Framework\App\Config\ScopeConfigInterface $config,
\Magento\Framework\App\Cache\TypeListInterface $cacheTypeList, \Magento\Framework\App\Cache\TypeListInterface $cacheTypeList,
ApiClient $api,
\Magento\Framework\Model\ResourceModel\AbstractResource $resource = null, \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null,
\Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null, \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null,
array $data = [] array $data = []
) { ) {
$this->api = $api;
parent::__construct($context, $registry, $config, $cacheTypeList, $resource, $resourceCollection, $data); parent::__construct($context, $registry, $config, $cacheTypeList, $resource, $resourceCollection, $data);
} }
/** /**
* Call before save api url * Call before save api url
* *
* @throws \Magento\Framework\Exception\ValidatorException
*
* @return void * @return void
*/ */
public function beforeSave() public function beforeSave()
{ {
$apiUrl = $this->getValue(); $this->setParams([
$apiKey = $this->getFieldsetDataValue('api_key'); 'url' => $this->getValue(),
$apiVersion = $this->getFieldsetDataValue('api_version'); 'apiKey' => $this->getFieldsetDataValue('api_key'),
'version' => $this->getFieldsetDataValue('api_version')
]);
if (!$this->isUrl($apiUrl)) { if (!$this->isUrl($this->getValue())) {
throw new \Magento\Framework\Exception\ValidatorException(__('Invalid CRM url')); throw new \Magento\Framework\Exception\ValidatorException(__('Invalid CRM url'));
} }
if (!$this->isHttps($apiUrl)) { if (!$this->isHttps($this->getValue())) {
$this->schemeEdit($apiUrl); $this->schemeEdit($this->getValue());
} }
$api = new ApiClient($apiUrl, $apiKey, $apiVersion); if ($this->validateApiUrl($this->api)) {
$this->setValue($this->getValue());
if ($this->validateApiUrl($api)) {
$this->setValue($apiUrl);
} }
parent::beforeSave(); parent::beforeSave();
} }
/**
* Call after save api url
*
* @return void
*/
public function afterSave()
{
return parent::afterSave();
}
/** /**
* Validate selected api url * Validate selected api url
* *
@ -77,7 +73,7 @@ class ApiUrl extends \Magento\Framework\App\Config\Value
* *
* @return boolean * @return boolean
*/ */
protected function validateApiUrl(ApiClient $api) private function validateApiUrl(ApiClient $api)
{ {
$response = $api->availableVersions(); $response = $api->availableVersions();
@ -99,7 +95,7 @@ class ApiUrl extends \Magento\Framework\App\Config\Value
* *
* @return boolean * @return boolean
*/ */
protected function isHttps($url) private function isHttps($url)
{ {
$url_array = parse_url($url); $url_array = parse_url($url);
@ -117,7 +113,7 @@ class ApiUrl extends \Magento\Framework\App\Config\Value
* *
* @return string * @return string
*/ */
protected function schemeEdit(&$url) private function schemeEdit(&$url)
{ {
$url_array = parse_url($url); $url_array = parse_url($url);
@ -135,4 +131,15 @@ class ApiUrl extends \Magento\Framework\App\Config\Value
{ {
return preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $url); return preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $url);
} }
/**
* @param array $data
*/
private function setParams(array $data)
{
$this->api->setUrl($data['url']);
$this->api->setApiKey($data['apiKey']);
$this->api->setVersion($data['version']);
$this->api->init();
}
} }

View File

@ -6,15 +6,17 @@ use Retailcrm\Retailcrm\Helper\Proxy as ApiClient;
class ApiVersion extends \Magento\Framework\App\Config\Value class ApiVersion extends \Magento\Framework\App\Config\Value
{ {
private $api;
/** /**
* ApiVersion constructor.
* @param \Magento\Framework\Model\Context $context * @param \Magento\Framework\Model\Context $context
* @param \Magento\Framework\Registry $registry * @param \Magento\Framework\Registry $registry
* @param \Magento\Framework\App\Config\ScopeConfigInterface $config * @param \Magento\Framework\App\Config\ScopeConfigInterface $config
* @param \Magento\Framework\App\Cache\TypeListInterface $cacheTypeList * @param \Magento\Framework\App\Cache\TypeListInterface $cacheTypeList
* @param \Magento\Framework\App\Config\ValueFactory $configValueFactory * @param \Magento\Framework\Model\ResourceModel\AbstractResource|null $resource
* @param \Magento\Framework\Model\ResourceModel\AbstractResource $resource * @param \Magento\Framework\Data\Collection\AbstractDb|null $resourceCollection
* @param \Magento\Framework\Data\Collection\AbstractDb $resourceCollection * @param ApiClient $api
* @param string $runModelPath
* @param array $data * @param array $data
*/ */
public function __construct( public function __construct(
@ -22,10 +24,12 @@ class ApiVersion extends \Magento\Framework\App\Config\Value
\Magento\Framework\Registry $registry, \Magento\Framework\Registry $registry,
\Magento\Framework\App\Config\ScopeConfigInterface $config, \Magento\Framework\App\Config\ScopeConfigInterface $config,
\Magento\Framework\App\Cache\TypeListInterface $cacheTypeList, \Magento\Framework\App\Cache\TypeListInterface $cacheTypeList,
ApiClient $api,
\Magento\Framework\Model\ResourceModel\AbstractResource $resource = null, \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null,
\Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null, \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null,
array $data = [] array $data = []
) { ) {
$this->api = $api;
parent::__construct($context, $registry, $config, $cacheTypeList, $resource, $resourceCollection, $data); parent::__construct($context, $registry, $config, $cacheTypeList, $resource, $resourceCollection, $data);
} }
@ -36,27 +40,17 @@ class ApiVersion extends \Magento\Framework\App\Config\Value
*/ */
public function beforeSave() public function beforeSave()
{ {
$apiUrl = $this->getFieldsetDataValue('api_url'); $this->setParams([
$apiKey = $this->getFieldsetDataValue('api_key'); 'url' => $this->getFieldsetDataValue('api_url'),
$apiVersion = $this->getValue(); 'apiKey' => $this->getFieldsetDataValue('api_key'),
'version' => $this->getValue()
]);
$api = new ApiClient($apiUrl, $apiKey, $apiVersion); $this->validateApiVersion($this->api, $this->getValue());
$this->validateApiVersion($api, $apiVersion);
parent::beforeSave(); parent::beforeSave();
} }
/**
* Call after save api version
*
* @return void
*/
public function afterSave()
{
return parent::afterSave();
}
/** /**
* Validate selected api version * Validate selected api version
* *
@ -67,7 +61,7 @@ class ApiVersion extends \Magento\Framework\App\Config\Value
* *
* @return void * @return void
*/ */
protected function validateApiVersion(ApiClient $api, $apiVersion) private function validateApiVersion(ApiClient $api, $apiVersion)
{ {
$apiVersions = [ $apiVersions = [
'v4' => '4.0', 'v4' => '4.0',
@ -90,4 +84,15 @@ class ApiVersion extends \Magento\Framework\App\Config\Value
} }
} }
} }
/**
* @param array $data
*/
private function setParams(array $data)
{
$this->api->setUrl($data['url']);
$this->api->setApiKey($data['apiKey']);
$this->api->setVersion($data['version']);
$this->api->init();
}
} }

View File

@ -2,77 +2,71 @@
namespace Retailcrm\Retailcrm\Model\History; namespace Retailcrm\Retailcrm\Model\History;
use Retailcrm\Retailcrm\Helper\Proxy as ApiClient;
class Exchange class Exchange
{ {
protected $_api; private $api;
protected $_config; private $config;
protected $_helper; private $helper;
protected $_logger; private $logger;
protected $_resourceConfig; private $resourceConfig;
protected $_customerFactory; private $customerFactory;
protected $_quote; private $quote;
protected $_customerRepository; private $customerRepository;
protected $_product; private $product;
protected $_shipconfig; private $shipconfig;
protected $_quoteManagement; private $quoteManagement;
protected $_registry; private $registry;
protected $_cacheTypeList; private $cacheTypeList;
protected $_order; private $order;
protected $_orderManagement; private $orderManagement;
//protected $_transaction; private $eventManager;
//protected $_invoiceService; private $objectManager;
protected $_eventManager; private $orderInterface;
protected $_objectManager; private $storeManager;
private $regionFactory;
public function __construct() public function __construct(
{ \Magento\Framework\App\ObjectManager $objectManager,
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); \Retailcrm\Retailcrm\Helper\Data $helper,
$helper = $objectManager->get('\Retailcrm\Retailcrm\Helper\Data'); \Magento\Framework\App\Config\ScopeConfigInterface $config,
$config = $objectManager->get('\Magento\Framework\App\Config\ScopeConfigInterface'); \Magento\Config\Model\ResourceModel\Config $resourceConfig,
$resourceConfig = $objectManager->get('Magento\Config\Model\ResourceModel\Config'); \Magento\Customer\Model\CustomerFactory $customerFactory,
$customerFactory = $objectManager->get('\Magento\Customer\Model\CustomerFactory'); \Magento\Quote\Model\QuoteFactory $quote,
$quote = $objectManager->get('\Magento\Quote\Model\QuoteFactory'); \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository,
$customerRepository = $objectManager->get('\Magento\Customer\Api\CustomerRepositoryInterface'); \Magento\Catalog\Model\Product $product,
$product = $objectManager->get('\Magento\Catalog\Model\Product'); \Magento\Shipping\Model\Config $shipconfig,
$shipconfig = $objectManager->get('\Magento\Shipping\Model\Config'); \Magento\Quote\Model\QuoteManagement $quoteManagement,
$quoteManagement = $objectManager->get('\Magento\Quote\Model\QuoteManagement'); \Magento\Framework\Registry $registry,
$registry = $objectManager->get('\Magento\Framework\Registry'); \Magento\Framework\App\Cache\TypeListInterface $cacheTypeList,
$cacheTypeList = $objectManager->get('\Magento\Framework\App\Cache\TypeListInterface'); \Magento\Sales\Api\Data\OrderInterface $orderInterface,
$order = $objectManager->get('\Magento\Sales\Api\Data\OrderInterface'); \Magento\Sales\Api\OrderManagementInterface $orderManagement,
$orderManagement = $objectManager->get('\Magento\Sales\Api\OrderManagementInterface'); \Magento\Framework\Event\Manager $eventManager,
//$invoiceService = $objectManager->get('\Magento\Sales\Model\Service\InvoiceService'); \Retailcrm\Retailcrm\Model\Logger\Logger $logger,
//$transaction = $objectManager->get('\Magento\Framework\DB\Transaction'); \Magento\Sales\Model\Order $order,
$eventManager = $objectManager->get('\Magento\Framework\Event\Manager'); \Magento\Store\Model\StoreManagerInterface $storeManager,
$logger = new \Retailcrm\Retailcrm\Model\Logger\Logger($objectManager); \Magento\Directory\Model\RegionFactory $regionFactory,
\Retailcrm\Retailcrm\Helper\Proxy $api
$this->_shipconfig = $shipconfig; ) {
$this->_logger = $logger; $this->shipconfig = $shipconfig;
$this->_helper = $helper; $this->logger = $logger;
$this->_config = $config; $this->helper = $helper;
$this->_resourceConfig = $resourceConfig; $this->config = $config;
$this->_customerFactory = $customerFactory; $this->resourceConfig = $resourceConfig;
$this->_quote = $quote; $this->customerFactory = $customerFactory;
$this->_customerRepository = $customerRepository; $this->quote = $quote;
$this->_product = $product; $this->customerRepository = $customerRepository;
$this->_quoteManagement = $quoteManagement; $this->product = $product;
$this->_registry = $registry; $this->quoteManagement = $quoteManagement;
$this->_cacheTypeList = $cacheTypeList; $this->registry = $registry;
$this->_order = $order; $this->cacheTypeList = $cacheTypeList;
$this->_orderManagement = $orderManagement; $this->orderInterface = $orderInterface;
//$this->_transaction = $transaction; $this->orderManagement = $orderManagement;
//$this->_invoiceService = $invoiceService; $this->eventManager = $eventManager;
$this->_eventManager = $eventManager; $this->objectManager = $objectManager;
$this->_objectManager = $objectManager; $this->order = $order;
$this->storeManager = $storeManager;
$url = $config->getValue('retailcrm/general/api_url'); $this->regionFactory = $regionFactory;
$key = $config->getValue('retailcrm/general/api_key'); $this->api = $api;
$version = $config->getValue('retailcrm/general/api_version');
if (!empty($url) && !empty($key)) {
$this->_api = new ApiClient($url, $key, $version);
}
} }
/** /**
@ -82,22 +76,26 @@ class Exchange
*/ */
public function ordersHistory() public function ordersHistory()
{ {
$this->_registry->register('RETAILCRM_HISTORY', true); if (!$this->api->isConfigured()) {
return false;
}
$this->registry->register('RETAILCRM_HISTORY', true);
$historyFilter = []; $historyFilter = [];
$historyOrder = []; $historyOrder = [];
$historyStart = $this->_config->getValue('retailcrm/general/filter_history'); $historyStart = $this->config->getValue('retailcrm/general/filter_history');
if ($historyStart && $historyStart > 0) { if ($historyStart && $historyStart > 0) {
$historyFilter['sinceId'] = $historyStart; $historyFilter['sinceId'] = $historyStart;
} }
while (true) { while (true) {
$response = $this->_api->ordersHistory($historyFilter); $response = $this->api->ordersHistory($historyFilter);
if ($response === false) { if ($response === false) {
return; return false;
} }
if (!$response->isSuccessful()) { if (!$response->isSuccessful()) {
@ -106,7 +104,7 @@ class Exchange
$orderH = isset($response['history']) ? $response['history'] : []; $orderH = isset($response['history']) ? $response['history'] : [];
if (count($orderH) == 0) { if (empty($orderH)) {
return true; return true;
} }
@ -115,20 +113,25 @@ class Exchange
$historyFilter['sinceId'] = $end['id']; $historyFilter['sinceId'] = $end['id'];
if ($response['pagination']['totalPageCount'] == 1) { if ($response['pagination']['totalPageCount'] == 1) {
$this->_resourceConfig->saveConfig('retailcrm/general/filter_history', $historyFilter['sinceId'], 'default', 0); $this->resourceConfig->saveConfig(
$this->_cacheTypeList->cleanType('config'); 'retailcrm/general/filter_history',
$historyFilter['sinceId'],
'default',
0
);
$this->cacheTypeList->cleanType('config');
$orders = self::assemblyOrder($historyOrder); $orders = self::assemblyOrder($historyOrder);
$this->_logger->writeDump($orders,'OrderHistory'); $this->logger->writeDump($orders, 'OrderHistory');
$this->processOrders($orders); $this->processOrders($orders);
return true; return true;
} }
}//endwhile }
$this->_registry->register('RETAILCRM_HISTORY', false); $this->registry->register('RETAILCRM_HISTORY', false);
} }
/** /**
@ -140,7 +143,7 @@ class Exchange
*/ */
private function processOrders($orders) private function processOrders($orders)
{ {
$this->_logger->writeDump($orders,'processOrders'); $this->logger->writeDump($orders, 'processOrders');
if (!empty($orders)) { if (!empty($orders)) {
foreach ($orders as $order) { foreach ($orders as $order) {
@ -162,17 +165,16 @@ class Exchange
*/ */
private function doCreate($order) private function doCreate($order)
{ {
$this->_logger->writeDump($order,'doCreate'); $this->logger->writeDump($order, 'doCreate');
$payments = $this->_config->getValue('retailcrm/Payment'); $payments = $this->config->getValue('retailcrm/Payment');
$shippings = $this->_config->getValue('retailcrm/Shipping'); $shippings = $this->config->getValue('retailcrm/Shipping');
$manager = $this->_objectManager->get('Magento\Store\Model\StoreManagerInterface'); $region = $this->regionFactory->create();
$region = $this->_objectManager->get('Magento\Directory\Model\RegionFactory')->create(); $store = $this->storeManager->getStore();
$store = $manager->getStore(); $websiteId = $this->storeManager->getStore()->getWebsiteId();
$websiteId = $manager->getStore()->getWebsiteId();
$customer = $this->_customerFactory->create(); $customer = $this->customerFactory->create();
$customer->setWebsiteId($websiteId); $customer->setWebsiteId($websiteId);
if (isset($order['customer']['externalId'])) { if (isset($order['customer']['externalId'])) {
@ -190,10 +192,10 @@ class Exchange
try { try {
$customer->save(); $customer->save();
} catch (\Exception $exception) { } catch (\Exception $exception) {
$this->_logger->writeRow($exception->getMessage()); $this->logger->writeRow($exception->getMessage());
} }
$this->_api->customersFixExternalIds( $this->api->customersFixExternalIds(
[ [
[ [
'id' => $order['customer']['id'], 'id' => $order['customer']['id'],
@ -204,23 +206,23 @@ class Exchange
} }
//Create object of quote //Create object of quote
$quote = $this->_quote->create(); $quote = $this->quote->create();
//set store for which you create quote //set store for which you create quote
$quote->setStore($store); $quote->setStore($store);
// if you have allready buyer id then you can load customer directly // if you have allready buyer id then you can load customer directly
$customer = $this->_customerRepository->getById($customer->getId()); $customer = $this->customerRepository->getById($customer->getId());
$quote->setCurrency(); $quote->setCurrency();
$quote->assignCustomer($customer); //Assign quote to customer $quote->assignCustomer($customer); //Assign quote to customer
//add items in quote //add items in quote
foreach ($order['items'] as $item) { foreach ($order['items'] as $item) {
$product = $this->_product->load($item['offer']['externalId']); $product = $this->product->load($item['offer']['externalId']);
$product->setPrice($item['initialPrice']); $product->setPrice($item['initialPrice']);
$quote->addProduct( $quote->addProduct(
$product, $product,
intval($item['quantity']) (int)$item['quantity']
); );
} }
@ -231,7 +233,7 @@ class Exchange
} }
$orderData = [ $orderData = [
'currency_id' => $manager->getStore()->getCurrentCurrency()->getCode(), 'currency_id' => $this->storeManager->getStore()->getCurrentCurrency()->getCode(),
'email' => $order['email'], 'email' => $order['email'],
'shipping_address' => [ 'shipping_address' => [
'firstname' => $order['firstName'], 'firstname' => $order['firstName'],
@ -267,9 +269,9 @@ class Exchange
->collectShippingRates() ->collectShippingRates()
->setShippingMethod($ShippingMethods); ->setShippingMethod($ShippingMethods);
if ($this->_api->getVersion() == 'v4') { if ($this->api->getVersion() == 'v4') {
$paymentType = $order['paymentType']; $paymentType = $order['paymentType'];
} elseif ($this->_api->getVersion() == 'v5') { } elseif ($this->api->getVersion() == 'v5') {
if ($order['payments']) { if ($order['payments']) {
$paymentType = $this->getPaymentMethod($order['payments']); $paymentType = $this->getPaymentMethod($order['payments']);
} }
@ -287,11 +289,11 @@ class Exchange
$quote->collectTotals()->save(); $quote->collectTotals()->save();
// Create Order From Quote // Create Order From Quote
$magentoOrder = $this->_quoteManagement->submit($quote); $magentoOrder = $this->quoteManagement->submit($quote);
$increment_id = $magentoOrder->getId(); $increment_id = $magentoOrder->getId();
$this->_api->ordersFixExternalIds( $this->api->ordersFixExternalIds(
[ [
[ [
'id' => $order['id'], 'id' => $order['id'],
@ -310,9 +312,9 @@ class Exchange
*/ */
private function doCreateUp($order) private function doCreateUp($order)
{ {
$this->_logger->writeDump($order,'doCreateUp'); $this->logger->writeDump($order, 'doCreateUp');
$response = $this->_api->ordersGet($order['id'], $by = 'id'); $response = $this->api->ordersGet($order['id'], $by = 'id');
if (!$response->isSuccessful()) { if (!$response->isSuccessful()) {
return; return;
@ -322,15 +324,14 @@ class Exchange
$order = $response['order']; $order = $response['order'];
} }
$payments = $this->_config->getValue('retailcrm/Payment'); $payments = $this->config->getValue('retailcrm/Payment');
$shippings = $this->_config->getValue('retailcrm/Shipping'); $shippings = $this->config->getValue('retailcrm/Shipping');
$manager = $this->_objectManager->get('Magento\Store\Model\StoreManagerInterface'); $region = $this->regionFactory->create();
$region = $this->_objectManager->get('Magento\Directory\Model\RegionFactory')->create(); $store = $this->storeManager->getStore();
$store = $manager->getStore(); $websiteId = $this->storeManager->getStore()->getWebsiteId();
$websiteId = $manager->getStore()->getWebsiteId();
$customer = $this->_customerFactory->create(); $customer = $this->customerFactory->create();
$customer->setWebsiteId($websiteId); $customer->setWebsiteId($websiteId);
if (isset($order['customer']['externalId'])) { if (isset($order['customer']['externalId'])) {
@ -338,7 +339,7 @@ class Exchange
} }
//Create object of quote //Create object of quote
$quote = $this->_quote->create(); $quote = $this->quote->create();
//set store for which you create quote //set store for which you create quote
$quote->setStore($store); $quote->setStore($store);
@ -346,7 +347,7 @@ class Exchange
// if you have allready buyer id then you can load customer directly // if you have allready buyer id then you can load customer directly
if ($customer->getId()) { if ($customer->getId()) {
$customer = $this->_customerRepository->getById($customer->getId()); $customer = $this->customerRepository->getById($customer->getId());
$quote->assignCustomer($customer); //Assign quote to customer $quote->assignCustomer($customer); //Assign quote to customer
} else { } else {
$quote->setCustomerEmail($order['email']); $quote->setCustomerEmail($order['email']);
@ -355,11 +356,11 @@ class Exchange
//add items in quote //add items in quote
foreach ($order['items'] as $item) { foreach ($order['items'] as $item) {
$product = $this->_product->load($item['offer']['externalId']); $product = $this->product->load($item['offer']['externalId']);
$product->setPrice($item['initialPrice']); $product->setPrice($item['initialPrice']);
$quote->addProduct( $quote->addProduct(
$product, $product,
intval($item['quantity']) (int)$item['quantity']
); );
} }
@ -370,9 +371,9 @@ class Exchange
} }
$orderData = [ $orderData = [
'currency_id' => $manager->getStore()->getCurrentCurrency()->getCode(), 'currency_id' => $this->storeManager->getStore()->getCurrentCurrency()->getCode(),
'email' => $order['email'], 'email' => $order['email'],
'shipping_address' =>array( 'shipping_address' => [
'firstname' => $order['firstName'], 'firstname' => $order['firstName'],
'lastname' => $order['lastName'], 'lastname' => $order['lastName'],
'street' => $order['delivery']['address']['street'], 'street' => $order['delivery']['address']['street'],
@ -382,7 +383,7 @@ class Exchange
'postcode' => $order['delivery']['address']['index'], 'postcode' => $order['delivery']['address']['index'],
'telephone' => $order['phone'], 'telephone' => $order['phone'],
'save_in_address_book' => 1 'save_in_address_book' => 1
), ],
'items'=> $products 'items'=> $products
]; ];
@ -406,18 +407,17 @@ class Exchange
->collectShippingRates() ->collectShippingRates()
->setShippingMethod($ShippingMethods); ->setShippingMethod($ShippingMethods);
if ($this->_api->getVersion() == 'v4') { if ($this->api->getVersion() == 'v4') {
$paymentType = $order['paymentType']; $paymentType = $order['paymentType'];
} elseif ($this->_api->getVersion() == 'v5') { } elseif ($this->api->getVersion() == 'v5') {
$paymentType = $this->getPaymentMethod($order['payments'], false); $paymentType = $this->getPaymentMethod($order['payments'], false);
} }
$quote->setPaymentMethod($payments[$paymentType]); $quote->setPaymentMethod($payments[$paymentType]);
$quote->setInventoryProcessed(false); $quote->setInventoryProcessed(false);
$originalId = $order['externalId']; $originalId = $order['externalId'];
$oldOrder = $this->_order->load($originalId); $oldOrder = $this->orderInterface->load($originalId);
$orderDataUp = [ $orderDataUp = [
'original_increment_id' => $oldOrder->getIncrementId(), 'original_increment_id' => $oldOrder->getIncrementId(),
@ -437,11 +437,11 @@ class Exchange
$quote->collectTotals()->save(); $quote->collectTotals()->save();
// Create Order From Quote // Create Order From Quote
$magentoOrder = $this->_quoteManagement->submit($quote,$orderDataUp); $magentoOrder = $this->quoteManagement->submit($quote, $orderDataUp);
$oldOrder->setStatus('canceled')->save(); $oldOrder->setStatus('canceled')->save();
$increment_id = $magentoOrder->getId(); $increment_id = $magentoOrder->getId();
$this->_api->ordersFixExternalIds( $this->api->ordersFixExternalIds(
[ [
[ [
'id' => $order['id'], 'id' => $order['id'],
@ -460,16 +460,16 @@ class Exchange
*/ */
private function doUpdate($order) private function doUpdate($order)
{ {
$this->_logger->writeDump($order,'doUpdate'); $this->logger->writeDump($order, 'doUpdate');
$Status = $this->_config->getValue('retailcrm/Status'); $Status = $this->config->getValue('retailcrm/Status');
$Status = array_flip(array_filter($Status)); $Status = array_flip(array_filter($Status));
$magentoOrder = $this->_order->load($order['externalId']); $magentoOrder = $this->order->load($order['externalId']);
$magentoOrderArr = $magentoOrder->getData(); $magentoOrderArr = $magentoOrder->getData();
$this->_logger->writeDump($magentoOrderArr, 'magentoOrderArr'); $this->logger->writeDump($magentoOrderArr, 'magentoOrderArr');
$this->_logger->writeDump($Status, 'status'); $this->logger->writeDump($Status, 'status');
if ((!empty($order['order_edit'])) && ($order['order_edit'] == 1)) { if ((!empty($order['order_edit'])) && ($order['order_edit'] == 1)) {
$this->doCreateUp($order); $this->doCreateUp($order);
@ -479,80 +479,13 @@ class Exchange
$change = $Status[$order['status']]; $change = $Status[$order['status']];
if ($change == 'canceled') { if ($change == 'canceled') {
$this->_orderManagement->cancel($magentoOrderArr['entity_id']); $this->orderManagement->cancel($magentoOrderArr['entity_id']);
} }
if($change == 'holded'){ $order_status = $this->order->load($magentoOrder->getId());
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $order_status->setStatus($change);
$order_status = $objectManager->get('Magento\Sales\Model\Order')->load($magentoOrder->getId());
$order_status->setStatus('holded');
$order_status->save(); $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();
}
}
} }
/** /**
@ -567,6 +500,7 @@ class Exchange
$orders = []; $orders = [];
foreach ($orderHistory as $change) { foreach ($orderHistory as $change) {
$orderId = $change['order']['id'];
$change['order'] = self::removeEmpty($change['order']); $change['order'] = self::removeEmpty($change['order']);
if (isset($change['order']['items'])) { if (isset($change['order']['items'])) {
@ -612,7 +546,10 @@ class Exchange
if (isset($orders[$change['order']['id']]['items']) if (isset($orders[$change['order']['id']]['items'])
&& $orders[$change['order']['id']]['items'][$change['item']['id']] && $orders[$change['order']['id']]['items'][$change['item']['id']]
) { ) {
$orders[$change['order']['id']]['items'][$change['item']['id']] = array_merge($orders[$change['order']['id']]['items'][$change['item']['id']], $change['item']); $orders[$change['order']['id']]['items'][$change['item']['id']] = array_merge(
$orders[$change['order']['id']]['items'][$change['item']['id']],
$change['item']
);
} else { } else {
$orders[$change['order']['id']]['items'][$change['item']['id']] = $change['item']; $orders[$change['order']['id']]['items'][$change['item']['id']] = $change['item'];
} }
@ -631,33 +568,41 @@ class Exchange
if (!empty($change['newValue']) && $change['field'] == 'order_product.quantity') { if (!empty($change['newValue']) && $change['field'] == 'order_product.quantity') {
$orders[$change['order']['id']]['order_edit'] = 1; $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 { } else {
if ((isset($fields['delivery'][$change['field']]))&&($fields['delivery'][$change['field']] == 'service')) { if (isset($fields['delivery'][$change['field']])
$orders[$change['order']['id']]['delivery']['service']['code'] = self::newValue($change['newValue']); && $fields['delivery'][$change['field']] == 'service'
) {
$orders[$orderId]['delivery']['service']['code'] = self::newValue($change['newValue']);
} elseif (isset($fields['delivery'][$change['field']])) { } elseif (isset($fields['delivery'][$change['field']])) {
$orders[$change['order']['id']]['delivery'][$fields['delivery'][$change['field']]] = self::newValue($change['newValue']); $field = $fields['delivery'][$change['field']];
$orders[$orderId]['delivery'][$field] = self::newValue($change['newValue']);
unset($field);
} elseif (isset($fields['orderAddress'][$change['field']])) { } elseif (isset($fields['orderAddress'][$change['field']])) {
$orders[$change['order']['id']]['delivery']['address'][$fields['orderAddress'][$change['field']]] = $change['newValue']; $field = $fields['orderAddress'][$change['field']];
$orders[$orderId]['delivery']['address'][$field] = self::newValue($change['newValue']);
unset($field);
} elseif (isset($fields['integrationDelivery'][$change['field']])) { } elseif (isset($fields['integrationDelivery'][$change['field']])) {
$orders[$change['order']['id']]['delivery']['service'][$fields['integrationDelivery'][$change['field']]] = self::newValue($change['newValue']); $field = $fields['integrationDelivery'][$change['field']];
$orders[$orderId]['delivery']['service'][$field] = self::newValue($change['newValue']);
unset($field);
} elseif (isset($fields['customerContragent'][$change['field']])) { } elseif (isset($fields['customerContragent'][$change['field']])) {
$orders[$change['order']['id']][$fields['customerContragent'][$change['field']]] = self::newValue($change['newValue']); $field = $fields['customerContragent'][$change['field']];
$orders[$orderId][$field] = self::newValue($change['newValue']);
unset($field);
} elseif (strripos($change['field'], 'custom_') !== false) { } elseif (strripos($change['field'], 'custom_') !== false) {
$orders[$change['order']['id']]['customFields'][str_replace('custom_', '', $change['field'])] = self::newValue($change['newValue']); $field = str_replace('custom_', '', $change['field']);
$orders[$orderId]['customFields'][$field] = self::newValue($change['newValue']);
unset($field);
} elseif (isset($fields['order'][$change['field']])) { } elseif (isset($fields['order'][$change['field']])) {
$orders[$change['order']['id']][$fields['order'][$change['field']]] = self::newValue($change['newValue']); $orders[$orderId][$fields['order'][$change['field']]] = self::newValue($change['newValue']);
} }
if (isset($change['created'])) { if (isset($change['created'])) {
$orders[$change['order']['id']]['create'] = 1; $orders[$orderId]['create'] = 1;
} }
if (isset($change['deleted'])) { if (isset($change['deleted'])) {
$orders[$change['order']['id']]['deleted'] = 1; $orders[$orderId]['deleted'] = 1;
} }
} }
} }
@ -716,7 +661,7 @@ class Exchange
*/ */
public function getAllShippingMethodsCode($mcode) public function getAllShippingMethodsCode($mcode)
{ {
$activeCarriers = $this->_shipconfig->getActiveCarriers(); $activeCarriers = $this->shipconfig->getActiveCarriers();
$storeScope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE; $storeScope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE;
foreach ($activeCarriers as $carrierCode => $carrierModel) { foreach ($activeCarriers as $carrierCode => $carrierModel) {
@ -744,7 +689,7 @@ class Exchange
* *
* @return mixed * @return mixed
*/ */
protected function getPaymentMethod($payments, $newOrder = true) private function getPaymentMethod($payments, $newOrder = true)
{ {
if (count($payments) == 1 || $newOrder) { if (count($payments) == 1 || $newOrder) {
$payment = reset($payments); $payment = reset($payments);

View File

@ -4,88 +4,101 @@ namespace Retailcrm\Retailcrm\Model\Icml;
class Icml class Icml
{ {
protected $_dd; private $dd;
protected $_eCategories; private $eCategories;
protected $_eOffers; private $eOffers;
protected $_shop; private $shop;
protected $_manager; private $manager;
protected $_category; private $category;
protected $_product; private $product;
protected $_storeManager; private $storeManager;
protected $_StockState; private $StockState;
protected $_configurable; private $configurable;
protected $_config; private $config;
private $dirList;
private $ddFactory;
public function __construct() public function __construct(
{ \Magento\Store\Model\StoreManagerInterface $manager,
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $categoryCollectionFactory,
$manager = $objectManager->get('Magento\Store\Model\StoreManagerInterface'); \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $product,
$categoryCollectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Category\CollectionFactory'); \Magento\Store\Model\StoreManagerInterface $storeManager,
$product = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory'); \Magento\CatalogInventory\Api\StockStateInterface $StockState,
$storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface'); \Magento\ConfigurableProduct\Model\Product\Type\Configurable $configurable,
$StockState = $objectManager->get('\Magento\CatalogInventory\Api\StockStateInterface'); \Magento\Framework\App\Config\ScopeConfigInterface $config,
$configurable = $objectManager->get('Magento\ConfigurableProduct\Model\Product\Type\Configurable'); \Magento\Framework\DomDocument\DomDocumentFactory $ddFactory,
$config = $objectManager->get('\Magento\Framework\App\Config\ScopeConfigInterface'); \Magento\Framework\Filesystem\DirectoryList $dirList
) {
$this->_configurable = $configurable; $this->configurable = $configurable;
$this->_StockState = $StockState; $this->StockState = $StockState;
$this->_storeManager = $storeManager; $this->storeManager = $storeManager;
$this->_product = $product; $this->product = $product;
$this->_category = $categoryCollectionFactory; $this->category = $categoryCollectionFactory;
$this->_manager = $manager; $this->manager = $manager;
$this->_config = $config; $this->config = $config;
$this->ddFactory = $ddFactory;
$this->dirList = $dirList;
} }
/**
* Generate icml catelog
*
* @return void
*/
public function generate() public function generate()
{ {
$this->_shop = $this->_manager->getStore()->getId(); $this->shop = $this->manager->getStore()->getId();
$string = '<?xml version="1.0" encoding="UTF-8"?> $string = '<?xml version="1.0" encoding="UTF-8"?>
<yml_catalog date="'.date('Y-m-d H:i:s').'"> <yml_catalog date="'.date('Y-m-d H:i:s').'">
<shop> <shop>
<name>'.$this->_manager->getStore()->getName().'</name> <name>'.$this->manager->getStore()->getName().'</name>
<categories/> <categories/>
<offers/> <offers/>
</shop> </shop>
</yml_catalog> </yml_catalog>
'; ';
$xml = new \SimpleXMLElement( $xml = simplexml_load_string(
$string, $string,
'\Magento\Framework\Simplexml\Element',
LIBXML_NOENT | LIBXML_NOCDATA | LIBXML_COMPACT | LIBXML_PARSEHUGE LIBXML_NOENT | LIBXML_NOCDATA | LIBXML_COMPACT | LIBXML_PARSEHUGE
); );
$this->_dd = new \DOMDocument(); $this->dd = $this->ddFactory->create();
$this->_dd->preserveWhiteSpace = false; $this->dd->preserveWhiteSpace = false;
$this->_dd->formatOutput = true; $this->dd->formatOutput = true;
$this->_dd->loadXML($xml->asXML()); $this->dd->loadXML($xml->asXML());
$this->_eCategories = $this->_dd-> $this->eCategories = $this->dd
getElementsByTagName('categories')->item(0); ->getElementsByTagName('categories')->item(0);
$this->_eOffers = $this->_dd $this->eOffers = $this->dd
->getElementsByTagName('offers')->item(0); ->getElementsByTagName('offers')->item(0);
$this->addCategories(); $this->addCategories();
$this->addOffers(); $this->addOffers();
$this->_dd->saveXML(); $this->dd->saveXML();
$dirlist = new \Magento\Framework\Filesystem\DirectoryList(''); $shopCode = $this->manager->getStore()->getCode();
$baseDir = $dirlist->getRoot(); $this->dd->save($this->dirList->getRoot() . '/retailcrm_' . $shopCode . '.xml');
$shopCode = $this->_manager->getStore()->getCode();
$this->_dd->save($baseDir . 'retailcrm_' . $shopCode . '.xml');
} }
/**
* Add product categories in icml catalog
*
* @return void
*/
private function addCategories() private function addCategories()
{ {
$collection = $this->_category->create(); $collection = $this->category->create();
$collection->addAttributeToSelect('*'); $collection->addAttributeToSelect('*');
foreach ($collection as $category) { foreach ($collection as $category) {
if ($category->getId() > 1) { if ($category->getId() > 1) {
$e = $this->_eCategories->appendChild( $e = $this->eCategories->appendChild(
$this->_dd->createElement('category') $this->dd->createElement('category')
); );
$e->appendChild($this->_dd->createTextNode($category->getName())); $e->appendChild($this->dd->createTextNode($category->getName()));
$e->setAttribute('id', $category->getId()); $e->setAttribute('id', $category->getId());
if ($category->getParentId() > 1) { if ($category->getParentId() > 1) {
@ -95,136 +108,31 @@ class Icml
} }
} }
/**
* Write products in icml catalog
*
* @return void
*/
private function addOffers() private function addOffers()
{ {
$offers = []; $offers = $this->buildOffers();
$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 = [];
$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) { foreach ($offers as $offer) {
$e = $this->_eOffers->appendChild( $this->addOffer($offer);
$this->_dd->createElement('offer') }
}
/**
* Write product in icml catalog
*
* @param array $offer
*
* @return void
*/
private function addOffer($offer)
{
$e = $this->eOffers->appendChild(
$this->dd->createElement('offer')
); );
$e->setAttribute('id', $offer['id']); $e->setAttribute('id', $offer['id']);
@ -239,74 +147,248 @@ class Icml
if (!empty($offer['categoryId'])) { if (!empty($offer['categoryId'])) {
foreach ($offer['categoryId'] as $categoryId) { foreach ($offer['categoryId'] as $categoryId) {
$e->appendChild( $e->appendChild(
$this->_dd->createElement('categoryId') $this->dd->createElement('categoryId')
)->appendChild( )->appendChild(
$this->_dd->createTextNode($categoryId) $this->dd->createTextNode($categoryId)
); );
} }
} else { } else {
$e->appendChild($this->_dd->createElement('categoryId', 1)); $e->appendChild($this->dd->createElement('categoryId', 1));
} }
$e->appendChild($this->_dd->createElement('productActivity')) $e->appendChild($this->dd->createElement('productActivity'))
->appendChild( ->appendChild(
$this->_dd->createTextNode($offer['productActivity']) $this->dd->createTextNode($offer['productActivity'])
); );
$e->appendChild($this->_dd->createElement('name')) $e->appendChild($this->dd->createElement('name'))
->appendChild( ->appendChild(
$this->_dd->createTextNode($offer['name']) $this->dd->createTextNode($offer['name'])
); );
$e->appendChild($this->_dd->createElement('productName')) $e->appendChild($this->dd->createElement('productName'))
->appendChild( ->appendChild(
$this->_dd->createTextNode($offer['productName']) $this->dd->createTextNode($offer['productName'])
); );
$e->appendChild($this->_dd->createElement('price')) $e->appendChild($this->dd->createElement('price'))
->appendChild( ->appendChild(
$this->_dd->createTextNode($offer['initialPrice']) $this->dd->createTextNode($offer['initialPrice'])
); );
if (!empty($offer['purchasePrice'])) { if (!empty($offer['purchasePrice'])) {
$e->appendChild($this->_dd->createElement('purchasePrice')) $e->appendChild($this->dd->createElement('purchasePrice'))
->appendChild( ->appendChild(
$this->_dd->createTextNode($offer['purchasePrice']) $this->dd->createTextNode($offer['purchasePrice'])
); );
} }
if (!empty($offer['picture'])) { if (!empty($offer['picture'])) {
$e->appendChild($this->_dd->createElement('picture')) $e->appendChild($this->dd->createElement('picture'))
->appendChild( ->appendChild(
$this->_dd->createTextNode($offer['picture']) $this->dd->createTextNode($offer['picture'])
); );
} }
if (!empty($offer['url'])) { if (!empty($offer['url'])) {
$e->appendChild($this->_dd->createElement('url')) $e->appendChild($this->dd->createElement('url'))
->appendChild( ->appendChild(
$this->_dd->createTextNode($offer['url']) $this->dd->createTextNode($offer['url'])
); );
} }
if (!empty($offer['vendor'])) { if (!empty($offer['vendor'])) {
$e->appendChild($this->_dd->createElement('vendor')) $e->appendChild($this->dd->createElement('vendor'))
->appendChild( ->appendChild(
$this->_dd->createTextNode($offer['vendor']) $this->dd->createTextNode($offer['vendor'])
); );
} }
if (!empty($offer['params'])) { if (!empty($offer['params'])) {
foreach ($offer['params'] as $param) { foreach ($offer['params'] as $param) {
$paramNode = $this->_dd->createElement('param'); $paramNode = $this->dd->createElement('param');
$paramNode->setAttribute('name', $param['name']); $paramNode->setAttribute('name', $param['name']);
$paramNode->setAttribute('code', $param['code']); $paramNode->setAttribute('code', $param['code']);
$paramNode->appendChild( $paramNode->appendChild(
$this->_dd->createTextNode($param['value']) $this->dd->createTextNode($param['value'])
); );
$e->appendChild($paramNode); $e->appendChild($paramNode);
} }
} }
} }
/**
* Build offers array
*
* @return array $offers
*/
private function buildOffers()
{
$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);
$customAdditionalAttributes = $this->config->getValue('retailcrm/Misc/attributes_to_export_into_icml');
foreach ($collection as $product) {
if ($product->getTypeId() == 'simple') {
$offers[] = $this->buildOffer($product);
}
if ($product->getTypeId() == 'configurable') {
$associated_products = $this->getAssociatedProducts($product);
foreach ($associated_products as $associatedProduct) {
$offers[] = $this->buildOffer($product, $associatedProduct);
}
}
}
return $offers;
}
/**
* Build offer array
*
* @param object $product
* @param object $associatedProduct
* @return array $offer
*/
private function buildOffer($product, $associatedProduct = null)
{
$offer = [];
$picUrl = $this->storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
$offer['id'] = $associatedProduct === null ? $product->getId() : $associatedProduct->getId();
$offer['productId'] = $product->getId();
if ($associatedProduct === null) {
$offer['productActivity'] = $product->isAvailable() ? 'Y' : 'N';
} else {
$offer['productActivity'] = $associatedProduct->isAvailable() ? 'Y' : 'N';
}
$offer['name'] = $associatedProduct === null ? $product->getName() : $associatedProduct->getName();
$offer['productName'] = $product->getName();
$offer['initialPrice'] = $associatedProduct === null
? $product->getFinalPrice()
: $associatedProduct->getFinalPrice();
$offer['url'] = $product->getProductUrl();
if ($associatedProduct === null) {
$offer['picture'] = $picUrl . 'catalog/product' . $product->getImage();
} else {
$offer['picture'] = $picUrl . 'catalog/product' . $associatedProduct->getImage();
}
$offer['quantity'] = $associatedProduct === null
? $this->getStockQuantity($product)
: $this->getStockQuantity($associatedProduct);
$offer['categoryId'] = $associatedProduct === null
? $product->getCategoryIds()
: $associatedProduct->getCategoryIds();
$offer['vendor'] = $associatedProduct === null
? $product->getAttributeText('manufacturer')
: $associatedProduct->getAttributeText('manufacturer');
$offer['params'] = $this->getOfferParams($product, $associatedProduct);
return $offer;
}
/**
* Get parameters offers
*
* @param object $product
* @param object $associatedProduct
* @return array $params
*/
private function getOfferParams($product, $associatedProduct = null)
{
$params = [];
if ($associatedProduct !== null) {
if ($associatedProduct->getResource()->getAttribute('color')) {
$colorAttribute = $associatedProduct->getResource()->getAttribute('color');
$color = $colorAttribute->getSource()->getOptionText($associatedProduct->getColor());
}
if (isset($color)) {
$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)) {
$params[] = [
'name' => 'Size',
'code' => 'size',
'value' => $size
];
}
}
$article = $associatedProduct === null ? $product->getSku() : $associatedProduct->getSku();
if (!empty($article)) {
$params[] = [
'name' => 'Article',
'code' => 'article',
'value' => $article
];
}
$weight = $associatedProduct === null ? $product->getWeight() : $associatedProduct->getWeight();
if (!empty($weight)) {
$params[] = [
'name' => 'Weight',
'code' => 'weight',
'value' => $weight
];
}
return $params;
}
/**
* Get associated products
*
* @param object $product
*
* @return object
*/
private function getAssociatedProducts($product)
{
return $this->configurable
->getUsedProductCollection($product)
->addAttributeToSelect('*')
->addFilterByRequiredOptions();
}
/**
* Get product stock quantity
*
* @param object $offer
* @return int $quantity
*/
private function getStockQuantity($offer)
{
$quantity = $this->StockState->getStockQty(
$offer->getId(),
$offer->getStore()->getWebsiteId()
);
return $quantity;
} }
} }

View File

@ -6,9 +6,9 @@ class Logger
{ {
private $logDir; private $logDir;
public function __construct(\Magento\Framework\ObjectManagerInterface $objectManager) public function __construct(
{ \Magento\Framework\Filesystem\DirectoryList $directory
$directory = $objectManager->get('\Magento\Framework\Filesystem\DirectoryList'); ) {
$this->logDir = $directory->getPath('log'); $this->logDir = $directory->getPath('log');
} }
@ -16,7 +16,7 @@ class Logger
* Write data in log file * Write data in log file
* *
* @param array $data * @param array $data
* @param str $fileName * @param string $fileName
* *
* @return void * @return void
*/ */
@ -41,8 +41,8 @@ class Logger
/** /**
* Write data in log file * Write data in log file
* *
* @param str $data * @param string $data
* @param str $fileName * @param string $fileName
* *
* @return void * @return void
*/ */
@ -65,11 +65,11 @@ class Logger
/** /**
* Clear file * Clear file
* *
* @param str $file * @param string $file
* *
* @return void * @return void
*/ */
protected function clear($file) private function clear($file)
{ {
file_put_contents($file, ''); file_put_contents($file, '');
} }
@ -77,11 +77,11 @@ class Logger
/** /**
* Check file size * Check file size
* *
* @param str $file * @param string $file
* *
* @return boolean * @return boolean
*/ */
protected function checkSize($file) private function checkSize($file)
{ {
if (!file_exists($file)) { if (!file_exists($file)) {
return true; return true;

View File

@ -6,39 +6,22 @@ use Retailcrm\Retailcrm\Helper\Proxy as ApiClient;
class Customer implements \Magento\Framework\Event\ObserverInterface class Customer implements \Magento\Framework\Event\ObserverInterface
{ {
protected $_api; private $api;
protected $_config; private $registry;
protected $_helper;
protected $_logger;
protected $_objectManager;
protected $registry;
public function __construct( public function __construct(
\Magento\Framework\ObjectManagerInterface $objectManager, \Magento\Framework\Registry $registry,
\Magento\Framework\App\Config\ScopeConfigInterface $config, ApiClient $api
\Magento\Framework\Registry $registry
) { ) {
$helper = $objectManager->get('\Retailcrm\Retailcrm\Helper\Data'); $this->api = $api;
$logger = $objectManager->get('\Retailcrm\Retailcrm\Model\Logger\Logger');
$this->_logger = $logger;
$this->_helper = $helper;
$this->_config = $config;
$this->_objectManager = $objectManager;
$this->registry = $registry; $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) public function execute(\Magento\Framework\Event\Observer $observer)
{ {
if ($this->registry->registry('RETAILCRM_HISTORY') === true) { if ($this->registry->registry('RETAILCRM_HISTORY') === true
|| !$this->api->isConfigured()
) {
return; return;
} }
@ -53,14 +36,14 @@ class Customer implements \Magento\Framework\Event\ObserverInterface
'createdAt' => date('Y-m-d H:i:s', strtotime($data->getCreatedAt())) 'createdAt' => date('Y-m-d H:i:s', strtotime($data->getCreatedAt()))
]; ];
$response = $this->_api->customersEdit($customer); $response = $this->api->customersEdit($customer);
if ($response === false) { if ($response === false) {
return; return;
} }
if (!$response->isSuccessful() && $response->errorMsg == $this->_api->getErrorText('errorNotFound')) { if (!$response->isSuccessful() && $response->errorMsg == $this->api->getErrorText('errorNotFound')) {
$this->_api->customersCreate($customer); $this->api->customersCreate($customer);
} }
} }
} }

View File

@ -7,40 +7,31 @@ use Retailcrm\Retailcrm\Helper\Proxy as ApiClient;
class OrderCreate implements \Magento\Framework\Event\ObserverInterface class OrderCreate implements \Magento\Framework\Event\ObserverInterface
{ {
protected $_api; private $api;
protected $_objectManager; private $config;
protected $_config; private $logger;
protected $_helper; private $registry;
protected $_logger; private $product;
protected $_registry;
/** /**
* Constructor * Constructor
* *
* @param \Magento\Framework\ObjectManagerInterface $objectManager
* @param \Magento\Framework\App\Config\ScopeConfigInterface $config * @param \Magento\Framework\App\Config\ScopeConfigInterface $config
* @param \Retailcrm\Retailcrm\Model\Logger\Logger $logger * @param \Retailcrm\Retailcrm\Model\Logger\Logger $logger
* @param \Magento\Framework\Registry $registry * @param \Magento\Framework\Registry $registry
*/ */
public function __construct( public function __construct(
\Magento\Framework\ObjectManagerInterface $objectManager,
\Magento\Framework\App\Config\ScopeConfigInterface $config, \Magento\Framework\App\Config\ScopeConfigInterface $config,
\Magento\Framework\Registry $registry \Magento\Framework\Registry $registry,
\Retailcrm\Retailcrm\Model\Logger\Logger $logger,
\Magento\Catalog\Model\ProductRepository $product,
ApiClient $api
) { ) {
$helper = $objectManager->get('\Retailcrm\Retailcrm\Helper\Data'); $this->logger = $logger;
$this->_logger = $objectManager->get('\Retailcrm\Retailcrm\Model\Logger\Logger'); $this->config = $config;
$this->_helper = $helper; $this->registry = $registry;
$this->_objectManager = $objectManager; $this->product = $product;
$this->_config = $config; $this->api = $api;
$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);
}
} }
/** /**
@ -52,7 +43,9 @@ class OrderCreate implements \Magento\Framework\Event\ObserverInterface
*/ */
public function execute(Observer $observer) public function execute(Observer $observer)
{ {
if ($this->_registry->registry('RETAILCRM_HISTORY') === true) { if ($this->registry->registry('RETAILCRM_HISTORY') === true
|| !$this->api->isConfigured()
) {
return; return;
} }
@ -62,36 +55,8 @@ class OrderCreate implements \Magento\Framework\Event\ObserverInterface
return; return;
} }
$items = [];
$addressObj = $order->getBillingAddress(); $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' => [
'externalId' => $item->getProductId()
]
];
unset($omproduct);
unset($price);
$items[] = $product;
}
}
$shippingCode = $this->getShippingCode($order->getShippingMethod()); $shippingCode = $this->getShippingCode($order->getShippingMethod());
$preparedOrder = [ $preparedOrder = [
@ -99,15 +64,21 @@ class OrderCreate implements \Magento\Framework\Event\ObserverInterface
'externalId' => $order->getId(), 'externalId' => $order->getId(),
'number' => $order->getRealOrderId(), 'number' => $order->getRealOrderId(),
'createdAt' => $order->getCreatedAt(), 'createdAt' => $order->getCreatedAt(),
'lastName' => $order->getCustomerLastname() ? $order->getCustomerLastname() : $addressObj->getLastname(), 'lastName' => $order->getCustomerLastname()
'firstName' => $order->getCustomerFirstname() ? $order->getCustomerFirstname() : $addressObj->getFirstname(), ? $order->getCustomerLastname()
'patronymic' => $order->getCustomerMiddlename() ? $order->getCustomerMiddlename() : $addressObj->getMiddlename(), : $addressObj->getLastname(),
'firstName' => $order->getCustomerFirstname()
? $order->getCustomerFirstname()
: $addressObj->getFirstname(),
'patronymic' => $order->getCustomerMiddlename()
? $order->getCustomerMiddlename()
: $addressObj->getMiddlename(),
'email' => $order->getCustomerEmail(), 'email' => $order->getCustomerEmail(),
'phone' => $addressObj->getTelephone(), 'phone' => $addressObj->getTelephone(),
'status' => $this->_config->getValue('retailcrm/Status/' . $order->getStatus()), 'status' => $this->config->getValue('retailcrm/Status/' . $order->getStatus()),
'items' => $items, 'items' => $this->getOrderItems($order),
'delivery' => [ 'delivery' => [
'code' => $this->_config->getValue('retailcrm/Shipping/' . $shippingCode), 'code' => $this->config->getValue('retailcrm/Shipping/' . $shippingCode),
'cost' => $order->getShippingAmount(), 'cost' => $order->getShippingAmount(),
'address' => [ 'address' => [
'index' => $addressObj->getData('postcode'), 'index' => $addressObj->getData('postcode'),
@ -133,14 +104,18 @@ class OrderCreate implements \Magento\Framework\Event\ObserverInterface
$preparedOrder['countryIso'] = $addressObj->getData('country_id'); $preparedOrder['countryIso'] = $addressObj->getData('country_id');
} }
if ($this->_api->getVersion() == 'v4') { if ($this->api->getVersion() == 'v4') {
$preparedOrder['paymentType'] = $this->_config->getValue('retailcrm/Payment/'.$order->getPayment()->getMethodInstance()->getCode()); $preparedOrder['paymentType'] = $this->config->getValue(
'retailcrm/Payment/' . $order->getPayment()->getMethodInstance()->getCode()
);
$preparedOrder['discount'] = abs($order->getDiscountAmount()); $preparedOrder['discount'] = abs($order->getDiscountAmount());
} elseif ($this->_api->getVersion() == 'v5') { } elseif ($this->api->getVersion() == 'v5') {
$preparedOrder['discountManualAmount'] = abs($order->getDiscountAmount()); $preparedOrder['discountManualAmount'] = abs($order->getDiscountAmount());
$payment = [ $payment = [
'type' => $this->_config->getValue('retailcrm/Payment/' . $order->getPayment()->getMethodInstance()->getCode()), 'type' => $this->config->getValue(
'retailcrm/Payment/' . $order->getPayment()->getMethodInstance()->getCode()
),
'externalId' => $order->getId(), 'externalId' => $order->getId(),
'order' => [ 'order' => [
'externalId' => $order->getId(), 'externalId' => $order->getId(),
@ -166,13 +141,37 @@ class OrderCreate implements \Magento\Framework\Event\ObserverInterface
unset($preparedOrder['status']); unset($preparedOrder['status']);
} }
$this->setCustomer(
$order,
$addressObj,
$preparedOrder
);
\Retailcrm\Retailcrm\Helper\Data::filterRecursive($preparedOrder);
$this->logger->writeDump($preparedOrder, 'CreateOrder');
$this->api->ordersCreate($preparedOrder);
return $this;
}
/**
* @param $order
* @param $addressObj
* @param $preparedOrder
*/
private function setCustomer($order, $addressObj, &$preparedOrder)
{
if ($order->getCustomerIsGuest() == 1) { if ($order->getCustomerIsGuest() == 1) {
$customer = $this->getCustomerByEmail($order->getCustomerEmail()); $customer = $this->getCustomerByEmail($order->getCustomerEmail());
if ($customer !== false) { if ($customer !== false) {
$preparedOrder['customer']['id'] = $customer['id']; $preparedOrder['customer']['id'] = $customer['id'];
} }
} elseif ($order->getCustomerIsGuest() == 0) { }
if ($order->getCustomerIsGuest() == 0) {
if ($this->existsInCrm($order->getCustomerId(), 'customersGet')) { if ($this->existsInCrm($order->getCustomerId(), 'customersGet')) {
$preparedOrder['customer']['externalId'] = $order->getCustomerId(); $preparedOrder['customer']['externalId'] = $order->getCustomerId();
} else { } else {
@ -189,19 +188,51 @@ class OrderCreate implements \Magento\Framework\Event\ObserverInterface
]; ];
} }
if ($this->_api->customersCreate($preparedCustomer)) { if ($this->api->customersCreate($preparedCustomer)) {
$preparedOrder['customer']['externalId'] = $order->getCustomerId(); $preparedOrder['customer']['externalId'] = $order->getCustomerId();
} }
} }
} }
}
$this->_helper->filterRecursive($preparedOrder); /**
* Get order products
*
* @param object $order
*
* @return array $items
*/
private function getOrderItems($order)
{
$items = [];
$this->_logger->writeDump($preparedOrder,'CreateOrder'); foreach ($order->getAllItems() as $item) {
if ($item->getProductType() == "simple") {
$price = $item->getPrice();
$this->_api->ordersCreate($preparedOrder); if ($price == 0) {
$magentoProduct = $this->product->getById($item->getProductId());
$price = $magentoProduct->getPrice();
}
return $this; $product = [
'productId' => $item->getProductId(),
'productName' => $item->getName(),
'quantity' => $item->getQtyOrdered(),
'initialPrice' => $price,
'offer' => [
'externalId' => $item->getProductId()
]
];
unset($magentoProduct);
unset($price);
$items[] = $product;
}
}
return $items;
} }
/** /**
@ -211,7 +242,7 @@ class OrderCreate implements \Magento\Framework\Event\ObserverInterface
* *
* @return string * @return string
*/ */
protected function getShippingCode($string) public function getShippingCode($string)
{ {
$split = array_values(explode('_', $string)); $split = array_values(explode('_', $string));
$length = count($split); $length = count($split);
@ -227,15 +258,15 @@ class OrderCreate implements \Magento\Framework\Event\ObserverInterface
* *
* @return boolean * @return boolean
*/ */
protected function existsInCrm($id, $method = 'ordersGet', $by = 'externalId') private function existsInCrm($id, $method = 'ordersGet', $by = 'externalId')
{ {
$response = $this->_api->{$method}($id, $by); $response = $this->api->{$method}($id, $by);
if ($response === false) { if ($response === false) {
return; return;
} }
if (!$response->isSuccessful() && $response->errorMsg == $this->_api->getErrorText('errorNotFound')) { if (!$response->isSuccessful() && $response->errorMsg == $this->api->getErrorText('errorNotFound')) {
return false; return false;
} }
@ -249,9 +280,9 @@ class OrderCreate implements \Magento\Framework\Event\ObserverInterface
* *
* @return mixed * @return mixed
*/ */
protected function getCustomerByEmail($email) private function getCustomerByEmail($email)
{ {
$response = $this->_api->customersList(['email' => $email]); $response = $this->api->customersList(['email' => $email]);
if ($response === false) { if ($response === false) {
return false; return false;

View File

@ -7,35 +7,25 @@ use Retailcrm\Retailcrm\Helper\Proxy as ApiClient;
class OrderUpdate implements \Magento\Framework\Event\ObserverInterface class OrderUpdate implements \Magento\Framework\Event\ObserverInterface
{ {
protected $_api; private $api;
protected $_config; private $config;
protected $_helper; private $registry;
protected $_objectManager;
protected $registry;
/** /**
* Constructor * Constructor
* *
* @param \Magento\Framework\ObjectManagerInterface $objectManager
* @param \Magento\Framework\App\Config\ScopeConfigInterface $config * @param \Magento\Framework\App\Config\ScopeConfigInterface $config
* @param \Magento\Framework\Registry $registry
* @param ApiClient $api
*/ */
public function __construct( public function __construct(
\Magento\Framework\ObjectManagerInterface $objectManager,
\Magento\Framework\App\Config\ScopeConfigInterface $config, \Magento\Framework\App\Config\ScopeConfigInterface $config,
\Magento\Framework\Registry $registry \Magento\Framework\Registry $registry,
ApiClient $api
) { ) {
$this->_helper = $objectManager->get('\Retailcrm\Retailcrm\Helper\Data'); $this->config = $config;
$this->_objectManager = $objectManager;
$this->_config = $config;
$this->registry = $registry; $this->registry = $registry;
$this->api = $api;
$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);
}
} }
/** /**
@ -47,7 +37,9 @@ class OrderUpdate implements \Magento\Framework\Event\ObserverInterface
*/ */
public function execute(Observer $observer) public function execute(Observer $observer)
{ {
if ($this->registry->registry('RETAILCRM_HISTORY') === true) { if ($this->registry->registry('RETAILCRM_HISTORY') === true
|| !$this->api->isConfigured()
) {
return; return;
} }
@ -56,24 +48,24 @@ class OrderUpdate implements \Magento\Framework\Event\ObserverInterface
if ($order) { if ($order) {
$preparedOrder = [ $preparedOrder = [
'externalId' => $order->getId(), 'externalId' => $order->getId(),
'status' => $this->_config->getValue('retailcrm/Status/' . $order->getStatus()) 'status' => $this->config->getValue('retailcrm/Status/' . $order->getStatus())
]; ];
if ($order->getBaseTotalDue() == 0) { if ($order->getBaseTotalDue() == 0) {
if ($this->_api->getVersion() == 'v4') { if ($this->api->getVersion() == 'v4') {
$preparedOrder['paymentStatus'] = 'paid'; $preparedOrder['paymentStatus'] = 'paid';
} elseif ($this->_api->getVersion() == 'v5') { } elseif ($this->api->getVersion() == 'v5') {
$payment = [ $payment = [
'externalId' => $order->getPayment()->getId(), 'externalId' => $order->getPayment()->getId(),
'status' => 'paid' 'status' => 'paid'
]; ];
$this->_api->ordersPaymentsEdit($payment); $this->api->ordersPaymentsEdit($payment);
} }
} }
$this->_helper->filterRecursive($preparedOrder); \Retailcrm\Retailcrm\Helper\Data::filterRecursive($preparedOrder);
$this->_api->ordersEdit($preparedOrder); $this->api->ordersEdit($preparedOrder);
} }
} }
} }

View File

@ -7,45 +7,38 @@ use Retailcrm\Retailcrm\Helper\Proxy as ApiClient;
class OrderNumber extends OrderCreate class OrderNumber extends OrderCreate
{ {
protected $_orderRepository; private $orderRepository;
protected $_searchCriteriaBuilder; private $searchCriteriaBuilder;
protected $_config; private $config;
protected $_filterBuilder; private $filterBuilder;
protected $_order; private $order;
protected $_helper; private $api;
protected $_api; private $logger;
protected $_logger; private $productRepository;
public function __construct() public function __construct(
{ \Magento\Sales\Model\OrderRepository $orderRepository,
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); \Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder,
$orderRepository = $objectManager->get('Magento\Sales\Model\OrderRepository'); \Magento\Framework\App\Config\ScopeConfigInterface $config,
$searchCriteriaBuilder = $objectManager->get('Magento\Framework\Api\SearchCriteriaBuilder'); \Magento\Framework\Api\FilterBuilder $filterBuilder,
$config = $objectManager->get('Magento\Framework\App\Config\ScopeConfigInterface'); \Magento\Sales\Api\Data\OrderInterface $order,
$filterBuilder = $objectManager->get('Magento\Framework\Api\FilterBuilder'); \Retailcrm\Retailcrm\Model\Logger\Logger $logger,
$order = $objectManager->get('\Magento\Sales\Api\Data\OrderInterface'); \Magento\Catalog\Model\ProductRepository $productRepository,
$helper = $objectManager->get('\Retailcrm\Retailcrm\Helper\Data'); ApiClient $api
) {
$this->_orderRepository = $orderRepository; $this->orderRepository = $orderRepository;
$this->_searchCriteriaBuilder = $searchCriteriaBuilder; $this->searchCriteriaBuilder = $searchCriteriaBuilder;
$this->_config = $config; $this->config = $config;
$this->_filterBuilder = $filterBuilder; $this->filterBuilder = $filterBuilder;
$this->_order = $order; $this->order = $order;
$this->_helper = $helper; $this->logger = $logger;
$this->_logger = $objectManager->get('\Retailcrm\Retailcrm\Model\Logger\Logger'); $this->productRepository = $productRepository;
$this->api = $api;
$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 ExportOrderNumber() public function exportOrderNumber()
{ {
$ordernumber = $this->_config->getValue('retailcrm/Load/number_order'); $ordernumber = $this->config->getValue('retailcrm/Load/number_order');
$ordersId = explode(",", $ordernumber); $ordersId = explode(",", $ordernumber);
$orders = []; $orders = [];
@ -57,7 +50,7 @@ class OrderNumber extends OrderCreate
unset($orders); unset($orders);
foreach ($chunked as $chunk) { foreach ($chunked as $chunk) {
$this->_api->ordersUpload($chunk); $this->api->ordersUpload($chunk);
time_nanosleep(0, 250000000); time_nanosleep(0, 250000000);
} }
@ -68,7 +61,7 @@ class OrderNumber extends OrderCreate
public function prepareOrder($id) public function prepareOrder($id)
{ {
$magentoOrder = $this->_order->load($id); $magentoOrder = $this->order->load($id);
$items = []; $items = [];
$addressObj = $magentoOrder->getBillingAddress(); $addressObj = $magentoOrder->getBillingAddress();
@ -78,10 +71,8 @@ class OrderNumber extends OrderCreate
$price = $item->getPrice(); $price = $item->getPrice();
if ($price == 0) { if ($price == 0) {
$om = \Magento\Framework\App\ObjectManager::getInstance(); $magentoProduct = $this->productRepository->getById($item->getProductId());
$omproduct = $om->get('Magento\Catalog\Model\ProductRepository') $price = $magentoProduct->getPrice();
->getById($item->getProductId());
$price = $omproduct->getPrice();
} }
$product = [ $product = [
@ -94,8 +85,7 @@ class OrderNumber extends OrderCreate
] ]
]; ];
unset($om); unset($magentoProduct);
unset($omproduct);
unset($price); unset($price);
$items[] = $product; $items[] = $product;
@ -114,12 +104,14 @@ class OrderNumber extends OrderCreate
'patronymic' => $magentoOrder->getCustomerMiddlename(), 'patronymic' => $magentoOrder->getCustomerMiddlename(),
'email' => $magentoOrder->getCustomerEmail(), 'email' => $magentoOrder->getCustomerEmail(),
'phone' => $addressObj->getTelephone(), 'phone' => $addressObj->getTelephone(),
'paymentType' => $this->_config->getValue('retailcrm/Payment/'.$magentoOrder->getPayment()->getMethodInstance()->getCode()), 'paymentType' => $this->config->getValue(
'status' => $this->_config->getValue('retailcrm/Status/'.$magentoOrder->getStatus()), 'retailcrm/Payment/' . $magentoOrder->getPayment()->getMethodInstance()->getCode()
),
'status' => $this->config->getValue('retailcrm/Status/'.$magentoOrder->getStatus()),
'discount' => abs($magentoOrder->getDiscountAmount()), 'discount' => abs($magentoOrder->getDiscountAmount()),
'items' => $items, 'items' => $items,
'delivery' => [ 'delivery' => [
'code' => $this->_config->getValue('retailcrm/Shipping/'.$ship), 'code' => $this->config->getValue('retailcrm/Shipping/'.$ship),
'cost' => $magentoOrder->getShippingAmount(), 'cost' => $magentoOrder->getShippingAmount(),
'address' => [ 'address' => [
'index' => $addressObj->getData('postcode'), 'index' => $addressObj->getData('postcode'),
@ -158,8 +150,8 @@ class OrderNumber extends OrderCreate
$preparedOrder['customer']['externalId'] = $magentoOrder->getCustomerId(); $preparedOrder['customer']['externalId'] = $magentoOrder->getCustomerId();
} }
$this->_logger->writeDump($preparedOrder,'OrderNumber'); $this->logger->writeDump($preparedOrder, 'OrderNumber');
return $this->_helper->filterRecursive($preparedOrder); return \Retailcrm\Retailcrm\Helper\Data::filterRecursive($preparedOrder);
} }
} }

View File

@ -0,0 +1,19 @@
<?php
namespace Retailcrm\Retailcrm\Model\Service;
class ConfigManager implements \Retailcrm\Retailcrm\Api\ConfigManagerInterface
{
private $config;
public function __construct(
\Magento\Framework\App\Config\ScopeConfigInterface $config
) {
$this->config = $config;
}
public function getConfigValue($path)
{
return $this->config->getValue($path);
}
}

View File

@ -4,28 +4,32 @@ namespace Retailcrm\Retailcrm\Model\Setting;
class Attribute implements \Magento\Framework\Option\ArrayInterface class Attribute implements \Magento\Framework\Option\ArrayInterface
{ {
protected $_entityType; private $entityType;
protected $_store; private $store;
public function __construct( public function __construct(
\Magento\Store\Model\Store $store, \Magento\Store\Model\Store $store,
\Magento\Eav\Model\Entity\Type $entityType \Magento\Eav\Model\Entity\Type $entityType
) { ) {
$this->_store = $store; $this->store = $store;
$this->_entityType = $entityType; $this->entityType = $entityType;
} }
public function toOptionArray() public function toOptionArray()
{ {
$types = ['text', 'multiselect', 'decimal']; $types = ['text', 'multiselect', 'decimal'];
$attributes = $this->_entityType->loadByCode('catalog_product')->getAttributeCollection(); $attributes = $this->entityType->loadByCode('catalog_product')->getAttributeCollection();
$attributes->addFieldToFilter('frontend_input', $types); $attributes->addFieldToFilter('frontend_input', $types);
$result = []; $result = [];
foreach ($attributes as $attr) { foreach ($attributes as $attr) {
if ($attr->getFrontendLabel()) { if ($attr->getFrontendLabel()) {
$result[] = array('value' => $attr->getAttributeId(), 'label' => $attr->getFrontendLabel(), 'title' => $attr->getAttributeCode()); $result[] = [
'value' => $attr->getAttributeId(),
'label' => $attr->getFrontendLabel(),
'title' => $attr->getAttributeCode()
];
} }
} }

View File

@ -4,23 +4,26 @@ namespace Retailcrm\Retailcrm\Model\Setting;
class Shipping implements \Magento\Framework\Option\ArrayInterface class Shipping implements \Magento\Framework\Option\ArrayInterface
{ {
protected $_entityType; private $entityType;
protected $_store; private $store;
private $config;
private $shippingConfig;
public function __construct( public function __construct(
\Magento\Store\Model\Store $store, \Magento\Store\Model\Store $store,
\Magento\Eav\Model\Entity\Type $entityType \Magento\Eav\Model\Entity\Type $entityType,
\Magento\Framework\App\Config\ScopeConfigInterface $config,
\Magento\Shipping\Model\Config $shippingConfig
) { ) {
$this->_store = $store; $this->store = $store;
$this->_entityType = $entityType; $this->entityType = $entityType;
$this->config = $config;
$this->shippingConfig = $shippingConfig;
} }
public function toOptionArray() public function toOptionArray()
{ {
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $activeShipping = $this->shippingConfig->getActiveCarriers();
$activeShipping = $objectManager->create('Magento\Shipping\Model\Config')->getActiveCarriers();
$config = $objectManager->get('Magento\Framework\App\Config\ScopeConfigInterface');
foreach ($activeShipping as $carrierCode => $carrierModel) { foreach ($activeShipping as $carrierCode => $carrierModel) {
$options = []; $options = [];
@ -36,7 +39,7 @@ class Shipping implements \Magento\Framework\Option\ArrayInterface
]; ];
} }
$carrierTitle = $config->getValue('carriers/' . $carrierCode . '/title'); $carrierTitle = $this->config->getValue('carriers/' . $carrierCode . '/title');
} }
$methods[] = [ $methods[] = [

View File

@ -4,14 +4,12 @@ namespace Retailcrm\Retailcrm\Test\Unit\Observer;
class CustomerTest extends \PHPUnit\Framework\TestCase class CustomerTest extends \PHPUnit\Framework\TestCase
{ {
protected $mockApi; private $mockApi;
protected $mockResponse; private $mockResponse;
protected $config; private $registry;
protected $registry; private $mockObserver;
protected $mockObserver; private $mockEvent;
protected $mockEvent; private $mockCustomer;
protected $objectManager;
protected $mockCustomer;
public function setUp() public function setUp()
{ {
@ -28,9 +26,6 @@ class CustomerTest extends \PHPUnit\Framework\TestCase
->setMethods(['isSuccessful']) ->setMethods(['isSuccessful'])
->getMock(); ->getMock();
$this->config = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class)
->getMockForAbstractClass();
$this->registry = $this->getMockBuilder(\Magento\Framework\Registry::class) $this->registry = $this->getMockBuilder(\Magento\Framework\Registry::class)
->disableOriginalConstructor() ->disableOriginalConstructor()
->getMock(); ->getMock();
@ -44,9 +39,6 @@ class CustomerTest extends \PHPUnit\Framework\TestCase
->setMethods(['getCustomer']) ->setMethods(['getCustomer'])
->getMock(); ->getMock();
$this->objectManager = $this->getMockBuilder(\Magento\Framework\ObjectManagerInterface::class)
->getMockForAbstractClass();
$this->mockCustomer = $this->getMockBuilder(\Magento\Customer\Model\Customer::class) $this->mockCustomer = $this->getMockBuilder(\Magento\Customer\Model\Customer::class)
->disableOriginalConstructor() ->disableOriginalConstructor()
->setMethods([ ->setMethods([
@ -59,13 +51,12 @@ class CustomerTest extends \PHPUnit\Framework\TestCase
->getMock(); ->getMock();
$this->unit = new \Retailcrm\Retailcrm\Model\Observer\Customer( $this->unit = new \Retailcrm\Retailcrm\Model\Observer\Customer(
$this->objectManager, $this->registry,
$this->config, $this->mockApi
$this->registry
); );
$reflection = new \ReflectionClass($this->unit); $reflection = new \ReflectionClass($this->unit);
$reflection_property = $reflection->getProperty('_api'); $reflection_property = $reflection->getProperty('api');
$reflection_property->setAccessible(true); $reflection_property->setAccessible(true);
$reflection_property->setValue($this->unit, $this->mockApi); $reflection_property->setValue($this->unit, $this->mockApi);
} }
@ -134,7 +125,7 @@ class CustomerTest extends \PHPUnit\Framework\TestCase
* *
* @return array * @return array
*/ */
protected function getAfterSaveCustomerTestData() private function getAfterSaveCustomerTestData()
{ {
return [ return [
'id' => 1, 'id' => 1,

View File

@ -7,24 +7,23 @@ namespace Retailcrm\Retailcrm\Test\Unit\Observer;
*/ */
class OrderCreateTest extends \PHPUnit\Framework\TestCase class OrderCreateTest extends \PHPUnit\Framework\TestCase
{ {
protected $objectManager; private $config;
protected $_config; private $unit;
protected $_unit; private $mockEvent;
protected $_mockEvent; private $mockObserver;
protected $_mockObserver; private $registry;
protected $_registry; private $mockApi;
protected $_mockApi; private $mockOrder;
protected $_mockOrder; private $mockItem;
protected $_mockItem; private $mockStore;
protected $_mockStore; private $mockBillingAddress;
protected $_mockBillingAddress; private $mockResponse;
protected $_mockResponse; private $mockPayment;
protected $_mockPayment; private $mockPaymentMethod;
protected $_mockPaymentMethod;
protected function setUp() public function setUp()
{ {
$this->_mockApi = $this->getMockBuilder(\Retailcrm\Retailcrm\Helper\Proxy::class) $this->mockApi = $this->getMockBuilder(\Retailcrm\Retailcrm\Helper\Proxy::class)
->disableOriginalConstructor() ->disableOriginalConstructor()
->setMethods([ ->setMethods([
'ordersGet', 'ordersGet',
@ -36,39 +35,27 @@ class OrderCreateTest extends \PHPUnit\Framework\TestCase
]) ])
->getMock(); ->getMock();
$this->_mockObserver = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) $this->mockObserver = $this->getMockBuilder(\Magento\Framework\Event\Observer::class)
->disableOriginalConstructor() ->disableOriginalConstructor()
->getMock(); ->getMock();
$this->_mockEvent = $this->getMockBuilder(\Magento\Framework\Event::class) $this->mockEvent = $this->getMockBuilder(\Magento\Framework\Event::class)
->disableOriginalConstructor() ->disableOriginalConstructor()
->setMethods(['getOrder']) ->setMethods(['getOrder'])
->getMock(); ->getMock();
$this->objectManager = $this->getMockBuilder(\Magento\Framework\ObjectManagerInterface::class) $this->config = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class)
->getMockForAbstractClass(); ->getMockForAbstractClass();
// mock Object Manager $this->logger = $this->getMockBuilder(\Retailcrm\Retailcrm\Model\Logger\Logger::class)
$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() ->disableOriginalConstructor()
->getMock(); ->getMock();
$this->_registry = $this->getMockBuilder(\Magento\Framework\Registry::class) $this->registry = $this->getMockBuilder(\Magento\Framework\Registry::class)
->disableOriginalConstructor() ->disableOriginalConstructor()
->getMock(); ->getMock();
$this->_mockOrder = $this->getMockBuilder(\Magento\Sales\Order::class) $this->mockOrder = $this->getMockBuilder(\Magento\Sales\Order::class)
->setMethods([ ->setMethods([
'getId', 'getId',
'getRealOrderId', 'getRealOrderId',
@ -91,16 +78,16 @@ class OrderCreateTest extends \PHPUnit\Framework\TestCase
]) ])
->getMock(); ->getMock();
$this->_mockPayment = $this->getMockBuilder(\Magento\Sales\Model\Order\Payment::class) $this->mockPayment = $this->getMockBuilder(\Magento\Sales\Model\Order\Payment::class)
->setMethods(['getMethodInstance']) ->setMethods(['getMethodInstance'])
->disableOriginalConstructor() ->disableOriginalConstructor()
->getMock(); ->getMock();
$this->_mockPaymentMethod = $this->getMockBuilder(\Magento\Payment\Model\MethodInterface::class) $this->mockPaymentMethod = $this->getMockBuilder(\Magento\Payment\Model\MethodInterface::class)
->disableOriginalConstructor() ->disableOriginalConstructor()
->getMockForAbstractClass(); ->getMockForAbstractClass();
$this->_mockItem = $this->getMockBuilder(\Magento\Sales\Model\Order\Item::class) $this->mockItem = $this->getMockBuilder(\Magento\Sales\Model\Order\Item::class)
->disableOriginalConstructor() ->disableOriginalConstructor()
->setMethods([ ->setMethods([
'getPrice', 'getPrice',
@ -111,31 +98,32 @@ class OrderCreateTest extends \PHPUnit\Framework\TestCase
]) ])
->getMock(); ->getMock();
$this->_mockStore = $this->getMockBuilder(\Magento\Store\Model\Store::class) $this->mockStore = $this->getMockBuilder(\Magento\Store\Model\Store::class)
->disableOriginalConstructor() ->disableOriginalConstructor()
->setMethods(['getCode']) ->setMethods(['getCode'])
->getMock(); ->getMock();
$this->_mockBillingAddress = $this->getMockBuilder(\Magento\Customer\Model\Address\AddressModelInterface::class) $this->mockBillingAddress = $this->getMockBuilder(\Magento\Customer\Model\Address\AddressModelInterface::class)
->disableOriginalConstructor() ->disableOriginalConstructor()
->setMethods(['getTelephone', 'getData']) ->setMethods(['getTelephone', 'getData'])
->getMockForAbstractClass(); ->getMockForAbstractClass();
$this->_mockResponse = $this->getMockBuilder(\RetailCrm\Response\ApiResponse::class) $this->mockResponse = $this->getMockBuilder(\RetailCrm\Response\ApiResponse::class)
->disableOriginalConstructor() ->disableOriginalConstructor()
->setMethods(['isSuccessful']) ->setMethods(['isSuccessful'])
->getMock(); ->getMock();
$this->_unit = new \Retailcrm\Retailcrm\Model\Observer\OrderCreate( $product = $this->getMockBuilder(\Magento\Catalog\Model\ProductRepository::class)
$this->objectManager, ->disableOriginalConstructor()
$this->_config, ->getMock();
$this->_registry
);
$reflection = new \ReflectionClass($this->_unit); $this->unit = new \Retailcrm\Retailcrm\Model\Observer\OrderCreate(
$reflection_property = $reflection->getProperty('_api'); $this->config,
$reflection_property->setAccessible(true); $this->registry,
$reflection_property->setValue($this->_unit, $this->_mockApi); $this->logger,
$product,
$this->mockApi
);
} }
/** /**
@ -154,43 +142,43 @@ class OrderCreateTest extends \PHPUnit\Framework\TestCase
$testData = $this->getAfterSaveOrderTestData(); $testData = $this->getAfterSaveOrderTestData();
// mock Response // mock Response
$this->_mockResponse->expects($this->any()) $this->mockResponse->expects($this->any())
->method('isSuccessful') ->method('isSuccessful')
->willReturn($isSuccessful); ->willReturn($isSuccessful);
$this->_mockResponse->errorMsg = $errorMsg; $this->mockResponse->errorMsg = $errorMsg;
// mock API // mock API
$this->_mockApi->expects($this->any()) $this->mockApi->expects($this->any())
->method('ordersGet') ->method('ordersGet')
->willReturn($this->_mockResponse); ->willReturn($this->mockResponse);
$this->_mockApi->expects($this->any()) $this->mockApi->expects($this->any())
->method('ordersCreate') ->method('ordersCreate')
->willReturn($this->_mockResponse); ->willReturn($this->mockResponse);
$this->_mockApi->expects($this->any()) $this->mockApi->expects($this->any())
->method('customersGet') ->method('customersGet')
->willReturn($this->_mockResponse); ->willReturn($this->mockResponse);
$this->_mockApi->expects($this->any()) $this->mockApi->expects($this->any())
->method('customersCreate') ->method('customersCreate')
->willReturn($this->_mockResponse); ->willReturn($this->mockResponse);
$this->_mockApi->expects($this->any()) $this->mockApi->expects($this->any())
->method('customersList') ->method('customersList')
->willReturn($this->_mockResponse); ->willReturn($this->mockResponse);
$this->_mockApi->expects($this->any()) $this->mockApi->expects($this->any())
->method('getVersion') ->method('getVersion')
->willReturn($apiVersion); ->willReturn($apiVersion);
// billing address mock set data // billing address mock set data
$this->_mockBillingAddress->expects($this->any()) $this->mockBillingAddress->expects($this->any())
->method('getTelephone') ->method('getTelephone')
->willReturn($testData['order.billingAddress']['telephone']); ->willReturn($testData['order.billingAddress']['telephone']);
$this->_mockBillingAddress->expects($this->any()) $this->mockBillingAddress->expects($this->any())
->method('getData') ->method('getData')
->with($this->logicalOr( ->with($this->logicalOr(
$this->equalTo('city'), $this->equalTo('city'),
@ -202,113 +190,113 @@ class OrderCreateTest extends \PHPUnit\Framework\TestCase
->will($this->returnCallback([$this, 'getCallbackDataAddress'])); ->will($this->returnCallback([$this, 'getCallbackDataAddress']));
// store mock set data // store mock set data
$this->_mockStore->expects($this->any()) $this->mockStore->expects($this->any())
->method('getCode') ->method('getCode')
->willReturn(1); ->willReturn(1);
// order item mock set data // order item mock set data
$this->_mockItem->expects($this->any()) $this->mockItem->expects($this->any())
->method('getProductType') ->method('getProductType')
->willReturn('simple'); ->willReturn('simple');
$this->_mockItem->expects($this->any()) $this->mockItem->expects($this->any())
->method('getPrice') ->method('getPrice')
->willReturn(999.99); ->willReturn(999.99);
$this->_mockItem->expects($this->any()) $this->mockItem->expects($this->any())
->method('getProductId') ->method('getProductId')
->willReturn(10); ->willReturn(10);
$this->_mockItem->expects($this->any()) $this->mockItem->expects($this->any())
->method('getName') ->method('getName')
->willReturn('Product name'); ->willReturn('Product name');
$this->_mockItem->expects($this->any()) $this->mockItem->expects($this->any())
->method('getQtyOrdered') ->method('getQtyOrdered')
->willReturn(3); ->willReturn(3);
// order mock set data // order mock set data
$this->_mockOrder->expects($this->any()) $this->mockOrder->expects($this->any())
->method('getId') ->method('getId')
->willReturn($testData['order.id']); ->willReturn($testData['order.id']);
$this->_mockOrder->expects($this->any()) $this->mockOrder->expects($this->any())
->method('getBillingAddress') ->method('getBillingAddress')
->willReturn($this->_mockBillingAddress); ->willReturn($this->mockBillingAddress);
$this->_mockOrder->expects($this->any()) $this->mockOrder->expects($this->any())
->method('getShippingMethod') ->method('getShippingMethod')
->willReturn($testData['order.shippingMethod']); ->willReturn($testData['order.shippingMethod']);
$this->_mockOrder->expects($this->any()) $this->mockOrder->expects($this->any())
->method('getStore') ->method('getStore')
->willReturn($this->_mockStore); ->willReturn($this->mockStore);
$this->_mockOrder->expects($this->any()) $this->mockOrder->expects($this->any())
->method('getRealOrderId') ->method('getRealOrderId')
->willReturn($testData['order.realOrderId']); ->willReturn($testData['order.realOrderId']);
$this->_mockOrder->expects($this->any()) $this->mockOrder->expects($this->any())
->method('getCreatedAt') ->method('getCreatedAt')
->willReturn(date('Y-m-d H:i:s')); ->willReturn(date('Y-m-d H:i:s'));
$this->_mockOrder->expects($this->any()) $this->mockOrder->expects($this->any())
->method('getCustomerLastname') ->method('getCustomerLastname')
->willReturn($testData['order.customerLastname']); ->willReturn($testData['order.customerLastname']);
$this->_mockOrder->expects($this->any()) $this->mockOrder->expects($this->any())
->method('getCustomerFirstname') ->method('getCustomerFirstname')
->willReturn($testData['order.customerFirstname']); ->willReturn($testData['order.customerFirstname']);
$this->_mockOrder->expects($this->any()) $this->mockOrder->expects($this->any())
->method('getCustomerMiddlename') ->method('getCustomerMiddlename')
->willReturn($testData['order.customerMiddlename']); ->willReturn($testData['order.customerMiddlename']);
$this->_mockOrder->expects($this->any()) $this->mockOrder->expects($this->any())
->method('getCustomerEmail') ->method('getCustomerEmail')
->willReturn($testData['order.customerEmail']); ->willReturn($testData['order.customerEmail']);
$this->_mockOrder->expects($this->any()) $this->mockOrder->expects($this->any())
->method('getAllItems') ->method('getAllItems')
->willReturn($testData['order.allItems']); ->willReturn($testData['order.allItems']);
$this->_mockOrder->expects($this->any()) $this->mockOrder->expects($this->any())
->method('getStatus') ->method('getStatus')
->willReturn($testData['order.status']); ->willReturn($testData['order.status']);
$this->_mockOrder->expects($this->any()) $this->mockOrder->expects($this->any())
->method('getCustomerIsGuest') ->method('getCustomerIsGuest')
->willReturn($customerIsGuest); ->willReturn($customerIsGuest);
$this->_mockOrder->expects($this->any()) $this->mockOrder->expects($this->any())
->method('getCustomerId') ->method('getCustomerId')
->willReturn(1); ->willReturn(1);
$this->_mockOrder->expects($this->any()) $this->mockOrder->expects($this->any())
->method('getPayment') ->method('getPayment')
->willReturn($this->_mockPayment); ->willReturn($this->mockPayment);
// mock Payment Method // mock Payment Method
$this->_mockPaymentMethod->expects($this->any()) $this->mockPaymentMethod->expects($this->any())
->method('getCode') ->method('getCode')
->willReturn($testData['order.paymentMethod']); ->willReturn($testData['order.paymentMethod']);
// mock Payment // mock Payment
$this->_mockPayment->expects($this->any()) $this->mockPayment->expects($this->any())
->method('getMethodInstance') ->method('getMethodInstance')
->willReturn($this->_mockPaymentMethod); ->willReturn($this->mockPaymentMethod);
// mock Event // mock Event
$this->_mockEvent->expects($this->once()) $this->mockEvent->expects($this->once())
->method('getOrder') ->method('getOrder')
->willReturn($this->_mockOrder); ->willReturn($this->mockOrder);
// mock Observer // mock Observer
$this->_mockObserver->expects($this->once()) $this->mockObserver->expects($this->once())
->method('getEvent') ->method('getEvent')
->willReturn($this->_mockEvent); ->willReturn($this->mockEvent);
$this->_unit->execute($this->_mockObserver); $this->unit->execute($this->mockObserver);
} }
/** /**
@ -316,7 +304,7 @@ class OrderCreateTest extends \PHPUnit\Framework\TestCase
* *
* @return array $testOrderData * @return array $testOrderData
*/ */
protected function getAfterSaveOrderTestData() private function getAfterSaveOrderTestData()
{ {
$testOrderData = [ $testOrderData = [
'order.id' => 1, 'order.id' => 1,
@ -332,7 +320,7 @@ class OrderCreateTest extends \PHPUnit\Framework\TestCase
'country_id' => 'RU' 'country_id' => 'RU'
] ]
], ],
'order.allItems' => [$this->_mockItem], 'order.allItems' => [$this->mockItem],
'order.shippingMethod' => 'flatrate_flatrate', 'order.shippingMethod' => 'flatrate_flatrate',
'order.paymentMethod' => 'checkmo', 'order.paymentMethod' => 'checkmo',
'order.customerLastname' => 'Test', 'order.customerLastname' => 'Test',

View File

@ -4,17 +4,17 @@ namespace Retailcrm\Retailcrm\Test\Unit\Observer;
class OrderUpdateTest extends \PHPUnit\Framework\TestCase class OrderUpdateTest extends \PHPUnit\Framework\TestCase
{ {
protected $unit; private $unit;
protected $objectManager; private $objectManager;
protected $config; private $config;
protected $mockApi; private $mockApi;
protected $mockObserver; private $mockObserver;
protected $mockEvent; private $mockEvent;
protected $mockOrder; private $mockOrder;
protected $mockPayment; private $mockPayment;
protected $registry; private $registry;
protected function setUp() public function setUp()
{ {
$this->mockApi = $this->getMockBuilder(\Retailcrm\Retailcrm\Helper\Proxy::class) $this->mockApi = $this->getMockBuilder(\Retailcrm\Retailcrm\Helper\Proxy::class)
->disableOriginalConstructor() ->disableOriginalConstructor()
@ -37,10 +37,6 @@ class OrderUpdateTest extends \PHPUnit\Framework\TestCase
$this->objectManager = $this->getMockBuilder(\Magento\Framework\ObjectManagerInterface::class) $this->objectManager = $this->getMockBuilder(\Magento\Framework\ObjectManagerInterface::class)
->getMockForAbstractClass(); ->getMockForAbstractClass();
$helper = $this->getMockBuilder(\Retailcrm\Retailcrm\Helper\Data::class)
->disableOriginalConstructor()
->getMock();
$this->mockOrder = $this->getMockBuilder(\Magento\Sales\Order::class) $this->mockOrder = $this->getMockBuilder(\Magento\Sales\Order::class)
->setMethods([ ->setMethods([
'getId', 'getId',
@ -55,12 +51,6 @@ class OrderUpdateTest extends \PHPUnit\Framework\TestCase
->disableOriginalConstructor() ->disableOriginalConstructor()
->getMock(); ->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) $this->config = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class)
->getMockForAbstractClass(); ->getMockForAbstractClass();
@ -69,15 +59,10 @@ class OrderUpdateTest extends \PHPUnit\Framework\TestCase
->getMock(); ->getMock();
$this->unit = new \Retailcrm\Retailcrm\Model\Observer\OrderUpdate( $this->unit = new \Retailcrm\Retailcrm\Model\Observer\OrderUpdate(
$this->objectManager,
$this->config, $this->config,
$this->registry $this->registry,
$this->mockApi
); );
$reflection = new \ReflectionClass($this->unit);
$reflection_property = $reflection->getProperty('_api');
$reflection_property->setAccessible(true);
$reflection_property->setValue($this->unit, $this->mockApi);
} }
/** /**
@ -133,10 +118,9 @@ class OrderUpdateTest extends \PHPUnit\Framework\TestCase
/** /**
* Get test order data * Get test order data
*
* @return array $testOrderData * @return array $testOrderData
*/ */
protected function getAfterUpdateOrderTestData() private function getAfterUpdateOrderTestData()
{ {
$testOrderData = [ $testOrderData = [
'order.id' => 1, 'order.id' => 1,

View File

@ -13,7 +13,7 @@
], ],
"authors": [ "authors": [
{ {
"name": "Retailcrm", "name": "RetailDriver LLC",
"email": "gorokh@retailcrm.ru", "email": "gorokh@retailcrm.ru",
"homepage": "https://www.retailcrm.ru", "homepage": "https://www.retailcrm.ru",
"role": "Developer" "role": "Developer"

View File

@ -1,11 +1,11 @@
<?xml version="1.0"?> <?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\Framework\Console\CommandList"> <type name="Retailcrm\Retailcrm\Helper\Proxy">
<arguments> <arguments>
<argument name="commands" xsi:type="array"> <argument name="pathUrl" xsi:type="const">Retailcrm\Retailcrm\Api\ConfigManagerInterface::URL_PATH</argument>
<item name="retailcrm_command" xsi:type="object">Retailcrm\Retailcrm\Console\Command\Command</item> <argument name="pathKey" xsi:type="const">Retailcrm\Retailcrm\Api\ConfigManagerInterface::KEY_PATH</argument>
</argument> <argument name="pathVersion" xsi:type="const">Retailcrm\Retailcrm\Api\ConfigManagerInterface::API_VERSION_PATH</argument>
</arguments> </arguments>
</type> </type>
</config> </config>