1
0
mirror of synced 2024-11-25 06:26:07 +03:00

Multiversions api (#8)

This commit is contained in:
Akolzin Dmitry 2018-03-12 16:34:48 +03:00 committed by Alex Lushpai
parent b5bb377379
commit 682fcb8545
37 changed files with 3271 additions and 1950 deletions

View File

@ -1,4 +1,5 @@
<?php
namespace Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Field;
use Magento\Framework\Data\Form\Element\AbstractElement;
@ -13,6 +14,7 @@ class Attributes extends \Magento\Config\Block\System\Config\Form\Field
$html .= '<td><ul id="' . $element->getId() . '_selected" class="ui_select selected sortable">';
$selected = explode(',', $element->getValue());
foreach ($selected as $value) {
if ($key = array_search($value, array_column($values, 'value'))) {
$html .= '<li value="' . $value . '" title="' . $values[$key]['title'] . '">';
@ -24,6 +26,7 @@ class Attributes extends \Magento\Config\Block\System\Config\Form\Field
$html .= '</ul></td><td>';
$html .= '<ul id="' . $element->getId() . '_source" class="ui_select source sortable">';
if ($values) {
foreach ($values as $option) {
if (!isset($option['selected'])) {
@ -57,5 +60,4 @@ class Attributes extends \Magento\Config\Block\System\Config\Form\Field
return $html;
}
}

View File

@ -0,0 +1,16 @@
<?php
namespace Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\ListMode;
class ListMode implements \Magento\Framework\Option\ArrayInterface
{
public function toOptionArray()
{
return [
['value' => 'grid', 'label' => __('Grid Only')],
['value' => 'list', 'label' => __('List Only')],
['value' => 'grid-list', 'label' => __('Grid (default) / List')],
['value' => 'list-grid', 'label' => __('List (default) / Grid')]
];
}
}

View File

@ -1,8 +1,9 @@
<?php
namespace Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Field;
use Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Field\Base;
use Magento\Framework\Data\Form\Element\AbstractElement;
use Retailcrm\Retailcrm\Helper\Proxy as ApiClient;
class Payment extends \Magento\Config\Block\System\Config\Form\Field
{
@ -15,43 +16,38 @@ class Payment extends \Magento\Config\Block\System\Config\Form\Field
public function __construct(
\Magento\Framework\Data\FormFactory $formFactory,
\Magento\Store\Model\System\Store $systemStore
)
{
$om = \Magento\Framework\App\ObjectManager::getInstance();
$logger = $om->get('\Psr\Log\LoggerInterface');
$this->_logger = $logger;
$base = new Base;
$this->_apiUrl = $base->_apiUrl;
$this->_apiKey = $base->_apiKey;
) {
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$config = $objectManager->get('\Magento\Framework\App\Config\ScopeConfigInterface');
$this->_apiUrl = $config->getValue('retailcrm/general/api_url');
$this->_apiKey = $config->getValue('retailcrm/general/api_key');
$this->_apiVersion = $config->getValue('retailcrm/general/api_version');
$this->_systemStore = $systemStore;
$this->_formFactory = $formFactory;
}
public function render(AbstractElement $element)
{
$values = $element->getValues();
$html = '';
$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))) {
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$paymentConfig = $objectManager->get('Magento\Payment\Model\Config');
$activePaymentMethods = $paymentConfig->getActiveMethods();
$client = new \Retailcrm\Retailcrm\Model\ApiClient\ApiClient($this->_apiUrl,$this->_apiKey);
$client = new ApiClient($this->_apiUrl, $this->_apiKey, $this->_apiVersion);
try {
$response = $client->paymentTypesList();
if ($response->isSuccessful()&&200 === $response->getStatusCode()) {
$paymentTypes = $response['paymentTypes'];
if ($response === false) {
return $htmlError;
}
} catch (Retailcrm\Retailcrm\Model\ApiClient\Exception\CurlException $e) {
$this->_logger->addDebug($e->getMessage());
if ($response->isSuccessful()) {
$paymentTypes = $response['paymentTypes'];
} else {
return $htmlError;
}
$config = \Magento\Framework\App\ObjectManager::getInstance()->get(
@ -68,7 +64,6 @@ class Payment extends \Magento\Config\Block\System\Config\Form\Field
$selected = $config->getValue('retailcrm/Payment/' . $payment);
foreach ($paymentTypes as $k => $value){
if ((!empty($selected)) && (($selected == $value['code']))) {
$select = 'selected="selected"';
}else{
@ -77,20 +72,16 @@ class Payment extends \Magento\Config\Block\System\Config\Form\Field
$html .= '<option '.$select.' value="'.$value['code'].'"> '.$value['name'].'</option>';
}
$html .= '</select>';
$html .= '</td>';
$html .= '</tr>';
$html .= '</table>';
}
return $html;
} else {
$html = '<div style="margin-left: 15px;"><b><i>Please check your API Url & API Key</i></b></div>';
return $html;
return $htmlError;
}
}
}

View File

@ -1,8 +1,9 @@
<?php
namespace Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Field;
use Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Field\Base;
use Magento\Framework\Data\Form\Element\AbstractElement;
use Retailcrm\Retailcrm\Helper\Proxy as ApiClient;
class Shipping extends \Magento\Config\Block\System\Config\Form\Field
{
@ -11,46 +12,43 @@ class Shipping extends \Magento\Config\Block\System\Config\Form\Field
protected $_systemStore;
protected $_formFactory;
protected $_logger;
protected $_objectManager;
public function __construct(
\Magento\Framework\Data\FormFactory $formFactory,
\Magento\Store\Model\System\Store $systemStore
)
{
$om = \Magento\Framework\App\ObjectManager::getInstance();
$logger = $om->get('\Psr\Log\LoggerInterface');
$this->_logger = $logger;
$base = new Base;
$this->_apiUrl = $base->_apiUrl;
$this->_apiKey = $base->_apiKey;
) {
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$config = $objectManager->get('\Magento\Framework\App\Config\ScopeConfigInterface');
$this->_apiUrl = $config->getValue('retailcrm/general/api_url');
$this->_apiKey = $config->getValue('retailcrm/general/api_key');
$this->_apiVersion = $config->getValue('retailcrm/general/api_version');
$this->_systemStore = $systemStore;
$this->_formFactory = $formFactory;
$this->_objectManager = $objectManager;
}
public function render(AbstractElement $element)
{
$values = $element->getValues();
$html = '';
$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)) {
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$shipConfig = $objectManager->get('Magento\Shipping\Model\Config');
$shipConfig = $this->_objectManager->get('Magento\Shipping\Model\Config');
$deliveryMethods = $shipConfig->getActiveCarriers();
$client = new \Retailcrm\Retailcrm\Model\ApiClient\ApiClient($this->_apiUrl,$this->_apiKey);
$client = new ApiClient($this->_apiUrl, $this->_apiKey, $this->_apiVersion);
try {
$response = $client->deliveryTypesList();
if ($response->isSuccessful()&&200 === $response->getStatusCode()) {
$deliveryTypes = $response['deliveryTypes'];
if ($response === false) {
return $htmlError;
}
} catch (Retailcrm\Retailcrm\Model\ApiClient\Exception\CurlException $e) {
$this->_logger->addDebug($e->getMessage());
if ($response->isSuccessful()) {
$deliveryTypes = $response['deliveryTypes'];
} else {
return $htmlError;
}
$config = \Magento\Framework\App\ObjectManager::getInstance()->get(
@ -67,7 +65,6 @@ class Shipping extends \Magento\Config\Block\System\Config\Form\Field
$selected = $config->getValue('retailcrm/Shipping/'.$delivery);
foreach ($deliveryTypes as $k => $value) {
if ((!empty($selected)) && (($selected == $value['code']))) {
$select ='selected="selected"';
}else{
@ -76,24 +73,16 @@ class Shipping extends \Magento\Config\Block\System\Config\Form\Field
$html .='<option '.$select.' value="'.$value['code'].'"> '.$value['name'].'</option>';
}
$html .='</select>';
$html .='</td>';
$html .='</tr>';
$html .='</table>';
}
return $html;
} else {
$html .= '<div style="margin-left: 15px;"><b><i>Please check your API Url & API Key</i></b></div>';
return $htmlError;
}
$html = '</div>';
return $html;
}
}

View File

@ -1,8 +1,9 @@
<?php
namespace Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Field;
use Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Field\Base;
use Magento\Framework\Data\Form\Element\AbstractElement;
use Retailcrm\Retailcrm\Helper\Proxy as ApiClient;
class Status extends \Magento\Config\Block\System\Config\Form\Field
{
@ -11,50 +12,46 @@ class Status extends \Magento\Config\Block\System\Config\Form\Field
protected $_systemStore;
protected $_formFactory;
protected $_logger;
protected $_objectManager;
public function __construct(
\Magento\Framework\Data\FormFactory $formFactory,
\Magento\Store\Model\System\Store $systemStore
)
{
$om = \Magento\Framework\App\ObjectManager::getInstance();
$logger = $om->get('\Psr\Log\LoggerInterface');
$this->_logger = $logger;
$base = new Base;
$this->_apiUrl = $base->_apiUrl;
$this->_apiKey = $base->_apiKey;
) {
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$config = $objectManager->get('\Magento\Framework\App\Config\ScopeConfigInterface');
$this->_apiUrl = $config->getValue('retailcrm/general/api_url');
$this->_apiKey = $config->getValue('retailcrm/general/api_key');
$this->_apiVersion = $config->getValue('retailcrm/general/api_version');
$this->_systemStore = $systemStore;
$this->_formFactory = $formFactory;
$this->_objectManager = $objectManager;
}
public function render(AbstractElement $element)
{
$values = $element->getValues();
$html = '';
$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))) {
$manager = \Magento\Framework\App\ObjectManager::getInstance();
$obj = $manager->create('Magento\Sales\Model\ResourceModel\Order\Status\Collection');
$statuses = $obj->toOptionArray();
$statusCollection = $this->_objectManager->create('Magento\Sales\Model\ResourceModel\Order\Status\Collection');
$statuses = $statusCollection->toOptionArray();
$client = new \Retailcrm\Retailcrm\Model\ApiClient\ApiClient($this->_apiUrl,$this->_apiKey);
$client = new ApiClient($this->_apiUrl, $this->_apiKey, $this->_apiVersion);
try {
$response = $client->statusesList();
if ($response->isSuccessful()&&200 === $response->getStatusCode()) {
$statusTypes = $response['statuses'];
}
} catch (Retailcrm\Retailcrm\Model\ApiClient\Exception\CurlException $e) {
$this->_logger->addDebug($e->getMessage());
if ($response === false) {
return $htmlError;
}
$config = \Magento\Framework\App\ObjectManager::getInstance()->get(
'Magento\Framework\App\Config\ScopeConfigInterface'
);
if ($response->isSuccessful()) {
$statusTypes = $response['statuses'];
} else {
return $htmlError;
}
$config = $this->_objectManager->get('Magento\Framework\App\Config\ScopeConfigInterface');
foreach ($statuses as $k => $status){
$html .= '<table id="' . $element->getId() . '_table">';
@ -66,9 +63,13 @@ class Status extends \Magento\Config\Block\System\Config\Form\Field
$selected = $config->getValue('retailcrm/Status/' . $status['value']);
$html .= '<option value=""> Select status </option>';
foreach ($statusTypes as $k=>$value){
if((!empty($selected))&&(($selected==$value['name']))||(($selected==$value['code']))){
foreach ($statusTypes as $k => $value){
if (
(!empty($selected))
&& (($selected == $value['name']))
|| (($selected == $value['code']))
) {
$select = 'selected="selected"';
} else {
$select = '';
@ -80,17 +81,11 @@ class Status extends \Magento\Config\Block\System\Config\Form\Field
$html .= '</td>';
$html .= '</tr>';
$html .= '</table>';
}
return $html;
} else {
$html = '<div style="margin-left: 15px;"><b><i>Please check your API Url & API Key</i></b></div>';
return $html;
return $htmlError;
}
}
}

View File

@ -1,5 +1,7 @@
<?php
namespace Retailcrm\Retailcrm\Block;
class Display extends \Magento\Framework\View\Element\Template
{
public function __construct(\Magento\Framework\View\Element\Template\Context $context)
@ -9,9 +11,6 @@ class Display extends \Magento\Framework\View\Element\Template
public function sayHello()
{
return __('Hello World');
}
}

View File

@ -1,13 +1,15 @@
<?php
namespace Retailcrm\Retailcrm\Controller\Index;
class Display extends \Magento\Framework\App\Action\Action
{
protected $_pageFactory;
public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Framework\View\Result\PageFactory $pageFactory)
{
\Magento\Framework\View\Result\PageFactory $pageFactory
) {
$this->_pageFactory = $pageFactory;
return parent::__construct($context);
}

View File

@ -10,12 +10,11 @@ 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
)
{
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');
@ -34,5 +33,4 @@ class Test extends \Magento\Framework\App\Action\Action
//
exit;
}
}

View File

@ -1,20 +1,19 @@
<?php
namespace Retailcrm\Retailcrm\Cron;
class Icml {
protected $_logger;
public function __construct() {
$om = \Magento\Framework\App\ObjectManager::getInstance();
$logger = $om->get('\Psr\Log\LoggerInterface');
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$logger = new \Retailcrm\Retailcrm\Model\Logger\Logger($objectManager);
$this->_logger = $logger;
}
public function execute() {
public function execute()
{
$Icml = new \Retailcrm\Retailcrm\Model\Icml\Icml();
$Icml->generate();
$this->_logger->addDebug('Cron Works: create icml');
}
}

View File

@ -1,20 +1,23 @@
<?php
namespace Retailcrm\Retailcrm\Cron;
class OrderHistory {
class OrderHistory
{
protected $_logger;
public function __construct() {
public function __construct()
{
$om = \Magento\Framework\App\ObjectManager::getInstance();
$logger = $om->get('\Psr\Log\LoggerInterface');
$logger = new \Retailcrm\Retailcrm\Model\Logger\Logger($om);
$this->_logger = $logger;
}
public function execute() {
public function execute()
{
$history = new \Retailcrm\Retailcrm\Model\History\Exchange();
$history->ordersHistory();
$this->_logger->addDebug('Cron Works: OrderHistory');
$this->_logger->writeRow('Cron Works: OrderHistory');
}
}

View File

@ -1,4 +1,5 @@
<?php
namespace Retailcrm\Retailcrm\Helper;
use Magento\Framework\App\Helper\AbstractHelper;

81
Helper/Proxy.php Normal file
View File

@ -0,0 +1,81 @@
<?php
namespace Retailcrm\Retailcrm\Helper;
use RetailCrm\ApiClient;
use Magento\Framework\App\ObjectManager;
use Retailcrm\Retailcrm\Model\Logger\Logger;
class Proxy
{
protected $logger;
protected $apiClient;
private $errorAccount = 'Account does not exist.';
private $errorNotFound = 'Not found';
private $errorApiKey = 'Wrong "apiKey" value.';
public function __construct ($url, $key, $apiVersion)
{
$objectManager = ObjectManager::getInstance();
$this->logger = new Logger($objectManager);
$this->apiClient = new ApiClient($url, $key, $apiVersion);
}
public function __call($method, $arguments)
{
try {
$response = call_user_func_array([$this->apiClient->request, $method], $arguments);
if (!$response->isSuccessful()) {
$this->logger->writeRow(
sprintf(
"[HTTP status %s] %s",
$response->getStatusCode(),
$response->getErrorMsg()
)
);
if (isset($response['errors'])) {
$this->logger->writeRow(implode(' :: ', $response['errors']));
}
}
} catch (\RetailCrm\Exception\CurlException $exception) {
$this->logger->writeRow($exception->getMessage());
return false;
} catch (\RetailCrm\Exception\InvalidJsonException $exception) {
$this->logger->writeRow($exception->getMessage());
return false;
} catch (\InvalidArgumentException $exception) {
$this->logger->writeRow($exception->getMessage());
}
return $response;
}
/**
* Get API version
*
* @return string
*/
public function getVersion()
{
if (!is_object($this->apiClient)) {
return false;
}
return $this->apiClient->getVersion();
}
/**
* Get error text message
*
* @param string $property
*
* @return string
*/
public function getErrorText($property)
{
return $this->{$property};
}
}

View File

@ -0,0 +1,138 @@
<?php
namespace Retailcrm\Retailcrm\Model\Config\Backend;
use Retailcrm\Retailcrm\Helper\Proxy as ApiClient;
class ApiUrl extends \Magento\Framework\App\Config\Value
{
/**
* @param \Magento\Framework\Model\Context $context
* @param \Magento\Framework\Registry $registry
* @param \Magento\Framework\App\Config\ScopeConfigInterface $config
* @param \Magento\Framework\App\Cache\TypeListInterface $cacheTypeList
* @param \Magento\Framework\App\Config\ValueFactory $configValueFactory
* @param \Magento\Framework\Model\ResourceModel\AbstractResource $resource
* @param \Magento\Framework\Data\Collection\AbstractDb $resourceCollection
* @param string $runModelPath
* @param array $data
*/
public function __construct(
\Magento\Framework\Model\Context $context,
\Magento\Framework\Registry $registry,
\Magento\Framework\App\Config\ScopeConfigInterface $config,
\Magento\Framework\App\Cache\TypeListInterface $cacheTypeList,
\Magento\Framework\Model\ResourceModel\AbstractResource $resource = null,
\Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null,
array $data = []
) {
parent::__construct($context, $registry, $config, $cacheTypeList, $resource, $resourceCollection, $data);
}
/**
* Call before save api url
*
* @return void
*/
public function beforeSave()
{
$apiUrl = $this->getValue();
$apiKey = $this->getFieldsetDataValue('api_key');
$apiVersion = $this->getFieldsetDataValue('api_version');
if (!$this->isUrl($apiUrl)) {
throw new \Magento\Framework\Exception\ValidatorException(__('Invalid CRM url'));
}
if (!$this->isHttps($apiUrl)) {
$this->schemeEdit($apiUrl);
}
$api = new ApiClient($apiUrl, $apiKey, $apiVersion);
if ($this->validateApiUrl($api)) {
$this->setValue($apiUrl);
}
parent::beforeSave();
}
/**
* Call after save api url
*
* @return void
*/
public function afterSave()
{
return parent::afterSave();
}
/**
* Validate selected api url
*
* @param ApiClient $api
* @param string $apiVersion
*
* @throws \Magento\Framework\Exception\ValidatorException
*
* @return boolean
*/
protected function validateApiUrl(ApiClient $api)
{
$response = $api->availableVersions();
if ($response === false) {
throw new \Magento\Framework\Exception\ValidatorException(__('Verify that the data entered is correct'));
} elseif (!$response->isSuccessful() && $response['errorMsg'] == $api->getErrorText ('errorApiKey')) {
throw new \Magento\Framework\Exception\ValidatorException(__('Invalid CRM api key'));
} elseif (isset($response['errorMsg']) && $response['errorMsg'] == $api->getErrorText('errorAccount')) {
throw new \Magento\Framework\Exception\ValidatorException(__('Invalid CRM api url'));
}
return true;
}
/**
* Check url scheme
*
* @param string $url
*
* @return boolean
*/
protected function isHttps($url)
{
$url_array = parse_url($url);
if ($url_array['scheme'] === 'https') {
return true;
} else {
return false;
}
}
/**
* Edit scheme from http to https
*
* @param string $url
*
* @return string
*/
protected function schemeEdit(&$url)
{
$url_array = parse_url($url);
$url = 'https://' . $url_array['host'];
}
/**
* Check url
*
* @param string $url
*
* @return type
*/
public function isUrl($url)
{
return preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $url);
}
}

View File

@ -0,0 +1,93 @@
<?php
namespace Retailcrm\Retailcrm\Model\Config\Backend;
use Retailcrm\Retailcrm\Helper\Proxy as ApiClient;
class ApiVersion extends \Magento\Framework\App\Config\Value
{
/**
* @param \Magento\Framework\Model\Context $context
* @param \Magento\Framework\Registry $registry
* @param \Magento\Framework\App\Config\ScopeConfigInterface $config
* @param \Magento\Framework\App\Cache\TypeListInterface $cacheTypeList
* @param \Magento\Framework\App\Config\ValueFactory $configValueFactory
* @param \Magento\Framework\Model\ResourceModel\AbstractResource $resource
* @param \Magento\Framework\Data\Collection\AbstractDb $resourceCollection
* @param string $runModelPath
* @param array $data
*/
public function __construct(
\Magento\Framework\Model\Context $context,
\Magento\Framework\Registry $registry,
\Magento\Framework\App\Config\ScopeConfigInterface $config,
\Magento\Framework\App\Cache\TypeListInterface $cacheTypeList,
\Magento\Framework\Model\ResourceModel\AbstractResource $resource = null,
\Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null,
array $data = []
) {
parent::__construct($context, $registry, $config, $cacheTypeList, $resource, $resourceCollection, $data);
}
/**
* Call before save api version
*
* @return void
*/
public function beforeSave()
{
$apiUrl = $this->getFieldsetDataValue('api_url');
$apiKey = $this->getFieldsetDataValue('api_key');
$apiVersion = $this->getValue();
$api = new ApiClient($apiUrl, $apiKey, $apiVersion);
$this->validateApiVersion($api, $apiVersion);
parent::beforeSave();
}
/**
* Call after save api version
*
* @return void
*/
public function afterSave()
{
return parent::afterSave();
}
/**
* Validate selected api version
*
* @param ApiClient $api
* @param string $apiVersion
*
* @throws \Magento\Framework\Exception\ValidatorException
*
* @return void
*/
protected function validateApiVersion(ApiClient $api, $apiVersion)
{
$apiVersions = [
'v4' => '4.0',
'v5' => '5.0'
];
$response = $api->availableVersions();
if ($response->isSuccessful()) {
$availableVersions = $response['versions'];
} else {
throw new \Magento\Framework\Exception\ValidatorException(__('Invalid CRM url or api key'));
}
if (isset($availableVersions)) {
if (in_array($apiVersions[$apiVersion], $availableVersions)) {
$this->setValue($this->getValue());
} else {
throw new \Magento\Framework\Exception\ValidatorException(__('Selected api version forbidden'));
}
}
}
}

View File

@ -1,6 +1,9 @@
<?php
namespace Retailcrm\Retailcrm\Model\History;
use Retailcrm\Retailcrm\Helper\Proxy as ApiClient;
class Exchange
{
protected $_api;
@ -21,29 +24,28 @@ class Exchange
//protected $_transaction;
//protected $_invoiceService;
protected $_eventManager;
protected $_objectManager;
public function __construct()
{
$om = \Magento\Framework\App\ObjectManager::getInstance();
$helper = $om->get('\Retailcrm\Retailcrm\Helper\Data');
$logger = $om->get('\Psr\Log\LoggerInterface');
$config = $om->get('\Magento\Framework\App\Config\ScopeConfigInterface');
$resourceConfig = $om->get('Magento\Config\Model\ResourceModel\Config');
$customerFactory = $om->get('\Magento\Customer\Model\CustomerFactory');
$quote = $om->get('\Magento\Quote\Model\QuoteFactory');
$customerRepository = $om->get('\Magento\Customer\Api\CustomerRepositoryInterface');
$product = $om->get('\Magento\Catalog\Model\Product');
$shipconfig = $om->get('\Magento\Shipping\Model\Config');
$quoteManagement = $om->get('\Magento\Quote\Model\QuoteManagement');
$registry = $om->get('\Magento\Framework\Registry');
$cacheTypeList = $om->get('\Magento\Framework\App\Cache\TypeListInterface');
$order = $om->get('\Magento\Sales\Api\Data\OrderInterface');
$orderManagement = $om->get('\Magento\Sales\Api\OrderManagementInterface');
//$invoiceService = $om->get('\Magento\Sales\Model\Service\InvoiceService');
//$transaction = $om->get('\Magento\Framework\DB\Transaction');
$eventManager = $om->get('\Magento\Framework\Event\Manager');
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$helper = $objectManager->get('\Retailcrm\Retailcrm\Helper\Data');
$config = $objectManager->get('\Magento\Framework\App\Config\ScopeConfigInterface');
$resourceConfig = $objectManager->get('Magento\Config\Model\ResourceModel\Config');
$customerFactory = $objectManager->get('\Magento\Customer\Model\CustomerFactory');
$quote = $objectManager->get('\Magento\Quote\Model\QuoteFactory');
$customerRepository = $objectManager->get('\Magento\Customer\Api\CustomerRepositoryInterface');
$product = $objectManager->get('\Magento\Catalog\Model\Product');
$shipconfig = $objectManager->get('\Magento\Shipping\Model\Config');
$quoteManagement = $objectManager->get('\Magento\Quote\Model\QuoteManagement');
$registry = $objectManager->get('\Magento\Framework\Registry');
$cacheTypeList = $objectManager->get('\Magento\Framework\App\Cache\TypeListInterface');
$order = $objectManager->get('\Magento\Sales\Api\Data\OrderInterface');
$orderManagement = $objectManager->get('\Magento\Sales\Api\OrderManagementInterface');
//$invoiceService = $objectManager->get('\Magento\Sales\Model\Service\InvoiceService');
//$transaction = $objectManager->get('\Magento\Framework\DB\Transaction');
$eventManager = $objectManager->get('\Magento\Framework\Event\Manager');
$logger = new \Retailcrm\Retailcrm\Model\Logger\Logger($objectManager);
$this->_shipconfig = $shipconfig;
$this->_logger = $logger;
@ -62,119 +64,122 @@ class Exchange
//$this->_transaction = $transaction;
//$this->_invoiceService = $invoiceService;
$this->_eventManager = $eventManager;
$this->_objectManager = $objectManager;
$url = $config->getValue('retailcrm/general/api_url');
$key = $config->getValue('retailcrm/general/api_key');
$version = $config->getValue('retailcrm/general/api_version');
if (!empty($url) && !empty($key)) {
$this->_api = new \Retailcrm\Retailcrm\Model\ApiClient\ApiClient($url,$key);
$this->_api = new ApiClient($url, $key, $version);
}
}
/**
* Get orders history from CRM
*
* @return boolean
*/
public function ordersHistory()
{
$historyFilter = array();
$historiOrder = array();
$this->_registry->register('RETAILCRM_HISTORY', true);
$historyFilter = [];
$historyOrder = [];
$historyStart = $this->_config->getValue('retailcrm/general/filter_history');
if ($historyStart && $historyStart > 0) {
$historyFilter['sinceId'] = $historyStart;
}
while (true) {
try {
$response = $this->_api->ordersHistory($historyFilter);
if ($response->isSuccessful()&&200 === $response->getStatusCode()) {
$nowTime = $response->getGeneratedAt();
} else {
$this->_logger->addDebug(
sprintf("Orders history error: [HTTP status %s] %s", $response->getStatusCode(), $response->getErrorMsg())
);
if (isset($response['errors'])) {
$this->_logger->addDebug(implode(' :: ', $response['errors']));
if ($response === false) {
return;
}
return false;
}
} catch (\Retailcrm\Retailcrm\Model\ApiClient\Exception\CurlException $e) {
$this->_logger->addDebug($e->getMessage());
return false;
if (!$response->isSuccessful()) {
return true;
}
$orderH = isset($response['history']) ? $response['history'] : array();
$orderH = isset($response['history']) ? $response['history'] : [];
if (count($orderH) == 0) {
return true;
}
$historiOrder = array_merge($historiOrder, $orderH);
$end = array_pop($response->history);
$historyOrder = array_merge($historyOrder, $orderH);
$end = array_pop($orderH);
$historyFilter['sinceId'] = $end['id'];
if ($response['pagination']['totalPageCount'] == 1) {
$this->_resourceConfig->saveConfig('retailcrm/general/filter_history', $historyFilter['sinceId'], 'default', 0);
$this->_cacheTypeList->cleanType('config');
$orders = self::assemblyOrder($historiOrder);
$orders = self::assemblyOrder($historyOrder);
$logger = new \Retailcrm\Retailcrm\Model\Logger\Logger();
$logger->write($orders,'OrderHistory');
$this->_logger->writeDump($orders,'OrderHistory');
$this->processOrders($orders, $nowTime);
$this->processOrders($orders);
return true;
}
}//endwhile
$this->_registry->register('RETAILCRM_HISTORY', false);
}
/**
* Process orders
*
* @param array $orders
*
* @return void
*/
private function processOrders($orders, $time)
private function processOrders($orders)
{
$logger = new \Retailcrm\Retailcrm\Model\Logger\Logger();
$logger->write($orders,'processOrders');
$this->_logger->writeDump($orders,'processOrders');
if (!empty($orders)) {
foreach ($orders as $order) {
if(!empty($order['externalId'])) {
if (isset($order['externalId']) && !empty($order['externalId'])) {
$this->doUpdate($order);
} else {
$this->doCreate($order);
}
}
die();
}
}
/**
* Create new order from CRM
*
* @param array $order
*
* @return void
*/
private function doCreate($order)
{
$logger = new \Retailcrm\Retailcrm\Model\Logger\Logger();
$logger->write($order,'doCreate');
$this->_logger->writeDump($order,'doCreate');
$payments = $this->_config->getValue('retailcrm/Payment');
$shippings = $this->_config->getValue('retailcrm/Shipping');
$om = \Magento\Framework\App\ObjectManager::getInstance();
$manager = $om->get('Magento\Store\Model\StoreManagerInterface');
$manager = $this->_objectManager->get('Magento\Store\Model\StoreManagerInterface');
$region = $this->_objectManager->get('Magento\Directory\Model\RegionFactory')->create();
$store = $manager->getStore();
$websiteId = $manager->getStore()->getWebsiteId();
$customer = $this->_customerFactory->create();
$customer->setWebsiteId($websiteId);
$customer->loadByEmail($order['email']);// load customet by email address
if(!$customer->getEntityId()){
if (isset($order['customer']['externalId'])) {
$customer->load($order['customer']['externalId']);
}
if (!$customer->getId()) {
//If not avilable then create this customer
$customer->setWebsiteId($websiteId)
->setStore($store)
@ -184,9 +189,18 @@ class Exchange
->setPassword($order['email']);
try {
$customer->save();
} catch (Exception $e) {
$this->_logger->addDebug($e->getMessage());
} catch (\Exception $exception) {
$this->_logger->writeRow($exception->getMessage());
}
$this->_api->customersFixExternalIds(
[
[
'id' => $order['customer']['id'],
'externalId' => $customer->getId()
]
]
);
}
//Create object of quote
@ -196,7 +210,7 @@ class Exchange
$quote->setStore($store);
// if you have allready buyer id then you can load customer directly
$customer = $this->_customerRepository->getById($customer->getEntityId());
$customer = $this->_customerRepository->getById($customer->getId());
$quote->setCurrency();
$quote->assignCustomer($customer); //Assign quote to customer
@ -210,27 +224,34 @@ class Exchange
);
}
$products = array();
$products = [];
foreach ($order['items'] as $item) {
$products[$item['offer']['externalId']] = array('qty' => $item['quantity']);
$products[$item['offer']['externalId']] = ['qty' => $item['quantity']];
}
$orderData = array(
'currency_id' => 'USD',
$orderData = [
'currency_id' => $manager->getStore()->getCurrentCurrency()->getCode(),
'email' => $order['email'],
'shipping_address' =>array(
'shipping_address' => [
'firstname' => $order['firstName'],
'lastname' => $order['lastName'],
'street' => $order['delivery']['address']['street'],
'city' => $order['delivery']['address']['city'],
'country_id' => $order['delivery']['address']['countryIso'],//US
'country_id' => $order['countryIso'],
'region' => $order['delivery']['address']['region'],
'postcode' => $order['delivery']['address']['index'],
'telephone' => $order['phone'],
'save_in_address_book' => 1
),
],
'items'=> $products
);
];
$region->loadByName($order['delivery']['address']['region'], $order['countryIso']);
if ($region->getId()) {
$orderData['shipping_address']['region_id'] = $region->getId();
}
$shippings = array_flip(array_filter($shippings));
$payments = array_flip(array_filter($payments));
@ -246,13 +267,21 @@ class Exchange
->collectShippingRates()
->setShippingMethod($ShippingMethods);
$quote->setPaymentMethod($payments[$order['paymentType']]);
if ($this->_api->getVersion() == 'v4') {
$paymentType = $order['paymentType'];
} elseif ($this->_api->getVersion() == 'v5') {
if ($order['payments']) {
$paymentType = $this->getPaymentMethod($order['payments']);
}
}
$quote->setPaymentMethod($payments[$paymentType]);
$quote->setInventoryProcessed(false);
$quote->save();
// Set Sales Order Payment
$quote->getPayment()->importData(['method' => $payments[$order['paymentType']]]);
$quote->getPayment()->importData(['method' => $payments[$paymentType]]);
// Collect Totals & Save Quote
$quote->collectTotals()->save();
@ -260,99 +289,52 @@ class Exchange
// Create Order From Quote
$magentoOrder = $this->_quoteManagement->submit($quote);
try {
$increment_id = $magentoOrder->getRealOrderId();
} catch (\Retailcrm\Retailcrm\Model\ApiClient\Exception\CurlException $e) {
$this->_logger->addDebug($e->getMessage());
}
$increment_id = $magentoOrder->getId();
try {
$response = $this->_api->ordersFixExternalIds(
array(
array(
$this->_api->ordersFixExternalIds(
[
[
'id' => $order['id'],
'externalId' => $increment_id
)
)
]
]
);
if (!$response->isSuccessful() || 200 !== $response->getStatusCode()) {
$this->_logger->addDebug(
sprintf(
"Orders fix error: [HTTP status %s] %s",
$response->getStatusCode(),
$response->getErrorMsg()
)
);
if (isset($response['errors'])) {
$this->_logger->addDebug(implode(' :: ', $response['errors']));
}
}
} catch (\Retailcrm\Retailcrm\Model\ApiClient\Exception\CurlException $e) {
$this->_logger->addDebug($e->getMessage());
}
}
/**
* Create old edited order
*
* @param array $order
*
* @return void
*/
private function doCreateUp($order)
{
$logger = new \Retailcrm\Retailcrm\Model\Logger\Logger();
$logger->write($order,'doCreateUp');
$this->_logger->writeDump($order,'doCreateUp');
try {
$response = $this->_api->ordersGet($order['id'], $by = 'id');
if ($response->isSuccessful() && 200 === $response->getStatusCode()) {
$order = $response->order;
} else {
$this->_logger->addDebug(
sprintf(
"Orders get error: [HTTP status %s] %s",
$response->getStatusCode(),
$response->getErrorMsg()
)
);
if (isset($response['errors'])) {
$this->_logger->addDebug(implode(' :: ', $response['errors']));
}
}
} catch (Retailcrm_Retailcrm_Model_Exception_CurlException $e) {
$this->_logger->addDebug($e->getMessage());
if (!$response->isSuccessful()) {
return;
}
if (isset($response['order'])) {
$order = $response['order'];
}
$payments = $this->_config->getValue('retailcrm/Payment');
$shippings = $this->_config->getValue('retailcrm/Shipping');
$om = \Magento\Framework\App\ObjectManager::getInstance();
$manager = $om->get('Magento\Store\Model\StoreManagerInterface');
$manager = $this->_objectManager->get('Magento\Store\Model\StoreManagerInterface');
$region = $this->_objectManager->get('Magento\Directory\Model\RegionFactory')->create();
$store = $manager->getStore();
$websiteId = $manager->getStore()->getWebsiteId();
$customer = $this->_customerFactory->create();
$customer->setWebsiteId($websiteId);
$customer->loadByEmail($order['email']);// load customet by email address
if(!$customer->getEntityId()){
//If not avilable then create this customer
$customer->setWebsiteId($websiteId)
->setStore($store)
->setFirstname($order['firstName'])
->setLastname($order['lastName'])
->setEmail($order['email'])
->setPassword($order['email']);
try {
$customer->save();
} catch (Exception $e) {
$this->_logger->addDebug($e->getMessage());
}
if (isset($order['customer']['externalId'])) {
$customer->load($order['customer']['externalId']); // load customet by external id
}
//Create object of quote
@ -360,11 +342,16 @@ class Exchange
//set store for which you create quote
$quote->setStore($store);
$quote->setCurrency();
// if you have allready buyer id then you can load customer directly
$customer = $this->_customerRepository->getById($customer->getEntityId());
$quote->setCurrency();
if ($customer->getId()) {
$customer = $this->_customerRepository->getById($customer->getId());
$quote->assignCustomer($customer); //Assign quote to customer
} else {
$quote->setCustomerEmail($order['email']);
$quote->setCustomerIsGuest(1);
}
//add items in quote
foreach($order['items'] as $item){
@ -376,27 +363,34 @@ class Exchange
);
}
$products = array();
$products = [];
foreach ($order['items'] as $item) {
$products[$item['offer']['externalId']] = array('qty' => $item['quantity']);
$products[$item['offer']['externalId']] = ['qty' => $item['quantity']];
}
$orderData = array(
'currency_id' => 'USD',
$orderData = [
'currency_id' => $manager->getStore()->getCurrentCurrency()->getCode(),
'email' => $order['email'],
'shipping_address' =>array(
'firstname' => $order['firstName'],
'lastname' => $order['lastName'],
'street' => $order['delivery']['address']['street'],
'city' => $order['delivery']['address']['city'],
'country_id' => $order['delivery']['address']['countryIso'],//US
'country_id' => $order['countryIso'],//US
'region' => $order['delivery']['address']['region'],
'postcode' => $order['delivery']['address']['index'],
'telephone' => $order['phone'],
'save_in_address_book' => 1
),
'items'=> $products
);
];
$region->loadByName($order['delivery']['address']['region'], $order['countryIso']);
if ($region->getId()) {
$orderData['shipping_address']['region_id'] = $region->getId();
}
$shippings = array_flip(array_filter($shippings));
$payments = array_flip(array_filter($payments));
@ -412,95 +406,70 @@ class Exchange
->collectShippingRates()
->setShippingMethod($ShippingMethods);
$quote->setPaymentMethod($payments[$order['paymentType']]);
if ($this->_api->getVersion() == 'v4') {
$paymentType = $order['paymentType'];
} elseif ($this->_api->getVersion() == 'v5') {
$paymentType = $this->getPaymentMethod($order['payments'], false);
}
$quote->setPaymentMethod($payments[$paymentType]);
$quote->setInventoryProcessed(false);
$originalId = $order['externalId'];
$oldOrder = $this->_order->loadByIncrementId($originalId);
$oldOrderArr = $oldOrder->getData();
$oldOrder = $this->_order->load($originalId);
if(!empty($oldOrderArr['original_increment_id'])) {
$originalId = $oldOrderArr['original_increment_id'];
}
$orderDataUp = array(
'original_increment_id' => $originalId,
$orderDataUp = [
'original_increment_id' => $oldOrder->getIncrementId(),
'relation_parent_id' => $oldOrder->getId(),
'relation_parent_real_id' => $oldOrder->getIncrementId(),
'edit_increment' => $oldOrder->getEditIncrement() + 1,
'increment_id' => $originalId.'-'.($oldOrder->getEditIncrement()+1)
);
print_r($orderDataUp);
'increment_id' => $oldOrder->getIncrementId() . '-' . ($oldOrder->getEditIncrement() + 1)
];
$quote->setReservedOrderId($orderDataUp['increment_id']);
$quote->save();
// Set Sales Order Payment
$quote->getPayment()->importData(['method' => $payments[$order['paymentType']]]);
$quote->getPayment()->importData(['method' => $payments[$paymentType]]);
// Collect Totals & Save Quote
$quote->collectTotals()->save();
// Create Order From Quote
$magentoOrder = $this->_quoteManagement->submit($quote,$orderDataUp);
$oldOrder->setStatus('canceled')->save();
$increment_id = $magentoOrder->getId();
try {
$increment_id = $magentoOrder->getRealOrderId();
} catch (\Retailcrm\Retailcrm\Model\ApiClient\Exception\CurlException $e) {
$this->_logger->addDebug($e->getMessage());
}
try {
$response = $this->_api->ordersFixExternalIds(
array(
array(
$this->_api->ordersFixExternalIds(
[
[
'id' => $order['id'],
'externalId' => $increment_id
)
)
]
]
);
if (!$response->isSuccessful() || 200 !== $response->getStatusCode()) {
$this->_logger->addDebug(
sprintf(
"Orders fix error: [HTTP status %s] %s",
$response->getStatusCode(),
$response->getErrorMsg()
)
);
if (isset($response['errors'])) {
$this->_logger->addDebug(implode(' :: ', $response['errors']));
}
}
} catch (\Retailcrm\Retailcrm\Model\ApiClient\Exception\CurlException $e) {
$this->_logger->addDebug($e->getMessage());
}
}
/**
* Edit order
*
* @param array $order
*
* @return void
*/
private function doUpdate($order)
{
$logger = new \Retailcrm\Retailcrm\Model\Logger\Logger();
$logger->write($order,'doUpdate');
$this->_logger->writeDump($order,'doUpdate');
$Status = $this->_config->getValue('retailcrm/Status');
$Status = array_flip(array_filter($Status));
$magentoOrder = $this->_order->loadByIncrementId($order['externalId']);
$magentoOrder = $this->_order->load($order['externalId']);
$magentoOrderArr = $magentoOrder->getData();
$logger->write($magentoOrderArr,'magentoOrderArr');
$logger->write($Status,'status');
$this->_logger->writeDump($magentoOrderArr, 'magentoOrderArr');
$this->_logger->writeDump($Status, 'status');
if ((!empty($order['order_edit'])) && ($order['order_edit'] == 1)) {
$this->doCreateUp($order);
@ -514,99 +483,95 @@ class Exchange
}
if($change == 'holded'){
$om = \Magento\Framework\App\ObjectManager::getInstance();
$order_status = $om->get('Magento\Sales\Model\Order')->load($magentoOrder->getId());
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$order_status = $objectManager->get('Magento\Sales\Model\Order')->load($magentoOrder->getId());
$order_status->setStatus('holded');
$order_status->save();
}
if(($change == 'complete')||($order['status']== 'complete')){
$om = \Magento\Framework\App\ObjectManager::getInstance();
$order_status = $om->get('Magento\Sales\Model\Order')->load($magentoOrder->getId());
$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'){
$om = \Magento\Framework\App\ObjectManager::getInstance();
$order_status = $om->get('Magento\Sales\Model\Order')->load($magentoOrder->getId());
$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'){
$om = \Magento\Framework\App\ObjectManager::getInstance();
$order_status = $om->get('Magento\Sales\Model\Order')->load($magentoOrder->getId());
$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'){
$om = \Magento\Framework\App\ObjectManager::getInstance();
$order_status = $om->get('Magento\Sales\Model\Order')->load($magentoOrder->getId());
$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'){
$om = \Magento\Framework\App\ObjectManager::getInstance();
$order_status = $om->get('Magento\Sales\Model\Order')->load($magentoOrder->getId());
$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'){
$om = \Magento\Framework\App\ObjectManager::getInstance();
$order_status = $om->get('Magento\Sales\Model\Order')->load($magentoOrder->getId());
$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'){
$om = \Magento\Framework\App\ObjectManager::getInstance();
$order_status = $om->get('Magento\Sales\Model\Order')->load($magentoOrder->getId());
$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'){
$om = \Magento\Framework\App\ObjectManager::getInstance();
$order_status = $om->get('Magento\Sales\Model\Order')->load($magentoOrder->getId());
$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'){
$om = \Magento\Framework\App\ObjectManager::getInstance();
$order_status = $om->get('Magento\Sales\Model\Order')->load($magentoOrder->getId());
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$order_status = $objectManager->get('Magento\Sales\Model\Order')->load($magentoOrder->getId());
$order_status->setStatus('pending_paypal');
$order_status->save();
}
}
}
}
/**
* Assembly orders from history
*
* @param array $orderHistory
*
* @return array $orders
*/
public static function assemblyOrder($orderHistory)
{
$orders = array();
$orders = [];
foreach ($orderHistory as $change) {
$change['order'] = self::removeEmpty($change['order']);
if (isset($change['order']['items'])) {
$items = array();
$items = [];
foreach ($change['order']['items'] as $item) {
if (isset($change['created'])) {
$item['create'] = 1;
@ -618,10 +583,6 @@ class Exchange
$change['order']['items'] = $items;
}
$logger = new \Retailcrm\Retailcrm\Model\Logger\Logger();
$logger->write($change,'retailcrmHistoryAssemblyOrder');
if (isset($change['order']['contragent']['contragentType'])) {
$change['order']['contragentType'] = self::newValue($change['order']['contragent']['contragentType']);
unset($change['order']['contragent']);
@ -629,8 +590,7 @@ class Exchange
if (isset($orders[$change['order']['id']])) {
$orders[$change['order']['id']] = array_merge($orders[$change['order']['id']], $change['order']);
}
else {
} else {
$orders[$change['order']['id']] = $change['order'];
}
@ -638,22 +598,22 @@ class Exchange
$orders[$change['order']['id']][$change['field']] = $change['newValue'];
}
if(($change['field'] != 'status')&&
($change['field'] != 'country')&&
($change['field'] != 'manager_comment')&&
($change['field'] != 'order_product.status')&&
($change['field'] != 'payment_status')&&
($change['field'] != 'prepay_sum')
if (($change['field'] != 'status')
&& ($change['field'] != 'country')
&& ($change['field'] != 'manager_comment')
&& ($change['field'] != 'order_product.status')
&& ($change['field'] != 'payment_status')
&& ($change['field'] != 'prepay_sum')
) {
$orders[$change['order']['id']]['order_edit'] = 1;
}
if (isset($change['item'])) {
if($orders[$change['order']['id']]['items'][$change['item']['id']]) {
if (isset($orders[$change['order']['id']]['items'])
&& $orders[$change['order']['id']]['items'][$change['item']['id']]
) {
$orders[$change['order']['id']]['items'][$change['item']['id']] = array_merge($orders[$change['order']['id']]['items'][$change['item']['id']], $change['item']);
}
else{
} else{
$orders[$change['order']['id']]['items'][$change['item']['id']] = $change['item'];
}
@ -675,27 +635,20 @@ class Exchange
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')) {
$orders[$change['order']['id']]['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']);
}
elseif(isset($fields['orderAddress'][$change['field']])) {
} elseif (isset($fields['orderAddress'][$change['field']])) {
$orders[$change['order']['id']]['delivery']['address'][$fields['orderAddress'][$change['field']]] = $change['newValue'];
}
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']);
}
elseif(isset($fields['customerContragent'][$change['field']])) {
} elseif (isset($fields['customerContragent'][$change['field']])) {
$orders[$change['order']['id']][$fields['customerContragent'][$change['field']]] = self::newValue($change['newValue']);
}
elseif(strripos($change['field'], 'custom_') !== false) {
} elseif (strripos($change['field'], 'custom_') !== false) {
$orders[$change['order']['id']]['customFields'][str_replace('custom_', '', $change['field'])] = self::newValue($change['newValue']);
}
elseif(isset($fields['order'][$change['field']])) {
} elseif (isset($fields['order'][$change['field']])) {
$orders[$change['order']['id']][$fields['order'][$change['field']]] = self::newValue($change['newValue']);
}
@ -712,9 +665,17 @@ class Exchange
return $orders;
}
/**
* Remove empty elements
*
* @param array $inputArray
*
* @return array $outputArray
*/
public static function removeEmpty($inputArray)
{
$outputArray = array();
$outputArray = [];
if (!empty($inputArray)) {
foreach ($inputArray as $key => $element) {
if(!empty($element) || $element === 0 || $element === '0') {
@ -730,6 +691,13 @@ class Exchange
return $outputArray;
}
/**
* Set new value
*
* @param mixed $value
*
* @return string $value
*/
public static function newValue($value)
{
if(isset($value['code'])) {
@ -739,16 +707,25 @@ class Exchange
}
}
/**
* Get shipping methods
*
* @param string $mcode
*
* @return string
*/
public function getAllShippingMethodsCode($mcode)
{
$activeCarriers = $this->_shipconfig->getActiveCarriers();
$storeScope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE;
foreach($activeCarriers as $carrierCode => $carrierModel)
{
$options = array();
foreach($activeCarriers as $carrierCode => $carrierModel) {
$options = [];
if ($carrierMethods = $carrierModel->getAllowedMethods()) {
foreach ($carrierMethods as $methodCode => $method) {
$code = $carrierCode . '_'. $methodCode;
if ($mcode == $carrierCode) {
$methods[$mcode] = $code;
}
@ -759,4 +736,30 @@ class Exchange
return $methods[$mcode];
}
/**
* Get payment type for api v5
*
* @param array $payments
* @param boolean $newOrder
*
* @return mixed
*/
protected function getPaymentMethod($payments, $newOrder = true)
{
if (count($payments) == 1 || $newOrder) {
$payment = reset($payments);
} elseif (count($payments) > 1 && !$newOrder) {
foreach ($payments as $paymentCrm) {
if (isset($paymentCrm['externalId'])) {
$payment = $paymentCrm;
}
}
}
if (isset($payment)) {
return $payment['type'];
}
return false;
}
}

View File

@ -1,4 +1,5 @@
<?php
namespace Retailcrm\Retailcrm\Model\Icml;
class Icml
@ -17,14 +18,14 @@ class Icml
public function __construct()
{
$om = \Magento\Framework\App\ObjectManager::getInstance();
$manager = $om->get('Magento\Store\Model\StoreManagerInterface');
$categoryCollectionFactory = $om->get('\Magento\Catalog\Model\ResourceModel\Category\CollectionFactory');
$product = $om->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$storeManager = $om->get('\Magento\Store\Model\StoreManagerInterface');
$StockState = $om->get('\Magento\CatalogInventory\Api\StockStateInterface');
$configurable = $om->get('Magento\ConfigurableProduct\Model\Product\Type\Configurable');
$config = $om->get('\Magento\Framework\App\Config\ScopeConfigInterface');
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$manager = $objectManager->get('Magento\Store\Model\StoreManagerInterface');
$categoryCollectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Category\CollectionFactory');
$product = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface');
$StockState = $objectManager->get('\Magento\CatalogInventory\Api\StockStateInterface');
$configurable = $objectManager->get('Magento\ConfigurableProduct\Model\Product\Type\Configurable');
$config = $objectManager->get('\Magento\Framework\App\Config\ScopeConfigInterface');
$this->_configurable = $configurable;
$this->_StockState = $StockState;
@ -72,7 +73,6 @@ class Icml
$baseDir = $dirlist->getRoot();
$shopCode = $this->_manager->getStore()->getCode();
$this->_dd->save($baseDir . 'retailcrm_' . $shopCode . '.xml');
}
private function addCategories()
@ -97,20 +97,19 @@ class Icml
private function addOffers()
{
$offers = array();
$offers = [];
$collection = $this->_product->create();
$collection->addFieldToFilter('visibility', 4);//catalog, search visible
$collection->addAttributeToSelect('*');
$picUrl = $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);;
$picUrl = $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
$baseUrl = $this->_storeManager->getStore()->getBaseUrl();
$customAdditionalAttributes = array();
$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();
@ -123,38 +122,36 @@ class Icml
$offer['quantity'] = $this->_StockState->getStockQty($product->getId(), $product->getStore()->getWebsiteId());
$offer['categoryId'] = $product->getCategoryIds();
$offer['vendor'] = $product->getAttributeText('manufacturer');
$offer['params'] = array();
$offer['params'] = [];
$article = $product->getSku();
if(!empty($article)) {
$offer['params'][] = array(
$offer['params'][] = [
'name' => 'Article',
'code' => 'article',
'value' => $article
);
];
}
$weight = $product->getWeight();
if(!empty($weight)) {
$offer['params'][] = array(
$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('*')
@ -172,34 +169,59 @@ class Icml
$offer['quantity'] = $this->_StockState->getStockQty($associatedProduct->getId(), $associatedProduct->getStore()->getWebsiteId());
$offer['categoryId'] = $associatedProduct->getCategoryIds();
$offer['vendor'] = $associatedProduct->getAttributeText('manufacturer');
$offer['params'] = array();
$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'][] = array(
$offer['params'][] = [
'name' => 'Article',
'code' => 'article',
'value' => $article
);
];
}
$weight = $associatedProduct->getWeight();
if(!empty($weight)) {
$offer['params'][] = array(
$offer['params'][] = [
'name' => 'Weight',
'code' => 'weight',
'value' => $weight
);
];
}
$offers[] = $offer;
}
}
}
foreach ($offers as $offer) {
$e = $this->_eOffers->appendChild(
$this->_dd->createElement('offer')
@ -286,7 +308,5 @@ class Icml
}
}
}
}
}

View File

@ -1,29 +1,94 @@
<?php
namespace Retailcrm\Retailcrm\Model\Logger;
class Logger
{
private $logPath;
private $files;
private $logDir;
public function __construct(
$logPath = '/app/code/Retailcrm/Retailcrm/Log/'
)
public function __construct(\Magento\Framework\ObjectManagerInterface $objectManager)
{
$this->logPath = $logPath;
$directory = $objectManager->get('\Magento\Framework\Filesystem\DirectoryList');
$this->logDir = $directory->getPath('log');
}
public function write($dump, $file)
/**
* Write data in log file
*
* @param array $data
* @param str $fileName
*
* @return void
*/
public function writeDump($data, $fileName)
{
$path =$this->logPath . $file.'.txt';
$f = fopen($_SERVER["DOCUMENT_ROOT"].$path, "a+");
fwrite($f, print_r(array(date('Y-m-d H:i:s'), array(
$dump
)),true));
fclose($f);
$filePath = $this->logDir . '/' . $fileName . '.log';
if (!$this->checkSize($filePath)) {
$this->clear($filePath);
}
$logData = [
'date' => date('Y-m-d H:i:s'),
'data' => $data
];
$file = fopen($filePath, "a+");
fwrite($file, print_r($logData, true));
fclose($file);
}
/**
* Write data in log file
*
* @param str $data
* @param str $fileName
*
* @return void
*/
public function writeRow($data, $fileName = 'retailcrm')
{
$filePath = $this->logDir . '/' . $fileName . '.log';
if (!$this->checkSize($filePath)) {
$this->clear($filePath);
}
$nowDate = date('Y-m-d H:i:s');
$logData = "[$nowDate] @ " . $data . "\n";
$file = fopen($filePath, "a+");
fwrite($file, $logData);
fclose($file);
}
/**
* Clear file
*
* @param str $file
*
* @return void
*/
protected function clear($file)
{
file_put_contents($file, '');
}
/**
* Check file size
*
* @param str $file
*
* @return boolean
*/
protected function checkSize($file)
{
if (!file_exists($file)) {
return true;
} elseif (filesize($file) > 10485760) {
return false;
}
return true;
}
}

View File

@ -1,7 +1,8 @@
<?php
namespace Retailcrm\Retailcrm\Model\Observer;
use Magento\Framework\Event\Observer;
use Retailcrm\Retailcrm\Helper\Proxy as ApiClient;
class Customer implements \Magento\Framework\Event\ObserverInterface
{
@ -9,51 +10,57 @@ class Customer implements \Magento\Framework\Event\ObserverInterface
protected $_config;
protected $_helper;
protected $_logger;
protected $_objectManager;
protected $registry;
public function __construct()
{
$om = \Magento\Framework\App\ObjectManager::getInstance();
$helper = $om->get('\Retailcrm\Retailcrm\Helper\Data');
$logger = $om->get('\Psr\Log\LoggerInterface');
$config = $om->get('\Magento\Framework\App\Config\ScopeConfigInterface');
public function __construct(
\Magento\Framework\ObjectManagerInterface $objectManager,
\Magento\Framework\App\Config\ScopeConfigInterface $config,
\Magento\Framework\Registry $registry
) {
$helper = $objectManager->get('\Retailcrm\Retailcrm\Helper\Data');
$logger = $objectManager->get('\Retailcrm\Retailcrm\Model\Logger\Logger');
$this->_logger = $logger;
$this->_helper = $helper;
$this->_config = $config;
$this->_objectManager = $objectManager;
$this->registry = $registry;
$url = $config->getValue('retailcrm/general/api_url');
$key = $config->getValue('retailcrm/general/api_key');
$version = $config->getValue('retailcrm/general/api_version');
if (!empty($url) && !empty($key)) {
$this->_api = new \Retailcrm\Retailcrm\Model\ApiClient\ApiClient($url,$key);
$this->_api = new ApiClient($url, $key, $version);
}
}
public function execute(\Magento\Framework\Event\Observer $observer)
{
if ($this->registry->registry('RETAILCRM_HISTORY') === true) {
return;
}
$data = $observer->getEvent()->getCustomer();
$customer = array(
$customer = [
'externalId' => $data->getId(),
'email' => $data->getEmail(),
'firstName' => $data->getFirstname(),
'patronymic' => $data->getMiddlename(),
'lastName' => $data->getLastname(),
'createdAt' => date('Y-m-d H:i:s', strtotime($data->getCreatedAt()))
);
];
$response = $this->_api->customersEdit($customer);
if ((404 === $response->getStatusCode()) &&($response['errorMsg']==='Not found')) {
if ($response === false) {
return;
}
if (!$response->isSuccessful() && $response->errorMsg == $this->_api->getErrorText('errorNotFound')) {
$this->_api->customersCreate($customer);
}
//$logger = new \Retailcrm\Retailcrm\Model\Logger\Logger();
//$logger->write($customer,'Customer');
}
}

View File

@ -1,7 +1,9 @@
<?php
namespace Retailcrm\Retailcrm\Model\Observer;
use Magento\Framework\Event\Observer;
use Retailcrm\Retailcrm\Helper\Proxy as ApiClient;
class OrderCreate implements \Magento\Framework\Event\ObserverInterface
{
@ -10,63 +12,79 @@ class OrderCreate implements \Magento\Framework\Event\ObserverInterface
protected $_config;
protected $_helper;
protected $_logger;
protected $_configurable;
protected $_registry;
/**
* Constructor
*
* @param \Magento\Framework\ObjectManagerInterface $objectManager
* @param \Magento\Framework\App\Config\ScopeConfigInterface $config
* @param \Retailcrm\Retailcrm\Model\Logger\Logger $logger
* @param \Magento\Framework\Registry $registry
*/
public function __construct(
\Magento\Framework\ObjectManager\ObjectManager $ObjectManager,
\Magento\Framework\App\Config\ScopeConfigInterface $config
)
{
$om = \Magento\Framework\App\ObjectManager::getInstance();
$helper = $om->get('\Retailcrm\Retailcrm\Helper\Data');
$logger = $om->get('\Psr\Log\LoggerInterface');
$configurable = $om->get('Magento\ConfigurableProduct\Model\Product\Type\Configurable');
$this->_configurable = $configurable;
$this->_logger = $logger;
\Magento\Framework\ObjectManagerInterface $objectManager,
\Magento\Framework\App\Config\ScopeConfigInterface $config,
\Magento\Framework\Registry $registry
) {
$helper = $objectManager->get('\Retailcrm\Retailcrm\Helper\Data');
$this->_logger = $objectManager->get('\Retailcrm\Retailcrm\Model\Logger\Logger');
$this->_helper = $helper;
$this->_objectManager = $ObjectManager;
$this->_objectManager = $objectManager;
$this->_config = $config;
$this->_registry = $registry;
$url = $config->getValue('retailcrm/general/api_url');
$key = $config->getValue('retailcrm/general/api_key');
$apiVersion = $config->getValue('retailcrm/general/api_version');
if (!empty($url) && !empty($key)) {
$this->_api = new \Retailcrm\Retailcrm\Model\ApiClient\ApiClient($url,$key);
$this->_api = new ApiClient($url, $key, $apiVersion);
}
}
}
public function execute(\Magento\Framework\Event\Observer $observer)
/**
* Execute send order in CRM
*
* @param Observer $observer
*
* @return $this
*/
public function execute(Observer $observer)
{
$order = $observer->getEvent()->getOrder();
$items = array();
$addressObj = $order->getBillingAddress();
if ($this->_registry->registry('RETAILCRM_HISTORY') === true) {
return;
}
$order = $observer->getEvent()->getOrder();
if ($this->existsInCrm($order->getId()) === true) {
return;
}
$items = [];
$addressObj = $order->getBillingAddress();
foreach ($order->getAllItems() as $item) {
if ($item->getProductType() == "simple") {
$price = $item->getPrice();
if ($price == 0) {
$om = \Magento\Framework\App\ObjectManager::getInstance();
$omproduct = $om->get('Magento\Catalog\Model\ProductRepository')
$omproduct = $this->_objectManager->get('Magento\Catalog\Model\ProductRepository')
->getById($item->getProductId());
$price = $omproduct->getPrice();
}
$product = array(
$product = [
'productId' => $item->getProductId(),
'productName' => $item->getName(),
'quantity' => $item->getQtyOrdered(),
'initialPrice' => $price,
'offer'=>array(
'offer' => [
'externalId' => $item->getProductId()
)
);
]
];
unset($om);
unset($omproduct);
unset($price);
@ -74,52 +92,73 @@ class OrderCreate implements \Magento\Framework\Event\ObserverInterface
}
}
$ship = $this->getShippingCode($order->getShippingMethod());
$shippingCode = $this->getShippingCode($order->getShippingMethod());
$preparedOrder = array(
$preparedOrder = [
'site' => $order->getStore()->getCode(),
'externalId' => $order->getRealOrderId(),
'externalId' => $order->getId(),
'number' => $order->getRealOrderId(),
'createdAt' => date('Y-m-d H:i:s'),
'lastName' => $order->getCustomerLastname(),
'firstName' => $order->getCustomerFirstname(),
'patronymic' => $order->getCustomerMiddlename(),
'createdAt' => $order->getCreatedAt(),
'lastName' => $order->getCustomerLastname() ? $order->getCustomerLastname() : $addressObj->getLastname(),
'firstName' => $order->getCustomerFirstname() ? $order->getCustomerFirstname() : $addressObj->getFirstname(),
'patronymic' => $order->getCustomerMiddlename() ? $order->getCustomerMiddlename() : $addressObj->getMiddlename(),
'email' => $order->getCustomerEmail(),
'phone' => $addressObj->getTelephone(),
'paymentType' => $this->_config->getValue('retailcrm/Payment/'.$order->getPayment()->getMethodInstance()->getCode()),
'status' => $this->_config->getValue('retailcrm/Status/' . $order->getStatus()),
'discount' => abs($order->getDiscountAmount()),
'items' => $items,
'delivery' => array(
'code' => $this->_config->getValue('retailcrm/Shipping/'.$ship),
'delivery' => [
'code' => $this->_config->getValue('retailcrm/Shipping/' . $shippingCode),
'cost' => $order->getShippingAmount(),
'address' => array(
'address' => [
'index' => $addressObj->getData('postcode'),
'city' => $addressObj->getData('city'),
'country' => $addressObj->getData('country_id'),
'street' => $addressObj->getData('street'),
'region' => $addressObj->getData('region'),
'text' => trim(
',',
implode(
',',
array(
[
$addressObj->getData('postcode'),
$addressObj->getData('city'),
$addressObj->getData('street'),
]
)
)
)
)
)
);
]
]
];
if ($addressObj->getData('country_id')) {
$preparedOrder['countryIso'] = $addressObj->getData('country_id');
}
if ($this->_api->getVersion() == 'v4') {
$preparedOrder['paymentType'] = $this->_config->getValue('retailcrm/Payment/'.$order->getPayment()->getMethodInstance()->getCode());
$preparedOrder['discount'] = abs($order->getDiscountAmount());
} elseif ($this->_api->getVersion() == 'v5') {
$preparedOrder['discountManualAmount'] = abs($order->getDiscountAmount());
$payment = [
'type' => $this->_config->getValue('retailcrm/Payment/' . $order->getPayment()->getMethodInstance()->getCode()),
'externalId' => $order->getId(),
'order' => [
'externalId' => $order->getId(),
]
];
if ($order->getBaseTotalDue() == 0) {
$payment['status'] = 'paid';
}
$preparedOrder['payments'][] = $payment;
}
if (trim($preparedOrder['delivery']['code']) == '') {
unset($preparedOrder['delivery']['code']);
}
if(trim($preparedOrder['paymentType']) == ''){
if (isset($preparedOrder['paymentType']) && trim($preparedOrder['paymentType']) == '') {
unset($preparedOrder['paymentType']);
}
@ -127,48 +166,51 @@ class OrderCreate implements \Magento\Framework\Event\ObserverInterface
unset($preparedOrder['status']);
}
if ($order->getCustomerIsGuest() == 0) {
$preparedCustomer = array(
'externalId' => $order->getCustomerId()
);
if ($order->getCustomerIsGuest() == 1) {
$customer = $this->getCustomerByEmail($order->getCustomerEmail());
if ($customer !== false) {
$preparedOrder['customer']['id'] = $customer['id'];
}
} elseif ($order->getCustomerIsGuest() == 0) {
if ($this->existsInCrm($order->getCustomerId(), 'customersGet')) {
$preparedOrder['customer']['externalId'] = $order->getCustomerId();
} else {
$preparedCustomer = [
'externalId' => $order->getCustomerId(),
'firstName' => $order->getCustomerFirstname(),
'lastName' => $order->getCustomerLastname(),
'email' => $order->getCustomerEmail()
];
if ($addressObj->getTelephone()) {
$preparedCustomer['phones'][] = [
'number' => $addressObj->getTelephone()
];
}
if ($this->_api->customersCreate($preparedCustomer)) {
$preparedOrder['customer']['externalId'] = $order->getCustomerId();
}
}
}
$this->_helper->filterRecursive($preparedOrder);
$logger = new \Retailcrm\Retailcrm\Model\Logger\Logger();
$logger->write($preparedOrder,'CreateOrder');
try {
$response = $this->_api->ordersCreate($preparedOrder);
if ($response->isSuccessful() && 201 === $response->getStatusCode()) {
$this->_logger->addDebug($response->id);
} else {
$this->_logger->addDebug(
sprintf(
"Order create error: [HTTP status %s] %s",
$response->getStatusCode(),
$response->getErrorMsg()
)
);
if (isset($response['errors'])) {
$this->_logger->addDebug(implode(' :: ', $response['errors']));
}
}
} catch (\Retailcrm\Retailcrm\Model\ApiClient\Exception\CurlException $e) {
$this->_logger->addDebug($e->getMessage());
}
$this->_logger->writeDump($preparedOrder,'CreateOrder');
$this->_api->ordersCreate($preparedOrder);
return $this;
}
/**
* Get shipping code
*
* @param string $string
*
* @return string
*/
protected function getShippingCode($string)
{
$split = array_values(explode('_', $string));
@ -177,4 +219,50 @@ class OrderCreate implements \Magento\Framework\Event\ObserverInterface
return implode('_', $prepare);
}
/**
* Check exists order or customer in CRM
*
* @param int $id
*
* @return boolean
*/
protected function existsInCrm($id, $method = 'ordersGet', $by = 'externalId')
{
$response = $this->_api->{$method}($id, $by);
if ($response === false) {
return;
}
if (!$response->isSuccessful() && $response->errorMsg == $this->_api->getErrorText('errorNotFound')) {
return false;
}
return true;
}
/**
* Get customer by email from CRM
*
* @param string $email
*
* @return mixed
*/
protected function getCustomerByEmail($email)
{
$response = $this->_api->customersList(['email' => $email]);
if ($response === false) {
return false;
}
if ($response->isSuccessful() && isset($response['customers'])) {
if (!empty($response['customers'])) {
return reset($response['customers']);
}
}
return false;
}
}

View File

@ -1,56 +1,79 @@
<?php
namespace Retailcrm\Retailcrm\Model\Observer;
use Magento\Framework\Event\Observer;
use Retailcrm\Retailcrm\Helper\Proxy as ApiClient;
class OrderUpdate implements \Magento\Framework\Event\ObserverInterface
{
protected $_api;
protected $_config;
protected $_helper;
protected $_logger;
protected $_objectManager;
protected $registry;
public function __construct()
{
$om = \Magento\Framework\App\ObjectManager::getInstance();
$helper = $om->get('\Retailcrm\Retailcrm\Helper\Data');
$logger = $om->get('\Psr\Log\LoggerInterface');
$config = $om->get('\Magento\Framework\App\Config\ScopeConfigInterface');
$this->_logger = $logger;
$this->_helper = $helper;
/**
* Constructor
*
* @param \Magento\Framework\ObjectManagerInterface $objectManager
* @param \Magento\Framework\App\Config\ScopeConfigInterface $config
*/
public function __construct(
\Magento\Framework\ObjectManagerInterface $objectManager,
\Magento\Framework\App\Config\ScopeConfigInterface $config,
\Magento\Framework\Registry $registry
) {
$this->_helper = $objectManager->get('\Retailcrm\Retailcrm\Helper\Data');
$this->_objectManager = $objectManager;
$this->_config = $config;
$this->registry = $registry;
$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 \Retailcrm\Retailcrm\Model\ApiClient\ApiClient($url,$key);
$this->_api = new ApiClient($url, $key, $apiVersion);
}
}
}
public function execute(\Magento\Framework\Event\Observer $observer)
/**
* Execute update order in CRM
*
* @param Observer $observer
*
* @return void
*/
public function execute(Observer $observer)
{
if ($this->registry->registry('RETAILCRM_HISTORY') === true) {
return;
}
$order = $observer->getEvent()->getOrder();
if(isset($order)){
if ($order) {
$preparedOrder = [
'externalId' => $order->getId(),
'status' => $this->_config->getValue('retailcrm/Status/' . $order->getStatus())
];
$preparedOrder = array(
'externalId' => $order->getRealOrderId(),
'status' => $this->_config->getValue('retailcrm/Status/'.$order->getStatus()),
);
if((float)$order->getBaseGrandTotal() == (float)$order->getTotalPaid()){
if ($order->getBaseTotalDue() == 0) {
if ($this->_api->getVersion() == 'v4') {
$preparedOrder['paymentStatus'] = 'paid';
} elseif ($this->_api->getVersion() == 'v5') {
$payment = [
'externalId' => $order->getPayment()->getId(),
'status' => 'paid'
];
$this->_api->ordersPaymentsEdit($payment);
}
}
$this->_helper->filterRecursive($preparedOrder);
$this->_api->ordersEdit($preparedOrder);
}
}
}

View File

@ -1,11 +1,11 @@
<?php
namespace Retailcrm\Retailcrm\Model\Order;
use \Retailcrm\Retailcrm\Observer;
use Retailcrm\Retailcrm\Model\Observer\OrderCreate;
use Retailcrm\Retailcrm\Helper\Proxy as ApiClient;
//use Psr\Log\LoggerInterface;
class OrderNumber extends \Retailcrm\Retailcrm\Model\Observer\OrderCreate
class OrderNumber extends OrderCreate
{
protected $_orderRepository;
protected $_searchCriteriaBuilder;
@ -14,16 +14,17 @@ class OrderNumber extends \Retailcrm\Retailcrm\Model\Observer\OrderCreate
protected $_order;
protected $_helper;
protected $_api;
protected $_logger;
public function __construct()
{
$om = \Magento\Framework\App\ObjectManager::getInstance();
$orderRepository = $om->get('Magento\Sales\Model\OrderRepository');
$searchCriteriaBuilder = $om->get('Magento\Framework\Api\SearchCriteriaBuilder');
$config = $om->get('Magento\Framework\App\Config\ScopeConfigInterface');
$filterBuilder = $om->get('Magento\Framework\Api\FilterBuilder');
$order = $om->get('\Magento\Sales\Api\Data\OrderInterface');
$helper = $om->get('\Retailcrm\Retailcrm\Helper\Data');
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$orderRepository = $objectManager->get('Magento\Sales\Model\OrderRepository');
$searchCriteriaBuilder = $objectManager->get('Magento\Framework\Api\SearchCriteriaBuilder');
$config = $objectManager->get('Magento\Framework\App\Config\ScopeConfigInterface');
$filterBuilder = $objectManager->get('Magento\Framework\Api\FilterBuilder');
$order = $objectManager->get('\Magento\Sales\Api\Data\OrderInterface');
$helper = $objectManager->get('\Retailcrm\Retailcrm\Helper\Data');
$this->_orderRepository = $orderRepository;
$this->_searchCriteriaBuilder = $searchCriteriaBuilder;
@ -31,12 +32,14 @@ class OrderNumber extends \Retailcrm\Retailcrm\Model\Observer\OrderCreate
$this->_filterBuilder = $filterBuilder;
$this->_order = $order;
$this->_helper = $helper;
$this->_logger = $objectManager->get('\Retailcrm\Retailcrm\Model\Logger\Logger');
$url = $config->getValue('retailcrm/general/api_url');
$key = $config->getValue('retailcrm/general/api_key');
$version = $config->getValue('retailcrm/general/api_version');
if (!empty($url) && !empty($key)) {
$this->_api = new \Retailcrm\Retailcrm\Model\ApiClient\ApiClient($url,$key);
$this->_api = new ApiClient($url, $key, $version);
}
}
@ -44,7 +47,7 @@ class OrderNumber extends \Retailcrm\Retailcrm\Model\Observer\OrderCreate
{
$ordernumber = $this->_config->getValue('retailcrm/Load/number_order');
$ordersId = explode(",", $ordernumber);
$orders = array();
$orders = [];
foreach ($ordersId as $id) {
$orders[] = $this->prepareOrder($id);
@ -61,20 +64,17 @@ class OrderNumber extends \Retailcrm\Retailcrm\Model\Observer\OrderCreate
unset($chunked);
return true;
}
public function prepareOrder($id)
{
$magentoOrder = $this->_order->loadByIncrementId($id);
$magentoOrderArr = $magentoOrder->getData();
$magentoOrder = $this->_order->load($id);
$items = array();
$items = [];
$addressObj = $magentoOrder->getBillingAddress();
foreach ($magentoOrder->getAllItems() as $item) {
if ($item->getProductType() == "simple") {
$price = $item->getPrice();
if ($price == 0){
@ -84,15 +84,15 @@ class OrderNumber extends \Retailcrm\Retailcrm\Model\Observer\OrderCreate
$price = $omproduct->getPrice();
}
$product = array(
$product = [
'productId' => $item->getProductId(),
'productName' => $item->getName(),
'quantity' => $item->getQtyOrdered(),
'initialPrice' => $price,
'offer'=>array(
'offer' => [
'externalId'=>$item->getProductId()
)
);
]
];
unset($om);
unset($omproduct);
@ -104,7 +104,7 @@ class OrderNumber extends \Retailcrm\Retailcrm\Model\Observer\OrderCreate
$ship = $this->getShippingCode($magentoOrder->getShippingMethod());
$preparedOrder = array(
$preparedOrder = [
'site' => $magentoOrder->getStore()->getCode(),
'externalId' => $magentoOrder->getRealOrderId(),
'number' => $magentoOrder->getRealOrderId(),
@ -118,10 +118,10 @@ class OrderNumber extends \Retailcrm\Retailcrm\Model\Observer\OrderCreate
'status' => $this->_config->getValue('retailcrm/Status/'.$magentoOrder->getStatus()),
'discount' => abs($magentoOrder->getDiscountAmount()),
'items' => $items,
'delivery' => array(
'delivery' => [
'code' => $this->_config->getValue('retailcrm/Shipping/'.$ship),
'cost' => $magentoOrder->getShippingAmount(),
'address' => array(
'address' => [
'index' => $addressObj->getData('postcode'),
'city' => $addressObj->getData('city'),
'country' => $addressObj->getData('country_id'),
@ -131,16 +131,16 @@ class OrderNumber extends \Retailcrm\Retailcrm\Model\Observer\OrderCreate
',',
implode(
',',
array(
[
$addressObj->getData('postcode'),
$addressObj->getData('city'),
$addressObj->getData('street'),
]
)
)
)
)
)
);
]
]
];
if (trim($preparedOrder['delivery']['code']) == ''){
unset($preparedOrder['delivery']['code']);
@ -158,11 +158,8 @@ class OrderNumber extends \Retailcrm\Retailcrm\Model\Observer\OrderCreate
$preparedOrder['customer']['externalId'] = $magentoOrder->getCustomerId();
}
$logger = new \Retailcrm\Retailcrm\Model\Logger\Logger();
$logger->write($preparedOrder,'OrderNumber');
$this->_logger->writeDump($preparedOrder,'OrderNumber');
return $this->_helper->filterRecursive($preparedOrder);
}
}

View File

@ -0,0 +1,14 @@
<?php
namespace Retailcrm\Retailcrm\Model\Setting;
class ApiVersions implements \Magento\Framework\Option\ArrayInterface
{
public function toOptionArray()
{
return [
['value' => 'v4', 'label' => 'v4'],
['value' => 'v5', 'label' => 'v5']
];
}
}

View File

@ -2,8 +2,6 @@
namespace Retailcrm\Retailcrm\Model\Setting;
//use Psr\Log\LoggerInterface;
class Attribute implements \Magento\Framework\Option\ArrayInterface
{
protected $_entityType;
@ -19,11 +17,12 @@ class Attribute implements \Magento\Framework\Option\ArrayInterface
public function toOptionArray()
{
$types = array('text', 'multiselect', 'decimal');
$types = ['text', 'multiselect', 'decimal'];
$attributes = $this->_entityType->loadByCode('catalog_product')->getAttributeCollection();
$attributes->addFieldToFilter('frontend_input', $types);
$result = array();
$result = [];
foreach ($attributes as $attr) {
if ($attr->getFrontendLabel()) {
$result[] = array('value' => $attr->getAttributeId(), 'label' => $attr->getFrontendLabel(), 'title' => $attr->getAttributeCode());
@ -32,6 +31,4 @@ class Attribute implements \Magento\Framework\Option\ArrayInterface
return $result;
}
}

View File

@ -2,8 +2,6 @@
namespace Retailcrm\Retailcrm\Model\Setting;
//use Psr\Log\LoggerInterface;
class Shipping implements \Magento\Framework\Option\ArrayInterface
{
protected $_entityType;
@ -19,30 +17,34 @@ class Shipping implements \Magento\Framework\Option\ArrayInterface
public function toOptionArray()
{
$om = \Magento\Framework\App\ObjectManager::getInstance();
$activeShipping = $om->create('Magento\Shipping\Model\Config')->getActiveCarriers();
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$activeShipping = $objectManager->create('Magento\Shipping\Model\Config')->getActiveCarriers();
$config = \Magento\Framework\App\ObjectManager::getInstance()->get(
'Magento\Framework\App\Config\ScopeConfigInterface'
);
$config = $objectManager->get('Magento\Framework\App\Config\ScopeConfigInterface');
foreach($activeShipping as $carrierCode => $carrierModel)
{
$options = array();
if( $carrierMethods = $carrierModel->getAllowedMethods() )
{
foreach ($carrierMethods as $methodCode => $method)
{
foreach ($activeShipping as $carrierCode => $carrierModel) {
$options = [];
if ($carrierModel->getAllowedMethods()) {
$carrierMethods = $carrierModel->getAllowedMethods();
foreach ($carrierMethods as $methodCode => $method) {
$code = $carrierCode . '_' . $methodCode;
$options[]=array('value'=>$code,'label'=>$method);
$options[] = [
'value' => $code,
'label' => $method
];
}
$carrierTitle =$config->getValue('carriers/'.$carrierCode.'/title');
$carrierTitle = $config->getValue('carriers/' . $carrierCode . '/title');
}
$methods[] = array('value'=>$options,'label'=>$carrierTitle);
$methods[] = [
'value' => $options,
'label' => $carrierTitle
];
}
return $methods;
}
}

View File

@ -10,11 +10,8 @@ class Status extends \Magento\Config\Model\Config\Backend\Serialized\ArraySerial
$exceptions = $this->getValue();
// Validations
$this->setValue($exceptions);
return parent::beforeSave();
}
}

View File

@ -1,16 +1,29 @@
Magento module
==============
Magento 2 module for interaction with [RetailCRM](http://www.retailcrm.ru) through [REST API](http://www.retailcrm.ru/docs/Developers/Index).
Magento 2 module for interaction with [retailCRM](http://www.retailcrm.ru).
Module allows:
* Exchange the orders with retailCRM
* Configure relations between dictionaries of RetailCRM and Magento (statuses, payments, delivery types and etc)
* Generate [ICML](http://www.retailcrm.ru/docs/Developers/ICML) (Intaro Markup Language) for catalog loading by RetailCRM
* Exchange the orders data with retailCRM
* Configure relations between dictionaries of retailCRM and Magento (statuses, payments, delivery types and etc)
* Generate [ICML](http://www.retailcrm.ru/docs/Developers/ICML) (Intaro Markup Language) export file for catalog loading by retailCRM
ICML
### ICML
By default ICML file is being generated by module every 4 hours. You can find file in the web root folder with name "retailcrm_{{shop_code}}.xml". For example, http://retailcrm.ru/retailcrm_default.xml
By default ICML file is being generated by module every 4 hours. You can find file in the web root folder with name "retailcrm_{{shop_code}}.xml". For example, http://example.org/retailcrm_default.xml
This module is compatible with Magento up to version 2.1.6
### Manual install
1) Run into your project root directory:
```bash
composer require retailcrm/api-client-php ~5.0
```
2) Unpack the archive with the module into the `app/code/Retailcrm/Retailcrm` directory.
3) Change `app/etc/config.php` file by adding `'Retailcrm_Retailcrm' => 1` line into `modules` array
This module is compatible with Magento up to version 2.2.3

31
README.ru.md Normal file
View File

@ -0,0 +1,31 @@
Magento module
==============
Модуль Magento 2 для интеграции с [retailCRM](http://www.retailcrm.ru).
Модуль позволяет:
* Производить обмен заказами с retailCRM
* Настроить соответствие справочников retailCRM и Magento (статусы, оплаты, типы доставки и т.д.)
* Создать [ICML](http://www.retailcrm.ru/docs/Developers/ICML) (Intaro Markup Language) для загрузки каталога товаров в retailCRM
### ICML
По умолчанию ICML-файл генерируется модулем каждые 4 часа. Вы можете найти файл в корневой директории с именем «retailcrm_{{shop_code}}.xml". Например, http://example.org/retailcrm_default.xml
### Ручная установка
1) Находясь в корневой директории проекта выполните команду:
```bash
composer require retailcrm/api-client-php ~5.0
```
2) Распакуйте архив с модулем в директорию "app/code/Retailcrm/Retailcrm".
3) В файле "app/etc/config.php" в массив `modules` добавьте элемент `'Retailcrm_Retailcrm' => 1`
В конфигурационный файл `composer.json` вашего проекта будет добавлена библиотека [retailcrm/api-client-php](https://github.com/retailcrm/api-client-php), которая будет установлена в директорию `vendor/`.
Этот модуль совместим с Magento 2 до версии 2.2.3

View File

@ -0,0 +1,159 @@
<?php
namespace Retailcrm\Retailcrm\Test\Unit\Observer;
class CustomerTest extends \PHPUnit\Framework\TestCase
{
protected $mockApi;
protected $mockResponse;
protected $config;
protected $registry;
protected $mockObserver;
protected $mockEvent;
protected $objectManager;
protected $mockCustomer;
public function setUp()
{
$this->mockApi = $this->getMockBuilder(\Retailcrm\Retailcrm\Helper\Proxy::class)
->disableOriginalConstructor()
->setMethods([
'customersEdit',
'customersCreate'
])
->getMock();
$this->mockResponse = $this->getMockBuilder(\RetailCrm\Response\ApiResponse::class)
->disableOriginalConstructor()
->setMethods(['isSuccessful'])
->getMock();
$this->config = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class)
->getMockForAbstractClass();
$this->registry = $this->getMockBuilder(\Magento\Framework\Registry::class)
->disableOriginalConstructor()
->getMock();
$this->mockObserver = $this->getMockBuilder(\Magento\Framework\Event\Observer::class)
->disableOriginalConstructor()
->getMock();
$this->mockEvent = $this->getMockBuilder(\Magento\Framework\Event::class)
->disableOriginalConstructor()
->setMethods(['getCustomer'])
->getMock();
$this->objectManager = $this->getMockBuilder(\Magento\Framework\ObjectManagerInterface::class)
->getMockForAbstractClass();
$this->mockCustomer = $this->getMockBuilder(\Magento\Customer\Model\Customer::class)
->disableOriginalConstructor()
->setMethods([
'getId',
'getEmail',
'getFirstname',
'getMiddlename',
'getLastname'
])
->getMock();
$this->unit = new \Retailcrm\Retailcrm\Model\Observer\Customer(
$this->objectManager,
$this->config,
$this->registry
);
$reflection = new \ReflectionClass($this->unit);
$reflection_property = $reflection->getProperty('_api');
$reflection_property->setAccessible(true);
$reflection_property->setValue($this->unit, $this->mockApi);
}
/**
* @param boolean $isSuccessful
* @dataProvider dataProviderCustomer
*/
public function testExecute(
$isSuccessful
) {
$testData = $this->getAfterSaveCustomerTestData();
// mock Response
$this->mockResponse->expects($this->any())
->method('isSuccessful')
->willReturn($isSuccessful);
$this->mockResponse->errorMsg = 'Not found';
// mock API
$this->mockApi->expects($this->any())
->method('customersEdit')
->willReturn($this->mockResponse);
$this->mockApi->expects($this->any())
->method('customersCreate')
->willReturn($this->mockResponse);
// mock Customer
$this->mockCustomer->expects($this->once())
->method('getId')
->willReturn($testData['id']);
$this->mockCustomer->expects($this->once())
->method('getEmail')
->willReturn($testData['email']);
$this->mockCustomer->expects($this->once())
->method('getFirstname')
->willReturn($testData['firstname']);
$this->mockCustomer->expects($this->once())
->method('getMiddlename')
->willReturn($testData['middlename']);
$this->mockCustomer->expects($this->once())
->method('getLastname')
->willReturn($testData['lastname']);
// mock Event
$this->mockEvent->expects($this->once())
->method('getCustomer')
->willReturn($this->mockCustomer);
// mock Observer
$this->mockObserver->expects($this->once())
->method('getEvent')
->willReturn($this->mockEvent);
$this->unit->execute($this->mockObserver);
}
/**
* Get test customer data
*
* @return array
*/
protected function getAfterSaveCustomerTestData()
{
return [
'id' => 1,
'email' => 'test@mail.com',
'firstname' => 'TestFirstname',
'lastname' => 'Testlastname',
'middlename' => 'Testmiddlename'
];
}
public function dataProviderCustomer()
{
return [
[
'is_successful' => true
],
[
'is_successful' => false
]
];
}
}

View File

@ -0,0 +1,426 @@
<?php
namespace Retailcrm\Retailcrm\Test\Unit\Observer;
/**
* Order create observer test class
*/
class OrderCreateTest extends \PHPUnit\Framework\TestCase
{
protected $objectManager;
protected $_config;
protected $_unit;
protected $_mockEvent;
protected $_mockObserver;
protected $_registry;
protected $_mockApi;
protected $_mockOrder;
protected $_mockItem;
protected $_mockStore;
protected $_mockBillingAddress;
protected $_mockResponse;
protected $_mockPayment;
protected $_mockPaymentMethod;
protected function setUp()
{
$this->_mockApi = $this->getMockBuilder(\Retailcrm\Retailcrm\Helper\Proxy::class)
->disableOriginalConstructor()
->setMethods([
'ordersGet',
'ordersCreate',
'customersGet',
'customersCreate',
'customersList',
'getVersion'
])
->getMock();
$this->_mockObserver = $this->getMockBuilder(\Magento\Framework\Event\Observer::class)
->disableOriginalConstructor()
->getMock();
$this->_mockEvent = $this->getMockBuilder(\Magento\Framework\Event::class)
->disableOriginalConstructor()
->setMethods(['getOrder'])
->getMock();
$this->objectManager = $this->getMockBuilder(\Magento\Framework\ObjectManagerInterface::class)
->getMockForAbstractClass();
// mock Object Manager
$this->objectManager->expects($this->any())
->method('get')
->with($this->logicalOr(
$this->equalTo('\Retailcrm\Retailcrm\Helper\Data'),
$this->equalTo('\Retailcrm\Retailcrm\Model\Logger\Logger')
))
->will($this->returnCallback([$this, 'getCallbackDataClasses']));
$this->_config = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class)
->getMockForAbstractClass();
$this->_logger = $this->getMockBuilder(\Retailcrm\Retailcrm\Model\Logger\Logger::class)
->disableOriginalConstructor()
->getMock();
$this->_registry = $this->getMockBuilder(\Magento\Framework\Registry::class)
->disableOriginalConstructor()
->getMock();
$this->_mockOrder = $this->getMockBuilder(\Magento\Sales\Order::class)
->setMethods([
'getId',
'getRealOrderId',
'getCreatedAt',
'getStore',
'getBillingAddress',
'getShippingMethod',
'getCustomerId',
'getCustomerLastname',
'getCustomerFirstname',
'getCustomerMiddlename',
'getCustomerEmail',
'getShippingAmount',
'getDiscountAmount',
'getPayment',
'getBaseTotalDue',
'getCustomerIsGuest',
'getAllItems',
'getStatus'
])
->getMock();
$this->_mockPayment = $this->getMockBuilder(\Magento\Sales\Model\Order\Payment::class)
->setMethods(['getMethodInstance'])
->disableOriginalConstructor()
->getMock();
$this->_mockPaymentMethod = $this->getMockBuilder(\Magento\Payment\Model\MethodInterface::class)
->disableOriginalConstructor()
->getMockForAbstractClass();
$this->_mockItem = $this->getMockBuilder(\Magento\Sales\Model\Order\Item::class)
->disableOriginalConstructor()
->setMethods([
'getPrice',
'getProductId',
'getName',
'getQtyOrdered',
'getProductType'
])
->getMock();
$this->_mockStore = $this->getMockBuilder(\Magento\Store\Model\Store::class)
->disableOriginalConstructor()
->setMethods(['getCode'])
->getMock();
$this->_mockBillingAddress = $this->getMockBuilder(\Magento\Customer\Model\Address\AddressModelInterface::class)
->disableOriginalConstructor()
->setMethods(['getTelephone', 'getData'])
->getMockForAbstractClass();
$this->_mockResponse = $this->getMockBuilder(\RetailCrm\Response\ApiResponse::class)
->disableOriginalConstructor()
->setMethods(['isSuccessful'])
->getMock();
$this->_unit = new \Retailcrm\Retailcrm\Model\Observer\OrderCreate(
$this->objectManager,
$this->_config,
$this->_registry
);
$reflection = new \ReflectionClass($this->_unit);
$reflection_property = $reflection->getProperty('_api');
$reflection_property->setAccessible(true);
$reflection_property->setValue($this->_unit, $this->_mockApi);
}
/**
* @param boolean $isSuccessful
* @param string $errorMsg
* @param int $customerIsGuest
* @param string $apiVersion
* @dataProvider dataProviderOrderCreate
*/
public function testExecute(
$isSuccessful,
$errorMsg,
$customerIsGuest,
$apiVersion
) {
$testData = $this->getAfterSaveOrderTestData();
// mock Response
$this->_mockResponse->expects($this->any())
->method('isSuccessful')
->willReturn($isSuccessful);
$this->_mockResponse->errorMsg = $errorMsg;
// mock API
$this->_mockApi->expects($this->any())
->method('ordersGet')
->willReturn($this->_mockResponse);
$this->_mockApi->expects($this->any())
->method('ordersCreate')
->willReturn($this->_mockResponse);
$this->_mockApi->expects($this->any())
->method('customersGet')
->willReturn($this->_mockResponse);
$this->_mockApi->expects($this->any())
->method('customersCreate')
->willReturn($this->_mockResponse);
$this->_mockApi->expects($this->any())
->method('customersList')
->willReturn($this->_mockResponse);
$this->_mockApi->expects($this->any())
->method('getVersion')
->willReturn($apiVersion);
// billing address mock set data
$this->_mockBillingAddress->expects($this->any())
->method('getTelephone')
->willReturn($testData['order.billingAddress']['telephone']);
$this->_mockBillingAddress->expects($this->any())
->method('getData')
->with($this->logicalOr(
$this->equalTo('city'),
$this->equalTo('region'),
$this->equalTo('street'),
$this->equalTo('postcode'),
$this->equalTo('country_id')
))
->will($this->returnCallback([$this, 'getCallbackDataAddress']));
// store mock set data
$this->_mockStore->expects($this->any())
->method('getCode')
->willReturn(1);
// order item mock set data
$this->_mockItem->expects($this->any())
->method('getProductType')
->willReturn('simple');
$this->_mockItem->expects($this->any())
->method('getPrice')
->willReturn(999.99);
$this->_mockItem->expects($this->any())
->method('getProductId')
->willReturn(10);
$this->_mockItem->expects($this->any())
->method('getName')
->willReturn('Product name');
$this->_mockItem->expects($this->any())
->method('getQtyOrdered')
->willReturn(3);
// order mock set data
$this->_mockOrder->expects($this->any())
->method('getId')
->willReturn($testData['order.id']);
$this->_mockOrder->expects($this->any())
->method('getBillingAddress')
->willReturn($this->_mockBillingAddress);
$this->_mockOrder->expects($this->any())
->method('getShippingMethod')
->willReturn($testData['order.shippingMethod']);
$this->_mockOrder->expects($this->any())
->method('getStore')
->willReturn($this->_mockStore);
$this->_mockOrder->expects($this->any())
->method('getRealOrderId')
->willReturn($testData['order.realOrderId']);
$this->_mockOrder->expects($this->any())
->method('getCreatedAt')
->willReturn(date('Y-m-d H:i:s'));
$this->_mockOrder->expects($this->any())
->method('getCustomerLastname')
->willReturn($testData['order.customerLastname']);
$this->_mockOrder->expects($this->any())
->method('getCustomerFirstname')
->willReturn($testData['order.customerFirstname']);
$this->_mockOrder->expects($this->any())
->method('getCustomerMiddlename')
->willReturn($testData['order.customerMiddlename']);
$this->_mockOrder->expects($this->any())
->method('getCustomerEmail')
->willReturn($testData['order.customerEmail']);
$this->_mockOrder->expects($this->any())
->method('getAllItems')
->willReturn($testData['order.allItems']);
$this->_mockOrder->expects($this->any())
->method('getStatus')
->willReturn($testData['order.status']);
$this->_mockOrder->expects($this->any())
->method('getCustomerIsGuest')
->willReturn($customerIsGuest);
$this->_mockOrder->expects($this->any())
->method('getCustomerId')
->willReturn(1);
$this->_mockOrder->expects($this->any())
->method('getPayment')
->willReturn($this->_mockPayment);
// mock Payment Method
$this->_mockPaymentMethod->expects($this->any())
->method('getCode')
->willReturn($testData['order.paymentMethod']);
// mock Payment
$this->_mockPayment->expects($this->any())
->method('getMethodInstance')
->willReturn($this->_mockPaymentMethod);
// mock Event
$this->_mockEvent->expects($this->once())
->method('getOrder')
->willReturn($this->_mockOrder);
// mock Observer
$this->_mockObserver->expects($this->once())
->method('getEvent')
->willReturn($this->_mockEvent);
$this->_unit->execute($this->_mockObserver);
}
/**
* Get test order data
*
* @return array $testOrderData
*/
protected function getAfterSaveOrderTestData()
{
$testOrderData = [
'order.id' => 1,
'order.status' => 'processing',
'order.realOrderId' => '000000001',
'order.billingAddress' => [
'telephone' => '890000000000',
'data' => [
'city' => 'Moscow',
'region' => 'Moscow',
'street' => 'TestStreet',
'postcode' => '111111',
'country_id' => 'RU'
]
],
'order.allItems' => [$this->_mockItem],
'order.shippingMethod' => 'flatrate_flatrate',
'order.paymentMethod' => 'checkmo',
'order.customerLastname' => 'Test',
'order.customerFirstname' => 'Test',
'order.customerMiddlename' => 'Test',
'order.customerEmail' => 'test@gmail.com'
];
return $testOrderData;
}
public function getCallbackDataAddress($dataKey)
{
$testData = $this->getAfterSaveOrderTestData();
return $testData['order.billingAddress']['data'][$dataKey];
}
public function getCallbackDataClasses($class)
{
$helper = $this->getMockBuilder(\Retailcrm\Retailcrm\Helper\Data::class)
->disableOriginalConstructor()
->getMock();
$logger = $this->getMockBuilder(\Retailcrm\Retailcrm\Model\Logger\Logger::class)
->disableOriginalConstructor()
->getMock();
if ($class == '\Retailcrm\Retailcrm\Helper\Data') {
return $helper;
}
if ($class == '\Retailcrm\Retailcrm\Model\Logger\Logger') {
return $logger;
}
}
public function dataProviderOrderCreate()
{
return [
[
'is_successful' => true,
'error_msg' => 'Not found',
'customer_is_guest' => 1,
'api_version' => 'v4'
],
[
'is_successful' => true,
'error_msg' => 'Not found',
'customer_is_guest' => 0,
'api_version' => 'v4'
],
[
'is_successful' => false,
'error_msg' => 'Not found',
'customer_is_guest' => 1,
'api_version' => 'v4'
],
[
'is_successful' => false,
'error_msg' => 'Not found',
'customer_is_guest' => 0,
'api_version' => 'v4'
],
[
'is_successful' => true,
'error_msg' => 'Not found',
'customer_is_guest' => 1,
'api_version' => 'v5'
],
[
'is_successful' => true,
'error_msg' => 'Not found',
'customer_is_guest' => 0,
'api_version' => 'v5'
],
[
'is_successful' => false,
'error_msg' => 'Not found',
'customer_is_guest' => 1,
'api_version' => 'v5'
],
[
'is_successful' => false,
'error_msg' => 'Not found',
'customer_is_guest' => 0,
'api_version' => 'v5'
]
];
}
}

View File

@ -0,0 +1,171 @@
<?php
namespace Retailcrm\Retailcrm\Test\Unit\Observer;
class OrderUpdateTest extends \PHPUnit\Framework\TestCase
{
protected $unit;
protected $objectManager;
protected $config;
protected $mockApi;
protected $mockObserver;
protected $mockEvent;
protected $mockOrder;
protected $mockPayment;
protected $registry;
protected function setUp()
{
$this->mockApi = $this->getMockBuilder(\Retailcrm\Retailcrm\Helper\Proxy::class)
->disableOriginalConstructor()
->setMethods([
'ordersEdit',
'ordersPaymentsEdit',
'getVersion'
])
->getMock();
$this->mockObserver = $this->getMockBuilder(\Magento\Framework\Event\Observer::class)
->disableOriginalConstructor()
->getMock();
$this->mockEvent = $this->getMockBuilder(\Magento\Framework\Event::class)
->disableOriginalConstructor()
->setMethods(['getOrder'])
->getMock();
$this->objectManager = $this->getMockBuilder(\Magento\Framework\ObjectManagerInterface::class)
->getMockForAbstractClass();
$helper = $this->getMockBuilder(\Retailcrm\Retailcrm\Helper\Data::class)
->disableOriginalConstructor()
->getMock();
$this->mockOrder = $this->getMockBuilder(\Magento\Sales\Order::class)
->setMethods([
'getId',
'getPayment',
'getBaseTotalDue',
'getStatus'
])
->getMock();
$this->mockPayment = $this->getMockBuilder(\Magento\Sales\Model\Order\Payment::class)
->setMethods(['getId'])
->disableOriginalConstructor()
->getMock();
// mock Object Manager
$this->objectManager->expects($this->any())
->method('get')
->with('\Retailcrm\Retailcrm\Helper\Data')
->willReturn($helper);
$this->config = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class)
->getMockForAbstractClass();
$this->registry = $this->getMockBuilder(\Magento\Framework\Registry::class)
->disableOriginalConstructor()
->getMock();
$this->unit = new \Retailcrm\Retailcrm\Model\Observer\OrderUpdate(
$this->objectManager,
$this->config,
$this->registry
);
$reflection = new \ReflectionClass($this->unit);
$reflection_property = $reflection->getProperty('_api');
$reflection_property->setAccessible(true);
$reflection_property->setValue($this->unit, $this->mockApi);
}
/**
* @param int $getBaseTotalDue
* @param string $apiVersion
* @dataProvider dataProviderOrderUpdate
*/
public function testExecute(
$getBaseTotalDue,
$apiVersion
) {
$testData = $this->getAfterUpdateOrderTestData();
// mock Payment
$this->mockPayment->expects($this->any())
->method('getId')
->willReturn(1);
// mock Order
$this->mockOrder->expects($this->once())
->method('getId')
->willReturn($testData['order.id']);
$this->mockOrder->expects($this->once())
->method('getStatus')
->willReturn($testData['order.status']);
$this->mockOrder->expects($this->once())
->method('getBaseTotalDue')
->willReturn($getBaseTotalDue);
$this->mockOrder->expects($this->any())
->method('getPayment')
->willReturn($this->mockPayment);
// mock Api
$this->mockApi->expects($this->any())
->method('getVersion')
->willReturn($apiVersion);
// mock Event
$this->mockEvent->expects($this->once())
->method('getOrder')
->willReturn($this->mockOrder);
// mock Observer
$this->mockObserver->expects($this->once())
->method('getEvent')
->willReturn($this->mockEvent);
$this->unit->execute($this->mockObserver);
}
/**
* Get test order data
*
* @return array $testOrderData
*/
protected function getAfterUpdateOrderTestData()
{
$testOrderData = [
'order.id' => 1,
'order.status' => 'processing',
'order.paymentMethod' => 'checkmo'
];
return $testOrderData;
}
public function dataProviderOrderUpdate()
{
return [
[
'get_base_total_due' => 0,
'api_version' => 'v4'
],
[
'get_base_total_due' => 1,
'api_version' => 'v4'
],
[
'get_base_total_due' => 0,
'api_version' => 'v5'
],
[
'get_base_total_due' => 1,
'api_version' => 'v5'
]
];
}
}

View File

@ -2,7 +2,8 @@
"name": "retailcrm/retailcrm",
"description": "Retailcrm",
"require": {
"php": "~5.5.0|~5.6.0|~7.0.0"
"php": "~5.5.0|~5.6.0|~7.0.0",
"retailcrm/api-client-php": "~5.0"
},
"type": "magento2-module",
"version": "1.0.0",

View File

@ -12,15 +12,22 @@
<group id="general" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="0" showInStore="0">
<label>General Configuration</label>
<field id="api_url" translate="label" type="text" sortOrder="1" showInDefault="1" showInWebsite="0" showInStore="0">
<field id="api_url" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="0" showInStore="0">
<label>API URL</label>
<comment>https://YourCrmName.retailcrm.ru</comment>
<backend_model>Retailcrm\Retailcrm\Model\Config\Backend\ApiUrl</backend_model>
</field>
<field id="api_key" translate="label" type="text" sortOrder="1" showInDefault="1" showInWebsite="0" showInStore="0">
<field id="api_key" translate="label" type="text" sortOrder="20" showInDefault="1" showInWebsite="0" showInStore="0">
<label>API Key</label>
<comment>To generate an API Key, log in to RetailCRM then select Admin > Integration > API Keys</comment>
</field>
<field id="api_version" translate="label" type="select" sortOrder="30" showInDefault="1" showInWebsite="0" showInStore="0">
<label>API Version</label>
<source_model>Retailcrm\Retailcrm\Model\Setting\ApiVersions</source_model>
<backend_model>Retailcrm\Retailcrm\Model\Config\Backend\ApiVersion</backend_model>
</field>
</group>
<group id="Misc" translate="label" type="text" sortOrder="20" showInDefault="2" showInWebsite="0" showInStore="0">

View File

@ -3,22 +3,13 @@
<default>
<retailcrm>
<general>
<api_url>test</api_url>
</general>
<section>
<general>
<api_key>{value}</api_key>
</general>
</section>
</retailcrm>
</default>
</config>

View File

@ -1,5 +1,11 @@
<?xml version="1.0"?>
<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">
<arguments>
<argument name="commands" xsi:type="array">
<item name="retailcrm_command" xsi:type="object">Retailcrm\Retailcrm\Console\Command\Command</item>
</argument>
</arguments>
</type>
</config>

View File

@ -1,10 +1,9 @@
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<!-- Order create -->
<event name="sales_order_place_after">
<observer name="sales_order_place_after" instance="Retailcrm\Retailcrm\Model\Observer\OrderCreate" />
<event name="sales_order_save_after">
<observer name="sales_order_save_after" instance="Retailcrm\Retailcrm\Model\Observer\OrderCreate" />
</event>
<!-- Order update -->
@ -18,8 +17,6 @@
<event name="customer_save_after">
<observer name="customer_save_after" instance="Retailcrm\Retailcrm\Model\Observer\Customer" />
</event>
</config>

View File

@ -7,6 +7,5 @@
<observer name="sales_order_place_after" disabled="true"/>
</event>
</config>