Multiversions api (#8)
This commit is contained in:
parent
b5bb377379
commit
682fcb8545
@ -72,4 +72,4 @@ class Button extends \Magento\Config\Block\System\Config\Form\Field
|
||||
|
||||
return $button->toHtml();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,61 +1,63 @@
|
||||
<?php
|
||||
|
||||
namespace Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Field;
|
||||
|
||||
use Magento\Framework\Data\Form\Element\AbstractElement;
|
||||
|
||||
class Attributes extends \Magento\Config\Block\System\Config\Form\Field
|
||||
{
|
||||
protected function _getElementHtml(AbstractElement $element)
|
||||
{
|
||||
$values = $element->getValues();
|
||||
$html = '<table id="' . $element->getId() . '_table" class="ui_select_table" cellspacing="0">';
|
||||
$html .= '<tbody><tr>';
|
||||
$html .= '<td><ul id="' . $element->getId() . '_selected" class="ui_select selected sortable">';
|
||||
|
||||
$selected = explode(',', $element->getValue());
|
||||
foreach ($selected as $value) {
|
||||
if ($key = array_search($value, array_column($values, 'value'))) {
|
||||
$html .= '<li value="' . $value . '" title="' . $values[$key]['title'] . '">';
|
||||
$html .= isset($values[$key]['label'])?$values[$key]['label']:'n/a';
|
||||
$html .= '</li>';
|
||||
$values[$key]['selected'] = TRUE;
|
||||
}
|
||||
}
|
||||
|
||||
$html .= '</ul></td><td>';
|
||||
$html .= '<ul id="' . $element->getId() . '_source" class="ui_select source sortable">';
|
||||
if ($values) {
|
||||
foreach ($values as $option) {
|
||||
if (!isset($option['selected'])) {
|
||||
$html .= '<li value="' . $option['value'] . '" title="' . $option['title'] . '">';
|
||||
$html .= isset($option['label'])?$option['label']:'n/a';
|
||||
$html .= '</li>';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$html .= '</ul></td></tr></tbody></table>';
|
||||
$html .= '<div style="display:none;">' . $element->getElementHtml() . '</div>';
|
||||
$html .= '<script type="text/javascript">
|
||||
require(["jquery"], function(jQuery){
|
||||
require(["BelVG_Pricelist/js/verpage", "ui/1.11.4"], function(){
|
||||
jQuery(document).ready( function() {
|
||||
jQuery("#' . $element->getId() . '_selected, #' . $element->getId() . '_source").sortable({
|
||||
connectWith: ".sortable",
|
||||
stop: function(event, ui) {
|
||||
var vals = [];
|
||||
jQuery("#' . $element->getId() . '_selected").find("li").each(function(index, element){
|
||||
vals.push(jQuery(element).val());
|
||||
});
|
||||
jQuery("#' . $element->getId() . '").val(vals);
|
||||
}
|
||||
}).disableSelection();
|
||||
});
|
||||
})
|
||||
})
|
||||
</script>';
|
||||
|
||||
return $html;
|
||||
}
|
||||
|
||||
}
|
||||
protected function _getElementHtml(AbstractElement $element)
|
||||
{
|
||||
$values = $element->getValues();
|
||||
$html = '<table id="' . $element->getId() . '_table" class="ui_select_table" cellspacing="0">';
|
||||
$html .= '<tbody><tr>';
|
||||
$html .= '<td><ul id="' . $element->getId() . '_selected" class="ui_select selected sortable">';
|
||||
|
||||
$selected = explode(',', $element->getValue());
|
||||
|
||||
foreach ($selected as $value) {
|
||||
if ($key = array_search($value, array_column($values, 'value'))) {
|
||||
$html .= '<li value="' . $value . '" title="' . $values[$key]['title'] . '">';
|
||||
$html .= isset($values[$key]['label'])?$values[$key]['label']:'n/a';
|
||||
$html .= '</li>';
|
||||
$values[$key]['selected'] = TRUE;
|
||||
}
|
||||
}
|
||||
|
||||
$html .= '</ul></td><td>';
|
||||
$html .= '<ul id="' . $element->getId() . '_source" class="ui_select source sortable">';
|
||||
|
||||
if ($values) {
|
||||
foreach ($values as $option) {
|
||||
if (!isset($option['selected'])) {
|
||||
$html .= '<li value="' . $option['value'] . '" title="' . $option['title'] . '">';
|
||||
$html .= isset($option['label'])?$option['label']:'n/a';
|
||||
$html .= '</li>';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$html .= '</ul></td></tr></tbody></table>';
|
||||
$html .= '<div style="display:none;">' . $element->getElementHtml() . '</div>';
|
||||
$html .= '<script type="text/javascript">
|
||||
require(["jquery"], function(jQuery){
|
||||
require(["BelVG_Pricelist/js/verpage", "ui/1.11.4"], function(){
|
||||
jQuery(document).ready( function() {
|
||||
jQuery("#' . $element->getId() . '_selected, #' . $element->getId() . '_source").sortable({
|
||||
connectWith: ".sortable",
|
||||
stop: function(event, ui) {
|
||||
var vals = [];
|
||||
jQuery("#' . $element->getId() . '_selected").find("li").each(function(index, element){
|
||||
vals.push(jQuery(element).val());
|
||||
});
|
||||
jQuery("#' . $element->getId() . '").val(vals);
|
||||
}
|
||||
}).disableSelection();
|
||||
});
|
||||
})
|
||||
})
|
||||
</script>';
|
||||
|
||||
return $html;
|
||||
}
|
||||
}
|
||||
|
16
Block/Adminhtml/System/Config/Form/Field/ListMode.php
Normal file
16
Block/Adminhtml/System/Config/Form/Field/ListMode.php
Normal 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')]
|
||||
];
|
||||
}
|
||||
}
|
@ -1,96 +1,87 @@
|
||||
<?php
|
||||
|
||||
namespace Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Field;
|
||||
|
||||
use Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Field\Base;
|
||||
use Magento\Framework\Data\Form\Element\AbstractElement;
|
||||
use Retailcrm\Retailcrm\Helper\Proxy as ApiClient;
|
||||
|
||||
class Payment extends \Magento\Config\Block\System\Config\Form\Field
|
||||
{
|
||||
protected $_apiUrl;
|
||||
protected $_apiKey;
|
||||
protected $_systemStore;
|
||||
protected $_formFactory;
|
||||
protected $_logger;
|
||||
|
||||
public function __construct(
|
||||
\Magento\Framework\Data\FormFactory $formFactory,
|
||||
\Magento\Store\Model\System\Store $systemStore
|
||||
|
||||
)
|
||||
{
|
||||
$om = \Magento\Framework\App\ObjectManager::getInstance();
|
||||
$logger = $om->get('\Psr\Log\LoggerInterface');
|
||||
$this->_logger = $logger;
|
||||
|
||||
$base = new Base;
|
||||
|
||||
$this->_apiUrl = $base->_apiUrl;
|
||||
$this->_apiKey = $base->_apiKey;
|
||||
|
||||
$this->_systemStore = $systemStore;
|
||||
$this->_formFactory = $formFactory;
|
||||
|
||||
}
|
||||
|
||||
public function render(AbstractElement $element)
|
||||
{
|
||||
$values = $element->getValues();
|
||||
$html = '';
|
||||
|
||||
if((!empty($this->_apiUrl))&&(!empty($this->_apiKey))){
|
||||
|
||||
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
|
||||
$paymentConfig = $objectManager->get('Magento\Payment\Model\Config');
|
||||
$activePaymentMethods = $paymentConfig->getActiveMethods();
|
||||
|
||||
$client = new \Retailcrm\Retailcrm\Model\ApiClient\ApiClient($this->_apiUrl,$this->_apiKey);
|
||||
|
||||
try {
|
||||
$response = $client->paymentTypesList();
|
||||
if ($response->isSuccessful()&&200 === $response->getStatusCode()) {
|
||||
$paymentTypes = $response['paymentTypes'];
|
||||
}
|
||||
} catch (Retailcrm\Retailcrm\Model\ApiClient\Exception\CurlException $e) {
|
||||
$this->_logger->addDebug($e->getMessage());
|
||||
}
|
||||
|
||||
$config = \Magento\Framework\App\ObjectManager::getInstance()->get(
|
||||
'Magento\Framework\App\Config\ScopeConfigInterface'
|
||||
);
|
||||
|
||||
foreach (array_keys($activePaymentMethods) as $k=>$payment){
|
||||
$html .='<table id="' . $element->getId() . '_table">';
|
||||
$html .='<tr id="row_retailcrm_payment_'.$payment.'">';
|
||||
$html .='<td class="label">'.$payment.'</td>';
|
||||
$html .='<td>';
|
||||
$html .='<select id="1" name="groups[Payment][fields]['.$payment.'][value]">';
|
||||
|
||||
$selected = $config->getValue('retailcrm/Payment/'.$payment);
|
||||
|
||||
foreach ($paymentTypes as $k=>$value){
|
||||
|
||||
if((!empty($selected))&&(($selected==$value['code']))){
|
||||
$select ='selected="selected"';
|
||||
}else{
|
||||
$select ='';
|
||||
}
|
||||
|
||||
$html .='<option '.$select.' value="'.$value['code'].'"> '.$value['name'].'</option>';
|
||||
}
|
||||
$html .='</select>';
|
||||
$html .='</td>';
|
||||
$html .='</tr>';
|
||||
$html .='</table>';
|
||||
|
||||
}
|
||||
|
||||
return $html;
|
||||
}else{
|
||||
$html = '<div style="margin-left: 15px;"><b><i>Please check your API Url & API Key</i></b></div>';
|
||||
|
||||
return $html;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
protected $_apiUrl;
|
||||
protected $_apiKey;
|
||||
protected $_systemStore;
|
||||
protected $_formFactory;
|
||||
protected $_logger;
|
||||
|
||||
public function __construct(
|
||||
\Magento\Framework\Data\FormFactory $formFactory,
|
||||
\Magento\Store\Model\System\Store $systemStore
|
||||
) {
|
||||
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
|
||||
$config = $objectManager->get('\Magento\Framework\App\Config\ScopeConfigInterface');
|
||||
$this->_apiUrl = $config->getValue('retailcrm/general/api_url');
|
||||
$this->_apiKey = $config->getValue('retailcrm/general/api_key');
|
||||
$this->_apiVersion = $config->getValue('retailcrm/general/api_version');
|
||||
$this->_systemStore = $systemStore;
|
||||
$this->_formFactory = $formFactory;
|
||||
}
|
||||
|
||||
public function render(AbstractElement $element)
|
||||
{
|
||||
$html = '';
|
||||
$htmlError = '<div style="margin-left: 15px;"><b><i>Please check your API Url & API Key</i></b></div>';
|
||||
|
||||
if ((!empty($this->_apiUrl)) && (!empty($this->_apiKey))) {
|
||||
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
|
||||
$paymentConfig = $objectManager->get('Magento\Payment\Model\Config');
|
||||
$activePaymentMethods = $paymentConfig->getActiveMethods();
|
||||
|
||||
$client = new ApiClient($this->_apiUrl, $this->_apiKey, $this->_apiVersion);
|
||||
|
||||
$response = $client->paymentTypesList();
|
||||
|
||||
if ($response === false) {
|
||||
return $htmlError;
|
||||
}
|
||||
|
||||
if ($response->isSuccessful()) {
|
||||
$paymentTypes = $response['paymentTypes'];
|
||||
} else {
|
||||
return $htmlError;
|
||||
}
|
||||
|
||||
$config = \Magento\Framework\App\ObjectManager::getInstance()->get(
|
||||
'Magento\Framework\App\Config\ScopeConfigInterface'
|
||||
);
|
||||
|
||||
foreach (array_keys($activePaymentMethods) as $k=>$payment){
|
||||
$html .='<table id="' . $element->getId() . '_table">';
|
||||
$html .='<tr id="row_retailcrm_payment_'.$payment.'">';
|
||||
$html .='<td class="label">'.$payment.'</td>';
|
||||
$html .='<td>';
|
||||
$html .='<select id="1" name="groups[Payment][fields]['.$payment.'][value]">';
|
||||
|
||||
$selected = $config->getValue('retailcrm/Payment/' . $payment);
|
||||
|
||||
foreach ($paymentTypes as $k => $value){
|
||||
if ((!empty($selected)) && (($selected == $value['code']))) {
|
||||
$select = 'selected="selected"';
|
||||
}else{
|
||||
$select = '';
|
||||
}
|
||||
|
||||
$html .= '<option '.$select.' value="'.$value['code'].'"> '.$value['name'].'</option>';
|
||||
}
|
||||
|
||||
$html .= '</select>';
|
||||
$html .= '</td>';
|
||||
$html .= '</tr>';
|
||||
$html .= '</table>';
|
||||
}
|
||||
|
||||
return $html;
|
||||
} else {
|
||||
return $htmlError;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,99 +1,88 @@
|
||||
<?php
|
||||
|
||||
namespace Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Field;
|
||||
|
||||
use Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Field\Base;
|
||||
use Magento\Framework\Data\Form\Element\AbstractElement;
|
||||
use Retailcrm\Retailcrm\Helper\Proxy as ApiClient;
|
||||
|
||||
class Shipping extends \Magento\Config\Block\System\Config\Form\Field
|
||||
{
|
||||
protected $_apiUrl;
|
||||
protected $_apiKey;
|
||||
protected $_systemStore;
|
||||
protected $_formFactory;
|
||||
protected $_logger;
|
||||
|
||||
public function __construct(
|
||||
\Magento\Framework\Data\FormFactory $formFactory,
|
||||
\Magento\Store\Model\System\Store $systemStore
|
||||
)
|
||||
{
|
||||
$om = \Magento\Framework\App\ObjectManager::getInstance();
|
||||
$logger = $om->get('\Psr\Log\LoggerInterface');
|
||||
$this->_logger = $logger;
|
||||
|
||||
$base = new Base;
|
||||
|
||||
$this->_apiUrl = $base->_apiUrl;
|
||||
$this->_apiKey = $base->_apiKey;
|
||||
|
||||
$this->_systemStore = $systemStore;
|
||||
$this->_formFactory = $formFactory;
|
||||
|
||||
}
|
||||
|
||||
public function render(AbstractElement $element)
|
||||
{
|
||||
$values = $element->getValues();
|
||||
$html = '';
|
||||
|
||||
if(!empty($this->_apiUrl) && !empty($this->_apiKey)) {
|
||||
|
||||
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
|
||||
$shipConfig = $objectManager->get('Magento\Shipping\Model\Config');
|
||||
$deliveryMethods = $shipConfig->getActiveCarriers();
|
||||
|
||||
$client = new \Retailcrm\Retailcrm\Model\ApiClient\ApiClient($this->_apiUrl,$this->_apiKey);
|
||||
|
||||
try {
|
||||
$response = $client->deliveryTypesList();
|
||||
if ($response->isSuccessful()&&200 === $response->getStatusCode()) {
|
||||
$deliveryTypes = $response['deliveryTypes'];
|
||||
}
|
||||
} catch (Retailcrm\Retailcrm\Model\ApiClient\Exception\CurlException $e) {
|
||||
$this->_logger->addDebug($e->getMessage());
|
||||
}
|
||||
|
||||
$config = \Magento\Framework\App\ObjectManager::getInstance()->get(
|
||||
'Magento\Framework\App\Config\ScopeConfigInterface'
|
||||
);
|
||||
|
||||
foreach (array_keys($deliveryMethods) as $k=>$delivery){
|
||||
$html .='<table id="' . $element->getId() . '_table">';
|
||||
$html .='<tr id="row_retailcrm_shipping_'.$delivery.'">';
|
||||
$html .='<td class="label">'.$delivery.'</td>';
|
||||
$html .='<td>';
|
||||
$html .='<select id="1" name="groups[Shipping][fields]['.$delivery.'][value]">';
|
||||
|
||||
$selected = $config->getValue('retailcrm/Shipping/'.$delivery);
|
||||
|
||||
foreach ($deliveryTypes as $k=>$value){
|
||||
|
||||
if((!empty($selected))&&(($selected==$value['code']))){
|
||||
$select ='selected="selected"';
|
||||
}else{
|
||||
$select ='';
|
||||
}
|
||||
|
||||
$html .='<option '.$select.' value="'.$value['code'].'"> '.$value['name'].'</option>';
|
||||
}
|
||||
$html .='</select>';
|
||||
$html .='</td>';
|
||||
$html .='</tr>';
|
||||
$html .='</table>';
|
||||
|
||||
}
|
||||
|
||||
return $html;
|
||||
|
||||
} else {
|
||||
$html .= '<div style="margin-left: 15px;"><b><i>Please check your API Url & API Key</i></b></div>';
|
||||
}
|
||||
|
||||
$html = '</div>';
|
||||
|
||||
return $html;
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
protected $_apiUrl;
|
||||
protected $_apiKey;
|
||||
protected $_systemStore;
|
||||
protected $_formFactory;
|
||||
protected $_logger;
|
||||
protected $_objectManager;
|
||||
|
||||
public function __construct(
|
||||
\Magento\Framework\Data\FormFactory $formFactory,
|
||||
\Magento\Store\Model\System\Store $systemStore
|
||||
) {
|
||||
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
|
||||
$config = $objectManager->get('\Magento\Framework\App\Config\ScopeConfigInterface');
|
||||
$this->_apiUrl = $config->getValue('retailcrm/general/api_url');
|
||||
$this->_apiKey = $config->getValue('retailcrm/general/api_key');
|
||||
$this->_apiVersion = $config->getValue('retailcrm/general/api_version');
|
||||
$this->_systemStore = $systemStore;
|
||||
$this->_formFactory = $formFactory;
|
||||
$this->_objectManager = $objectManager;
|
||||
}
|
||||
|
||||
public function render(AbstractElement $element)
|
||||
{
|
||||
$html = '';
|
||||
$htmlError = '<div style="margin-left: 15px;"><b><i>Please check your API Url & API Key</i></b></div>';
|
||||
|
||||
if (!empty($this->_apiUrl) && !empty($this->_apiKey)) {
|
||||
$shipConfig = $this->_objectManager->get('Magento\Shipping\Model\Config');
|
||||
$deliveryMethods = $shipConfig->getActiveCarriers();
|
||||
|
||||
$client = new ApiClient($this->_apiUrl, $this->_apiKey, $this->_apiVersion);
|
||||
|
||||
$response = $client->deliveryTypesList();
|
||||
|
||||
if ($response === false) {
|
||||
return $htmlError;
|
||||
}
|
||||
|
||||
if ($response->isSuccessful()) {
|
||||
$deliveryTypes = $response['deliveryTypes'];
|
||||
} else {
|
||||
return $htmlError;
|
||||
}
|
||||
|
||||
$config = \Magento\Framework\App\ObjectManager::getInstance()->get(
|
||||
'Magento\Framework\App\Config\ScopeConfigInterface'
|
||||
);
|
||||
|
||||
foreach (array_keys($deliveryMethods) as $k => $delivery) {
|
||||
$html .='<table id="' . $element->getId() . '_table">';
|
||||
$html .='<tr id="row_retailcrm_shipping_'.$delivery.'">';
|
||||
$html .='<td class="label">'.$delivery.'</td>';
|
||||
$html .='<td>';
|
||||
$html .='<select id="1" name="groups[Shipping][fields]['.$delivery.'][value]">';
|
||||
|
||||
$selected = $config->getValue('retailcrm/Shipping/'.$delivery);
|
||||
|
||||
foreach ($deliveryTypes as $k => $value) {
|
||||
if ((!empty($selected)) && (($selected == $value['code']))) {
|
||||
$select ='selected="selected"';
|
||||
}else{
|
||||
$select ='';
|
||||
}
|
||||
|
||||
$html .='<option '.$select.' value="'.$value['code'].'"> '.$value['name'].'</option>';
|
||||
}
|
||||
|
||||
$html .='</select>';
|
||||
$html .='</td>';
|
||||
$html .='</tr>';
|
||||
$html .='</table>';
|
||||
}
|
||||
|
||||
return $html;
|
||||
} else {
|
||||
return $htmlError;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,96 +1,91 @@
|
||||
<?php
|
||||
|
||||
namespace Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Field;
|
||||
|
||||
use Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Field\Base;
|
||||
use Magento\Framework\Data\Form\Element\AbstractElement;
|
||||
use Retailcrm\Retailcrm\Helper\Proxy as ApiClient;
|
||||
|
||||
class Status extends \Magento\Config\Block\System\Config\Form\Field
|
||||
{
|
||||
protected $_apiUrl;
|
||||
protected $_apiKey;
|
||||
protected $_systemStore;
|
||||
protected $_formFactory;
|
||||
protected $_logger;
|
||||
|
||||
public function __construct(
|
||||
\Magento\Framework\Data\FormFactory $formFactory,
|
||||
\Magento\Store\Model\System\Store $systemStore
|
||||
)
|
||||
{
|
||||
$om = \Magento\Framework\App\ObjectManager::getInstance();
|
||||
$logger = $om->get('\Psr\Log\LoggerInterface');
|
||||
$this->_logger = $logger;
|
||||
|
||||
$base = new Base;
|
||||
|
||||
$this->_apiUrl = $base->_apiUrl;
|
||||
$this->_apiKey = $base->_apiKey;
|
||||
|
||||
$this->_systemStore = $systemStore;
|
||||
$this->_formFactory = $formFactory;
|
||||
|
||||
}
|
||||
|
||||
public function render(AbstractElement $element)
|
||||
{
|
||||
$values = $element->getValues();
|
||||
$html = '';
|
||||
|
||||
if((!empty($this->_apiUrl))&&(!empty($this->_apiKey))){
|
||||
$manager = \Magento\Framework\App\ObjectManager::getInstance();
|
||||
$obj = $manager->create('Magento\Sales\Model\ResourceModel\Order\Status\Collection');
|
||||
$statuses = $obj->toOptionArray();
|
||||
|
||||
$client = new \Retailcrm\Retailcrm\Model\ApiClient\ApiClient($this->_apiUrl,$this->_apiKey);
|
||||
|
||||
try {
|
||||
$response = $client->statusesList();
|
||||
if ($response->isSuccessful()&&200 === $response->getStatusCode()) {
|
||||
$statusTypes = $response['statuses'];
|
||||
}
|
||||
} catch (Retailcrm\Retailcrm\Model\ApiClient\Exception\CurlException $e) {
|
||||
$this->_logger->addDebug($e->getMessage());
|
||||
}
|
||||
|
||||
$config = \Magento\Framework\App\ObjectManager::getInstance()->get(
|
||||
'Magento\Framework\App\Config\ScopeConfigInterface'
|
||||
);
|
||||
|
||||
foreach ($statuses as $k => $status){
|
||||
$html .='<table id="' . $element->getId() . '_table">';
|
||||
$html .='<tr id="row_retailcrm_status_'.$status['label'].'">';
|
||||
$html .='<td class="label">'.$status['label'].'</td>';
|
||||
$html .='<td>';
|
||||
$html .='<select name="groups[Status][fields]['.$status['value'].'][value]">';
|
||||
|
||||
$selected = $config->getValue('retailcrm/Status/'.$status['value']);
|
||||
|
||||
$html .='<option value=""> Select status </option>';
|
||||
foreach ($statusTypes as $k=>$value){
|
||||
|
||||
if((!empty($selected))&&(($selected==$value['name']))||(($selected==$value['code']))){
|
||||
$select ='selected="selected"';
|
||||
}else{
|
||||
$select ='';
|
||||
}
|
||||
|
||||
$html .='<option '.$select.'value="'.$value['code'].'"> '.$value['name'].'</option>';
|
||||
}
|
||||
$html .='</select>';
|
||||
$html .='</td>';
|
||||
$html .='</tr>';
|
||||
$html .='</table>';
|
||||
|
||||
}
|
||||
|
||||
return $html;
|
||||
|
||||
}else{
|
||||
$html = '<div style="margin-left: 15px;"><b><i>Please check your API Url & API Key</i></b></div>';
|
||||
|
||||
return $html;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
protected $_apiUrl;
|
||||
protected $_apiKey;
|
||||
protected $_systemStore;
|
||||
protected $_formFactory;
|
||||
protected $_logger;
|
||||
protected $_objectManager;
|
||||
|
||||
public function __construct(
|
||||
\Magento\Framework\Data\FormFactory $formFactory,
|
||||
\Magento\Store\Model\System\Store $systemStore
|
||||
) {
|
||||
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
|
||||
$config = $objectManager->get('\Magento\Framework\App\Config\ScopeConfigInterface');
|
||||
$this->_apiUrl = $config->getValue('retailcrm/general/api_url');
|
||||
$this->_apiKey = $config->getValue('retailcrm/general/api_key');
|
||||
$this->_apiVersion = $config->getValue('retailcrm/general/api_version');
|
||||
$this->_systemStore = $systemStore;
|
||||
$this->_formFactory = $formFactory;
|
||||
$this->_objectManager = $objectManager;
|
||||
}
|
||||
|
||||
public function render(AbstractElement $element)
|
||||
{
|
||||
$html = '';
|
||||
$htmlError = '<div style="margin-left: 15px;"><b><i>Please check your API Url & API Key</i></b></div>';
|
||||
|
||||
if ((!empty($this->_apiUrl)) && (!empty($this->_apiKey))) {
|
||||
$statusCollection = $this->_objectManager->create('Magento\Sales\Model\ResourceModel\Order\Status\Collection');
|
||||
$statuses = $statusCollection->toOptionArray();
|
||||
|
||||
$client = new ApiClient($this->_apiUrl, $this->_apiKey, $this->_apiVersion);
|
||||
|
||||
$response = $client->statusesList();
|
||||
|
||||
if ($response === false) {
|
||||
return $htmlError;
|
||||
}
|
||||
|
||||
if ($response->isSuccessful()) {
|
||||
$statusTypes = $response['statuses'];
|
||||
} else {
|
||||
return $htmlError;
|
||||
}
|
||||
|
||||
$config = $this->_objectManager->get('Magento\Framework\App\Config\ScopeConfigInterface');
|
||||
|
||||
foreach ($statuses as $k => $status){
|
||||
$html .= '<table id="' . $element->getId() . '_table">';
|
||||
$html .= '<tr id="row_retailcrm_status_' . $status['label'] . '">';
|
||||
$html .= '<td class="label">' . $status['label'] . '</td>';
|
||||
$html .= '<td>';
|
||||
$html .= '<select name="groups[Status][fields][' . $status['value'] . '][value]">';
|
||||
|
||||
$selected = $config->getValue('retailcrm/Status/' . $status['value']);
|
||||
|
||||
$html .= '<option value=""> Select status </option>';
|
||||
|
||||
foreach ($statusTypes as $k => $value){
|
||||
if (
|
||||
(!empty($selected))
|
||||
&& (($selected == $value['name']))
|
||||
|| (($selected == $value['code']))
|
||||
) {
|
||||
$select = 'selected="selected"';
|
||||
} else {
|
||||
$select = '';
|
||||
}
|
||||
|
||||
$html .= '<option ' . $select . 'value="' . $value['code'] . '"> ' . $value['name'] . '</option>';
|
||||
}
|
||||
$html .= '</select>';
|
||||
$html .= '</td>';
|
||||
$html .= '</tr>';
|
||||
$html .= '</table>';
|
||||
}
|
||||
|
||||
return $html;
|
||||
} else {
|
||||
return $htmlError;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,17 +1,16 @@
|
||||
<?php
|
||||
|
||||
namespace Retailcrm\Retailcrm\Block;
|
||||
|
||||
class Display extends \Magento\Framework\View\Element\Template
|
||||
{
|
||||
public function __construct(\Magento\Framework\View\Element\Template\Context $context)
|
||||
{
|
||||
parent::__construct($context);
|
||||
}
|
||||
|
||||
public function sayHello()
|
||||
{
|
||||
|
||||
return __('Hello World');
|
||||
|
||||
parent::__construct($context);
|
||||
}
|
||||
|
||||
}
|
||||
public function sayHello()
|
||||
{
|
||||
return __('Hello World');
|
||||
}
|
||||
}
|
||||
|
@ -1,19 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace Retailcrm\Retailcrm\Controller\Index;
|
||||
|
||||
class Display extends \Magento\Framework\App\Action\Action
|
||||
{
|
||||
protected $_pageFactory;
|
||||
public function __construct(
|
||||
\Magento\Framework\App\Action\Context $context,
|
||||
\Magento\Framework\View\Result\PageFactory $pageFactory)
|
||||
{
|
||||
$this->_pageFactory = $pageFactory;
|
||||
return parent::__construct($context);
|
||||
}
|
||||
protected $_pageFactory;
|
||||
|
||||
public function execute()
|
||||
{
|
||||
return $this->_pageFactory->create();
|
||||
}
|
||||
public function __construct(
|
||||
\Magento\Framework\App\Action\Context $context,
|
||||
\Magento\Framework\View\Result\PageFactory $pageFactory
|
||||
) {
|
||||
$this->_pageFactory = $pageFactory;
|
||||
return parent::__construct($context);
|
||||
}
|
||||
|
||||
public function execute()
|
||||
{
|
||||
return $this->_pageFactory->create();
|
||||
}
|
||||
}
|
@ -7,25 +7,24 @@ use Psr\Log\LoggerInterface;
|
||||
|
||||
class Test extends \Magento\Framework\App\Action\Action
|
||||
{
|
||||
protected $logger;
|
||||
protected $logger;
|
||||
|
||||
public function __construct(
|
||||
LoggerInterface $logger
|
||||
,\Magento\Framework\App\Action\Context $context
|
||||
,\Magento\Framework\View\Page\Config $pageConfig
|
||||
,\Magento\Framework\App\Config\ScopeConfigInterface $config
|
||||
)
|
||||
{
|
||||
$this->logger = $logger;
|
||||
|
||||
$api_url = $config->getValue('retailcrm/general/api_url');
|
||||
$api_key = $config->getValue('retailcrm/general/api_key');
|
||||
|
||||
var_dump($api_key);
|
||||
var_dump($api_url);
|
||||
|
||||
//$this->logger->debug($api_url);
|
||||
|
||||
LoggerInterface $logger,
|
||||
\Magento\Framework\App\Action\Context $context,
|
||||
\Magento\Framework\View\Page\Config $pageConfig,
|
||||
\Magento\Framework\App\Config\ScopeConfigInterface $config
|
||||
) {
|
||||
$this->logger = $logger;
|
||||
|
||||
$api_url = $config->getValue('retailcrm/general/api_url');
|
||||
$api_key = $config->getValue('retailcrm/general/api_key');
|
||||
|
||||
var_dump($api_key);
|
||||
var_dump($api_url);
|
||||
|
||||
//$this->logger->debug($api_url);
|
||||
|
||||
parent::__construct($context);
|
||||
}
|
||||
|
||||
@ -33,6 +32,5 @@ class Test extends \Magento\Framework\App\Action\Action
|
||||
{
|
||||
//
|
||||
exit;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,20 +1,19 @@
|
||||
<?php
|
||||
|
||||
namespace Retailcrm\Retailcrm\Cron;
|
||||
|
||||
class Icml {
|
||||
protected $_logger;
|
||||
|
||||
public function __construct() {
|
||||
$om = \Magento\Framework\App\ObjectManager::getInstance();
|
||||
$logger = $om->get('\Psr\Log\LoggerInterface');
|
||||
$this->_logger = $logger;
|
||||
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
|
||||
$logger = new \Retailcrm\Retailcrm\Model\Logger\Logger($objectManager);
|
||||
$this->_logger = $logger;
|
||||
}
|
||||
|
||||
public function execute() {
|
||||
$Icml = new \Retailcrm\Retailcrm\Model\Icml\Icml();
|
||||
$Icml->generate();
|
||||
|
||||
$this->_logger->addDebug('Cron Works: create icml');
|
||||
public function execute()
|
||||
{
|
||||
$Icml = new \Retailcrm\Retailcrm\Model\Icml\Icml();
|
||||
$Icml->generate();
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -1,20 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace Retailcrm\Retailcrm\Cron;
|
||||
|
||||
class OrderHistory {
|
||||
class OrderHistory
|
||||
{
|
||||
protected $_logger;
|
||||
|
||||
public function __construct() {
|
||||
public function __construct()
|
||||
{
|
||||
$om = \Magento\Framework\App\ObjectManager::getInstance();
|
||||
$logger = $om->get('\Psr\Log\LoggerInterface');
|
||||
$this->_logger = $logger;
|
||||
}
|
||||
|
||||
public function execute() {
|
||||
$history = new \Retailcrm\Retailcrm\Model\History\Exchange();
|
||||
$history->ordersHistory();
|
||||
|
||||
$this->_logger->addDebug('Cron Works: OrderHistory');
|
||||
$logger = new \Retailcrm\Retailcrm\Model\Logger\Logger($om);
|
||||
$this->_logger = $logger;
|
||||
}
|
||||
|
||||
}
|
||||
public function execute()
|
||||
{
|
||||
$history = new \Retailcrm\Retailcrm\Model\History\Exchange();
|
||||
$history->ordersHistory();
|
||||
|
||||
$this->_logger->writeRow('Cron Works: OrderHistory');
|
||||
}
|
||||
}
|
||||
|
@ -1,4 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace Retailcrm\Retailcrm\Helper;
|
||||
|
||||
use Magento\Framework\App\Helper\AbstractHelper;
|
||||
@ -47,21 +48,21 @@ class Data extends AbstractHelper
|
||||
*/
|
||||
public function filterRecursive($haystack)
|
||||
{
|
||||
foreach ($haystack as $key => $value) {
|
||||
if (is_array($value)) {
|
||||
$haystack[$key] = self::filterRecursive($haystack[$key]);
|
||||
}
|
||||
|
||||
if (is_null($haystack[$key])
|
||||
|| $haystack[$key] === ''
|
||||
|| count($haystack[$key]) == 0
|
||||
) {
|
||||
unset($haystack[$key]);
|
||||
} elseif (!is_array($value)) {
|
||||
$haystack[$key] = trim($value);
|
||||
}
|
||||
}
|
||||
|
||||
return $haystack;
|
||||
foreach ($haystack as $key => $value) {
|
||||
if (is_array($value)) {
|
||||
$haystack[$key] = self::filterRecursive($haystack[$key]);
|
||||
}
|
||||
|
||||
if (is_null($haystack[$key])
|
||||
|| $haystack[$key] === ''
|
||||
|| count($haystack[$key]) == 0
|
||||
) {
|
||||
unset($haystack[$key]);
|
||||
} elseif (!is_array($value)) {
|
||||
$haystack[$key] = trim($value);
|
||||
}
|
||||
}
|
||||
|
||||
return $haystack;
|
||||
}
|
||||
}
|
81
Helper/Proxy.php
Normal file
81
Helper/Proxy.php
Normal 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};
|
||||
}
|
||||
}
|
138
Model/Config/Backend/ApiUrl.php
Normal file
138
Model/Config/Backend/ApiUrl.php
Normal 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);
|
||||
}
|
||||
}
|
93
Model/Config/Backend/ApiVersion.php
Normal file
93
Model/Config/Backend/ApiVersion.php
Normal 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
@ -1,4 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace Retailcrm\Retailcrm\Model\Icml;
|
||||
|
||||
class Icml
|
||||
@ -17,26 +18,26 @@ class Icml
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$om = \Magento\Framework\App\ObjectManager::getInstance();
|
||||
$manager = $om->get('Magento\Store\Model\StoreManagerInterface');
|
||||
$categoryCollectionFactory = $om->get('\Magento\Catalog\Model\ResourceModel\Category\CollectionFactory');
|
||||
$product = $om->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
|
||||
$storeManager = $om->get('\Magento\Store\Model\StoreManagerInterface');
|
||||
$StockState = $om->get('\Magento\CatalogInventory\Api\StockStateInterface');
|
||||
$configurable = $om->get('Magento\ConfigurableProduct\Model\Product\Type\Configurable');
|
||||
$config = $om->get('\Magento\Framework\App\Config\ScopeConfigInterface');
|
||||
|
||||
$this->_configurable = $configurable;
|
||||
$this->_StockState = $StockState;
|
||||
$this->_storeManager = $storeManager;
|
||||
$this->_product = $product;
|
||||
$this->_category = $categoryCollectionFactory;
|
||||
$this->_manager = $manager;
|
||||
$this->_config = $config;
|
||||
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
|
||||
$manager = $objectManager->get('Magento\Store\Model\StoreManagerInterface');
|
||||
$categoryCollectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Category\CollectionFactory');
|
||||
$product = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
|
||||
$storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface');
|
||||
$StockState = $objectManager->get('\Magento\CatalogInventory\Api\StockStateInterface');
|
||||
$configurable = $objectManager->get('Magento\ConfigurableProduct\Model\Product\Type\Configurable');
|
||||
$config = $objectManager->get('\Magento\Framework\App\Config\ScopeConfigInterface');
|
||||
|
||||
$this->_configurable = $configurable;
|
||||
$this->_StockState = $StockState;
|
||||
$this->_storeManager = $storeManager;
|
||||
$this->_product = $product;
|
||||
$this->_category = $categoryCollectionFactory;
|
||||
$this->_manager = $manager;
|
||||
$this->_config = $config;
|
||||
}
|
||||
|
||||
public function generate()
|
||||
{
|
||||
public function generate()
|
||||
{
|
||||
$this->_shop = $this->_manager->getStore()->getId();
|
||||
|
||||
$string = '<?xml version="1.0" encoding="UTF-8"?>
|
||||
@ -71,222 +72,241 @@ class Icml
|
||||
$dirlist = new \Magento\Framework\Filesystem\DirectoryList('');
|
||||
$baseDir = $dirlist->getRoot();
|
||||
$shopCode = $this->_manager->getStore()->getCode();
|
||||
$this->_dd->save($baseDir . 'retailcrm_' . $shopCode . '.xml');
|
||||
|
||||
$this->_dd->save($baseDir . 'retailcrm_' . $shopCode . '.xml');
|
||||
}
|
||||
|
||||
|
||||
private function addCategories()
|
||||
{
|
||||
$collection = $this->_category->create();
|
||||
$collection->addAttributeToSelect('*');
|
||||
|
||||
foreach ($collection as $category) {
|
||||
if($category->getId()>1){
|
||||
$e = $this->_eCategories->appendChild(
|
||||
$this->_dd->createElement('category')
|
||||
);
|
||||
$e->appendChild($this->_dd->createTextNode($category->getName()));
|
||||
$e->setAttribute('id', $category->getId());
|
||||
|
||||
if ($category->getParentId() > 1) {
|
||||
$e->setAttribute('parentId', $category->getParentId());
|
||||
}
|
||||
}
|
||||
}
|
||||
$collection = $this->_category->create();
|
||||
$collection->addAttributeToSelect('*');
|
||||
|
||||
foreach ($collection as $category) {
|
||||
if ($category->getId() > 1){
|
||||
$e = $this->_eCategories->appendChild(
|
||||
$this->_dd->createElement('category')
|
||||
);
|
||||
$e->appendChild($this->_dd->createTextNode($category->getName()));
|
||||
$e->setAttribute('id', $category->getId());
|
||||
|
||||
if ($category->getParentId() > 1) {
|
||||
$e->setAttribute('parentId', $category->getParentId());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private function addOffers()
|
||||
{
|
||||
$offers = array();
|
||||
|
||||
$offers = [];
|
||||
|
||||
$collection = $this->_product->create();
|
||||
$collection->addFieldToFilter('visibility', 4);//catalog, search visible
|
||||
$collection->addAttributeToSelect('*');
|
||||
|
||||
$picUrl = $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);;
|
||||
$baseUrl = $this->_storeManager->getStore()->getBaseUrl();
|
||||
|
||||
$customAdditionalAttributes = array();
|
||||
$customAdditionalAttributes = $this->_config->getValue('retailcrm/Misc/attributes_to_export_into_icml');
|
||||
|
||||
foreach ($collection as $product) {
|
||||
|
||||
if($product->getTypeId() == 'simple') {
|
||||
$offer['id'] = $product->getId();
|
||||
$offer['productId'] = $product->getId();
|
||||
$offer['productActivity'] = $product->isAvailable() ? 'Y' : 'N';
|
||||
$offer['name'] = $product->getName();
|
||||
$offer['productName'] = $product->getName();
|
||||
$offer['initialPrice'] = $product->getFinalPrice();
|
||||
$offer['url'] = $product->getProductUrl();
|
||||
$offer['picture'] = $picUrl.'catalog/product'.$product->getImage();
|
||||
$offer['quantity'] = $this->_StockState->getStockQty($product->getId(), $product->getStore()->getWebsiteId());
|
||||
$offer['categoryId'] = $product->getCategoryIds();
|
||||
$offer['vendor'] = $product->getAttributeText('manufacturer');
|
||||
$offer['params'] = array();
|
||||
|
||||
|
||||
$article = $product->getSku();
|
||||
if(!empty($article)) {
|
||||
$offer['params'][] = array(
|
||||
'name' => 'Article',
|
||||
'code' => 'article',
|
||||
'value' => $article
|
||||
);
|
||||
}
|
||||
|
||||
$weight = $product->getWeight();
|
||||
if(!empty($weight)) {
|
||||
$offer['params'][] = array(
|
||||
'name' => 'Weight',
|
||||
'code' => 'weight',
|
||||
'value' => $weight
|
||||
);
|
||||
}
|
||||
|
||||
if(!empty($customAdditionalAttributes)) {
|
||||
//var_dump($customAdditionalAttributes);
|
||||
}
|
||||
|
||||
|
||||
$offers[] = $offer;
|
||||
|
||||
}
|
||||
|
||||
if($product->getTypeId() == 'configurable') {
|
||||
|
||||
$associated_products = $this->_configurable
|
||||
->getUsedProductCollection($product)
|
||||
->addAttributeToSelect('*')
|
||||
->addFilterByRequiredOptions();
|
||||
|
||||
foreach ($associated_products as $associatedProduct) {
|
||||
$offer['id'] = $associatedProduct->getId();
|
||||
$offer['productId'] = $product->getId();
|
||||
$offer['productActivity'] = $associatedProduct->isAvailable() ? 'Y' : 'N';
|
||||
$offer['name'] = $associatedProduct->getName();
|
||||
$offer['productName'] = $product->getName();
|
||||
$offer['initialPrice'] = $associatedProduct->getFinalPrice();
|
||||
$offer['url'] = $product->getProductUrl();
|
||||
$offer['picture'] = $picUrl.'catalog/product'.$associatedProduct->getImage();
|
||||
$offer['quantity'] = $this->_StockState->getStockQty($associatedProduct->getId(), $associatedProduct->getStore()->getWebsiteId());
|
||||
$offer['categoryId'] = $associatedProduct->getCategoryIds();
|
||||
$offer['vendor'] = $associatedProduct->getAttributeText('manufacturer');
|
||||
$offer['params'] = array();
|
||||
|
||||
$article = $associatedProduct->getSku();
|
||||
if(!empty($article)) {
|
||||
$offer['params'][] = array(
|
||||
'name' => 'Article',
|
||||
'code' => 'article',
|
||||
'value' => $article
|
||||
);
|
||||
}
|
||||
|
||||
$weight = $associatedProduct->getWeight();
|
||||
if(!empty($weight)) {
|
||||
$offer['params'][] = array(
|
||||
'name' => 'Weight',
|
||||
'code' => 'weight',
|
||||
'value' => $weight
|
||||
);
|
||||
}
|
||||
|
||||
$offers[] = $offer;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
foreach ($offers as $offer) {
|
||||
$e = $this->_eOffers->appendChild(
|
||||
$this->_dd->createElement('offer')
|
||||
);
|
||||
|
||||
$e->setAttribute('id', $offer['id']);
|
||||
$e->setAttribute('productId', $offer['productId']);
|
||||
|
||||
if (!empty($offer['quantity'])) {
|
||||
$e->setAttribute('quantity', (int) $offer['quantity']);
|
||||
} else {
|
||||
$e->setAttribute('quantity', 0);
|
||||
}
|
||||
|
||||
if (!empty($offer['categoryId'])) {
|
||||
foreach ($offer['categoryId'] as $categoryId) {
|
||||
$e->appendChild(
|
||||
$this->_dd->createElement('categoryId')
|
||||
)->appendChild(
|
||||
$this->_dd->createTextNode($categoryId)
|
||||
);
|
||||
}
|
||||
} else {
|
||||
$e->appendChild($this->_dd->createElement('categoryId', 1));
|
||||
}
|
||||
|
||||
$e->appendChild($this->_dd->createElement('productActivity'))
|
||||
->appendChild(
|
||||
$this->_dd->createTextNode($offer['productActivity'])
|
||||
);
|
||||
|
||||
$e->appendChild($this->_dd->createElement('name'))
|
||||
->appendChild(
|
||||
$this->_dd->createTextNode($offer['name'])
|
||||
);
|
||||
|
||||
$e->appendChild($this->_dd->createElement('productName'))
|
||||
->appendChild(
|
||||
$this->_dd->createTextNode($offer['productName'])
|
||||
);
|
||||
|
||||
$e->appendChild($this->_dd->createElement('price'))
|
||||
->appendChild(
|
||||
$this->_dd->createTextNode($offer['initialPrice'])
|
||||
);
|
||||
|
||||
if (!empty($offer['purchasePrice'])) {
|
||||
$e->appendChild($this->_dd->createElement('purchasePrice'))
|
||||
->appendChild(
|
||||
$this->_dd->createTextNode($offer['purchasePrice'])
|
||||
);
|
||||
}
|
||||
|
||||
if (!empty($offer['picture'])) {
|
||||
$e->appendChild($this->_dd->createElement('picture'))
|
||||
->appendChild(
|
||||
$this->_dd->createTextNode($offer['picture'])
|
||||
);
|
||||
}
|
||||
|
||||
if (!empty($offer['url'])) {
|
||||
$e->appendChild($this->_dd->createElement('url'))
|
||||
->appendChild(
|
||||
$this->_dd->createTextNode($offer['url'])
|
||||
);
|
||||
}
|
||||
|
||||
if (!empty($offer['vendor'])) {
|
||||
$e->appendChild($this->_dd->createElement('vendor'))
|
||||
->appendChild(
|
||||
$this->_dd->createTextNode($offer['vendor'])
|
||||
);
|
||||
}
|
||||
|
||||
if(!empty($offer['params'])) {
|
||||
foreach($offer['params'] as $param) {
|
||||
$paramNode = $this->_dd->createElement('param');
|
||||
$paramNode->setAttribute('name', $param['name']);
|
||||
$paramNode->setAttribute('code', $param['code']);
|
||||
$paramNode->appendChild(
|
||||
$this->_dd->createTextNode($param['value'])
|
||||
);
|
||||
$e->appendChild($paramNode);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
$collection->addAttributeToSelect('*');
|
||||
|
||||
$picUrl = $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
|
||||
$baseUrl = $this->_storeManager->getStore()->getBaseUrl();
|
||||
|
||||
$customAdditionalAttributes = [];
|
||||
$customAdditionalAttributes = $this->_config->getValue('retailcrm/Misc/attributes_to_export_into_icml');
|
||||
|
||||
foreach ($collection as $product) {
|
||||
if ($product->getTypeId() == 'simple') {
|
||||
$offer['id'] = $product->getId();
|
||||
$offer['productId'] = $product->getId();
|
||||
$offer['productActivity'] = $product->isAvailable() ? 'Y' : 'N';
|
||||
$offer['name'] = $product->getName();
|
||||
$offer['productName'] = $product->getName();
|
||||
$offer['initialPrice'] = $product->getFinalPrice();
|
||||
$offer['url'] = $product->getProductUrl();
|
||||
$offer['picture'] = $picUrl.'catalog/product'.$product->getImage();
|
||||
$offer['quantity'] = $this->_StockState->getStockQty($product->getId(), $product->getStore()->getWebsiteId());
|
||||
$offer['categoryId'] = $product->getCategoryIds();
|
||||
$offer['vendor'] = $product->getAttributeText('manufacturer');
|
||||
$offer['params'] = [];
|
||||
|
||||
$article = $product->getSku();
|
||||
|
||||
if(!empty($article)) {
|
||||
$offer['params'][] = [
|
||||
'name' => 'Article',
|
||||
'code' => 'article',
|
||||
'value' => $article
|
||||
];
|
||||
}
|
||||
|
||||
$weight = $product->getWeight();
|
||||
|
||||
if(!empty($weight)) {
|
||||
$offer['params'][] = [
|
||||
'name' => 'Weight',
|
||||
'code' => 'weight',
|
||||
'value' => $weight
|
||||
];
|
||||
}
|
||||
|
||||
if(!empty($customAdditionalAttributes)) {
|
||||
//var_dump($customAdditionalAttributes);
|
||||
}
|
||||
|
||||
$offers[] = $offer;
|
||||
}
|
||||
|
||||
if ($product->getTypeId() == 'configurable') {
|
||||
$associated_products = $this->_configurable
|
||||
->getUsedProductCollection($product)
|
||||
->addAttributeToSelect('*')
|
||||
->addFilterByRequiredOptions();
|
||||
|
||||
foreach ($associated_products as $associatedProduct) {
|
||||
$offer['id'] = $associatedProduct->getId();
|
||||
$offer['productId'] = $product->getId();
|
||||
$offer['productActivity'] = $associatedProduct->isAvailable() ? 'Y' : 'N';
|
||||
$offer['name'] = $associatedProduct->getName();
|
||||
$offer['productName'] = $product->getName();
|
||||
$offer['initialPrice'] = $associatedProduct->getFinalPrice();
|
||||
$offer['url'] = $product->getProductUrl();
|
||||
$offer['picture'] = $picUrl.'catalog/product'.$associatedProduct->getImage();
|
||||
$offer['quantity'] = $this->_StockState->getStockQty($associatedProduct->getId(), $associatedProduct->getStore()->getWebsiteId());
|
||||
$offer['categoryId'] = $associatedProduct->getCategoryIds();
|
||||
$offer['vendor'] = $associatedProduct->getAttributeText('manufacturer');
|
||||
$offer['params'] = [];
|
||||
|
||||
$article = $associatedProduct->getSku();
|
||||
|
||||
if ($associatedProduct->getResource()->getAttribute('color')) {
|
||||
$colorAttribute = $associatedProduct->getResource()->getAttribute('color');
|
||||
$color = $colorAttribute->getSource()->getOptionText($associatedProduct->getColor());
|
||||
}
|
||||
|
||||
if (isset($color)) {
|
||||
$offer['params'][] = [
|
||||
'name' => 'Color',
|
||||
'code' => 'color',
|
||||
'value' => $color
|
||||
];
|
||||
}
|
||||
|
||||
if ($associatedProduct->getResource()->getAttribute('size')) {
|
||||
$sizeAttribute = $associatedProduct->getResource()->getAttribute('size');
|
||||
$size = $sizeAttribute->getSource()->getOptionText($associatedProduct->getSize());
|
||||
}
|
||||
|
||||
if (isset($size)) {
|
||||
$offer['params'][] = [
|
||||
'name' => 'Size',
|
||||
'code' => 'size',
|
||||
'value' => $size
|
||||
];
|
||||
}
|
||||
|
||||
if (!empty($article)) {
|
||||
$offer['params'][] = [
|
||||
'name' => 'Article',
|
||||
'code' => 'article',
|
||||
'value' => $article
|
||||
];
|
||||
}
|
||||
|
||||
$weight = $associatedProduct->getWeight();
|
||||
|
||||
if(!empty($weight)) {
|
||||
$offer['params'][] = [
|
||||
'name' => 'Weight',
|
||||
'code' => 'weight',
|
||||
'value' => $weight
|
||||
];
|
||||
}
|
||||
|
||||
$offers[] = $offer;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($offers as $offer) {
|
||||
$e = $this->_eOffers->appendChild(
|
||||
$this->_dd->createElement('offer')
|
||||
);
|
||||
|
||||
$e->setAttribute('id', $offer['id']);
|
||||
$e->setAttribute('productId', $offer['productId']);
|
||||
|
||||
if (!empty($offer['quantity'])) {
|
||||
$e->setAttribute('quantity', (int) $offer['quantity']);
|
||||
} else {
|
||||
$e->setAttribute('quantity', 0);
|
||||
}
|
||||
|
||||
if (!empty($offer['categoryId'])) {
|
||||
foreach ($offer['categoryId'] as $categoryId) {
|
||||
$e->appendChild(
|
||||
$this->_dd->createElement('categoryId')
|
||||
)->appendChild(
|
||||
$this->_dd->createTextNode($categoryId)
|
||||
);
|
||||
}
|
||||
} else {
|
||||
$e->appendChild($this->_dd->createElement('categoryId', 1));
|
||||
}
|
||||
|
||||
$e->appendChild($this->_dd->createElement('productActivity'))
|
||||
->appendChild(
|
||||
$this->_dd->createTextNode($offer['productActivity'])
|
||||
);
|
||||
|
||||
$e->appendChild($this->_dd->createElement('name'))
|
||||
->appendChild(
|
||||
$this->_dd->createTextNode($offer['name'])
|
||||
);
|
||||
|
||||
$e->appendChild($this->_dd->createElement('productName'))
|
||||
->appendChild(
|
||||
$this->_dd->createTextNode($offer['productName'])
|
||||
);
|
||||
|
||||
$e->appendChild($this->_dd->createElement('price'))
|
||||
->appendChild(
|
||||
$this->_dd->createTextNode($offer['initialPrice'])
|
||||
);
|
||||
|
||||
if (!empty($offer['purchasePrice'])) {
|
||||
$e->appendChild($this->_dd->createElement('purchasePrice'))
|
||||
->appendChild(
|
||||
$this->_dd->createTextNode($offer['purchasePrice'])
|
||||
);
|
||||
}
|
||||
|
||||
if (!empty($offer['picture'])) {
|
||||
$e->appendChild($this->_dd->createElement('picture'))
|
||||
->appendChild(
|
||||
$this->_dd->createTextNode($offer['picture'])
|
||||
);
|
||||
}
|
||||
|
||||
if (!empty($offer['url'])) {
|
||||
$e->appendChild($this->_dd->createElement('url'))
|
||||
->appendChild(
|
||||
$this->_dd->createTextNode($offer['url'])
|
||||
);
|
||||
}
|
||||
|
||||
if (!empty($offer['vendor'])) {
|
||||
$e->appendChild($this->_dd->createElement('vendor'))
|
||||
->appendChild(
|
||||
$this->_dd->createTextNode($offer['vendor'])
|
||||
);
|
||||
}
|
||||
|
||||
if(!empty($offer['params'])) {
|
||||
foreach($offer['params'] as $param) {
|
||||
$paramNode = $this->_dd->createElement('param');
|
||||
$paramNode->setAttribute('name', $param['name']);
|
||||
$paramNode->setAttribute('code', $param['code']);
|
||||
$paramNode->appendChild(
|
||||
$this->_dd->createTextNode($param['value'])
|
||||
);
|
||||
$e->appendChild($paramNode);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,29 +1,94 @@
|
||||
<?php
|
||||
|
||||
namespace Retailcrm\Retailcrm\Model\Logger;
|
||||
|
||||
class Logger
|
||||
{
|
||||
private $logPath;
|
||||
private $files;
|
||||
|
||||
public function __construct(
|
||||
$logPath = '/app/code/Retailcrm/Retailcrm/Log/'
|
||||
)
|
||||
private $logDir;
|
||||
|
||||
public function __construct(\Magento\Framework\ObjectManagerInterface $objectManager)
|
||||
{
|
||||
$this->logPath = $logPath;
|
||||
|
||||
}
|
||||
|
||||
public function write($dump, $file)
|
||||
{
|
||||
$path =$this->logPath . $file.'.txt';
|
||||
|
||||
$f = fopen($_SERVER["DOCUMENT_ROOT"].$path, "a+");
|
||||
fwrite($f, print_r(array(date('Y-m-d H:i:s'), array(
|
||||
$dump
|
||||
)),true));
|
||||
fclose($f);
|
||||
|
||||
$directory = $objectManager->get('\Magento\Framework\Filesystem\DirectoryList');
|
||||
$this->logDir = $directory->getPath('log');
|
||||
}
|
||||
|
||||
/**
|
||||
* Write data in log file
|
||||
*
|
||||
* @param array $data
|
||||
* @param str $fileName
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function writeDump($data, $fileName)
|
||||
{
|
||||
$filePath = $this->logDir . '/' . $fileName . '.log';
|
||||
|
||||
if (!$this->checkSize($filePath)) {
|
||||
$this->clear($filePath);
|
||||
}
|
||||
|
||||
$logData = [
|
||||
'date' => date('Y-m-d H:i:s'),
|
||||
'data' => $data
|
||||
];
|
||||
|
||||
$file = fopen($filePath, "a+");
|
||||
fwrite($file, print_r($logData, true));
|
||||
fclose($file);
|
||||
}
|
||||
|
||||
/**
|
||||
* Write data in log file
|
||||
*
|
||||
* @param str $data
|
||||
* @param str $fileName
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function writeRow($data, $fileName = 'retailcrm')
|
||||
{
|
||||
$filePath = $this->logDir . '/' . $fileName . '.log';
|
||||
|
||||
if (!$this->checkSize($filePath)) {
|
||||
$this->clear($filePath);
|
||||
}
|
||||
|
||||
$nowDate = date('Y-m-d H:i:s');
|
||||
$logData = "[$nowDate] @ " . $data . "\n";
|
||||
|
||||
$file = fopen($filePath, "a+");
|
||||
fwrite($file, $logData);
|
||||
fclose($file);
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear file
|
||||
*
|
||||
* @param str $file
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function clear($file)
|
||||
{
|
||||
file_put_contents($file, '');
|
||||
}
|
||||
|
||||
/**
|
||||
* Check file size
|
||||
*
|
||||
* @param str $file
|
||||
*
|
||||
* @return boolean
|
||||
*/
|
||||
protected function checkSize($file)
|
||||
{
|
||||
if (!file_exists($file)) {
|
||||
return true;
|
||||
} elseif (filesize($file) > 10485760) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
@ -1,59 +1,66 @@
|
||||
<?php
|
||||
|
||||
namespace Retailcrm\Retailcrm\Model\Observer;
|
||||
use Magento\Framework\Event\Observer;
|
||||
|
||||
use Retailcrm\Retailcrm\Helper\Proxy as ApiClient;
|
||||
|
||||
class Customer implements \Magento\Framework\Event\ObserverInterface
|
||||
{
|
||||
protected $_api;
|
||||
protected $_config;
|
||||
protected $_helper;
|
||||
protected $_logger;
|
||||
protected $_api;
|
||||
protected $_config;
|
||||
protected $_helper;
|
||||
protected $_logger;
|
||||
protected $_objectManager;
|
||||
protected $registry;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$om = \Magento\Framework\App\ObjectManager::getInstance();
|
||||
$helper = $om->get('\Retailcrm\Retailcrm\Helper\Data');
|
||||
$logger = $om->get('\Psr\Log\LoggerInterface');
|
||||
$config = $om->get('\Magento\Framework\App\Config\ScopeConfigInterface');
|
||||
|
||||
$this->_logger = $logger;
|
||||
$this->_helper = $helper;
|
||||
$this->_config = $config;
|
||||
|
||||
$url = $config->getValue('retailcrm/general/api_url');
|
||||
$key = $config->getValue('retailcrm/general/api_key');
|
||||
|
||||
if(!empty($url) && !empty($key)) {
|
||||
$this->_api = new \Retailcrm\Retailcrm\Model\ApiClient\ApiClient($url,$key);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public function execute(\Magento\Framework\Event\Observer $observer)
|
||||
{
|
||||
$data = $observer->getEvent()->getCustomer();
|
||||
|
||||
$customer = array(
|
||||
'externalId' => $data->getId(),
|
||||
'email' => $data->getEmail(),
|
||||
'firstName' => $data->getFirstname(),
|
||||
'patronymic' => $data->getMiddlename(),
|
||||
'lastName' => $data->getLastname(),
|
||||
'createdAt' => date('Y-m-d H:i:s', strtotime($data->getCreatedAt()))
|
||||
);
|
||||
|
||||
$response = $this->_api->customersEdit($customer);
|
||||
|
||||
if ((404 === $response->getStatusCode()) &&($response['errorMsg']==='Not found')) {
|
||||
$this->_api->customersCreate($customer);
|
||||
}
|
||||
|
||||
//$logger = new \Retailcrm\Retailcrm\Model\Logger\Logger();
|
||||
//$logger->write($customer,'Customer');
|
||||
|
||||
}
|
||||
|
||||
|
||||
public function __construct(
|
||||
\Magento\Framework\ObjectManagerInterface $objectManager,
|
||||
\Magento\Framework\App\Config\ScopeConfigInterface $config,
|
||||
\Magento\Framework\Registry $registry
|
||||
) {
|
||||
$helper = $objectManager->get('\Retailcrm\Retailcrm\Helper\Data');
|
||||
$logger = $objectManager->get('\Retailcrm\Retailcrm\Model\Logger\Logger');
|
||||
|
||||
}
|
||||
$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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,180 +1,268 @@
|
||||
<?php
|
||||
|
||||
namespace Retailcrm\Retailcrm\Model\Observer;
|
||||
|
||||
use Magento\Framework\Event\Observer;
|
||||
use Retailcrm\Retailcrm\Helper\Proxy as ApiClient;
|
||||
|
||||
class OrderCreate implements \Magento\Framework\Event\ObserverInterface
|
||||
{
|
||||
protected $_api;
|
||||
protected $_objectManager;
|
||||
protected $_config;
|
||||
protected $_helper;
|
||||
protected $_logger;
|
||||
protected $_configurable;
|
||||
protected $_api;
|
||||
protected $_objectManager;
|
||||
protected $_config;
|
||||
protected $_helper;
|
||||
protected $_logger;
|
||||
protected $_registry;
|
||||
|
||||
public function __construct(
|
||||
\Magento\Framework\ObjectManager\ObjectManager $ObjectManager,
|
||||
\Magento\Framework\App\Config\ScopeConfigInterface $config
|
||||
)
|
||||
{
|
||||
$om = \Magento\Framework\App\ObjectManager::getInstance();
|
||||
$helper = $om->get('\Retailcrm\Retailcrm\Helper\Data');
|
||||
$logger = $om->get('\Psr\Log\LoggerInterface');
|
||||
$configurable = $om->get('Magento\ConfigurableProduct\Model\Product\Type\Configurable');
|
||||
|
||||
$this->_configurable = $configurable;
|
||||
$this->_logger = $logger;
|
||||
$this->_helper = $helper;
|
||||
$this->_objectManager = $ObjectManager;
|
||||
$this->_config = $config;
|
||||
|
||||
$url = $config->getValue('retailcrm/general/api_url');
|
||||
$key = $config->getValue('retailcrm/general/api_key');
|
||||
|
||||
if(!empty($url) && !empty($key)) {
|
||||
$this->_api = new \Retailcrm\Retailcrm\Model\ApiClient\ApiClient($url,$key);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public function execute(\Magento\Framework\Event\Observer $observer)
|
||||
{
|
||||
$order = $observer->getEvent()->getOrder();
|
||||
$items = array();
|
||||
$addressObj = $order->getBillingAddress();
|
||||
|
||||
|
||||
foreach ($order->getAllItems() as $item) {
|
||||
if ($item->getProductType() == "simple") {
|
||||
|
||||
$price = $item->getPrice();
|
||||
|
||||
if($price == 0){
|
||||
$om = \Magento\Framework\App\ObjectManager::getInstance();
|
||||
$omproduct = $om->get('Magento\Catalog\Model\ProductRepository')
|
||||
->getById($item->getProductId());
|
||||
$price = $omproduct->getPrice();
|
||||
}
|
||||
|
||||
$product = array(
|
||||
'productId' => $item->getProductId(),
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param \Magento\Framework\ObjectManagerInterface $objectManager
|
||||
* @param \Magento\Framework\App\Config\ScopeConfigInterface $config
|
||||
* @param \Retailcrm\Retailcrm\Model\Logger\Logger $logger
|
||||
* @param \Magento\Framework\Registry $registry
|
||||
*/
|
||||
public function __construct(
|
||||
\Magento\Framework\ObjectManagerInterface $objectManager,
|
||||
\Magento\Framework\App\Config\ScopeConfigInterface $config,
|
||||
\Magento\Framework\Registry $registry
|
||||
) {
|
||||
$helper = $objectManager->get('\Retailcrm\Retailcrm\Helper\Data');
|
||||
$this->_logger = $objectManager->get('\Retailcrm\Retailcrm\Model\Logger\Logger');
|
||||
$this->_helper = $helper;
|
||||
$this->_objectManager = $objectManager;
|
||||
$this->_config = $config;
|
||||
$this->_registry = $registry;
|
||||
|
||||
$url = $config->getValue('retailcrm/general/api_url');
|
||||
$key = $config->getValue('retailcrm/general/api_key');
|
||||
$apiVersion = $config->getValue('retailcrm/general/api_version');
|
||||
|
||||
if (!empty($url) && !empty($key)) {
|
||||
$this->_api = new ApiClient($url, $key, $apiVersion);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute send order in CRM
|
||||
*
|
||||
* @param Observer $observer
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
public function execute(Observer $observer)
|
||||
{
|
||||
if ($this->_registry->registry('RETAILCRM_HISTORY') === true) {
|
||||
return;
|
||||
}
|
||||
|
||||
$order = $observer->getEvent()->getOrder();
|
||||
|
||||
if ($this->existsInCrm($order->getId()) === true) {
|
||||
return;
|
||||
}
|
||||
|
||||
$items = [];
|
||||
$addressObj = $order->getBillingAddress();
|
||||
|
||||
foreach ($order->getAllItems() as $item) {
|
||||
if ($item->getProductType() == "simple") {
|
||||
$price = $item->getPrice();
|
||||
|
||||
if ($price == 0) {
|
||||
$omproduct = $this->_objectManager->get('Magento\Catalog\Model\ProductRepository')
|
||||
->getById($item->getProductId());
|
||||
$price = $omproduct->getPrice();
|
||||
}
|
||||
|
||||
$product = [
|
||||
'productId' => $item->getProductId(),
|
||||
'productName' => $item->getName(),
|
||||
'quantity' => $item->getQtyOrdered(),
|
||||
'initialPrice' => $price,
|
||||
'offer'=>array(
|
||||
'externalId'=>$item->getProductId()
|
||||
)
|
||||
);
|
||||
|
||||
unset($om);
|
||||
unset($omproduct);
|
||||
unset($price);
|
||||
|
||||
$items[] = $product;
|
||||
}
|
||||
}
|
||||
|
||||
$ship = $this->getShippingCode($order->getShippingMethod());
|
||||
|
||||
$preparedOrder = array(
|
||||
'site' => $order->getStore()->getCode(),
|
||||
'externalId' => $order->getRealOrderId(),
|
||||
'number' => $order->getRealOrderId(),
|
||||
'createdAt' => date('Y-m-d H:i:s'),
|
||||
'lastName' => $order->getCustomerLastname(),
|
||||
'firstName' => $order->getCustomerFirstname(),
|
||||
'patronymic' => $order->getCustomerMiddlename(),
|
||||
'email' => $order->getCustomerEmail(),
|
||||
'phone' => $addressObj->getTelephone(),
|
||||
'paymentType' => $this->_config->getValue('retailcrm/Payment/'.$order->getPayment()->getMethodInstance()->getCode()),
|
||||
'status' => $this->_config->getValue('retailcrm/Status/'.$order->getStatus()),
|
||||
'discount' => abs($order->getDiscountAmount()),
|
||||
'items' => $items,
|
||||
'delivery' => array(
|
||||
'code' => $this->_config->getValue('retailcrm/Shipping/'.$ship),
|
||||
'cost' => $order->getShippingAmount(),
|
||||
'address' => array(
|
||||
'index' => $addressObj->getData('postcode'),
|
||||
'city' => $addressObj->getData('city'),
|
||||
'country' => $addressObj->getData('country_id'),
|
||||
'street' => $addressObj->getData('street'),
|
||||
'region' => $addressObj->getData('region'),
|
||||
'text' => trim(
|
||||
',',
|
||||
implode(
|
||||
',',
|
||||
array(
|
||||
$addressObj->getData('postcode'),
|
||||
$addressObj->getData('city'),
|
||||
$addressObj->getData('street'),
|
||||
)
|
||||
)
|
||||
)
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
|
||||
if(trim($preparedOrder['delivery']['code']) == ''){
|
||||
unset($preparedOrder['delivery']['code']);
|
||||
}
|
||||
|
||||
if(trim($preparedOrder['paymentType']) == ''){
|
||||
unset($preparedOrder['paymentType']);
|
||||
}
|
||||
|
||||
if(trim($preparedOrder['status']) == ''){
|
||||
unset($preparedOrder['status']);
|
||||
}
|
||||
|
||||
if ($order->getCustomerIsGuest() == 0) {
|
||||
$preparedCustomer = array(
|
||||
'externalId' => $order->getCustomerId()
|
||||
);
|
||||
|
||||
if ($this->_api->customersCreate($preparedCustomer)) {
|
||||
$preparedOrder['customer']['externalId'] = $order->getCustomerId();
|
||||
}
|
||||
}
|
||||
|
||||
$this->_helper->filterRecursive($preparedOrder);
|
||||
|
||||
$logger = new \Retailcrm\Retailcrm\Model\Logger\Logger();
|
||||
$logger->write($preparedOrder,'CreateOrder');
|
||||
|
||||
try {
|
||||
$response = $this->_api->ordersCreate($preparedOrder);
|
||||
if ($response->isSuccessful() && 201 === $response->getStatusCode()) {
|
||||
$this->_logger->addDebug($response->id);
|
||||
|
||||
} else {
|
||||
$this->_logger->addDebug(
|
||||
sprintf(
|
||||
"Order create error: [HTTP status %s] %s",
|
||||
$response->getStatusCode(),
|
||||
$response->getErrorMsg()
|
||||
)
|
||||
);
|
||||
|
||||
if (isset($response['errors'])) {
|
||||
$this->_logger->addDebug(implode(' :: ', $response['errors']));
|
||||
}
|
||||
}
|
||||
} catch (\Retailcrm\Retailcrm\Model\ApiClient\Exception\CurlException $e) {
|
||||
$this->_logger->addDebug($e->getMessage());
|
||||
|
||||
}
|
||||
|
||||
|
||||
return $this;
|
||||
}
|
||||
'offer' => [
|
||||
'externalId' => $item->getProductId()
|
||||
]
|
||||
];
|
||||
|
||||
protected function getShippingCode($string)
|
||||
{
|
||||
$split = array_values(explode('_', $string));
|
||||
$length = count($split);
|
||||
$prepare = array_slice($split, 0, $length/2);
|
||||
|
||||
return implode('_', $prepare);
|
||||
}
|
||||
unset($omproduct);
|
||||
unset($price);
|
||||
|
||||
$items[] = $product;
|
||||
}
|
||||
}
|
||||
|
||||
$shippingCode = $this->getShippingCode($order->getShippingMethod());
|
||||
|
||||
$preparedOrder = [
|
||||
'site' => $order->getStore()->getCode(),
|
||||
'externalId' => $order->getId(),
|
||||
'number' => $order->getRealOrderId(),
|
||||
'createdAt' => $order->getCreatedAt(),
|
||||
'lastName' => $order->getCustomerLastname() ? $order->getCustomerLastname() : $addressObj->getLastname(),
|
||||
'firstName' => $order->getCustomerFirstname() ? $order->getCustomerFirstname() : $addressObj->getFirstname(),
|
||||
'patronymic' => $order->getCustomerMiddlename() ? $order->getCustomerMiddlename() : $addressObj->getMiddlename(),
|
||||
'email' => $order->getCustomerEmail(),
|
||||
'phone' => $addressObj->getTelephone(),
|
||||
'status' => $this->_config->getValue('retailcrm/Status/' . $order->getStatus()),
|
||||
'items' => $items,
|
||||
'delivery' => [
|
||||
'code' => $this->_config->getValue('retailcrm/Shipping/' . $shippingCode),
|
||||
'cost' => $order->getShippingAmount(),
|
||||
'address' => [
|
||||
'index' => $addressObj->getData('postcode'),
|
||||
'city' => $addressObj->getData('city'),
|
||||
'street' => $addressObj->getData('street'),
|
||||
'region' => $addressObj->getData('region'),
|
||||
'text' => trim(
|
||||
',',
|
||||
implode(
|
||||
',',
|
||||
[
|
||||
$addressObj->getData('postcode'),
|
||||
$addressObj->getData('city'),
|
||||
$addressObj->getData('street'),
|
||||
]
|
||||
)
|
||||
)
|
||||
]
|
||||
]
|
||||
];
|
||||
|
||||
if ($addressObj->getData('country_id')) {
|
||||
$preparedOrder['countryIso'] = $addressObj->getData('country_id');
|
||||
}
|
||||
|
||||
if ($this->_api->getVersion() == 'v4') {
|
||||
$preparedOrder['paymentType'] = $this->_config->getValue('retailcrm/Payment/'.$order->getPayment()->getMethodInstance()->getCode());
|
||||
$preparedOrder['discount'] = abs($order->getDiscountAmount());
|
||||
} elseif ($this->_api->getVersion() == 'v5') {
|
||||
$preparedOrder['discountManualAmount'] = abs($order->getDiscountAmount());
|
||||
|
||||
$payment = [
|
||||
'type' => $this->_config->getValue('retailcrm/Payment/' . $order->getPayment()->getMethodInstance()->getCode()),
|
||||
'externalId' => $order->getId(),
|
||||
'order' => [
|
||||
'externalId' => $order->getId(),
|
||||
]
|
||||
];
|
||||
|
||||
if ($order->getBaseTotalDue() == 0) {
|
||||
$payment['status'] = 'paid';
|
||||
}
|
||||
|
||||
$preparedOrder['payments'][] = $payment;
|
||||
}
|
||||
|
||||
if (trim($preparedOrder['delivery']['code']) == '') {
|
||||
unset($preparedOrder['delivery']['code']);
|
||||
}
|
||||
|
||||
if (isset($preparedOrder['paymentType']) && trim($preparedOrder['paymentType']) == '') {
|
||||
unset($preparedOrder['paymentType']);
|
||||
}
|
||||
|
||||
if (trim($preparedOrder['status']) == '') {
|
||||
unset($preparedOrder['status']);
|
||||
}
|
||||
|
||||
if ($order->getCustomerIsGuest() == 1) {
|
||||
$customer = $this->getCustomerByEmail($order->getCustomerEmail());
|
||||
|
||||
if ($customer !== false) {
|
||||
$preparedOrder['customer']['id'] = $customer['id'];
|
||||
}
|
||||
} elseif ($order->getCustomerIsGuest() == 0) {
|
||||
if ($this->existsInCrm($order->getCustomerId(), 'customersGet')) {
|
||||
$preparedOrder['customer']['externalId'] = $order->getCustomerId();
|
||||
} else {
|
||||
$preparedCustomer = [
|
||||
'externalId' => $order->getCustomerId(),
|
||||
'firstName' => $order->getCustomerFirstname(),
|
||||
'lastName' => $order->getCustomerLastname(),
|
||||
'email' => $order->getCustomerEmail()
|
||||
];
|
||||
|
||||
if ($addressObj->getTelephone()) {
|
||||
$preparedCustomer['phones'][] = [
|
||||
'number' => $addressObj->getTelephone()
|
||||
];
|
||||
}
|
||||
|
||||
if ($this->_api->customersCreate($preparedCustomer)) {
|
||||
$preparedOrder['customer']['externalId'] = $order->getCustomerId();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$this->_helper->filterRecursive($preparedOrder);
|
||||
|
||||
$this->_logger->writeDump($preparedOrder,'CreateOrder');
|
||||
|
||||
$this->_api->ordersCreate($preparedOrder);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get shipping code
|
||||
*
|
||||
* @param string $string
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function getShippingCode($string)
|
||||
{
|
||||
$split = array_values(explode('_', $string));
|
||||
$length = count($split);
|
||||
$prepare = array_slice($split, 0, $length/2);
|
||||
|
||||
return implode('_', $prepare);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check exists order or customer in CRM
|
||||
*
|
||||
* @param int $id
|
||||
*
|
||||
* @return boolean
|
||||
*/
|
||||
protected function existsInCrm($id, $method = 'ordersGet', $by = 'externalId')
|
||||
{
|
||||
$response = $this->_api->{$method}($id, $by);
|
||||
|
||||
if ($response === false) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!$response->isSuccessful() && $response->errorMsg == $this->_api->getErrorText('errorNotFound')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get customer by email from CRM
|
||||
*
|
||||
* @param string $email
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
protected function getCustomerByEmail($email)
|
||||
{
|
||||
$response = $this->_api->customersList(['email' => $email]);
|
||||
|
||||
if ($response === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($response->isSuccessful() && isset($response['customers'])) {
|
||||
if (!empty($response['customers'])) {
|
||||
return reset($response['customers']);
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
@ -1,56 +1,79 @@
|
||||
<?php
|
||||
|
||||
namespace Retailcrm\Retailcrm\Model\Observer;
|
||||
|
||||
use Magento\Framework\Event\Observer;
|
||||
use Retailcrm\Retailcrm\Helper\Proxy as ApiClient;
|
||||
|
||||
class OrderUpdate implements \Magento\Framework\Event\ObserverInterface
|
||||
{
|
||||
protected $_api;
|
||||
protected $_config;
|
||||
protected $_helper;
|
||||
protected $_logger;
|
||||
protected $_api;
|
||||
protected $_config;
|
||||
protected $_helper;
|
||||
protected $_objectManager;
|
||||
protected $registry;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$om = \Magento\Framework\App\ObjectManager::getInstance();
|
||||
$helper = $om->get('\Retailcrm\Retailcrm\Helper\Data');
|
||||
$logger = $om->get('\Psr\Log\LoggerInterface');
|
||||
$config = $om->get('\Magento\Framework\App\Config\ScopeConfigInterface');
|
||||
|
||||
$this->_logger = $logger;
|
||||
$this->_helper = $helper;
|
||||
$this->_config = $config;
|
||||
|
||||
$url = $config->getValue('retailcrm/general/api_url');
|
||||
$key = $config->getValue('retailcrm/general/api_key');
|
||||
|
||||
if(!empty($url) && !empty($key)) {
|
||||
$this->_api = new \Retailcrm\Retailcrm\Model\ApiClient\ApiClient($url,$key);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public function execute(\Magento\Framework\Event\Observer $observer)
|
||||
{
|
||||
$order = $observer->getEvent()->getOrder();
|
||||
|
||||
if(isset($order)){
|
||||
|
||||
$preparedOrder = array(
|
||||
'externalId' => $order->getRealOrderId(),
|
||||
'status' => $this->_config->getValue('retailcrm/Status/'.$order->getStatus()),
|
||||
);
|
||||
|
||||
if((float)$order->getBaseGrandTotal() == (float)$order->getTotalPaid()){
|
||||
$preparedOrder['paymentStatus'] = 'paid';
|
||||
}
|
||||
|
||||
$this->_helper->filterRecursive($preparedOrder);
|
||||
$this->_api->ordersEdit($preparedOrder);
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param \Magento\Framework\ObjectManagerInterface $objectManager
|
||||
* @param \Magento\Framework\App\Config\ScopeConfigInterface $config
|
||||
*/
|
||||
public function __construct(
|
||||
\Magento\Framework\ObjectManagerInterface $objectManager,
|
||||
\Magento\Framework\App\Config\ScopeConfigInterface $config,
|
||||
\Magento\Framework\Registry $registry
|
||||
) {
|
||||
$this->_helper = $objectManager->get('\Retailcrm\Retailcrm\Helper\Data');
|
||||
$this->_objectManager = $objectManager;
|
||||
$this->_config = $config;
|
||||
$this->registry = $registry;
|
||||
|
||||
}
|
||||
$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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,168 +1,165 @@
|
||||
<?php
|
||||
|
||||
namespace Retailcrm\Retailcrm\Model\Order;
|
||||
|
||||
use \Retailcrm\Retailcrm\Observer;
|
||||
use Retailcrm\Retailcrm\Model\Observer\OrderCreate;
|
||||
use Retailcrm\Retailcrm\Helper\Proxy as ApiClient;
|
||||
|
||||
//use Psr\Log\LoggerInterface;
|
||||
|
||||
class OrderNumber extends \Retailcrm\Retailcrm\Model\Observer\OrderCreate
|
||||
class OrderNumber extends OrderCreate
|
||||
{
|
||||
protected $_orderRepository;
|
||||
protected $_searchCriteriaBuilder;
|
||||
protected $_config;
|
||||
protected $_filterBuilder;
|
||||
protected $_order;
|
||||
protected $_helper;
|
||||
protected $_api;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$om = \Magento\Framework\App\ObjectManager::getInstance();
|
||||
$orderRepository = $om->get('Magento\Sales\Model\OrderRepository');
|
||||
$searchCriteriaBuilder = $om->get('Magento\Framework\Api\SearchCriteriaBuilder');
|
||||
$config = $om->get('Magento\Framework\App\Config\ScopeConfigInterface');
|
||||
$filterBuilder = $om->get('Magento\Framework\Api\FilterBuilder');
|
||||
$order = $om->get('\Magento\Sales\Api\Data\OrderInterface');
|
||||
$helper = $om->get('\Retailcrm\Retailcrm\Helper\Data');
|
||||
|
||||
$this->_orderRepository = $orderRepository;
|
||||
protected $_orderRepository;
|
||||
protected $_searchCriteriaBuilder;
|
||||
protected $_config;
|
||||
protected $_filterBuilder;
|
||||
protected $_order;
|
||||
protected $_helper;
|
||||
protected $_api;
|
||||
protected $_logger;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
|
||||
$orderRepository = $objectManager->get('Magento\Sales\Model\OrderRepository');
|
||||
$searchCriteriaBuilder = $objectManager->get('Magento\Framework\Api\SearchCriteriaBuilder');
|
||||
$config = $objectManager->get('Magento\Framework\App\Config\ScopeConfigInterface');
|
||||
$filterBuilder = $objectManager->get('Magento\Framework\Api\FilterBuilder');
|
||||
$order = $objectManager->get('\Magento\Sales\Api\Data\OrderInterface');
|
||||
$helper = $objectManager->get('\Retailcrm\Retailcrm\Helper\Data');
|
||||
|
||||
$this->_orderRepository = $orderRepository;
|
||||
$this->_searchCriteriaBuilder = $searchCriteriaBuilder;
|
||||
$this->_config = $config;
|
||||
$this->_filterBuilder = $filterBuilder;
|
||||
$this->_order = $order;
|
||||
$this->_helper = $helper;
|
||||
|
||||
$this->_logger = $objectManager->get('\Retailcrm\Retailcrm\Model\Logger\Logger');
|
||||
|
||||
$url = $config->getValue('retailcrm/general/api_url');
|
||||
$key = $config->getValue('retailcrm/general/api_key');
|
||||
|
||||
if(!empty($url) && !empty($key)) {
|
||||
$this->_api = new \Retailcrm\Retailcrm\Model\ApiClient\ApiClient($url,$key);
|
||||
$version = $config->getValue('retailcrm/general/api_version');
|
||||
|
||||
if (!empty($url) && !empty($key)) {
|
||||
$this->_api = new ApiClient($url, $key, $version);
|
||||
}
|
||||
}
|
||||
|
||||
public function ExportOrderNumber()
|
||||
{
|
||||
$ordernumber = $this->_config->getValue('retailcrm/Load/number_order');
|
||||
$ordersId = explode(",", $ordernumber);
|
||||
$orders = array();
|
||||
|
||||
foreach ($ordersId as $id) {
|
||||
$orders[] = $this->prepareOrder($id);
|
||||
}
|
||||
|
||||
$chunked = array_chunk($orders, 50);
|
||||
unset($orders);
|
||||
|
||||
foreach ($chunked as $chunk) {
|
||||
$this->_api->ordersUpload($chunk);
|
||||
time_nanosleep(0, 250000000);
|
||||
}
|
||||
|
||||
unset($chunked);
|
||||
|
||||
return true;
|
||||
|
||||
}
|
||||
|
||||
public function prepareOrder($id)
|
||||
{
|
||||
$magentoOrder = $this->_order->loadByIncrementId($id);
|
||||
$magentoOrderArr = $magentoOrder->getData();
|
||||
|
||||
$items = array();
|
||||
$addressObj = $magentoOrder->getBillingAddress();
|
||||
|
||||
foreach ($magentoOrder->getAllItems() as $item) {
|
||||
if ($item->getProductType() == "simple") {
|
||||
|
||||
$price = $item->getPrice();
|
||||
|
||||
if($price == 0){
|
||||
$om = \Magento\Framework\App\ObjectManager::getInstance();
|
||||
$omproduct = $om->get('Magento\Catalog\Model\ProductRepository')
|
||||
->getById($item->getProductId());
|
||||
$price = $omproduct->getPrice();
|
||||
}
|
||||
|
||||
$product = array(
|
||||
'productId' => $item->getProductId(),
|
||||
'productName' => $item->getName(),
|
||||
'quantity' => $item->getQtyOrdered(),
|
||||
'initialPrice' => $price,
|
||||
'offer'=>array(
|
||||
'externalId'=>$item->getProductId()
|
||||
)
|
||||
);
|
||||
|
||||
unset($om);
|
||||
unset($omproduct);
|
||||
unset($price);
|
||||
|
||||
$items[] = $product;
|
||||
}
|
||||
}
|
||||
|
||||
$ship = $this->getShippingCode($magentoOrder->getShippingMethod());
|
||||
|
||||
$preparedOrder = array(
|
||||
'site' => $magentoOrder->getStore()->getCode(),
|
||||
'externalId' => $magentoOrder->getRealOrderId(),
|
||||
'number' => $magentoOrder->getRealOrderId(),
|
||||
'createdAt' => date('Y-m-d H:i:s'),
|
||||
'lastName' => $magentoOrder->getCustomerLastname(),
|
||||
'firstName' => $magentoOrder->getCustomerFirstname(),
|
||||
'patronymic' => $magentoOrder->getCustomerMiddlename(),
|
||||
'email' => $magentoOrder->getCustomerEmail(),
|
||||
'phone' => $addressObj->getTelephone(),
|
||||
'paymentType' => $this->_config->getValue('retailcrm/Payment/'.$magentoOrder->getPayment()->getMethodInstance()->getCode()),
|
||||
'status' => $this->_config->getValue('retailcrm/Status/'.$magentoOrder->getStatus()),
|
||||
'discount' => abs($magentoOrder->getDiscountAmount()),
|
||||
'items' => $items,
|
||||
'delivery' => array(
|
||||
'code' => $this->_config->getValue('retailcrm/Shipping/'.$ship),
|
||||
'cost' => $magentoOrder->getShippingAmount(),
|
||||
'address' => array(
|
||||
'index' => $addressObj->getData('postcode'),
|
||||
'city' => $addressObj->getData('city'),
|
||||
'country' => $addressObj->getData('country_id'),
|
||||
'street' => $addressObj->getData('street'),
|
||||
'region' => $addressObj->getData('region'),
|
||||
'text' => trim(
|
||||
',',
|
||||
implode(
|
||||
',',
|
||||
array(
|
||||
$addressObj->getData('postcode'),
|
||||
$addressObj->getData('city'),
|
||||
$addressObj->getData('street'),
|
||||
)
|
||||
)
|
||||
)
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
if(trim($preparedOrder['delivery']['code']) == ''){
|
||||
unset($preparedOrder['delivery']['code']);
|
||||
}
|
||||
|
||||
if(trim($preparedOrder['paymentType']) == ''){
|
||||
unset($preparedOrder['paymentType']);
|
||||
}
|
||||
|
||||
if(trim($preparedOrder['status']) == ''){
|
||||
unset($preparedOrder['status']);
|
||||
}
|
||||
|
||||
if ($magentoOrder->getCustomerIsGuest() == 0) {
|
||||
$preparedOrder['customer']['externalId'] = $magentoOrder->getCustomerId();
|
||||
}
|
||||
|
||||
$logger = new \Retailcrm\Retailcrm\Model\Logger\Logger();
|
||||
$logger->write($preparedOrder,'OrderNumber');
|
||||
|
||||
return $this->_helper->filterRecursive($preparedOrder);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
public function ExportOrderNumber()
|
||||
{
|
||||
$ordernumber = $this->_config->getValue('retailcrm/Load/number_order');
|
||||
$ordersId = explode(",", $ordernumber);
|
||||
$orders = [];
|
||||
|
||||
foreach ($ordersId as $id) {
|
||||
$orders[] = $this->prepareOrder($id);
|
||||
}
|
||||
|
||||
$chunked = array_chunk($orders, 50);
|
||||
unset($orders);
|
||||
|
||||
foreach ($chunked as $chunk) {
|
||||
$this->_api->ordersUpload($chunk);
|
||||
time_nanosleep(0, 250000000);
|
||||
}
|
||||
|
||||
unset($chunked);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public function prepareOrder($id)
|
||||
{
|
||||
$magentoOrder = $this->_order->load($id);
|
||||
|
||||
$items = [];
|
||||
$addressObj = $magentoOrder->getBillingAddress();
|
||||
|
||||
foreach ($magentoOrder->getAllItems() as $item) {
|
||||
if ($item->getProductType() == "simple") {
|
||||
$price = $item->getPrice();
|
||||
|
||||
if ($price == 0){
|
||||
$om = \Magento\Framework\App\ObjectManager::getInstance();
|
||||
$omproduct = $om->get('Magento\Catalog\Model\ProductRepository')
|
||||
->getById($item->getProductId());
|
||||
$price = $omproduct->getPrice();
|
||||
}
|
||||
|
||||
$product = [
|
||||
'productId' => $item->getProductId(),
|
||||
'productName' => $item->getName(),
|
||||
'quantity' => $item->getQtyOrdered(),
|
||||
'initialPrice' => $price,
|
||||
'offer' => [
|
||||
'externalId'=>$item->getProductId()
|
||||
]
|
||||
];
|
||||
|
||||
unset($om);
|
||||
unset($omproduct);
|
||||
unset($price);
|
||||
|
||||
$items[] = $product;
|
||||
}
|
||||
}
|
||||
|
||||
$ship = $this->getShippingCode($magentoOrder->getShippingMethod());
|
||||
|
||||
$preparedOrder = [
|
||||
'site' => $magentoOrder->getStore()->getCode(),
|
||||
'externalId' => $magentoOrder->getRealOrderId(),
|
||||
'number' => $magentoOrder->getRealOrderId(),
|
||||
'createdAt' => date('Y-m-d H:i:s'),
|
||||
'lastName' => $magentoOrder->getCustomerLastname(),
|
||||
'firstName' => $magentoOrder->getCustomerFirstname(),
|
||||
'patronymic' => $magentoOrder->getCustomerMiddlename(),
|
||||
'email' => $magentoOrder->getCustomerEmail(),
|
||||
'phone' => $addressObj->getTelephone(),
|
||||
'paymentType' => $this->_config->getValue('retailcrm/Payment/'.$magentoOrder->getPayment()->getMethodInstance()->getCode()),
|
||||
'status' => $this->_config->getValue('retailcrm/Status/'.$magentoOrder->getStatus()),
|
||||
'discount' => abs($magentoOrder->getDiscountAmount()),
|
||||
'items' => $items,
|
||||
'delivery' => [
|
||||
'code' => $this->_config->getValue('retailcrm/Shipping/'.$ship),
|
||||
'cost' => $magentoOrder->getShippingAmount(),
|
||||
'address' => [
|
||||
'index' => $addressObj->getData('postcode'),
|
||||
'city' => $addressObj->getData('city'),
|
||||
'country' => $addressObj->getData('country_id'),
|
||||
'street' => $addressObj->getData('street'),
|
||||
'region' => $addressObj->getData('region'),
|
||||
'text' => trim(
|
||||
',',
|
||||
implode(
|
||||
',',
|
||||
[
|
||||
$addressObj->getData('postcode'),
|
||||
$addressObj->getData('city'),
|
||||
$addressObj->getData('street'),
|
||||
]
|
||||
)
|
||||
)
|
||||
]
|
||||
]
|
||||
];
|
||||
|
||||
if (trim($preparedOrder['delivery']['code']) == ''){
|
||||
unset($preparedOrder['delivery']['code']);
|
||||
}
|
||||
|
||||
if (trim($preparedOrder['paymentType']) == ''){
|
||||
unset($preparedOrder['paymentType']);
|
||||
}
|
||||
|
||||
if (trim($preparedOrder['status']) == ''){
|
||||
unset($preparedOrder['status']);
|
||||
}
|
||||
|
||||
if ($magentoOrder->getCustomerIsGuest() == 0) {
|
||||
$preparedOrder['customer']['externalId'] = $magentoOrder->getCustomerId();
|
||||
}
|
||||
|
||||
$this->_logger->writeDump($preparedOrder,'OrderNumber');
|
||||
|
||||
return $this->_helper->filterRecursive($preparedOrder);
|
||||
}
|
||||
}
|
||||
|
14
Model/Setting/ApiVersions.php
Normal file
14
Model/Setting/ApiVersions.php
Normal 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']
|
||||
];
|
||||
}
|
||||
}
|
@ -2,36 +2,33 @@
|
||||
|
||||
namespace Retailcrm\Retailcrm\Model\Setting;
|
||||
|
||||
//use Psr\Log\LoggerInterface;
|
||||
|
||||
class Attribute implements \Magento\Framework\Option\ArrayInterface
|
||||
{
|
||||
protected $_entityType;
|
||||
protected $_store;
|
||||
|
||||
public function __construct(
|
||||
\Magento\Store\Model\Store $store,
|
||||
\Magento\Eav\Model\Entity\Type $entityType
|
||||
) {
|
||||
$this->_store = $store;
|
||||
$this->_entityType = $entityType;
|
||||
}
|
||||
|
||||
public function toOptionArray()
|
||||
{
|
||||
$types = array('text', 'multiselect', 'decimal');
|
||||
$attributes = $this->_entityType->loadByCode('catalog_product')->getAttributeCollection();
|
||||
$attributes->addFieldToFilter('frontend_input', $types);
|
||||
|
||||
$result = array();
|
||||
foreach ($attributes as $attr) {
|
||||
if ($attr->getFrontendLabel()) {
|
||||
$result[] = array('value' => $attr->getAttributeId(), 'label' => $attr->getFrontendLabel(), 'title' => $attr->getAttributeCode());
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
|
||||
protected $_entityType;
|
||||
protected $_store;
|
||||
|
||||
public function __construct(
|
||||
\Magento\Store\Model\Store $store,
|
||||
\Magento\Eav\Model\Entity\Type $entityType
|
||||
) {
|
||||
$this->_store = $store;
|
||||
$this->_entityType = $entityType;
|
||||
}
|
||||
|
||||
public function toOptionArray()
|
||||
{
|
||||
$types = ['text', 'multiselect', 'decimal'];
|
||||
$attributes = $this->_entityType->loadByCode('catalog_product')->getAttributeCollection();
|
||||
$attributes->addFieldToFilter('frontend_input', $types);
|
||||
|
||||
$result = [];
|
||||
|
||||
foreach ($attributes as $attr) {
|
||||
if ($attr->getFrontendLabel()) {
|
||||
$result[] = array('value' => $attr->getAttributeId(), 'label' => $attr->getFrontendLabel(), 'title' => $attr->getAttributeCode());
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
|
@ -2,47 +2,49 @@
|
||||
|
||||
namespace Retailcrm\Retailcrm\Model\Setting;
|
||||
|
||||
//use Psr\Log\LoggerInterface;
|
||||
|
||||
class Shipping implements \Magento\Framework\Option\ArrayInterface
|
||||
{
|
||||
protected $_entityType;
|
||||
protected $_store;
|
||||
|
||||
public function __construct(
|
||||
\Magento\Store\Model\Store $store,
|
||||
\Magento\Eav\Model\Entity\Type $entityType
|
||||
) {
|
||||
$this->_store = $store;
|
||||
$this->_entityType = $entityType;
|
||||
}
|
||||
|
||||
public function toOptionArray()
|
||||
{
|
||||
$om = \Magento\Framework\App\ObjectManager::getInstance();
|
||||
$activeShipping = $om->create('Magento\Shipping\Model\Config')->getActiveCarriers();
|
||||
|
||||
$config = \Magento\Framework\App\ObjectManager::getInstance()->get(
|
||||
'Magento\Framework\App\Config\ScopeConfigInterface'
|
||||
);
|
||||
|
||||
foreach($activeShipping as $carrierCode => $carrierModel)
|
||||
{
|
||||
$options = array();
|
||||
if( $carrierMethods = $carrierModel->getAllowedMethods() )
|
||||
{
|
||||
foreach ($carrierMethods as $methodCode => $method)
|
||||
{
|
||||
$code= $carrierCode.'_'.$methodCode;
|
||||
$options[]=array('value'=>$code,'label'=>$method);
|
||||
}
|
||||
$carrierTitle =$config->getValue('carriers/'.$carrierCode.'/title');
|
||||
|
||||
}
|
||||
$methods[] = array('value'=>$options,'label'=>$carrierTitle);
|
||||
}
|
||||
|
||||
return $methods;
|
||||
|
||||
}
|
||||
}
|
||||
protected $_entityType;
|
||||
protected $_store;
|
||||
|
||||
public function __construct(
|
||||
\Magento\Store\Model\Store $store,
|
||||
\Magento\Eav\Model\Entity\Type $entityType
|
||||
) {
|
||||
$this->_store = $store;
|
||||
$this->_entityType = $entityType;
|
||||
}
|
||||
|
||||
public function toOptionArray()
|
||||
{
|
||||
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
|
||||
$activeShipping = $objectManager->create('Magento\Shipping\Model\Config')->getActiveCarriers();
|
||||
|
||||
$config = $objectManager->get('Magento\Framework\App\Config\ScopeConfigInterface');
|
||||
|
||||
foreach ($activeShipping as $carrierCode => $carrierModel) {
|
||||
$options = [];
|
||||
|
||||
if ($carrierModel->getAllowedMethods()) {
|
||||
$carrierMethods = $carrierModel->getAllowedMethods();
|
||||
|
||||
foreach ($carrierMethods as $methodCode => $method) {
|
||||
$code = $carrierCode . '_' . $methodCode;
|
||||
$options[] = [
|
||||
'value' => $code,
|
||||
'label' => $method
|
||||
];
|
||||
}
|
||||
|
||||
$carrierTitle = $config->getValue('carriers/' . $carrierCode . '/title');
|
||||
}
|
||||
|
||||
$methods[] = [
|
||||
'value' => $options,
|
||||
'label' => $carrierTitle
|
||||
];
|
||||
}
|
||||
|
||||
return $methods;
|
||||
}
|
||||
}
|
||||
|
@ -9,12 +9,9 @@ class Status extends \Magento\Config\Model\Config\Backend\Serialized\ArraySerial
|
||||
// For value validations
|
||||
$exceptions = $this->getValue();
|
||||
|
||||
// Validations
|
||||
|
||||
// Validations
|
||||
$this->setValue($exceptions);
|
||||
|
||||
return parent::beforeSave();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
27
README.md
27
README.md
@ -1,16 +1,29 @@
|
||||
Magento module
|
||||
==============
|
||||
|
||||
Magento 2 module for interaction with [RetailCRM](http://www.retailcrm.ru) through [REST API](http://www.retailcrm.ru/docs/Developers/Index).
|
||||
Magento 2 module for interaction with [retailCRM](http://www.retailcrm.ru).
|
||||
|
||||
Module allows:
|
||||
|
||||
* Exchange the orders with retailCRM
|
||||
* Configure relations between dictionaries of RetailCRM and Magento (statuses, payments, delivery types and etc)
|
||||
* Generate [ICML](http://www.retailcrm.ru/docs/Developers/ICML) (Intaro Markup Language) for catalog loading by RetailCRM
|
||||
* Exchange the orders data with retailCRM
|
||||
* Configure relations between dictionaries of retailCRM and Magento (statuses, payments, delivery types and etc)
|
||||
* Generate [ICML](http://www.retailcrm.ru/docs/Developers/ICML) (Intaro Markup Language) export file for catalog loading by retailCRM
|
||||
|
||||
ICML
|
||||
### ICML
|
||||
|
||||
By default ICML file is being generated by module every 4 hours. You can find file in the web root folder with name "retailcrm_{{shop_code}}.xml". For example, http://retailcrm.ru/retailcrm_default.xml
|
||||
By default ICML file is being generated by module every 4 hours. You can find file in the web root folder with name "retailcrm_{{shop_code}}.xml". For example, http://example.org/retailcrm_default.xml
|
||||
|
||||
This module is compatible with Magento up to version 2.1.6
|
||||
### Manual install
|
||||
|
||||
|
||||
1) Run into your project root directory:
|
||||
```bash
|
||||
composer require retailcrm/api-client-php ~5.0
|
||||
```
|
||||
|
||||
2) Unpack the archive with the module into the `app/code/Retailcrm/Retailcrm` directory.
|
||||
|
||||
3) Change `app/etc/config.php` file by adding `'Retailcrm_Retailcrm' => 1` line into `modules` array
|
||||
|
||||
|
||||
This module is compatible with Magento up to version 2.2.3
|
||||
|
31
README.ru.md
Normal file
31
README.ru.md
Normal 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
|
159
Test/Unit/Observer/CustomerTest.php
Normal file
159
Test/Unit/Observer/CustomerTest.php
Normal 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
|
||||
]
|
||||
];
|
||||
}
|
||||
}
|
426
Test/Unit/Observer/OrderCreateTest.php
Normal file
426
Test/Unit/Observer/OrderCreateTest.php
Normal 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'
|
||||
]
|
||||
];
|
||||
}
|
||||
}
|
171
Test/Unit/Observer/OrderUpdateTest.php
Normal file
171
Test/Unit/Observer/OrderUpdateTest.php
Normal 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'
|
||||
]
|
||||
];
|
||||
}
|
||||
}
|
@ -2,7 +2,8 @@
|
||||
"name": "retailcrm/retailcrm",
|
||||
"description": "Retailcrm",
|
||||
"require": {
|
||||
"php": "~5.5.0|~5.6.0|~7.0.0"
|
||||
"php": "~5.5.0|~5.6.0|~7.0.0",
|
||||
"retailcrm/api-client-php": "~5.0"
|
||||
},
|
||||
"type": "magento2-module",
|
||||
"version": "1.0.0",
|
||||
|
@ -11,16 +11,23 @@
|
||||
<resource>Retailcrm_Retailcrm::retailcrm_configuration</resource>
|
||||
<group id="general" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="0" showInStore="0">
|
||||
<label>General Configuration</label>
|
||||
|
||||
<field id="api_url" translate="label" type="text" sortOrder="1" showInDefault="1" showInWebsite="0" showInStore="0">
|
||||
|
||||
<field id="api_url" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="0" showInStore="0">
|
||||
<label>API URL</label>
|
||||
<comment>https://YourCrmName.retailcrm.ru</comment>
|
||||
<backend_model>Retailcrm\Retailcrm\Model\Config\Backend\ApiUrl</backend_model>
|
||||
</field>
|
||||
|
||||
<field id="api_key" translate="label" type="text" sortOrder="1" showInDefault="1" showInWebsite="0" showInStore="0">
|
||||
|
||||
<field id="api_key" translate="label" type="text" sortOrder="20" showInDefault="1" showInWebsite="0" showInStore="0">
|
||||
<label>API Key</label>
|
||||
<comment>To generate an API Key, log in to RetailCRM then select Admin > Integration > API Keys</comment>
|
||||
</field>
|
||||
|
||||
<field id="api_version" translate="label" type="select" sortOrder="30" showInDefault="1" showInWebsite="0" showInStore="0">
|
||||
<label>API Version</label>
|
||||
<source_model>Retailcrm\Retailcrm\Model\Setting\ApiVersions</source_model>
|
||||
<backend_model>Retailcrm\Retailcrm\Model\Config\Backend\ApiVersion</backend_model>
|
||||
</field>
|
||||
</group>
|
||||
|
||||
<group id="Misc" translate="label" type="text" sortOrder="20" showInDefault="2" showInWebsite="0" showInStore="0">
|
||||
|
@ -3,22 +3,13 @@
|
||||
<default>
|
||||
<retailcrm>
|
||||
<general>
|
||||
|
||||
<api_url>test</api_url>
|
||||
<api_url>test</api_url>
|
||||
</general>
|
||||
|
||||
<section>
|
||||
<general>
|
||||
<api_key>{value}</api_key>
|
||||
</general>
|
||||
|
||||
|
||||
|
||||
</general>
|
||||
</section>
|
||||
|
||||
</retailcrm>
|
||||
|
||||
|
||||
|
||||
</default>
|
||||
</config>
|
10
etc/di.xml
10
etc/di.xml
@ -1,5 +1,11 @@
|
||||
<?xml version="1.0"?>
|
||||
|
||||
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
|
||||
|
||||
</config>
|
||||
<type name="Magento\Framework\Console\CommandList">
|
||||
<arguments>
|
||||
<argument name="commands" xsi:type="array">
|
||||
<item name="retailcrm_command" xsi:type="object">Retailcrm\Retailcrm\Console\Command\Command</item>
|
||||
</argument>
|
||||
</arguments>
|
||||
</type>
|
||||
</config>
|
||||
|
@ -1,25 +1,22 @@
|
||||
<?xml version="1.0"?>
|
||||
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
|
||||
|
||||
<!-- Order create -->
|
||||
|
||||
<event name="sales_order_place_after">
|
||||
<observer name="sales_order_place_after" instance="Retailcrm\Retailcrm\Model\Observer\OrderCreate" />
|
||||
</event>
|
||||
|
||||
<!-- 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>
|
||||
|
||||
<!-- Order create -->
|
||||
|
||||
<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>
|
||||
|
||||
|
||||
|
@ -4,9 +4,8 @@
|
||||
<!-- Order create -->
|
||||
|
||||
<event name="sales_order_place_after">
|
||||
<observer name="sales_order_place_after" disabled="true"/>
|
||||
<observer name="sales_order_place_after" disabled="true"/>
|
||||
</event>
|
||||
|
||||
|
||||
</config>
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user