1
0
mirror of synced 2024-11-25 14:36:08 +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,61 +1,63 @@
<?php <?php
namespace Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Field; namespace Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Field;
use Magento\Framework\Data\Form\Element\AbstractElement; use Magento\Framework\Data\Form\Element\AbstractElement;
class Attributes extends \Magento\Config\Block\System\Config\Form\Field class Attributes extends \Magento\Config\Block\System\Config\Form\Field
{ {
protected function _getElementHtml(AbstractElement $element) protected function _getElementHtml(AbstractElement $element)
{ {
$values = $element->getValues(); $values = $element->getValues();
$html = '<table id="' . $element->getId() . '_table" class="ui_select_table" cellspacing="0">'; $html = '<table id="' . $element->getId() . '_table" class="ui_select_table" cellspacing="0">';
$html .= '<tbody><tr>'; $html .= '<tbody><tr>';
$html .= '<td><ul id="' . $element->getId() . '_selected" class="ui_select selected sortable">'; $html .= '<td><ul id="' . $element->getId() . '_selected" class="ui_select selected sortable">';
$selected = explode(',', $element->getValue()); $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'] . '">';
$html .= isset($values[$key]['label'])?$values[$key]['label']:'n/a';
$html .= '</li>';
$values[$key]['selected'] = TRUE;
}
}
$html .= '</ul></td><td>'; foreach ($selected as $value) {
$html .= '<ul id="' . $element->getId() . '_source" class="ui_select source sortable">'; if ($key = array_search($value, array_column($values, 'value'))) {
if ($values) { $html .= '<li value="' . $value . '" title="' . $values[$key]['title'] . '">';
foreach ($values as $option) { $html .= isset($values[$key]['label'])?$values[$key]['label']:'n/a';
if (!isset($option['selected'])) { $html .= '</li>';
$html .= '<li value="' . $option['value'] . '" title="' . $option['title'] . '">'; $values[$key]['selected'] = TRUE;
$html .= isset($option['label'])?$option['label']:'n/a'; }
$html .= '</li>'; }
}
}
}
$html .= '</ul></td></tr></tbody></table>'; $html .= '</ul></td><td>';
$html .= '<div style="display:none;">' . $element->getElementHtml() . '</div>'; $html .= '<ul id="' . $element->getId() . '_source" class="ui_select source sortable">';
$html .= '<script type="text/javascript">
require(["jquery"], function(jQuery){
require(["BelVG_Pricelist/js/verpage", "ui/1.11.4"], function(){
jQuery(document).ready( function() {
jQuery("#' . $element->getId() . '_selected, #' . $element->getId() . '_source").sortable({
connectWith: ".sortable",
stop: function(event, ui) {
var vals = [];
jQuery("#' . $element->getId() . '_selected").find("li").each(function(index, element){
vals.push(jQuery(element).val());
});
jQuery("#' . $element->getId() . '").val(vals);
}
}).disableSelection();
});
})
})
</script>';
return $html; if ($values) {
} foreach ($values as $option) {
if (!isset($option['selected'])) {
$html .= '<li value="' . $option['value'] . '" title="' . $option['title'] . '">';
$html .= isset($option['label'])?$option['label']:'n/a';
$html .= '</li>';
}
}
}
$html .= '</ul></td></tr></tbody></table>';
$html .= '<div style="display:none;">' . $element->getElementHtml() . '</div>';
$html .= '<script type="text/javascript">
require(["jquery"], function(jQuery){
require(["BelVG_Pricelist/js/verpage", "ui/1.11.4"], function(){
jQuery(document).ready( function() {
jQuery("#' . $element->getId() . '_selected, #' . $element->getId() . '_source").sortable({
connectWith: ".sortable",
stop: function(event, ui) {
var vals = [];
jQuery("#' . $element->getId() . '_selected").find("li").each(function(index, element){
vals.push(jQuery(element).val());
});
jQuery("#' . $element->getId() . '").val(vals);
}
}).disableSelection();
});
})
})
</script>';
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,96 +1,87 @@
<?php <?php
namespace Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Field; 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 Magento\Framework\Data\Form\Element\AbstractElement;
use Retailcrm\Retailcrm\Helper\Proxy as ApiClient;
class Payment extends \Magento\Config\Block\System\Config\Form\Field class Payment extends \Magento\Config\Block\System\Config\Form\Field
{ {
protected $_apiUrl; protected $_apiUrl;
protected $_apiKey; protected $_apiKey;
protected $_systemStore; protected $_systemStore;
protected $_formFactory; protected $_formFactory;
protected $_logger; protected $_logger;
public function __construct( public function __construct(
\Magento\Framework\Data\FormFactory $formFactory, \Magento\Framework\Data\FormFactory $formFactory,
\Magento\Store\Model\System\Store $systemStore \Magento\Store\Model\System\Store $systemStore
) {
$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)
{ {
$om = \Magento\Framework\App\ObjectManager::getInstance(); $html = '';
$logger = $om->get('\Psr\Log\LoggerInterface'); $htmlError = '<div style="margin-left: 15px;"><b><i>Please check your API Url & API Key</i></b></div>';
$this->_logger = $logger;
$base = new Base; if ((!empty($this->_apiUrl)) && (!empty($this->_apiKey))) {
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$paymentConfig = $objectManager->get('Magento\Payment\Model\Config');
$activePaymentMethods = $paymentConfig->getActiveMethods();
$this->_apiUrl = $base->_apiUrl; $client = new ApiClient($this->_apiUrl, $this->_apiKey, $this->_apiVersion);
$this->_apiKey = $base->_apiKey;
$this->_systemStore = $systemStore; $response = $client->paymentTypesList();
$this->_formFactory = $formFactory;
} if ($response === false) {
return $htmlError;
}
public function render(AbstractElement $element) if ($response->isSuccessful()) {
{ $paymentTypes = $response['paymentTypes'];
$values = $element->getValues(); } else {
$html = ''; return $htmlError;
}
if((!empty($this->_apiUrl))&&(!empty($this->_apiKey))){ $config = \Magento\Framework\App\ObjectManager::getInstance()->get(
'Magento\Framework\App\Config\ScopeConfigInterface'
);
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); foreach (array_keys($activePaymentMethods) as $k=>$payment){
$paymentConfig = $objectManager->get('Magento\Payment\Model\Config'); $html .='<table id="' . $element->getId() . '_table">';
$activePaymentMethods = $paymentConfig->getActiveMethods(); $html .='<tr id="row_retailcrm_payment_'.$payment.'">';
$html .='<td class="label">'.$payment.'</td>';
$html .='<td>';
$html .='<select id="1" name="groups[Payment][fields]['.$payment.'][value]">';
$client = new \Retailcrm\Retailcrm\Model\ApiClient\ApiClient($this->_apiUrl,$this->_apiKey); $selected = $config->getValue('retailcrm/Payment/' . $payment);
try { foreach ($paymentTypes as $k => $value){
$response = $client->paymentTypesList(); if ((!empty($selected)) && (($selected == $value['code']))) {
if ($response->isSuccessful()&&200 === $response->getStatusCode()) { $select = 'selected="selected"';
$paymentTypes = $response['paymentTypes']; }else{
} $select = '';
} catch (Retailcrm\Retailcrm\Model\ApiClient\Exception\CurlException $e) { }
$this->_logger->addDebug($e->getMessage());
}
$config = \Magento\Framework\App\ObjectManager::getInstance()->get( $html .= '<option '.$select.' value="'.$value['code'].'"> '.$value['name'].'</option>';
'Magento\Framework\App\Config\ScopeConfigInterface' }
);
foreach (array_keys($activePaymentMethods) as $k=>$payment){
$html .='<table id="' . $element->getId() . '_table">';
$html .='<tr id="row_retailcrm_payment_'.$payment.'">';
$html .='<td class="label">'.$payment.'</td>';
$html .='<td>';
$html .='<select id="1" name="groups[Payment][fields]['.$payment.'][value]">';
$selected = $config->getValue('retailcrm/Payment/'.$payment);
foreach ($paymentTypes as $k=>$value){
if((!empty($selected))&&(($selected==$value['code']))){
$select ='selected="selected"';
}else{
$select ='';
}
$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;
}
}
$html .= '</select>';
$html .= '</td>';
$html .= '</tr>';
$html .= '</table>';
}
return $html;
} else {
return $htmlError;
}
}
} }

View File

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

View File

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

View File

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

View File

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

View File

@ -7,24 +7,23 @@ use Psr\Log\LoggerInterface;
class Test extends \Magento\Framework\App\Action\Action class Test extends \Magento\Framework\App\Action\Action
{ {
protected $logger; protected $logger;
public function __construct( public function __construct(
LoggerInterface $logger LoggerInterface $logger,
,\Magento\Framework\App\Action\Context $context \Magento\Framework\App\Action\Context $context,
,\Magento\Framework\View\Page\Config $pageConfig \Magento\Framework\View\Page\Config $pageConfig,
,\Magento\Framework\App\Config\ScopeConfigInterface $config \Magento\Framework\App\Config\ScopeConfigInterface $config
) ) {
{ $this->logger = $logger;
$this->logger = $logger;
$api_url = $config->getValue('retailcrm/general/api_url'); $api_url = $config->getValue('retailcrm/general/api_url');
$api_key = $config->getValue('retailcrm/general/api_key'); $api_key = $config->getValue('retailcrm/general/api_key');
var_dump($api_key); var_dump($api_key);
var_dump($api_url); var_dump($api_url);
//$this->logger->debug($api_url); //$this->logger->debug($api_url);
parent::__construct($context); parent::__construct($context);
} }
@ -34,5 +33,4 @@ class Test extends \Magento\Framework\App\Action\Action
// //
exit; exit;
} }
} }

View File

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

View File

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

View File

@ -1,4 +1,5 @@
<?php <?php
namespace Retailcrm\Retailcrm\Helper; namespace Retailcrm\Retailcrm\Helper;
use Magento\Framework\App\Helper\AbstractHelper; use Magento\Framework\App\Helper\AbstractHelper;
@ -47,21 +48,21 @@ class Data extends AbstractHelper
*/ */
public function filterRecursive($haystack) public function filterRecursive($haystack)
{ {
foreach ($haystack as $key => $value) { foreach ($haystack as $key => $value) {
if (is_array($value)) { if (is_array($value)) {
$haystack[$key] = self::filterRecursive($haystack[$key]); $haystack[$key] = self::filterRecursive($haystack[$key]);
} }
if (is_null($haystack[$key]) if (is_null($haystack[$key])
|| $haystack[$key] === '' || $haystack[$key] === ''
|| count($haystack[$key]) == 0 || count($haystack[$key]) == 0
) { ) {
unset($haystack[$key]); unset($haystack[$key]);
} elseif (!is_array($value)) { } elseif (!is_array($value)) {
$haystack[$key] = trim($value); $haystack[$key] = trim($value);
} }
} }
return $haystack; return $haystack;
} }
} }

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'));
}
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,4 +1,5 @@
<?php <?php
namespace Retailcrm\Retailcrm\Model\Icml; namespace Retailcrm\Retailcrm\Model\Icml;
class Icml class Icml
@ -17,25 +18,25 @@ class Icml
public function __construct() public function __construct()
{ {
$om = \Magento\Framework\App\ObjectManager::getInstance(); $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$manager = $om->get('Magento\Store\Model\StoreManagerInterface'); $manager = $objectManager->get('Magento\Store\Model\StoreManagerInterface');
$categoryCollectionFactory = $om->get('\Magento\Catalog\Model\ResourceModel\Category\CollectionFactory'); $categoryCollectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Category\CollectionFactory');
$product = $om->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory'); $product = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$storeManager = $om->get('\Magento\Store\Model\StoreManagerInterface'); $storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface');
$StockState = $om->get('\Magento\CatalogInventory\Api\StockStateInterface'); $StockState = $objectManager->get('\Magento\CatalogInventory\Api\StockStateInterface');
$configurable = $om->get('Magento\ConfigurableProduct\Model\Product\Type\Configurable'); $configurable = $objectManager->get('Magento\ConfigurableProduct\Model\Product\Type\Configurable');
$config = $om->get('\Magento\Framework\App\Config\ScopeConfigInterface'); $config = $objectManager->get('\Magento\Framework\App\Config\ScopeConfigInterface');
$this->_configurable = $configurable; $this->_configurable = $configurable;
$this->_StockState = $StockState; $this->_StockState = $StockState;
$this->_storeManager = $storeManager; $this->_storeManager = $storeManager;
$this->_product = $product; $this->_product = $product;
$this->_category = $categoryCollectionFactory; $this->_category = $categoryCollectionFactory;
$this->_manager = $manager; $this->_manager = $manager;
$this->_config = $config; $this->_config = $config;
} }
public function generate() public function generate()
{ {
$this->_shop = $this->_manager->getStore()->getId(); $this->_shop = $this->_manager->getStore()->getId();
@ -72,221 +73,240 @@ class Icml
$baseDir = $dirlist->getRoot(); $baseDir = $dirlist->getRoot();
$shopCode = $this->_manager->getStore()->getCode(); $shopCode = $this->_manager->getStore()->getCode();
$this->_dd->save($baseDir . 'retailcrm_' . $shopCode . '.xml'); $this->_dd->save($baseDir . 'retailcrm_' . $shopCode . '.xml');
} }
private function addCategories() private function addCategories()
{ {
$collection = $this->_category->create(); $collection = $this->_category->create();
$collection->addAttributeToSelect('*'); $collection->addAttributeToSelect('*');
foreach ($collection as $category) { foreach ($collection as $category) {
if($category->getId()>1){ if ($category->getId() > 1){
$e = $this->_eCategories->appendChild( $e = $this->_eCategories->appendChild(
$this->_dd->createElement('category') $this->_dd->createElement('category')
); );
$e->appendChild($this->_dd->createTextNode($category->getName())); $e->appendChild($this->_dd->createTextNode($category->getName()));
$e->setAttribute('id', $category->getId()); $e->setAttribute('id', $category->getId());
if ($category->getParentId() > 1) { if ($category->getParentId() > 1) {
$e->setAttribute('parentId', $category->getParentId()); $e->setAttribute('parentId', $category->getParentId());
} }
} }
} }
} }
private function addOffers() private function addOffers()
{ {
$offers = array(); $offers = [];
$collection = $this->_product->create(); $collection = $this->_product->create();
$collection->addFieldToFilter('visibility', 4);//catalog, search visible $collection->addFieldToFilter('visibility', 4);//catalog, search visible
$collection->addAttributeToSelect('*'); $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(); $baseUrl = $this->_storeManager->getStore()->getBaseUrl();
$customAdditionalAttributes = array(); $customAdditionalAttributes = [];
$customAdditionalAttributes = $this->_config->getValue('retailcrm/Misc/attributes_to_export_into_icml'); $customAdditionalAttributes = $this->_config->getValue('retailcrm/Misc/attributes_to_export_into_icml');
foreach ($collection as $product) { foreach ($collection as $product) {
if ($product->getTypeId() == 'simple') {
$offer['id'] = $product->getId();
$offer['productId'] = $product->getId();
$offer['productActivity'] = $product->isAvailable() ? 'Y' : 'N';
$offer['name'] = $product->getName();
$offer['productName'] = $product->getName();
$offer['initialPrice'] = $product->getFinalPrice();
$offer['url'] = $product->getProductUrl();
$offer['picture'] = $picUrl.'catalog/product'.$product->getImage();
$offer['quantity'] = $this->_StockState->getStockQty($product->getId(), $product->getStore()->getWebsiteId());
$offer['categoryId'] = $product->getCategoryIds();
$offer['vendor'] = $product->getAttributeText('manufacturer');
$offer['params'] = [];
if($product->getTypeId() == 'simple') { $article = $product->getSku();
$offer['id'] = $product->getId();
$offer['productId'] = $product->getId();
$offer['productActivity'] = $product->isAvailable() ? 'Y' : 'N';
$offer['name'] = $product->getName();
$offer['productName'] = $product->getName();
$offer['initialPrice'] = $product->getFinalPrice();
$offer['url'] = $product->getProductUrl();
$offer['picture'] = $picUrl.'catalog/product'.$product->getImage();
$offer['quantity'] = $this->_StockState->getStockQty($product->getId(), $product->getStore()->getWebsiteId());
$offer['categoryId'] = $product->getCategoryIds();
$offer['vendor'] = $product->getAttributeText('manufacturer');
$offer['params'] = array();
if(!empty($article)) {
$offer['params'][] = [
'name' => 'Article',
'code' => 'article',
'value' => $article
];
}
$article = $product->getSku(); $weight = $product->getWeight();
if(!empty($article)) {
$offer['params'][] = array(
'name' => 'Article',
'code' => 'article',
'value' => $article
);
}
$weight = $product->getWeight(); if(!empty($weight)) {
if(!empty($weight)) { $offer['params'][] = [
$offer['params'][] = array( 'name' => 'Weight',
'name' => 'Weight', 'code' => 'weight',
'code' => 'weight', 'value' => $weight
'value' => $weight ];
); }
}
if(!empty($customAdditionalAttributes)) { if(!empty($customAdditionalAttributes)) {
//var_dump($customAdditionalAttributes); //var_dump($customAdditionalAttributes);
} }
$offers[] = $offer;
}
$offers[] = $offer; if ($product->getTypeId() == 'configurable') {
$associated_products = $this->_configurable
->getUsedProductCollection($product)
->addAttributeToSelect('*')
->addFilterByRequiredOptions();
} foreach ($associated_products as $associatedProduct) {
$offer['id'] = $associatedProduct->getId();
$offer['productId'] = $product->getId();
$offer['productActivity'] = $associatedProduct->isAvailable() ? 'Y' : 'N';
$offer['name'] = $associatedProduct->getName();
$offer['productName'] = $product->getName();
$offer['initialPrice'] = $associatedProduct->getFinalPrice();
$offer['url'] = $product->getProductUrl();
$offer['picture'] = $picUrl.'catalog/product'.$associatedProduct->getImage();
$offer['quantity'] = $this->_StockState->getStockQty($associatedProduct->getId(), $associatedProduct->getStore()->getWebsiteId());
$offer['categoryId'] = $associatedProduct->getCategoryIds();
$offer['vendor'] = $associatedProduct->getAttributeText('manufacturer');
$offer['params'] = [];
if($product->getTypeId() == 'configurable') { $article = $associatedProduct->getSku();
$associated_products = $this->_configurable if ($associatedProduct->getResource()->getAttribute('color')) {
->getUsedProductCollection($product) $colorAttribute = $associatedProduct->getResource()->getAttribute('color');
->addAttributeToSelect('*') $color = $colorAttribute->getSource()->getOptionText($associatedProduct->getColor());
->addFilterByRequiredOptions(); }
foreach ($associated_products as $associatedProduct) { if (isset($color)) {
$offer['id'] = $associatedProduct->getId(); $offer['params'][] = [
$offer['productId'] = $product->getId(); 'name' => 'Color',
$offer['productActivity'] = $associatedProduct->isAvailable() ? 'Y' : 'N'; 'code' => 'color',
$offer['name'] = $associatedProduct->getName(); 'value' => $color
$offer['productName'] = $product->getName(); ];
$offer['initialPrice'] = $associatedProduct->getFinalPrice(); }
$offer['url'] = $product->getProductUrl();
$offer['picture'] = $picUrl.'catalog/product'.$associatedProduct->getImage();
$offer['quantity'] = $this->_StockState->getStockQty($associatedProduct->getId(), $associatedProduct->getStore()->getWebsiteId());
$offer['categoryId'] = $associatedProduct->getCategoryIds();
$offer['vendor'] = $associatedProduct->getAttributeText('manufacturer');
$offer['params'] = array();
$article = $associatedProduct->getSku(); if ($associatedProduct->getResource()->getAttribute('size')) {
if(!empty($article)) { $sizeAttribute = $associatedProduct->getResource()->getAttribute('size');
$offer['params'][] = array( $size = $sizeAttribute->getSource()->getOptionText($associatedProduct->getSize());
'name' => 'Article', }
'code' => 'article',
'value' => $article
);
}
$weight = $associatedProduct->getWeight(); if (isset($size)) {
if(!empty($weight)) { $offer['params'][] = [
$offer['params'][] = array( 'name' => 'Size',
'name' => 'Weight', 'code' => 'size',
'code' => 'weight', 'value' => $size
'value' => $weight ];
); }
}
$offers[] = $offer; if (!empty($article)) {
} $offer['params'][] = [
'name' => 'Article',
'code' => 'article',
'value' => $article
];
}
$weight = $associatedProduct->getWeight();
} if(!empty($weight)) {
} $offer['params'][] = [
'name' => 'Weight',
'code' => 'weight',
'value' => $weight
];
}
$offers[] = $offer;
}
}
}
foreach ($offers as $offer) { foreach ($offers as $offer) {
$e = $this->_eOffers->appendChild( $e = $this->_eOffers->appendChild(
$this->_dd->createElement('offer') $this->_dd->createElement('offer')
); );
$e->setAttribute('id', $offer['id']); $e->setAttribute('id', $offer['id']);
$e->setAttribute('productId', $offer['productId']); $e->setAttribute('productId', $offer['productId']);
if (!empty($offer['quantity'])) { if (!empty($offer['quantity'])) {
$e->setAttribute('quantity', (int) $offer['quantity']); $e->setAttribute('quantity', (int) $offer['quantity']);
} else { } else {
$e->setAttribute('quantity', 0); $e->setAttribute('quantity', 0);
} }
if (!empty($offer['categoryId'])) { if (!empty($offer['categoryId'])) {
foreach ($offer['categoryId'] as $categoryId) { foreach ($offer['categoryId'] as $categoryId) {
$e->appendChild( $e->appendChild(
$this->_dd->createElement('categoryId') $this->_dd->createElement('categoryId')
)->appendChild( )->appendChild(
$this->_dd->createTextNode($categoryId) $this->_dd->createTextNode($categoryId)
); );
} }
} else { } else {
$e->appendChild($this->_dd->createElement('categoryId', 1)); $e->appendChild($this->_dd->createElement('categoryId', 1));
} }
$e->appendChild($this->_dd->createElement('productActivity')) $e->appendChild($this->_dd->createElement('productActivity'))
->appendChild( ->appendChild(
$this->_dd->createTextNode($offer['productActivity']) $this->_dd->createTextNode($offer['productActivity'])
); );
$e->appendChild($this->_dd->createElement('name')) $e->appendChild($this->_dd->createElement('name'))
->appendChild( ->appendChild(
$this->_dd->createTextNode($offer['name']) $this->_dd->createTextNode($offer['name'])
); );
$e->appendChild($this->_dd->createElement('productName')) $e->appendChild($this->_dd->createElement('productName'))
->appendChild( ->appendChild(
$this->_dd->createTextNode($offer['productName']) $this->_dd->createTextNode($offer['productName'])
); );
$e->appendChild($this->_dd->createElement('price')) $e->appendChild($this->_dd->createElement('price'))
->appendChild( ->appendChild(
$this->_dd->createTextNode($offer['initialPrice']) $this->_dd->createTextNode($offer['initialPrice'])
); );
if (!empty($offer['purchasePrice'])) { if (!empty($offer['purchasePrice'])) {
$e->appendChild($this->_dd->createElement('purchasePrice')) $e->appendChild($this->_dd->createElement('purchasePrice'))
->appendChild( ->appendChild(
$this->_dd->createTextNode($offer['purchasePrice']) $this->_dd->createTextNode($offer['purchasePrice'])
); );
} }
if (!empty($offer['picture'])) { if (!empty($offer['picture'])) {
$e->appendChild($this->_dd->createElement('picture')) $e->appendChild($this->_dd->createElement('picture'))
->appendChild( ->appendChild(
$this->_dd->createTextNode($offer['picture']) $this->_dd->createTextNode($offer['picture'])
); );
} }
if (!empty($offer['url'])) { if (!empty($offer['url'])) {
$e->appendChild($this->_dd->createElement('url')) $e->appendChild($this->_dd->createElement('url'))
->appendChild( ->appendChild(
$this->_dd->createTextNode($offer['url']) $this->_dd->createTextNode($offer['url'])
); );
} }
if (!empty($offer['vendor'])) { if (!empty($offer['vendor'])) {
$e->appendChild($this->_dd->createElement('vendor')) $e->appendChild($this->_dd->createElement('vendor'))
->appendChild( ->appendChild(
$this->_dd->createTextNode($offer['vendor']) $this->_dd->createTextNode($offer['vendor'])
); );
} }
if(!empty($offer['params'])) {
foreach($offer['params'] as $param) {
$paramNode = $this->_dd->createElement('param');
$paramNode->setAttribute('name', $param['name']);
$paramNode->setAttribute('code', $param['code']);
$paramNode->appendChild(
$this->_dd->createTextNode($param['value'])
);
$e->appendChild($paramNode);
}
}
}
if(!empty($offer['params'])) {
foreach($offer['params'] as $param) {
$paramNode = $this->_dd->createElement('param');
$paramNode->setAttribute('name', $param['name']);
$paramNode->setAttribute('code', $param['code']);
$paramNode->appendChild(
$this->_dd->createTextNode($param['value'])
);
$e->appendChild($paramNode);
}
}
}
} }
} }

