1
0
mirror of synced 2024-11-22 04:56:07 +03:00

Multiversions api (#8)

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

View File

@ -72,4 +72,4 @@ class Button extends \Magento\Config\Block\System\Config\Form\Field
return $button->toHtml(); return $button->toHtml();
} }
} }

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

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

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

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,25 +7,24 @@ 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);
} }
@ -33,6 +32,5 @@ 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() {
$history = new \Retailcrm\Retailcrm\Model\History\Exchange();
$history->ordersHistory();
$this->_logger->addDebug('Cron Works: OrderHistory');
} }
} public function execute()
{
$history = new \Retailcrm\Retailcrm\Model\History\Exchange();
$history->ordersHistory();
$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,26 +18,26 @@ 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();
$string = '<?xml version="1.0" encoding="UTF-8"?> $string = '<?xml version="1.0" encoding="UTF-8"?>
@ -71,222 +72,241 @@ class Icml
$dirlist = new \Magento\Framework\Filesystem\DirectoryList(''); $dirlist = new \Magento\Framework\Filesystem\DirectoryList('');
$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') {
if($product->getTypeId() == 'simple') { $offer['id'] = $product->getId();
$offer['id'] = $product->getId(); $offer['productId'] = $product->getId();
$offer['productId'] = $product->getId(); $offer['productActivity'] = $product->isAvailable() ? 'Y' : 'N';
$offer['productActivity'] = $product->isAvailable() ? 'Y' : 'N'; $offer['name'] = $product->getName();
$offer['name'] = $product->getName(); $offer['productName'] = $product->getName();
$offer['productName'] = $product->getName(); $offer['initialPrice'] = $product->getFinalPrice();
$offer['initialPrice'] = $product->getFinalPrice(); $offer['url'] = $product->getProductUrl();
$offer['url'] = $product->getProductUrl(); $offer['picture'] = $picUrl.'catalog/product'.$product->getImage();
$offer['picture'] = $picUrl.'catalog/product'.$product->getImage(); $offer['quantity'] = $this->_StockState->getStockQty($product->getId(), $product->getStore()->getWebsiteId());
$offer['quantity'] = $this->_StockState->getStockQty($product->getId(), $product->getStore()->getWebsiteId()); $offer['categoryId'] = $product->getCategoryIds();
$offer['categoryId'] = $product->getCategoryIds(); $offer['vendor'] = $product->getAttributeText('manufacturer');
$offer['vendor'] = $product->getAttributeText('manufacturer'); $offer['params'] = [];
$offer['params'] = array();
$article = $product->getSku();
$article = $product->getSku(); if(!empty($article)) {
if(!empty($article)) { $offer['params'][] = [
$offer['params'][] = array( 'name' => 'Article',
'name' => 'Article', 'code' => 'article',
'code' => 'article', 'value' => $article
'value' => $article ];
); }
}
$weight = $product->getWeight();
$weight = $product->getWeight();
if(!empty($weight)) { if(!empty($weight)) {
$offer['params'][] = array( $offer['params'][] = [
'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
if($product->getTypeId() == 'configurable') { ->getUsedProductCollection($product)
->addAttributeToSelect('*')
$associated_products = $this->_configurable ->addFilterByRequiredOptions();
->getUsedProductCollection($product)
->addAttributeToSelect('*') foreach ($associated_products as $associatedProduct) {
->addFilterByRequiredOptions(); $offer['id'] = $associatedProduct->getId();
$offer['productId'] = $product->getId();
foreach ($associated_products as $associatedProduct) { $offer['productActivity'] = $associatedProduct->isAvailable() ? 'Y' : 'N';
$offer['id'] = $associatedProduct->getId(); $offer['name'] = $associatedProduct->getName();
$offer['productId'] = $product->getId(); $offer['productName'] = $product->getName();
$offer['productActivity'] = $associatedProduct->isAvailable() ? 'Y' : 'N'; $offer['initialPrice'] = $associatedProduct->getFinalPrice();
$offer['name'] = $associatedProduct->getName(); $offer['url'] = $product->getProductUrl();
$offer['productName'] = $product->getName(); $offer['picture'] = $picUrl.'catalog/product'.$associatedProduct->getImage();
$offer['initialPrice'] = $associatedProduct->getFinalPrice(); $offer['quantity'] = $this->_StockState->getStockQty($associatedProduct->getId(), $associatedProduct->getStore()->getWebsiteId());
$offer['url'] = $product->getProductUrl(); $offer['categoryId'] = $associatedProduct->getCategoryIds();
$offer['picture'] = $picUrl.'catalog/product'.$associatedProduct->getImage(); $offer['vendor'] = $associatedProduct->getAttributeText('manufacturer');
$offer['quantity'] = $this->_StockState->getStockQty($associatedProduct->getId(), $associatedProduct->getStore()->getWebsiteId()); $offer['params'] = [];
$offer['categoryId'] = $associatedProduct->getCategoryIds();
$offer['vendor'] = $associatedProduct->getAttributeText('manufacturer'); $article = $associatedProduct->getSku();
$offer['params'] = array();
if ($associatedProduct->getResource()->getAttribute('color')) {
$article = $associatedProduct->getSku(); $colorAttribute = $associatedProduct->getResource()->getAttribute('color');
if(!empty($article)) { $color = $colorAttribute->getSource()->getOptionText($associatedProduct->getColor());
$offer['params'][] = array( }
'name' => 'Article',
'code' => 'article', if (isset($color)) {
'value' => $article $offer['params'][] = [
); 'name' => 'Color',
} 'code' => 'color',
'value' => $color
$weight = $associatedProduct->getWeight(); ];
if(!empty($weight)) { }
$offer['params'][] = array(
'name' => 'Weight', if ($associatedProduct->getResource()->getAttribute('size')) {
'code' => 'weight', $sizeAttribute = $associatedProduct->getResource()->getAttribute('size');
'value' => $weight $size = $sizeAttribute->getSource()->getOptionText($associatedProduct->getSize());
); }
}
if (isset($size)) {
$offers[] = $offer; $offer['params'][] = [
} 'name' => 'Size',
'code' => 'size',
'value' => $size
} ];
} }
if (!empty($article)) {
foreach ($offers as $offer) { $offer['params'][] = [
$e = $this->_eOffers->appendChild( 'name' => 'Article',
$this->_dd->createElement('offer') 'code' => 'article',
); 'value' => $article
];
$e->setAttribute('id', $offer['id']); }
$e->setAttribute('productId', $offer['productId']);
$weight = $associatedProduct->getWeight();
if (!empty($offer['quantity'])) {
$e->setAttribute('quantity', (int) $offer['quantity']); if(!empty($weight)) {
} else { $offer['params'][] = [
$e->setAttribute('quantity', 0); 'name' => 'Weight',
} 'code' => 'weight',
'value' => $weight
if (!empty($offer['categoryId'])) { ];
foreach ($offer['categoryId'] as $categoryId) { }
$e->appendChild(
$this->_dd->createElement('categoryId') $offers[] = $offer;
)->appendChild( }
$this->_dd->createTextNode($categoryId) }
); }
}
} else { foreach ($offers as $offer) {
$e->appendChild($this->_dd->createElement('categoryId', 1)); $e = $this->_eOffers->appendChild(
} $this->_dd->createElement('offer')
);
$e->appendChild($this->_dd->createElement('productActivity'))
->appendChild( $e->setAttribute('id', $offer['id']);
$this->_dd->createTextNode($offer['productActivity']) $e->setAttribute('productId', $offer['productId']);
);
if (!empty($offer['quantity'])) {
$e->appendChild($this->_dd->createElement('name')) $e->setAttribute('quantity', (int) $offer['quantity']);
->appendChild( } else {
$this->_dd->createTextNode($offer['name']) $e->setAttribute('quantity', 0);
); }
$e->appendChild($this->_dd->createElement('productName')) if (!empty($offer['categoryId'])) {
->appendChild( foreach ($offer['categoryId'] as $categoryId) {
$this->_dd->createTextNode($offer['productName']) $e->appendChild(
); $this->_dd->createElement('categoryId')
)->appendChild(
$e->appendChild($this->_dd->createElement('price')) $this->_dd->createTextNode($categoryId)
->appendChild( );
$this->_dd->createTextNode($offer['initialPrice']) }
); } else {
$e->appendChild($this->_dd->createElement('categoryId', 1));
if (!empty($offer['purchasePrice'])) { }
$e->appendChild($this->_dd->createElement('purchasePrice'))
->appendChild( $e->appendChild($this->_dd->createElement('productActivity'))
$this->_dd->createTextNode($offer['purchasePrice']) ->appendChild(
); $this->_dd->createTextNode($offer['productActivity'])
} );
if (!empty($offer['picture'])) { $e->appendChild($this->_dd->createElement('name'))
$e->appendChild($this->_dd->createElement('picture')) ->appendChild(
->appendChild( $this->_dd->createTextNode($offer['name'])
$this->_dd->createTextNode($offer['picture']) );
);
} $e->appendChild($this->_dd->createElement('productName'))
->appendChild(
if (!empty($offer['url'])) { $this->_dd->createTextNode($offer['productName'])
$e->appendChild($this->_dd->createElement('url')) );
->appendChild(
$this->_dd->createTextNode($offer['url']) $e->appendChild($this->_dd->createElement('price'))
); ->appendChild(
} $this->_dd->createTextNode($offer['initialPrice'])
);
if (!empty($offer['vendor'])) {
$e->appendChild($this->_dd->createElement('vendor')) if (!empty($offer['purchasePrice'])) {
->appendChild( $e->appendChild($this->_dd->createElement('purchasePrice'))
$this->_dd->createTextNode($offer['vendor']) ->appendChild(
); $this->_dd->createTextNode($offer['purchasePrice'])
} );
}
if(!empty($offer['params'])) {
foreach($offer['params'] as $param) { if (!empty($offer['picture'])) {
$paramNode = $this->_dd->createElement('param'); $e->appendChild($this->_dd->createElement('picture'))
$paramNode->setAttribute('name', $param['name']); ->appendChild(
$paramNode->setAttribute('code', $param['code']); $this->_dd->createTextNode($offer['picture'])
$paramNode->appendChild( );
$this->_dd->createTextNode($param['value']) }
);
$e->appendChild($paramNode); if (!empty($offer['url'])) {
} $e->appendChild($this->_dd->createElement('url'))
} ->appendChild(
} $this->_dd->createTextNode($offer['url'])
);
} }
} if (!empty($offer['vendor'])) {
$e->appendChild($this->_dd->createElement('vendor'))
->appendChild(
$this->_dd->createTextNode($offer['vendor'])
);
}
if(!empty($offer['params'])) {
foreach($offer['params'] as $param) {
$paramNode = $this->_dd->createElement('param');
$paramNode->setAttribute('name', $param['name']);
$paramNode->setAttribute('code', $param['code']);
$paramNode->appendChild(
$this->_dd->createTextNode($param['value'])
);
$e->appendChild($paramNode);
}
}
}
}
}

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(\Magento\Framework\ObjectManagerInterface $objectManager)
public function __construct(
$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)
{
$path =$this->logPath . $file.'.txt';
$f = fopen($_SERVER["DOCUMENT_ROOT"].$path, "a+");
fwrite($f, print_r(array(date('Y-m-d H:i:s'), array(
$dump
)),true));
fclose($f);
} }
/**
* Write data in log file
*
* @param array $data
* @param str $fileName
*
* @return void
*/
public function writeDump($data, $fileName)
{
$filePath = $this->logDir . '/' . $fileName . '.log';
if (!$this->checkSize($filePath)) {
$this->clear($filePath);
}
$logData = [
'date' => date('Y-m-d H:i:s'),
'data' => $data
];
$file = fopen($filePath, "a+");
fwrite($file, print_r($logData, true));
fclose($file);
}
/**
* Write data in log file
*
* @param str $data
* @param str $fileName
*
* @return void
*/
public function writeRow($data, $fileName = 'retailcrm')
{
$filePath = $this->logDir . '/' . $fileName . '.log';
if (!$this->checkSize($filePath)) {
$this->clear($filePath);
}
$nowDate = date('Y-m-d H:i:s');
$logData = "[$nowDate] @ " . $data . "\n";
$file = fopen($filePath, "a+");
fwrite($file, $logData);
fclose($file);
}
/**
* Clear file
*
* @param str $file
*
* @return void
*/
protected function clear($file)
{
file_put_contents($file, '');
}
/**
* Check file size
*
* @param str $file
*
* @return boolean
*/
protected function checkSize($file)
{
if (!file_exists($file)) {
return true;
} elseif (filesize($file) > 10485760) {
return false;
}
return true;
}
} }

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->_helper = $helper;
$this->_config = $config;
$url = $config->getValue('retailcrm/general/api_url');
$key = $config->getValue('retailcrm/general/api_key');
if(!empty($url) && !empty($key)) {
$this->_api = new \Retailcrm\Retailcrm\Model\ApiClient\ApiClient($url,$key);
}
}
public function execute(\Magento\Framework\Event\Observer $observer)
{
$data = $observer->getEvent()->getCustomer();
$customer = array(
'externalId' => $data->getId(),
'email' => $data->getEmail(),
'firstName' => $data->getFirstname(),
'patronymic' => $data->getMiddlename(),
'lastName' => $data->getLastname(),
'createdAt' => date('Y-m-d H:i:s', strtotime($data->getCreatedAt()))
);
$response = $this->_api->customersEdit($customer);
if ((404 === $response->getStatusCode()) &&($response['errorMsg']==='Not found')) {
$this->_api->customersCreate($customer);
}
//$logger = new \Retailcrm\Retailcrm\Model\Logger\Logger();
//$logger->write($customer,'Customer');
}
} $this->_logger = $logger;
$this->_helper = $helper;
$this->_config = $config;
$this->_objectManager = $objectManager;
$this->registry = $registry;
$url = $config->getValue('retailcrm/general/api_url');
$key = $config->getValue('retailcrm/general/api_key');
$version = $config->getValue('retailcrm/general/api_version');
if (!empty($url) && !empty($key)) {
$this->_api = new ApiClient($url, $key, $version);
}
}
public function execute(\Magento\Framework\Event\Observer $observer)
{
if ($this->registry->registry('RETAILCRM_HISTORY') === true) {
return;
}
$data = $observer->getEvent()->getCustomer();
$customer = [
'externalId' => $data->getId(),
'email' => $data->getEmail(),
'firstName' => $data->getFirstname(),
'patronymic' => $data->getMiddlename(),
'lastName' => $data->getLastname(),
'createdAt' => date('Y-m-d H:i:s', strtotime($data->getCreatedAt()))
];
$response = $this->_api->customersEdit($customer);
if ($response === false) {
return;
}
if (!$response->isSuccessful() && $response->errorMsg == $this->_api->getErrorText('errorNotFound')) {
$this->_api->customersCreate($customer);
}
}
}

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

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(
$this->_logger = $logger; \Magento\Framework\ObjectManagerInterface $objectManager,
$this->_helper = $helper; \Magento\Framework\App\Config\ScopeConfigInterface $config,
$this->_config = $config; \Magento\Framework\Registry $registry
) {
$url = $config->getValue('retailcrm/general/api_url'); $this->_helper = $objectManager->get('\Retailcrm\Retailcrm\Helper\Data');
$key = $config->getValue('retailcrm/general/api_key'); $this->_objectManager = $objectManager;
$this->_config = $config;
if(!empty($url) && !empty($key)) { $this->registry = $registry;
$this->_api = new \Retailcrm\Retailcrm\Model\ApiClient\ApiClient($url,$key);
}
}
public function execute(\Magento\Framework\Event\Observer $observer)
{
$order = $observer->getEvent()->getOrder();
if(isset($order)){
$preparedOrder = array(
'externalId' => $order->getRealOrderId(),
'status' => $this->_config->getValue('retailcrm/Status/'.$order->getStatus()),
);
if((float)$order->getBaseGrandTotal() == (float)$order->getTotalPaid()){
$preparedOrder['paymentStatus'] = 'paid';
}
$this->_helper->filterRecursive($preparedOrder);
$this->_api->ordersEdit($preparedOrder);
}
}
} $url = $config->getValue('retailcrm/general/api_url');
$key = $config->getValue('retailcrm/general/api_key');
$apiVersion = $config->getValue('retailcrm/general/api_version');
if (!empty($url) && !empty($key)) {
$this->_api = new ApiClient($url, $key, $apiVersion);
}
}
/**
* Execute update order in CRM
*
* @param Observer $observer
*
* @return void
*/
public function execute(Observer $observer)
{
if ($this->registry->registry('RETAILCRM_HISTORY') === true) {
return;
}
$order = $observer->getEvent()->getOrder();
if ($order) {
$preparedOrder = [
'externalId' => $order->getId(),
'status' => $this->_config->getValue('retailcrm/Status/' . $order->getStatus())
];
if ($order->getBaseTotalDue() == 0) {
if ($this->_api->getVersion() == 'v4') {
$preparedOrder['paymentStatus'] = 'paid';
} elseif ($this->_api->getVersion() == 'v5') {
$payment = [
'externalId' => $order->getPayment()->getId(),
'status' => 'paid'
];
$this->_api->ordersPaymentsEdit($payment);
}
}
$this->_helper->filterRecursive($preparedOrder);
$this->_api->ordersEdit($preparedOrder);
}
}
}

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(); {
$orderRepository = $om->get('Magento\Sales\Model\OrderRepository'); $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$searchCriteriaBuilder = $om->get('Magento\Framework\Api\SearchCriteriaBuilder'); $orderRepository = $objectManager->get('Magento\Sales\Model\OrderRepository');
$config = $om->get('Magento\Framework\App\Config\ScopeConfigInterface'); $searchCriteriaBuilder = $objectManager->get('Magento\Framework\Api\SearchCriteriaBuilder');
$filterBuilder = $om->get('Magento\Framework\Api\FilterBuilder'); $config = $objectManager->get('Magento\Framework\App\Config\ScopeConfigInterface');
$order = $om->get('\Magento\Sales\Api\Data\OrderInterface'); $filterBuilder = $objectManager->get('Magento\Framework\Api\FilterBuilder');
$helper = $om->get('\Retailcrm\Retailcrm\Helper\Data'); $order = $objectManager->get('\Magento\Sales\Api\Data\OrderInterface');
$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)) {
$this->_api = new \Retailcrm\Retailcrm\Model\ApiClient\ApiClient($url,$key); if (!empty($url) && !empty($key)) {
$this->_api = new ApiClient($url, $key, $version);
} }
} }
public function ExportOrderNumber() public function ExportOrderNumber()
{ {
$ordernumber = $this->_config->getValue('retailcrm/Load/number_order'); $ordernumber = $this->_config->getValue('retailcrm/Load/number_order');
$ordersId = explode(",", $ordernumber); $ordersId = explode(",", $ordernumber);
$orders = 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)
public function prepareOrder($id) {
{ $magentoOrder = $this->_order->load($id);
$magentoOrder = $this->_order->loadByIncrementId($id);
$magentoOrderArr = $magentoOrder->getData(); $items = [];
$addressObj = $magentoOrder->getBillingAddress();
$items = array();
$addressObj = $magentoOrder->getBillingAddress(); foreach ($magentoOrder->getAllItems() as $item) {
if ($item->getProductType() == "simple") {
foreach ($magentoOrder->getAllItems() as $item) { $price = $item->getPrice();
if ($item->getProductType() == "simple") {
if ($price == 0){
$price = $item->getPrice(); $om = \Magento\Framework\App\ObjectManager::getInstance();
$omproduct = $om->get('Magento\Catalog\Model\ProductRepository')
if($price == 0){ ->getById($item->getProductId());
$om = \Magento\Framework\App\ObjectManager::getInstance(); $price = $omproduct->getPrice();
$omproduct = $om->get('Magento\Catalog\Model\ProductRepository') }
->getById($item->getProductId());
$price = $omproduct->getPrice(); $product = [
} 'productId' => $item->getProductId(),
'productName' => $item->getName(),
$product = array( 'quantity' => $item->getQtyOrdered(),
'productId' => $item->getProductId(), 'initialPrice' => $price,
'productName' => $item->getName(), 'offer' => [
'quantity' => $item->getQtyOrdered(), 'externalId'=>$item->getProductId()
'initialPrice' => $price, ]
'offer'=>array( ];
'externalId'=>$item->getProductId()
) unset($om);
); unset($omproduct);
unset($price);
unset($om);
unset($omproduct); $items[] = $product;
unset($price); }
}
$items[] = $product;
} $ship = $this->getShippingCode($magentoOrder->getShippingMethod());
}
$preparedOrder = [
$ship = $this->getShippingCode($magentoOrder->getShippingMethod()); 'site' => $magentoOrder->getStore()->getCode(),
'externalId' => $magentoOrder->getRealOrderId(),
$preparedOrder = array( 'number' => $magentoOrder->getRealOrderId(),
'site' => $magentoOrder->getStore()->getCode(), 'createdAt' => date('Y-m-d H:i:s'),
'externalId' => $magentoOrder->getRealOrderId(), 'lastName' => $magentoOrder->getCustomerLastname(),
'number' => $magentoOrder->getRealOrderId(), 'firstName' => $magentoOrder->getCustomerFirstname(),
'createdAt' => date('Y-m-d H:i:s'), 'patronymic' => $magentoOrder->getCustomerMiddlename(),
'lastName' => $magentoOrder->getCustomerLastname(), 'email' => $magentoOrder->getCustomerEmail(),
'firstName' => $magentoOrder->getCustomerFirstname(), 'phone' => $addressObj->getTelephone(),
'patronymic' => $magentoOrder->getCustomerMiddlename(), 'paymentType' => $this->_config->getValue('retailcrm/Payment/'.$magentoOrder->getPayment()->getMethodInstance()->getCode()),
'email' => $magentoOrder->getCustomerEmail(), 'status' => $this->_config->getValue('retailcrm/Status/'.$magentoOrder->getStatus()),
'phone' => $addressObj->getTelephone(), 'discount' => abs($magentoOrder->getDiscountAmount()),
'paymentType' => $this->_config->getValue('retailcrm/Payment/'.$magentoOrder->getPayment()->getMethodInstance()->getCode()), 'items' => $items,
'status' => $this->_config->getValue('retailcrm/Status/'.$magentoOrder->getStatus()), 'delivery' => [
'discount' => abs($magentoOrder->getDiscountAmount()), 'code' => $this->_config->getValue('retailcrm/Shipping/'.$ship),
'items' => $items, 'cost' => $magentoOrder->getShippingAmount(),
'delivery' => array( 'address' => [
'code' => $this->_config->getValue('retailcrm/Shipping/'.$ship), 'index' => $addressObj->getData('postcode'),
'cost' => $magentoOrder->getShippingAmount(), 'city' => $addressObj->getData('city'),
'address' => array( 'country' => $addressObj->getData('country_id'),
'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 (trim($preparedOrder['delivery']['code']) == ''){
); unset($preparedOrder['delivery']['code']);
}
if(trim($preparedOrder['delivery']['code']) == ''){
unset($preparedOrder['delivery']['code']); if (trim($preparedOrder['paymentType']) == ''){
} unset($preparedOrder['paymentType']);
}
if(trim($preparedOrder['paymentType']) == ''){
unset($preparedOrder['paymentType']); if (trim($preparedOrder['status']) == ''){
} unset($preparedOrder['status']);
}
if(trim($preparedOrder['status']) == ''){
unset($preparedOrder['status']); if ($magentoOrder->getCustomerIsGuest() == 0) {
} $preparedOrder['customer']['externalId'] = $magentoOrder->getCustomerId();
}
if ($magentoOrder->getCustomerIsGuest() == 0) {
$preparedOrder['customer']['externalId'] = $magentoOrder->getCustomerId(); $this->_logger->writeDump($preparedOrder,'OrderNumber');
}
return $this->_helper->filterRecursive($preparedOrder);
$logger = new \Retailcrm\Retailcrm\Model\Logger\Logger(); }
$logger->write($preparedOrder,'OrderNumber'); }
return $this->_helper->filterRecursive($preparedOrder);
}
}

View File

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

View File

@ -2,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()) { foreach ($attributes as $attr) {
$result[] = array('value' => $attr->getAttributeId(), 'label' => $attr->getFrontendLabel(), 'title' => $attr->getAttributeCode()); if ($attr->getFrontendLabel()) {
} $result[] = array('value' => $attr->getAttributeId(), 'label' => $attr->getFrontendLabel(), 'title' => $attr->getAttributeCode());
} }
}
return $result;
} 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) {
$options = [];
foreach($activeShipping as $carrierCode => $carrierModel)
{ if ($carrierModel->getAllowedMethods()) {
$options = array(); $carrierMethods = $carrierModel->getAllowedMethods();
if( $carrierMethods = $carrierModel->getAllowedMethods() )
{ foreach ($carrierMethods as $methodCode => $method) {
foreach ($carrierMethods as $methodCode => $method) $code = $carrierCode . '_' . $methodCode;
{ $options[] = [
$code= $carrierCode.'_'.$methodCode; 'value' => $code,
$options[]=array('value'=>$code,'label'=>$method); 'label' => $method
} ];
$carrierTitle =$config->getValue('carriers/'.$carrierCode.'/title'); }
} $carrierTitle = $config->getValue('carriers/' . $carrierCode . '/title');
$methods[] = array('value'=>$options,'label'=>$carrierTitle); }
}
$methods[] = [
return $methods; 'value' => $options,
'label' => $carrierTitle
} ];
} }
return $methods;
}
}

View File

@ -9,12 +9,9 @@ class Status extends \Magento\Config\Model\Config\Backend\Serialized\ArraySerial
// For value validations // For value validations
$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

@ -11,16 +11,23 @@
<resource>Retailcrm_Retailcrm::retailcrm_configuration</resource> <resource>Retailcrm_Retailcrm::retailcrm_configuration</resource>
<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">
</config> <arguments>
<argument name="commands" xsi:type="array">
<item name="retailcrm_command" xsi:type="object">Retailcrm\Retailcrm\Console\Command\Command</item>
</argument>
</arguments>
</type>
</config>

View File

@ -1,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_place_after">
<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>
<!-- after customer save -->
<event name="customer_save_after">
<observer name="customer_save_after" instance="Retailcrm\Retailcrm\Model\Observer\Customer" />
</event>
<event name="sales_order_save_after">
<observer name="sales_order_save_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>
<!-- 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>