View File

@ -1,29 +1,94 @@
<?php <?php
namespace Retailcrm\Retailcrm\Model\Logger; namespace Retailcrm\Retailcrm\Model\Logger;
class Logger class Logger
{ {
private $logPath; private $logDir;
private $files;
public function __construct( public function __construct(\Magento\Framework\ObjectManagerInterface $objectManager)
$logPath = '/app/code/Retailcrm/Retailcrm/Log/'
)
{ {
$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'; $filePath = $this->logDir . '/' . $fileName . '.log';
$f = fopen($_SERVER["DOCUMENT_ROOT"].$path, "a+"); if (!$this->checkSize($filePath)) {
fwrite($f, print_r(array(date('Y-m-d H:i:s'), array( $this->clear($filePath);
$dump }
)),true));
fclose($f);
$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,59 +1,66 @@
<?php <?php
namespace Retailcrm\Retailcrm\Model\Observer; namespace Retailcrm\Retailcrm\Model\Observer;
use Magento\Framework\Event\Observer;
use Retailcrm\Retailcrm\Helper\Proxy as ApiClient;
class Customer implements \Magento\Framework\Event\ObserverInterface class Customer implements \Magento\Framework\Event\ObserverInterface
{ {
protected $_api; protected $_api;
protected $_config; protected $_config;
protected $_helper; protected $_helper;
protected $_logger; protected $_logger;
protected $_objectManager;
protected $registry;
public function __construct() public function __construct(
{ \Magento\Framework\ObjectManagerInterface $objectManager,
$om = \Magento\Framework\App\ObjectManager::getInstance(); \Magento\Framework\App\Config\ScopeConfigInterface $config,
$helper = $om->get('\Retailcrm\Retailcrm\Helper\Data'); \Magento\Framework\Registry $registry
$logger = $om->get('\Psr\Log\LoggerInterface'); ) {
$config = $om->get('\Magento\Framework\App\Config\ScopeConfigInterface'); $helper = $objectManager->get('\Retailcrm\Retailcrm\Helper\Data');
$logger = $objectManager->get('\Retailcrm\Retailcrm\Model\Logger\Logger');
$this->_logger = $logger; $this->_logger = $logger;
$this->_helper = $helper; $this->_helper = $helper;
$this->_config = $config; $this->_config = $config;
$this->_objectManager = $objectManager;
$this->registry = $registry;
$url = $config->getValue('retailcrm/general/api_url'); $url = $config->getValue('retailcrm/general/api_url');
$key = $config->getValue('retailcrm/general/api_key'); $key = $config->getValue('retailcrm/general/api_key');
$version = $config->getValue('retailcrm/general/api_version');
if(!empty($url) && !empty($key)) { 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;
}
public function execute(\Magento\Framework\Event\Observer $observer) $data = $observer->getEvent()->getCustomer();
{
$data = $observer->getEvent()->getCustomer();
$customer = array( $customer = [
'externalId' => $data->getId(), 'externalId' => $data->getId(),
'email' => $data->getEmail(), 'email' => $data->getEmail(),
'firstName' => $data->getFirstname(), 'firstName' => $data->getFirstname(),
'patronymic' => $data->getMiddlename(), 'patronymic' => $data->getMiddlename(),
'lastName' => $data->getLastname(), 'lastName' => $data->getLastname(),
'createdAt' => date('Y-m-d H:i:s', strtotime($data->getCreatedAt())) 'createdAt' => date('Y-m-d H:i:s', strtotime($data->getCreatedAt()))
); ];
$response = $this->_api->customersEdit($customer);
if ((404 === $response->getStatusCode()) &&($response['errorMsg']==='Not found')) {
$this->_api->customersCreate($customer);
}
//$logger = new \Retailcrm\Retailcrm\Model\Logger\Logger();
//$logger->write($customer,'Customer');
}
$response = $this->_api->customersEdit($customer);
if ($response === false) {
return;
}
if (!$response->isSuccessful() && $response->errorMsg == $this->_api->getErrorText('errorNotFound')) {
$this->_api->customersCreate($customer);
}
}
} }

View File

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

View File

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

View File

@ -1,168 +1,165 @@
<?php <?php
namespace Retailcrm\Retailcrm\Model\Order; 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 OrderCreate
class OrderNumber extends \Retailcrm\Retailcrm\Model\Observer\OrderCreate
{ {
protected $_orderRepository; protected $_orderRepository;
protected $_searchCriteriaBuilder; protected $_searchCriteriaBuilder;
protected $_config; protected $_config;
protected $_filterBuilder; protected $_filterBuilder;
protected $_order; protected $_order;
protected $_helper; protected $_helper;
protected $_api; protected $_api;
protected $_logger;
public function __construct() public function __construct()
{ {
$om = \Magento\Framework\App\ObjectManager::getInstance(); $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$orderRepository = $om->get('Magento\Sales\Model\OrderRepository'); $orderRepository = $objectManager->get('Magento\Sales\Model\OrderRepository');
$searchCriteriaBuilder = $om->get('Magento\Framework\Api\SearchCriteriaBuilder'); $searchCriteriaBuilder = $objectManager->get('Magento\Framework\Api\SearchCriteriaBuilder');
$config = $om->get('Magento\Framework\App\Config\ScopeConfigInterface'); $config = $objectManager->get('Magento\Framework\App\Config\ScopeConfigInterface');
$filterBuilder = $om->get('Magento\Framework\Api\FilterBuilder'); $filterBuilder = $objectManager->get('Magento\Framework\Api\FilterBuilder');
$order = $om->get('\Magento\Sales\Api\Data\OrderInterface'); $order = $objectManager->get('\Magento\Sales\Api\Data\OrderInterface');
$helper = $om->get('\Retailcrm\Retailcrm\Helper\Data'); $helper = $objectManager->get('\Retailcrm\Retailcrm\Helper\Data');
$this->_orderRepository = $orderRepository; $this->_orderRepository = $orderRepository;
$this->_searchCriteriaBuilder = $searchCriteriaBuilder; $this->_searchCriteriaBuilder = $searchCriteriaBuilder;
$this->_config = $config; $this->_config = $config;
$this->_filterBuilder = $filterBuilder; $this->_filterBuilder = $filterBuilder;
$this->_order = $order; $this->_order = $order;
$this->_helper = $helper; $this->_helper = $helper;
$this->_logger = $objectManager->get('\Retailcrm\Retailcrm\Model\Logger\Logger');
$url = $config->getValue('retailcrm/general/api_url'); $url = $config->getValue('retailcrm/general/api_url');
$key = $config->getValue('retailcrm/general/api_key'); $key = $config->getValue('retailcrm/general/api_key');
$version = $config->getValue('retailcrm/general/api_version');
if(!empty($url) && !empty($key)) { if (!empty($url) && !empty($key)) {
$this->_api = new \Retailcrm\Retailcrm\Model\ApiClient\ApiClient($url,$key); $this->_api = new ApiClient($url, $key, $version);
} }
} }
public function ExportOrderNumber() public function ExportOrderNumber()
{ {
$ordernumber = $this->_config->getValue('retailcrm/Load/number_order'); $ordernumber = $this->_config->getValue('retailcrm/Load/number_order');
$ordersId = explode(",", $ordernumber); $ordersId = explode(",", $ordernumber);
$orders = array(); $orders = [];
foreach ($ordersId as $id) { foreach ($ordersId as $id) {
$orders[] = $this->prepareOrder($id); $orders[] = $this->prepareOrder($id);
} }
$chunked = array_chunk($orders, 50); $chunked = array_chunk($orders, 50);
unset($orders); unset($orders);
foreach ($chunked as $chunk) { foreach ($chunked as $chunk) {
$this->_api->ordersUpload($chunk); $this->_api->ordersUpload($chunk);
time_nanosleep(0, 250000000); time_nanosleep(0, 250000000);
} }
unset($chunked); unset($chunked);
return true; return true;
}
} public function prepareOrder($id)
{
$magentoOrder = $this->_order->load($id);
public function prepareOrder($id) $items = [];
{ $addressObj = $magentoOrder->getBillingAddress();
$magentoOrder = $this->_order->loadByIncrementId($id);
$magentoOrderArr = $magentoOrder->getData();
$items = array(); foreach ($magentoOrder->getAllItems() as $item) {
$addressObj = $magentoOrder->getBillingAddress(); if ($item->getProductType() == "simple") {
$price = $item->getPrice();
foreach ($magentoOrder->getAllItems() as $item) { if ($price == 0){
if ($item->getProductType() == "simple") { $om = \Magento\Framework\App\ObjectManager::getInstance();
$omproduct = $om->get('Magento\Catalog\Model\ProductRepository')
->getById($item->getProductId());
$price = $omproduct->getPrice();
}
$price = $item->getPrice(); $product = [
'productId' => $item->getProductId(),
'productName' => $item->getName(),
'quantity' => $item->getQtyOrdered(),
'initialPrice' => $price,
'offer' => [
'externalId'=>$item->getProductId()
]
];
if($price == 0){ unset($om);
$om = \Magento\Framework\App\ObjectManager::getInstance(); unset($omproduct);
$omproduct = $om->get('Magento\Catalog\Model\ProductRepository') unset($price);
->getById($item->getProductId());
$price = $omproduct->getPrice();
}
$product = array( $items[] = $product;
'productId' => $item->getProductId(), }
'productName' => $item->getName(), }
'quantity' => $item->getQtyOrdered(),
'initialPrice' => $price,
'offer'=>array(
'externalId'=>$item->getProductId()
)
);
unset($om); $ship = $this->getShippingCode($magentoOrder->getShippingMethod());
unset($omproduct);
unset($price);
$items[] = $product; $preparedOrder = [
} 'site' => $magentoOrder->getStore()->getCode(),
} 'externalId' => $magentoOrder->getRealOrderId(),
'number' => $magentoOrder->getRealOrderId(),
'createdAt' => date('Y-m-d H:i:s'),
'lastName' => $magentoOrder->getCustomerLastname(),
'firstName' => $magentoOrder->getCustomerFirstname(),
'patronymic' => $magentoOrder->getCustomerMiddlename(),
'email' => $magentoOrder->getCustomerEmail(),
'phone' => $addressObj->getTelephone(),
'paymentType' => $this->_config->getValue('retailcrm/Payment/'.$magentoOrder->getPayment()->getMethodInstance()->getCode()),
'status' => $this->_config->getValue('retailcrm/Status/'.$magentoOrder->getStatus()),
'discount' => abs($magentoOrder->getDiscountAmount()),
'items' => $items,
'delivery' => [
'code' => $this->_config->getValue('retailcrm/Shipping/'.$ship),
'cost' => $magentoOrder->getShippingAmount(),
'address' => [
'index' => $addressObj->getData('postcode'),
'city' => $addressObj->getData('city'),
'country' => $addressObj->getData('country_id'),
'street' => $addressObj->getData('street'),
'region' => $addressObj->getData('region'),
'text' => trim(
',',
implode(
',',
[
$addressObj->getData('postcode'),
$addressObj->getData('city'),
$addressObj->getData('street'),
]
)
)
]
]
];
$ship = $this->getShippingCode($magentoOrder->getShippingMethod()); if (trim($preparedOrder['delivery']['code']) == ''){
unset($preparedOrder['delivery']['code']);
}
$preparedOrder = array( if (trim($preparedOrder['paymentType']) == ''){
'site' => $magentoOrder->getStore()->getCode(), unset($preparedOrder['paymentType']);
'externalId' => $magentoOrder->getRealOrderId(), }
'number' => $magentoOrder->getRealOrderId(),
'createdAt' => date('Y-m-d H:i:s'),
'lastName' => $magentoOrder->getCustomerLastname(),
'firstName' => $magentoOrder->getCustomerFirstname(),
'patronymic' => $magentoOrder->getCustomerMiddlename(),
'email' => $magentoOrder->getCustomerEmail(),
'phone' => $addressObj->getTelephone(),
'paymentType' => $this->_config->getValue('retailcrm/Payment/'.$magentoOrder->getPayment()->getMethodInstance()->getCode()),
'status' => $this->_config->getValue('retailcrm/Status/'.$magentoOrder->getStatus()),
'discount' => abs($magentoOrder->getDiscountAmount()),
'items' => $items,
'delivery' => array(
'code' => $this->_config->getValue('retailcrm/Shipping/'.$ship),
'cost' => $magentoOrder->getShippingAmount(),
'address' => array(
'index' => $addressObj->getData('postcode'),
'city' => $addressObj->getData('city'),
'country' => $addressObj->getData('country_id'),
'street' => $addressObj->getData('street'),
'region' => $addressObj->getData('region'),
'text' => trim(
',',
implode(
',',
array(
$addressObj->getData('postcode'),
$addressObj->getData('city'),
$addressObj->getData('street'),
)
)
)
)
)
);
if(trim($preparedOrder['delivery']['code']) == ''){ if (trim($preparedOrder['status']) == ''){
unset($preparedOrder['delivery']['code']); unset($preparedOrder['status']);
} }
if(trim($preparedOrder['paymentType']) == ''){ if ($magentoOrder->getCustomerIsGuest() == 0) {
unset($preparedOrder['paymentType']); $preparedOrder['customer']['externalId'] = $magentoOrder->getCustomerId();
} }
if(trim($preparedOrder['status']) == ''){ $this->_logger->writeDump($preparedOrder,'OrderNumber');
unset($preparedOrder['status']);
}
if ($magentoOrder->getCustomerIsGuest() == 0) {
$preparedOrder['customer']['externalId'] = $magentoOrder->getCustomerId();
}
$logger = new \Retailcrm\Retailcrm\Model\Logger\Logger();
$logger->write($preparedOrder,'OrderNumber');
return $this->_helper->filterRecursive($preparedOrder);
}
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,36 +2,33 @@
namespace Retailcrm\Retailcrm\Model\Setting; namespace Retailcrm\Retailcrm\Model\Setting;
//use Psr\Log\LoggerInterface;
class Attribute implements \Magento\Framework\Option\ArrayInterface class Attribute implements \Magento\Framework\Option\ArrayInterface
{ {
protected $_entityType; protected $_entityType;
protected $_store; protected $_store;
public function __construct( public function __construct(
\Magento\Store\Model\Store $store, \Magento\Store\Model\Store $store,
\Magento\Eav\Model\Entity\Type $entityType \Magento\Eav\Model\Entity\Type $entityType
) { ) {
$this->_store = $store; $this->_store = $store;
$this->_entityType = $entityType; $this->_entityType = $entityType;
} }
public function toOptionArray() public function toOptionArray()
{ {
$types = array('text', 'multiselect', 'decimal'); $types = ['text', 'multiselect', 'decimal'];
$attributes = $this->_entityType->loadByCode('catalog_product')->getAttributeCollection(); $attributes = $this->_entityType->loadByCode('catalog_product')->getAttributeCollection();
$attributes->addFieldToFilter('frontend_input', $types); $attributes->addFieldToFilter('frontend_input', $types);
$result = array(); $result = [];
foreach ($attributes as $attr) {
if ($attr->getFrontendLabel()) {
$result[] = array('value' => $attr->getAttributeId(), 'label' => $attr->getFrontendLabel(), 'title' => $attr->getAttributeCode());
}
}
return $result;
}
foreach ($attributes as $attr) {
if ($attr->getFrontendLabel()) {
$result[] = array('value' => $attr->getAttributeId(), 'label' => $attr->getFrontendLabel(), 'title' => $attr->getAttributeCode());
}
}
return $result;
}
} }

View File

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

View File

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

View File

@ -1,16 +1,29 @@
Magento module 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: Module allows:
* Exchange the orders with retailCRM * Exchange the orders data with retailCRM
* Configure relations between dictionaries of RetailCRM and Magento (statuses, payments, delivery types and etc) * 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 * 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", "name": "retailcrm/retailcrm",
"description": "Retailcrm", "description": "Retailcrm",
"require": { "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", "type": "magento2-module",
"version": "1.0.0", "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"> <group id="general" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="0" showInStore="0">
<label>General Configuration</label> <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> <label>API URL</label>
<comment>https://YourCrmName.retailcrm.ru</comment> <comment>https://YourCrmName.retailcrm.ru</comment>
<backend_model>Retailcrm\Retailcrm\Model\Config\Backend\ApiUrl</backend_model>
</field> </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> <label>API Key</label>
<comment>To generate an API Key, log in to RetailCRM then select Admin > Integration > API Keys</comment> <comment>To generate an API Key, log in to RetailCRM then select Admin > Integration > API Keys</comment>
</field> </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>
<group id="Misc" translate="label" type="text" sortOrder="20" showInDefault="2" showInWebsite="0" showInStore="0"> <group id="Misc" translate="label" type="text" sortOrder="20" showInDefault="2" showInWebsite="0" showInStore="0">

View File

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

View File

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

View File

@ -1,25 +1,22 @@
<?xml version="1.0"?> <?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd"> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<!-- Order create -->
<!-- Order create --> <event name="sales_order_save_after">
<observer name="sales_order_save_after" instance="Retailcrm\Retailcrm\Model\Observer\OrderCreate" />
</event>
<event name="sales_order_place_after"> <!-- Order update -->
<observer name="sales_order_place_after" instance="Retailcrm\Retailcrm\Model\Observer\OrderCreate" />
</event>
<!-- Order update --> <event name="sales_order_save_commit_after">
<observer name="sales_order_save_commit_after" instance="Retailcrm\Retailcrm\Model\Observer\OrderUpdate" />
<event name="sales_order_save_commit_after"> </event>
<observer name="sales_order_save_commit_after" instance="Retailcrm\Retailcrm\Model\Observer\OrderUpdate" />
</event>
<!-- after customer save -->
<event name="customer_save_after">
<observer name="customer_save_after" instance="Retailcrm\Retailcrm\Model\Observer\Customer" />
</event>
<!-- after customer save -->
<event name="customer_save_after">
<observer name="customer_save_after" instance="Retailcrm\Retailcrm\Model\Observer\Customer" />
</event>
</config> </config>

View File

@ -4,9 +4,8 @@
<!-- Order create --> <!-- Order create -->
<event name="sales_order_place_after"> <event name="sales_order_place_after">
<observer name="sales_order_place_after" disabled="true"/> <observer name="sales_order_place_after" disabled="true"/>
</event> </event>
</config> </config>