1
0
mirror of synced 2024-11-28 16:06:06 +03:00

Multisite, tests, travis

This commit is contained in:
Akolzin Dmitry 2018-05-15 15:54:55 +03:00
parent 6b83c72f93
commit 7e7556fef3
32 changed files with 1498 additions and 615 deletions

View File

@ -30,3 +30,12 @@ before_script:
script: script:
- cd ../magento2 - cd ../magento2
- php vendor/phpunit/phpunit/phpunit -c dev/tests/unit/phpunit.xml.dist app/code/Retailcrm/Retailcrm/Test/Unit/ - php vendor/phpunit/phpunit/phpunit -c dev/tests/unit/phpunit.xml.dist app/code/Retailcrm/Retailcrm/Test/Unit/
deploy:
skip_cleanup: true
provider: script
script: make
on:
php: 7.2
branch: master
condition: "$DEPLOY = true"

14
Makefile Normal file
View File

@ -0,0 +1,14 @@
FILE = $(TRAVIS_BUILD_DIR)/VERSION
VERSION = `cat $(FILE)`
ARCHIVE_NAME = '/tmp/retailcrm-retailcrm-'$(VERSION)'.zip'
all: build_archive send_to_ftp delete_archive
build_archive:
cd src; zip -r $(ARCHIVE_NAME) ./*
send_to_ftp:
curl -T $(ARCHIVE_NAME) -u $(FTP_USER):$(FTP_PASSWORD) ftp://$(FTP_HOST)/public_html/
delete_archive:
rm -f $(ARCHIVE_NAME)

1
VERSION Normal file
View File

@ -0,0 +1 @@
1.0.0

View File

@ -1,63 +0,0 @@
<?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
{
public 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;
}
}

View File

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

View File

@ -1,78 +0,0 @@
<?php
namespace Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Field;
use Magento\Framework\Data\Form\Element\AbstractElement;
class Payment extends \Magento\Config\Block\System\Config\Form\Field
{
private $systemStore;
private $formFactory;
private $config;
private $paymentConfig;
private $client;
public function __construct(
\Magento\Framework\Data\FormFactory $formFactory,
\Magento\Store\Model\System\Store $systemStore,
\Magento\Framework\App\Config\ScopeConfigInterface $config,
\Magento\Payment\Model\Config $paymentConfig,
\Retailcrm\Retailcrm\Helper\Proxy $client
) {
$this->systemStore = $systemStore;
$this->formFactory = $formFactory;
$this->config = $config;
$this->paymentConfig = $paymentConfig;
$this->client = $client;
}
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 ($this->client->isConfigured()) {
$activePaymentMethods = $this->paymentConfig->getActiveMethods();
$response = $this->client->paymentTypesList();
if ($response === false) {
return $htmlError;
}
if ($response->isSuccessful()) {
$paymentTypes = $response['paymentTypes'];
} else {
return $htmlError;
}
foreach ($activePaymentMethods as $code => $payment) {
$html .= '<table id="' . $element->getId() . '_table">';
$html .= '<tr id="row_retailcrm_payment_' . $code . '">';
$html .= '<td class="label">' . $payment->getTitle() . '</td>';
$html .= '<td>';
$html .= '<select id="1" name="groups[Payment][fields][' . $code . '][value]">';
$selected = $this->config->getValue('retailcrm/Payment/' . $code);
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;
}
}
}

View File

@ -1,78 +0,0 @@
<?php
namespace Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Field;
use Magento\Framework\Data\Form\Element\AbstractElement;
class Shipping extends \Magento\Config\Block\System\Config\Form\Field
{
private $systemStore;
private $formFactory;
private $config;
private $shippingConfig;
private $client;
public function __construct(
\Magento\Framework\Data\FormFactory $formFactory,
\Magento\Store\Model\System\Store $systemStore,
\Magento\Framework\App\Config\ScopeConfigInterface $config,
\Magento\Shipping\Model\Config $shippingConfig,
\Retailcrm\Retailcrm\Helper\Proxy $client
) {
$this->systemStore = $systemStore;
$this->formFactory = $formFactory;
$this->config = $config;
$this->shippingConfig = $shippingConfig;
$this->client = $client;
}
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 ($this->client->isConfigured()) {
$deliveryMethods = $this->shippingConfig->getActiveCarriers();
$response = $this->client->deliveryTypesList();
if ($response === false) {
return $htmlError;
}
if ($response->isSuccessful()) {
$deliveryTypes = $response['deliveryTypes'];
} else {
return $htmlError;
}
foreach ($deliveryMethods as $code => $delivery) {
$html .= '<table id="' . $element->getId() . '_table">';
$html .= '<tr id="row_retailcrm_shipping_'. $code . '">';
$html .= '<td class="label">' . $delivery->getConfigData('title') . '</td>';
$html .= '<td>';
$html .= '<select id="1" name="groups[Shipping][fields][' . $code . '][value]">';
$selected = $this->config->getValue('retailcrm/Shipping/' . $code);
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;
}
}
}

View File

@ -1,82 +0,0 @@
<?php
namespace Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Field;
use Magento\Framework\Data\Form\Element\AbstractElement;
class Status extends \Magento\Config\Block\System\Config\Form\Field
{
private $systemStore;
private $formFactory;
private $config;
private $statusCollection;
private $client;
public function __construct(
\Magento\Framework\Data\FormFactory $formFactory,
\Magento\Store\Model\System\Store $systemStore,
\Magento\Framework\App\Config\ScopeConfigInterface $config,
\Magento\Sales\Model\ResourceModel\Order\Status\Collection $statusCollection,
\Retailcrm\Retailcrm\Helper\Proxy $client
) {
$this->systemStore = $systemStore;
$this->formFactory = $formFactory;
$this->config = $config;
$this->statusCollection = $statusCollection;
$this->client = $client;
}
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 ($this->client->isConfigured()) {
$statuses = $this->statusCollection->toOptionArray();
$response = $this->client->statusesList();
if ($response === false) {
return $htmlError;
}
if ($response->isSuccessful()) {
$statusTypes = $response['statuses'];
} else {
return $htmlError;
}
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 = $this->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;
}
}
}

View File

@ -0,0 +1,164 @@
<?php
namespace Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Fieldset;
use Magento\Framework\Data\Form\Element\AbstractElement;
class Payment extends \Magento\Config\Block\System\Config\Form\Fieldset
{
/**
* Dummy element
*
* @var \Magento\Framework\DataObject
*/
protected $_dummyElement;
/**
* Field renderer
*
* @var \Magento\Config\Block\System\Config\Form\Field
*/
protected $_fieldRenderer;
private $paymentConfig;
private $client;
public function __construct(
\Magento\Backend\Block\Context $context,
\Magento\Backend\Model\Auth\Session $authSession,
\Magento\Framework\View\Helper\Js $jsHelper,
\Magento\Payment\Model\Config $paymentConfig,
\Retailcrm\Retailcrm\Helper\Proxy $client,
array $data = []
) {
$this->paymentConfig = $paymentConfig;
$this->client = $client;
parent::__construct($context, $authSession, $jsHelper, $data);
}
/**
* Get field renderer
*
* @return \Magento\Config\Block\System\Config\Form\Field
*/
protected function _getFieldRenderer()
{
if (empty($this->_fieldRenderer)) {
$this->_fieldRenderer = $this->getLayout()->getBlockSingleton(
\Magento\Config\Block\System\Config\Form\Field::class
);
}
return $this->_fieldRenderer;
}
/**
* Get dummy element
*
* @return \Magento\Framework\DataObject
*/
protected function _getDummyElement()
{
if (empty($this->_dummyElement)) {
$this->_dummyElement = new \Magento\Framework\DataObject(['showInDefault' => 1, 'showInWebsite' => 1]);
}
return $this->_dummyElement;
}
public function render(AbstractElement $element)
{
$html = '';
$htmlError = '<div style="margin-left: 15px;"><b><i>Please check your API Url & API Key</i></b></div>';
$html .= $this->_getHeaderHtml($element);
if ($this->client->isConfigured()) {
$paymentMethods = $this->paymentConfig->getActiveMethods();
foreach ($paymentMethods as $code => $payment) {
$html .= $this->_getFieldHtml($element, $payment);
}
} else {
$html .= $htmlError;
}
$html .= $this->_getFooterHtml($element);
return $html;
}
/**
* Get options values
*
* @return array
*/
private function getValues()
{
$defaultValues = [
[
'value' => '',
'label' => ''
]
];
$values = [];
$response = $this->client->paymentTypesList();
if ($response === false) {
return $defaultValues;
}
if ($response->isSuccessful()) {
$paymentsTypes = $response['paymentTypes'];
} else {
return $defaultValues;
}
foreach ($paymentsTypes as $paymentType) {
$values[] = [
'label' => $paymentType['name'],
'value' => $paymentType['code']
];
}
return $values;
}
/**
* Get field html
*
* @param \Magento\Framework\Data\Form\Element\AbstractElement $fieldset
* @param \Magento\Payment\Model\Method\AbstractMethod $payment
*
* @return string
*/
protected function _getFieldHtml($fieldset, $payment)
{
$configData = $this->getConfigData();
$path = 'retailcrm/' . $fieldset->getId() . '/' . $payment->getCode();
$data = isset($configData[$path]) ? $configData[$path] : [];
$e = $this->_getDummyElement();
$field = $fieldset->addField(
$payment->getCode(),
'select',
[
'name' => 'groups[' . $fieldset->getId() . '][fields][' . $payment->getCode() . '][value]',
'label' => $payment->getTitle(),
'value' => isset($data) ? $data : '',
'values' => $this->getValues(),
'inherit' => true,
'can_use_default_value' => $this->getForm()->canUseDefaultValue($e),
'can_use_website_value' => $this->getForm()->canUseWebsiteValue($e)
]
)->setRenderer(
$this->_getFieldRenderer()
);
return $field->toHtml();
}
}

View File

@ -0,0 +1,170 @@
<?php
namespace Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Fieldset;
use Magento\Framework\Data\Form\Element\AbstractElement;
class Shipping extends \Magento\Config\Block\System\Config\Form\Fieldset
{
/**
* Dummy element
*
* @var \Magento\Framework\DataObject
*/
protected $_dummyElement;
/**
* Field renderer
*
* @var \Magento\Config\Block\System\Config\Form\Field
*/
protected $_fieldRenderer;
private $shippingConfig;
private $client;
public function __construct(
\Magento\Backend\Block\Context $context,
\Magento\Backend\Model\Auth\Session $authSession,
\Magento\Framework\View\Helper\Js $jsHelper,
\Magento\Shipping\Model\Config $shippingConfig,
\Retailcrm\Retailcrm\Helper\Proxy $client,
array $data = []
) {
$this->shippingConfig = $shippingConfig;
$this->client = $client;
parent::__construct($context, $authSession, $jsHelper, $data);
}
/**
* Get field renderer
*
* @return \Magento\Config\Block\System\Config\Form\Field
*/
protected function _getFieldRenderer()
{
if (empty($this->_fieldRenderer)) {
$this->_fieldRenderer = $this->getLayout()->getBlockSingleton(
\Magento\Config\Block\System\Config\Form\Field::class
);
}
return $this->_fieldRenderer;
}
/**
* Get dummy element
*
* @return \Magento\Framework\DataObject
*/
protected function _getDummyElement()
{
if (empty($this->_dummyElement)) {
$this->_dummyElement = new \Magento\Framework\DataObject(['showInDefault' => 1, 'showInWebsite' => 1]);
}
return $this->_dummyElement;
}
/**
* Render element
*
* @param AbstractElement $element
* @return string
*/
public function render(AbstractElement $element)
{
$html = '';
$htmlError = '<div style="margin-left: 15px;"><b><i>Please check your API Url & API Key</i></b></div>';
$html .= $this->_getHeaderHtml($element);
if ($this->client->isConfigured()) {
$deliveryMethods = $this->shippingConfig->getActiveCarriers();
foreach ($deliveryMethods as $code => $delivery) {
$html .= $this->_getFieldHtml($element, $delivery);
}
} else {
$html .= $htmlError;
}
$html .= $this->_getFooterHtml($element);
return $html;
}
/**
* Get options values
*
* @return array
*/
private function getValues()
{
$defaultValues = [
[
'value' => '',
'label' => ''
]
];
$values = [];
$response = $this->client->deliveryTypesList();
if ($response === false) {
return $defaultValues;
}
if ($response->isSuccessful()) {
$deliveryTypes = $response['deliveryTypes'];
} else {
return $defaultValues;
}
foreach ($deliveryTypes as $deliveryType) {
$values[] = [
'label' => $deliveryType['name'],
'value' => $deliveryType['code']
];
}
return $values;
}
/**
* Get field html
*
* @param \Magento\Framework\Data\Form\Element\AbstractElement $fieldset
* @param \Magento\Shipping\Model\Carrier\AbstractCarrier $shipping
*
* @return string
*/
protected function _getFieldHtml($fieldset, $shipping)
{
$configData = $this->getConfigData();
$path = 'retailcrm/' . $fieldset->getId() . '/' . $shipping->getCarrierCode();
$data = isset($configData[$path]) ? $configData[$path] : [];
$e = $this->_getDummyElement();
$field = $fieldset->addField(
$shipping->getCarrierCode(),
'select',
[
'name' => 'groups[' . $fieldset->getId() . '][fields][' . $shipping->getCarrierCode() . '][value]',
'label' => $shipping->getConfigData('title'),
'value' => isset($data) ? $data : '',
'values' => $this->getValues(),
'inherit' => true,
'can_use_default_value' => $this->getForm()->canUseDefaultValue($e),
'can_use_website_value' => $this->getForm()->canUseWebsiteValue($e)
]
)->setRenderer(
$this->_getFieldRenderer()
);
return $field->toHtml();
}
}

View File

@ -0,0 +1,161 @@
<?php
namespace Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Fieldset;
use Magento\Framework\Data\Form\Element\AbstractElement;
class Site extends \Magento\Config\Block\System\Config\Form\Fieldset
{
/**
* Dummy element
*
* @var \Magento\Framework\DataObject
*/
protected $_dummyElement;
/**
* Field renderer
*
* @var \Magento\Config\Block\System\Config\Form\Field
*/
protected $_fieldRenderer;
private $client;
public function __construct(
\Magento\Backend\Block\Context $context,
\Magento\Backend\Model\Auth\Session $authSession,
\Magento\Framework\View\Helper\Js $jsHelper,
\Retailcrm\Retailcrm\Helper\Proxy $client,
array $data = []
) {
$this->client = $client;
parent::__construct($context, $authSession, $jsHelper, $data);
}
/**
* Get field renderer
*
* @return \Magento\Config\Block\System\Config\Form\Field
*/
protected function _getFieldRenderer()
{
if (empty($this->_fieldRenderer)) {
$this->_fieldRenderer = $this->getLayout()->getBlockSingleton(
\Magento\Config\Block\System\Config\Form\Field::class
);
}
return $this->_fieldRenderer;
}
/**
* Get dummy element
*
* @return \Magento\Framework\DataObject
*/
protected function _getDummyElement()
{
if (empty($this->_dummyElement)) {
$this->_dummyElement = new \Magento\Framework\DataObject(['showInDefault' => 1, 'showInWebsite' => 0]);
}
return $this->_dummyElement;
}
/**
* Render element
*
* @param AbstractElement $element
* @return string
*/
public function render(AbstractElement $element)
{
$html = '';
$htmlError = '<div style="margin-left: 15px;"><b><i>Please check your API Url & API Key</i></b></div>';
$html .= $this->_getHeaderHtml($element);
if ($this->client->isConfigured()) {
$html .= $this->_getFieldHtml($element);
} else {
$html .= $htmlError;
}
$html .= $this->_getFooterHtml($element);
return $html;
}
/**
* Get options values
*
* @return array
*/
private function getValues()
{
$defaultValues = [
[
'value' => '',
'label' => ''
]
];
$values = [];
$response = $this->client->sitesList();
if ($response === false) {
return $defaultValues;
}
if ($response->isSuccessful()) {
$sites = $response['sites'];
} else {
return $defaultValues;
}
foreach ($sites as $site) {
$values[] = [
'label' => $site['name'],
'value' => $site['code']
];
}
return $values;
}
/**
* Get field html
*
* @param \Magento\Framework\Data\Form\Element\AbstractElement $fieldset
* @param \Magento\Shipping\Model\Carrier\AbstractCarrier $shipping
*
* @return string
*/
protected function _getFieldHtml($fieldset)
{
$configData = $this->getConfigData();
$path = 'retailcrm/' . $fieldset->getId() . '/default';
$data = isset($configData[$path]) ? $configData[$path] : [];
$e = $this->_getDummyElement();
$field = $fieldset->addField(
'default',
'select',
[
'name' => 'groups[' . $fieldset->getId() . '][fields][default][value]',
'label' => 'Default site',
'value' => isset($data) ? $data : '',
'values' => $this->getValues(),
'inherit' => isset($data['inherit']) ? $data['inherit'] : '',
'can_use_default_value' => $this->getForm()->canUseDefaultValue($e),
'can_use_website_value' => $this->getForm()->canUseWebsiteValue($e)
]
)->setRenderer(
$this->_getFieldRenderer()
);
return $field->toHtml();
}
}

View File

@ -0,0 +1,168 @@
<?php
namespace Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Fieldset;
use Magento\Framework\Data\Form\Element\AbstractElement;
class Sites extends \Magento\Config\Block\System\Config\Form\Fieldset
{
/**
* Dummy element
*
* @var \Magento\Framework\DataObject
*/
protected $_dummyElement;
/**
* Field renderer
*
* @var \Magento\Config\Block\System\Config\Form\Field
*/
protected $_fieldRenderer;
private $storeManager;
private $client;
public function __construct(
\Magento\Backend\Block\Context $context,
\Magento\Backend\Model\Auth\Session $authSession,
\Magento\Framework\View\Helper\Js $jsHelper,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Retailcrm\Retailcrm\Helper\Proxy $client,
array $data = []
) {
$this->storeManager = $storeManager;
$this->client = $client;
parent::__construct($context, $authSession, $jsHelper, $data);
}
/**
* Get field renderer
*
* @return \Magento\Config\Block\System\Config\Form\Field
*/
protected function _getFieldRenderer()
{
if (empty($this->_fieldRenderer)) {
$this->_fieldRenderer = $this->getLayout()->getBlockSingleton(
\Magento\Config\Block\System\Config\Form\Field::class
);
}
return $this->_fieldRenderer;
}
/**
* Get dummy element
*
* @return \Magento\Framework\DataObject
*/
protected function _getDummyElement()
{
if (empty($this->_dummyElement)) {
$this->_dummyElement = new \Magento\Framework\DataObject(['showInDefault' => 1, 'showInWebsite' => 0]);
}
return $this->_dummyElement;
}
/**
* Render element
*
* @param AbstractElement $element
* @return string
*/
public function render(AbstractElement $element)
{
$html = '';
$htmlError = '<div style="margin-left: 15px;"><b><i>Please check your API Url & API Key</i></b></div>';
$html .= $this->_getHeaderHtml($element);
if ($this->client->isConfigured()) {
$website = $this->storeManager->getWebsite($this->getRequest()->getParam('website', 0));
foreach ($website->getStores() as $store) {
$html .= $this->_getFieldHtml($element, $store);
}
} else {
$html .= $htmlError;
}
$html .= $this->_getFooterHtml($element);
return $html;
}
/**
* Get options values
*
* @return array
*/
private function getValues()
{
$defaultValues = [
[
'value' => '',
'label' => ''
]
];
$values = [];
$response = $this->client->sitesList();
if ($response === false) {
return $defaultValues;
}
if ($response->isSuccessful()) {
$sites = $response['sites'];
} else {
return $defaultValues;
}
foreach ($sites as $site) {
$values[] = [
'label' => $site['name'],
'value' => $site['code']
];
}
return $values;
}
/**
* Get field html
*
* @param \Magento\Framework\Data\Form\Element\AbstractElement $fieldset
* @param \Magento\Shipping\Model\Carrier\AbstractCarrier $shipping
*
* @return string
*/
protected function _getFieldHtml($fieldset, $store)
{
$configData = $this->getConfigData();
$path = 'retailcrm/' . $fieldset->getId() . '/' . $store->getCode();
$data = isset($configData[$path]) ? $configData[$path] : [];
$e = $this->_getDummyElement();
$field = $fieldset->addField(
$store->getCode(),
'select',
[
'name' => 'groups[' . $fieldset->getId() . '][fields][' . $store->getCode() . '][value]',
'label' => $store->getName(),
'value' => isset($data) ? $data : '',
'values' => $this->getValues(),
'inherit' => isset($data['inherit']) ? $data['inherit'] : '',
'can_use_default_value' => $this->getForm()->canUseDefaultValue($e),
'can_use_website_value' => $this->getForm()->canUseWebsiteValue($e)
]
)->setRenderer(
$this->_getFieldRenderer()
);
return $field->toHtml();
}
}

View File

@ -0,0 +1,164 @@
<?php
namespace Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Fieldset;
use Magento\Framework\Data\Form\Element\AbstractElement;
class Status extends \Magento\Config\Block\System\Config\Form\Fieldset
{
/**
* Dummy element
*
* @var \Magento\Framework\DataObject
*/
protected $_dummyElement;
/**
* Field renderer
*
* @var \Magento\Config\Block\System\Config\Form\Field
*/
protected $_fieldRenderer;
private $statusCollection;
private $client;
public function __construct(
\Magento\Backend\Block\Context $context,
\Magento\Backend\Model\Auth\Session $authSession,
\Magento\Framework\View\Helper\Js $jsHelper,
\Magento\Sales\Model\ResourceModel\Order\Status\Collection $statusCollection,
\Retailcrm\Retailcrm\Helper\Proxy $client,
array $data = []
) {
$this->statusCollection = $statusCollection;
$this->client = $client;
parent::__construct($context, $authSession, $jsHelper, $data);
}
/**
* Get field renderer
*
* @return \Magento\Config\Block\System\Config\Form\Field
*/
protected function _getFieldRenderer()
{
if (empty($this->_fieldRenderer)) {
$this->_fieldRenderer = $this->getLayout()->getBlockSingleton(
\Magento\Config\Block\System\Config\Form\Field::class
);
}
return $this->_fieldRenderer;
}
/**
* Get dummy element
*
* @return \Magento\Framework\DataObject
*/
protected function _getDummyElement()
{
if (empty($this->_dummyElement)) {
$this->_dummyElement = new \Magento\Framework\DataObject(['showInDefault' => 1, 'showInWebsite' => 1]);
}
return $this->_dummyElement;
}
public function render(AbstractElement $element)
{
$html = '';
$htmlError = '<div style="margin-left: 15px;"><b><i>Please check your API Url & API Key</i></b></div>';
$html .= $this->_getHeaderHtml($element);
if ($this->client->isConfigured()) {
$statuses = $this->statusCollection->toOptionArray();;
foreach ($statuses as $code => $status) {
$html .= $this->_getFieldHtml($element, $status);
}
} else {
$html .= $htmlError;
}
$html .= $this->_getFooterHtml($element);
return $html;
}
/**
* Get options values
*
* @return array
*/
private function getValues()
{
$defaultValues = [
[
'value' => '',
'label' => ''
]
];
$values = [];
$response = $this->client->statusesList();
if ($response === false) {
return $defaultValues;
}
if ($response->isSuccessful()) {
$statuses = $response['statuses'];
} else {
return $defaultValues;
}
foreach ($statuses as $status) {
$values[] = [
'label' => $status['name'],
'value' => $status['code']
];
}
return $values;
}
/**
* Get field html
*
* @param \Magento\Framework\Data\Form\Element\AbstractElement $fieldset
* @param array $status
*
* @return string
*/
protected function _getFieldHtml($fieldset, $status)
{
$configData = $this->getConfigData();
$path = 'retailcrm/' . $fieldset->getId() . '/' . $status['value'];
$data = isset($configData[$path]) ? $configData[$path] : [];
$e = $this->_getDummyElement();
$field = $fieldset->addField(
$status['value'],
'select',
[
'name' => 'groups[' . $fieldset->getId() . '][fields][' . $status['value'] . '][value]',
'label' => $status['label'],
'value' => isset($data) ? $data : '',
'values' => $this->getValues(),
'inherit' => true,
'can_use_default_value' => $this->getForm()->canUseDefaultValue($e),
'can_use_website_value' => $this->getForm()->canUseWebsiteValue($e)
]
)->setRenderer(
$this->_getFieldRenderer()
);
return $field->toHtml();
}
}

View File

@ -4,23 +4,21 @@ namespace Retailcrm\Retailcrm\Helper;
use Magento\Framework\App\Helper\AbstractHelper; use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Store\Model\StoreManagerInterface; use Magento\Store\Model\StoreManagerInterface;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\App\Helper\Context; use Magento\Framework\App\Helper\Context;
use Magento\Store\Model\ScopeInterface; use Magento\Store\Model\ScopeInterface;
class Data extends AbstractHelper class Data extends AbstractHelper
{ {
private $storeManager; private $storeManager;
private $objectManager;
const XML_PATH_RETAILCRM = 'retailcrm/'; const XML_PATH_RETAILCRM = 'retailcrm/';
const XML_PATH_DEFAULT_SITE = 'retailcrm_site/default';
const XML_PATH_SITES = 'retailcrm_sites/';
public function __construct( public function __construct(
Context $context, Context $context,
ObjectManagerInterface $objectManager,
StoreManagerInterface $storeManager StoreManagerInterface $storeManager
) { ) {
$this->objectManager = $objectManager;
$this->storeManager = $storeManager; $this->storeManager = $storeManager;
parent::__construct($context); parent::__construct($context);
} }
@ -39,6 +37,57 @@ class Data extends AbstractHelper
return $this->getConfigValue(self::XML_PATH_RETAILCRM . $code, $storeId); return $this->getConfigValue(self::XML_PATH_RETAILCRM . $code, $storeId);
} }
/**
* Get site code
*
* @param $store
*
* @return mixed|null
*/
public function getSite($store)
{
if (is_int($store)) {
$store = $this->storeManager->getStore($store);
}
$websitesConfig = $this->scopeConfig->getValue(
self::XML_PATH_RETAILCRM . self::XML_PATH_SITES . $store->getCode(),
ScopeInterface::SCOPE_WEBSITES
);
if (!$websitesConfig) {
$defaultSite = $this->scopeConfig->getValue(self::XML_PATH_RETAILCRM . self::XML_PATH_DEFAULT_SITE);
if (!$defaultSite) {
return null;
}
return $defaultSite;
}
return $websitesConfig;
}
public function getMappingSites()
{
$sites = [];
$websites = $this->storeManager->getWebsites();
foreach ($websites as $website) {
foreach ($website->getStores() as $store) {
$site = $this->scopeConfig->getValue(
self::XML_PATH_RETAILCRM . self::XML_PATH_SITES . $store->getCode(),
ScopeInterface::SCOPE_WEBSITES,
$website->getId()
);
$sites[$site] = $store->getId();
}
}
return $sites;
}
/** /**
* Recursive array filter * Recursive array filter
* *

View File

@ -54,8 +54,9 @@ class Proxy
if (!$response->isSuccessful()) { if (!$response->isSuccessful()) {
$this->logger->writeRow( $this->logger->writeRow(
sprintf( sprintf(
"[HTTP status %s] %s", "[HTTP status %s] %s - %s",
$response->getStatusCode(), $response->getStatusCode(),
$method,
$response->getErrorMsg() $response->getErrorMsg()
) )
); );
@ -135,6 +136,32 @@ class Proxy
return $this->apiClient->getVersion(); return $this->apiClient->getVersion();
} }
/**
* Set site code
*
* @param $site
*/
public function setSite($site)
{
if ($this->isConfigured()) {
$this->apiClient->request->setSite($site);
}
}
/**
* Get site code
*
* @return null | mixed
*/
public function getSite()
{
if ($this->isConfigured()) {
return $this->apiClient->request->getSite();
}
return null;
}
/** /**
* Get error text message * Get error text message
* *

View File

@ -167,13 +167,19 @@ class Exchange
{ {
$this->logger->writeDump($order, 'doCreate'); $this->logger->writeDump($order, 'doCreate');
$payments = $this->config->getValue('retailcrm/Payment'); $payments = $this->config->getValue('retailcrm/retailcrm_payment');
$shippings = $this->config->getValue('retailcrm/Shipping'); $shippings = $this->config->getValue('retailcrm/retailcrm_shipping');
$sites = $this->helper->getMappingSites();
$region = $this->regionFactory->create(); if ($sites) {
$store = $this->storeManager->getStore($sites[$order['site']]);
$websiteId = $store->getWebsiteId();
} else {
$store = $this->storeManager->getStore(); $store = $this->storeManager->getStore();
$websiteId = $this->storeManager->getStore()->getWebsiteId(); $websiteId = $this->storeManager->getStore()->getWebsiteId();
}
$region = $this->regionFactory->create();
$customer = $this->customerFactory->create(); $customer = $this->customerFactory->create();
$customer->setWebsiteId($websiteId); $customer->setWebsiteId($websiteId);
@ -324,18 +330,25 @@ class Exchange
$order = $response['order']; $order = $response['order'];
} }
$payments = $this->config->getValue('retailcrm/Payment'); $payments = $this->config->getValue('retailcrm/retailcrm_payment');
$shippings = $this->config->getValue('retailcrm/Shipping'); $shippings = $this->config->getValue('retailcrm/retailcrm_shipping');
$region = $this->regionFactory->create(); $region = $this->regionFactory->create();
$sites = $this->helper->getMappingSites();
if ($sites) {
$store = $this->storeManager->getStore($sites[$order['site']]);
$websiteId = $store->getWebsiteId();
} else {
$store = $this->storeManager->getStore(); $store = $this->storeManager->getStore();
$websiteId = $this->storeManager->getStore()->getWebsiteId(); $websiteId = $this->storeManager->getStore()->getWebsiteId();
}
$customer = $this->customerFactory->create(); $customer = $this->customerFactory->create();
$customer->setWebsiteId($websiteId); $customer->setWebsiteId($websiteId);
if (isset($order['customer']['externalId'])) { if (isset($order['customer']['externalId'])) {
$customer->load($order['customer']['externalId']); // load customet by external id $customer->load($order['customer']['externalId']); // load customer by external id
} }
//Create object of quote //Create object of quote
@ -345,7 +358,7 @@ class Exchange
$quote->setStore($store); $quote->setStore($store);
$quote->setCurrency(); $quote->setCurrency();
// if you have allready buyer id then you can load customer directly // if you have all ready buyer id then you can load customer directly
if ($customer->getId()) { if ($customer->getId()) {
$customer = $this->customerRepository->getById($customer->getId()); $customer = $this->customerRepository->getById($customer->getId());
$quote->assignCustomer($customer); //Assign quote to customer $quote->assignCustomer($customer); //Assign quote to customer
@ -462,7 +475,7 @@ class Exchange
{ {
$this->logger->writeDump($order, 'doUpdate'); $this->logger->writeDump($order, 'doUpdate');
$Status = $this->config->getValue('retailcrm/Status'); $Status = $this->config->getValue('retailcrm/retailcrm_status');
$Status = array_flip(array_filter($Status)); $Status = array_flip(array_filter($Status));
$magentoOrder = $this->order->load($order['externalId']); $magentoOrder = $this->order->load($order['externalId']);
@ -662,11 +675,8 @@ class Exchange
public function getAllShippingMethodsCode($mcode) public function getAllShippingMethodsCode($mcode)
{ {
$activeCarriers = $this->shipconfig->getActiveCarriers(); $activeCarriers = $this->shipconfig->getActiveCarriers();
$storeScope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE;
foreach ($activeCarriers as $carrierCode => $carrierModel) { foreach ($activeCarriers as $carrierCode => $carrierModel) {
$options = [];
if ($carrierMethods = $carrierModel->getAllowedMethods()) { if ($carrierMethods = $carrierModel->getAllowedMethods()) {
foreach ($carrierMethods as $methodCode => $method) { foreach ($carrierMethods as $methodCode => $method) {
$code = $carrierCode . '_'. $methodCode; $code = $carrierCode . '_'. $methodCode;

View File

@ -3,18 +3,22 @@
namespace Retailcrm\Retailcrm\Model\Observer; namespace Retailcrm\Retailcrm\Model\Observer;
use Retailcrm\Retailcrm\Helper\Proxy as ApiClient; use Retailcrm\Retailcrm\Helper\Proxy as ApiClient;
use Retailcrm\Retailcrm\Helper\Data as Helper;
class Customer implements \Magento\Framework\Event\ObserverInterface class Customer implements \Magento\Framework\Event\ObserverInterface
{ {
private $api; private $api;
private $registry; private $registry;
private $customer; private $customer;
private $helper;
public function __construct( public function __construct(
\Magento\Framework\Registry $registry, \Magento\Framework\Registry $registry,
Helper $helper,
ApiClient $api ApiClient $api
) { ) {
$this->api = $api; $this->api = $api;
$this->helper = $helper;
$this->registry = $registry; $this->registry = $registry;
$this->customer = []; $this->customer = [];
} }
@ -24,7 +28,7 @@ class Customer implements \Magento\Framework\Event\ObserverInterface
if ($this->registry->registry('RETAILCRM_HISTORY') === true if ($this->registry->registry('RETAILCRM_HISTORY') === true
|| !$this->api->isConfigured() || !$this->api->isConfigured()
) { ) {
return; return false;
} }
$data = $observer->getEvent()->getCustomer(); $data = $observer->getEvent()->getCustomer();
@ -41,12 +45,15 @@ class Customer implements \Magento\Framework\Event\ObserverInterface
$response = $this->api->customersEdit($this->customer); $response = $this->api->customersEdit($this->customer);
if ($response === false) { if ($response === false) {
return; return false;
} }
if (!$response->isSuccessful() && $response->errorMsg == $this->api->getErrorText('errorNotFound')) { if (!$response->isSuccessful() && $response->errorMsg == $this->api->getErrorText('errorNotFound')) {
$this->api->setSite($this->helper->getSite($data->getStore()));
$this->api->customersCreate($this->customer); $this->api->customersCreate($this->customer);
} }
return $this;
} }
/** /**

View File

@ -4,12 +4,15 @@ namespace Retailcrm\Retailcrm\Model\Observer;
use Magento\Framework\Event\Observer; use Magento\Framework\Event\Observer;
use Retailcrm\Retailcrm\Helper\Proxy as ApiClient; use Retailcrm\Retailcrm\Helper\Proxy as ApiClient;
use RetailCrm\Retailcrm\Helper\Data as Helper;
class OrderCreate implements \Magento\Framework\Event\ObserverInterface class OrderCreate implements \Magento\Framework\Event\ObserverInterface
{ {
private $api; protected $api;
private $config; protected $config;
private $logger; protected $logger;
protected $helper;
private $registry; private $registry;
private $product; private $product;
private $order; private $order;
@ -18,20 +21,25 @@ class OrderCreate implements \Magento\Framework\Event\ObserverInterface
* Constructor * Constructor
* *
* @param \Magento\Framework\App\Config\ScopeConfigInterface $config * @param \Magento\Framework\App\Config\ScopeConfigInterface $config
* @param \Retailcrm\Retailcrm\Model\Logger\Logger $logger
* @param \Magento\Framework\Registry $registry * @param \Magento\Framework\Registry $registry
* @param \Retailcrm\Retailcrm\Model\Logger\Logger $logger
* @param \Magento\Catalog\Model\ProductRepository $product
* @param Helper $helper
* @param ApiClient $api
*/ */
public function __construct( public function __construct(
\Magento\Framework\App\Config\ScopeConfigInterface $config, \Magento\Framework\App\Config\ScopeConfigInterface $config,
\Magento\Framework\Registry $registry, \Magento\Framework\Registry $registry,
\Retailcrm\Retailcrm\Model\Logger\Logger $logger, \Retailcrm\Retailcrm\Model\Logger\Logger $logger,
\Magento\Catalog\Model\ProductRepository $product, \Magento\Catalog\Model\ProductRepository $product,
Helper $helper,
ApiClient $api ApiClient $api
) { ) {
$this->logger = $logger; $this->logger = $logger;
$this->config = $config; $this->config = $config;
$this->registry = $registry; $this->registry = $registry;
$this->product = $product; $this->product = $product;
$this->helper = $helper;
$this->api = $api; $this->api = $api;
$this->order = []; $this->order = [];
} }
@ -41,20 +49,22 @@ class OrderCreate implements \Magento\Framework\Event\ObserverInterface
* *
* @param Observer $observer * @param Observer $observer
* *
* @return null * @return mixed
*/ */
public function execute(Observer $observer) public function execute(Observer $observer)
{ {
if ($this->registry->registry('RETAILCRM_HISTORY') === true if ($this->registry->registry('RETAILCRM_HISTORY') === true
|| !$this->api->isConfigured() || !$this->api->isConfigured()
) { ) {
return; return false;
} }
$order = $observer->getEvent()->getOrder(); $order = $observer->getEvent()->getOrder();
$this->api->setSite($this->helper->getSite($order->getStore()));
if ($this->existsInCrm($order->getId()) === true) { if ($this->existsInCrm($order->getId()) === true) {
return; return false;
} }
$addressObj = $order->getBillingAddress(); $addressObj = $order->getBillingAddress();
@ -62,7 +72,6 @@ class OrderCreate implements \Magento\Framework\Event\ObserverInterface
$shippingCode = $this->getShippingCode($order->getShippingMethod()); $shippingCode = $this->getShippingCode($order->getShippingMethod());
$this->order = [ $this->order = [
'site' => $order->getStore()->getCode(),
'externalId' => $order->getId(), 'externalId' => $order->getId(),
'number' => $order->getRealOrderId(), 'number' => $order->getRealOrderId(),
'createdAt' => $order->getCreatedAt(), 'createdAt' => $order->getCreatedAt(),
@ -77,10 +86,10 @@ class OrderCreate implements \Magento\Framework\Event\ObserverInterface
: $addressObj->getMiddlename(), : $addressObj->getMiddlename(),
'email' => $order->getCustomerEmail(), 'email' => $order->getCustomerEmail(),
'phone' => $addressObj->getTelephone(), 'phone' => $addressObj->getTelephone(),
'status' => $this->config->getValue('retailcrm/Status/' . $order->getStatus()), 'status' => $this->config->getValue('retailcrm/retailcrm_status/' . $order->getStatus()),
'items' => $this->getOrderItems($order), 'items' => $this->getOrderItems($order),
'delivery' => [ 'delivery' => [
'code' => $this->config->getValue('retailcrm/Shipping/' . $shippingCode), 'code' => $this->config->getValue('retailcrm/retailcrm_shipping/' . $shippingCode),
'cost' => $order->getShippingAmount(), 'cost' => $order->getShippingAmount(),
'address' => [ 'address' => [
'index' => $addressObj->getData('postcode'), 'index' => $addressObj->getData('postcode'),
@ -108,7 +117,7 @@ class OrderCreate implements \Magento\Framework\Event\ObserverInterface
if ($this->api->getVersion() == 'v4') { if ($this->api->getVersion() == 'v4') {
$this->order['paymentType'] = $this->config->getValue( $this->order['paymentType'] = $this->config->getValue(
'retailcrm/Payment/' . $order->getPayment()->getMethodInstance()->getCode() 'retailcrm/retailcrm_payment/' . $order->getPayment()->getMethodInstance()->getCode()
); );
$this->order['discount'] = abs($order->getDiscountAmount()); $this->order['discount'] = abs($order->getDiscountAmount());
} elseif ($this->api->getVersion() == 'v5') { } elseif ($this->api->getVersion() == 'v5') {
@ -116,7 +125,7 @@ class OrderCreate implements \Magento\Framework\Event\ObserverInterface
$payment = [ $payment = [
'type' => $this->config->getValue( 'type' => $this->config->getValue(
'retailcrm/Payment/' . $order->getPayment()->getMethodInstance()->getCode() 'retailcrm/retailcrm_payment/' . $order->getPayment()->getMethodInstance()->getCode()
), ),
'externalId' => $order->getId(), 'externalId' => $order->getId(),
'order' => [ 'order' => [
@ -148,11 +157,13 @@ class OrderCreate implements \Magento\Framework\Event\ObserverInterface
$addressObj $addressObj
); );
\Retailcrm\Retailcrm\Helper\Data::filterRecursive($this->order); Helper::filterRecursive($this->order);
$this->logger->writeDump($this->order, 'CreateOrder'); $this->logger->writeDump($this->order, 'CreateOrder');
$this->api->ordersCreate($this->order); $this->api->ordersCreate($this->order);
return $this;
} }
/** /**
@ -253,15 +264,18 @@ class OrderCreate implements \Magento\Framework\Event\ObserverInterface
* Check exists order or customer in CRM * Check exists order or customer in CRM
* *
* @param int $id * @param int $id
* @param string $method
* @param string $by
* @param string $site
* *
* @return boolean * @return boolean
*/ */
private function existsInCrm($id, $method = 'ordersGet', $by = 'externalId') private function existsInCrm($id, $method = 'ordersGet', $by = 'externalId', $site = null)
{ {
$response = $this->api->{$method}($id, $by); $response = $this->api->{$method}($id, $by, $site);
if ($response === false) { if ($response === false) {
return; return false;
} }
if (!$response->isSuccessful() && $response->errorMsg == $this->api->getErrorText('errorNotFound')) { if (!$response->isSuccessful() && $response->errorMsg == $this->api->getErrorText('errorNotFound')) {

View File

@ -4,6 +4,7 @@ namespace Retailcrm\Retailcrm\Model\Observer;
use Magento\Framework\Event\Observer; use Magento\Framework\Event\Observer;
use Retailcrm\Retailcrm\Helper\Proxy as ApiClient; use Retailcrm\Retailcrm\Helper\Proxy as ApiClient;
use RetailCrm\Retailcrm\Helper\Data as Helper;
class OrderUpdate implements \Magento\Framework\Event\ObserverInterface class OrderUpdate implements \Magento\Framework\Event\ObserverInterface
{ {
@ -11,21 +12,25 @@ class OrderUpdate implements \Magento\Framework\Event\ObserverInterface
private $config; private $config;
private $registry; private $registry;
private $order; private $order;
private $helper;
/** /**
* Constructor * Constructor
* *
* @param \Magento\Framework\App\Config\ScopeConfigInterface $config * @param \Magento\Framework\App\Config\ScopeConfigInterface $config
* @param \Magento\Framework\Registry $registry * @param \Magento\Framework\Registry $registry
* @param Helper $helper
* @param ApiClient $api * @param ApiClient $api
*/ */
public function __construct( public function __construct(
\Magento\Framework\App\Config\ScopeConfigInterface $config, \Magento\Framework\App\Config\ScopeConfigInterface $config,
\Magento\Framework\Registry $registry, \Magento\Framework\Registry $registry,
Helper $helper,
ApiClient $api ApiClient $api
) { ) {
$this->config = $config; $this->config = $config;
$this->registry = $registry; $this->registry = $registry;
$this->helper = $helper;
$this->api = $api; $this->api = $api;
$this->order = []; $this->order = [];
} }
@ -35,14 +40,14 @@ class OrderUpdate implements \Magento\Framework\Event\ObserverInterface
* *
* @param Observer $observer * @param Observer $observer
* *
* @return void * @return mixed
*/ */
public function execute(Observer $observer) public function execute(Observer $observer)
{ {
if ($this->registry->registry('RETAILCRM_HISTORY') === true if ($this->registry->registry('RETAILCRM_HISTORY') === true
|| !$this->api->isConfigured() || !$this->api->isConfigured()
) { ) {
return; return false;
} }
$order = $observer->getEvent()->getOrder(); $order = $observer->getEvent()->getOrder();
@ -50,7 +55,7 @@ class OrderUpdate implements \Magento\Framework\Event\ObserverInterface
if ($order) { if ($order) {
$this->order = [ $this->order = [
'externalId' => $order->getId(), 'externalId' => $order->getId(),
'status' => $this->config->getValue('retailcrm/Status/' . $order->getStatus()) 'status' => $this->config->getValue('retailcrm/retailcrm_status/' . $order->getStatus())
]; ];
if ($order->getBaseTotalDue() == 0) { if ($order->getBaseTotalDue() == 0) {
@ -66,9 +71,12 @@ class OrderUpdate implements \Magento\Framework\Event\ObserverInterface
} }
} }
\Retailcrm\Retailcrm\Helper\Data::filterRecursive($this->order); Helper::filterRecursive($this->order);
$this->api->setSite($this->helper->getSite($order->getStore()));
$this->api->ordersEdit($this->order); $this->api->ordersEdit($this->order);
} }
return $this;
} }
/** /**

View File

@ -2,38 +2,25 @@
namespace Retailcrm\Retailcrm\Model\Order; namespace Retailcrm\Retailcrm\Model\Order;
use Retailcrm\Retailcrm\Model\Observer\OrderCreate; use RetailCrm\Retailcrm\Helper\Data as Helper;
use Retailcrm\Retailcrm\Helper\Proxy as ApiClient; use Retailcrm\Retailcrm\Helper\Proxy as ApiClient;
use Retailcrm\Retailcrm\Model\Observer\OrderCreate;
class OrderNumber extends OrderCreate class OrderNumber extends OrderCreate
{ {
private $orderRepository; private $salesOrder;
private $searchCriteriaBuilder;
private $config;
private $filterBuilder;
private $order;
private $api;
private $logger;
private $productRepository;
public function __construct( public function __construct(
\Magento\Sales\Model\OrderRepository $orderRepository,
\Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder,
\Magento\Framework\App\Config\ScopeConfigInterface $config, \Magento\Framework\App\Config\ScopeConfigInterface $config,
\Magento\Framework\Api\FilterBuilder $filterBuilder, \Magento\Framework\Registry $registry,
\Magento\Sales\Api\Data\OrderInterface $order,
\Retailcrm\Retailcrm\Model\Logger\Logger $logger, \Retailcrm\Retailcrm\Model\Logger\Logger $logger,
\Magento\Catalog\Model\ProductRepository $productRepository, \Magento\Catalog\Model\ProductRepository $product,
ApiClient $api Helper $helper,
ApiClient $api,
\Magento\Sales\Api\Data\OrderInterface $salesOrder
) { ) {
$this->orderRepository = $orderRepository; $this->salesOrder = $salesOrder;
$this->searchCriteriaBuilder = $searchCriteriaBuilder; parent::__construct($config, $registry, $logger, $product, $helper, $api);
$this->config = $config;
$this->filterBuilder = $filterBuilder;
$this->order = $order;
$this->logger = $logger;
$this->productRepository = $productRepository;
$this->api = $api;
} }
public function exportOrderNumber() public function exportOrderNumber()
@ -43,26 +30,28 @@ class OrderNumber extends OrderCreate
$orders = []; $orders = [];
foreach ($ordersId as $id) { foreach ($ordersId as $id) {
$orders[] = $this->prepareOrder($id); $magentoOrder = $this->salesOrder->load($id);
$orders[$magentoOrder->getStore()->getId()][] = $this->prepareOrder($magentoOrder);
} }
$chunked = array_chunk($orders, 50); foreach ($orders as $storeId => $ordersStore) {
unset($orders); $chunked = array_chunk($ordersStore, 50);
unset($ordersStore);
foreach ($chunked as $chunk) { foreach ($chunked as $chunk) {
$this->api->setSite($this->helper->getSite($storeId));
$this->api->ordersUpload($chunk); $this->api->ordersUpload($chunk);
time_nanosleep(0, 250000000); time_nanosleep(0, 250000000);
} }
unset($chunked); unset($chunked);
}
return true; return true;
} }
public function prepareOrder($id) public function prepareOrder($magentoOrder)
{ {
$magentoOrder = $this->order->load($id);
$items = []; $items = [];
$addressObj = $magentoOrder->getBillingAddress(); $addressObj = $magentoOrder->getBillingAddress();
@ -95,7 +84,6 @@ class OrderNumber extends OrderCreate
$ship = $this->getShippingCode($magentoOrder->getShippingMethod()); $ship = $this->getShippingCode($magentoOrder->getShippingMethod());
$preparedOrder = [ $preparedOrder = [
'site' => $magentoOrder->getStore()->getCode(),
'externalId' => $magentoOrder->getRealOrderId(), 'externalId' => $magentoOrder->getRealOrderId(),
'number' => $magentoOrder->getRealOrderId(), 'number' => $magentoOrder->getRealOrderId(),
'createdAt' => date('Y-m-d H:i:s'), 'createdAt' => date('Y-m-d H:i:s'),
@ -152,6 +140,6 @@ class OrderNumber extends OrderCreate
$this->logger->writeDump($preparedOrder, 'OrderNumber'); $this->logger->writeDump($preparedOrder, 'OrderNumber');
return \Retailcrm\Retailcrm\Helper\Data::filterRecursive($preparedOrder); return Helper::filterRecursive($preparedOrder);
} }
} }

View File

@ -1 +1 @@
README Magento 2 module for interaction with retailCRM

View File

@ -0,0 +1,101 @@
<?php
namespace Retailcrm\Retailcrm\Test\Helpers;
class FieldsetTest extends \PHPUnit\Framework\TestCase
{
protected $elementMock;
protected $authSessionMock;
protected $userMock;
protected $requestMock;
protected $urlModelMock;
protected $layoutMock;
protected $helperMock;
protected $groupMock;
protected $objectManager;
protected $context;
protected $form;
protected $testElementId = 'test_element_id';
protected $testFieldSetCss = 'test_fieldset_css';
public function setUp()
{
$this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this);
$factoryMock = $this->createMock(\Magento\Framework\Data\Form\Element\Factory::class);
$collectionFactoryMock = $this->createMock(\Magento\Framework\Data\Form\Element\CollectionFactory::class);
$escaperMock = $this->createMock(\Magento\Framework\Escaper::class);
$formElementMock = $this->createMock(\Magento\Framework\Data\Form\Element\Select::class);
$factoryMock->expects($this->any())->method('create')->willReturn($formElementMock);
$formElementMock->expects($this->any())->method('setRenderer')->willReturn($formElementMock);
$elementCollection = $this->objectManager->getObject(\Magento\Framework\Data\Form\Element\Collection::class);
// element mock
$this->elementMock = $this->getMockBuilder(\Magento\Framework\Data\Form\Element\AbstractElement::class)
->setMethods([
'getId',
'getHtmlId',
'getName',
'getElements',
'getLegend',
'getComment',
'getIsNested',
'getExpanded',
'getForm',
'addField'
])
->setConstructorArgs([$factoryMock, $collectionFactoryMock, $escaperMock])
->getMockForAbstractClass();
$this->elementMock->expects($this->any())
->method('getId')
->willReturn($this->testElementId);
$this->elementMock->expects($this->any())
->method('getHtmlId')
->willReturn($this->testElementId);
$this->elementMock->expects($this->any())
->method('addField')
->willReturn($formElementMock);
$this->elementMock->expects($this->any())
->method('getElements')
->willReturn($elementCollection);
$this->authSessionMock = $this->getMockBuilder(\Magento\Backend\Model\Auth\Session::class)
->setMethods(['getUser'])
->disableOriginalConstructor()
->getMock();
$this->userMock = $this->getMockBuilder(\Magento\User\Model\User::class)
->setMethods(['getExtra'])
->disableOriginalConstructor()
->getMock();
$this->authSessionMock->expects($this->any())
->method('getUser')
->willReturn($this->userMock);
$this->requestMock = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class)
->disableOriginalConstructor()
->getMock();
$this->requestMock->expects($this->any())
->method('getParam')
->willReturn('Test Param');
$factoryCollection = $this->createMock(\Magento\Framework\Data\Form\Element\CollectionFactory::class);
$elementCollection = $this->createMock(\Magento\Framework\Data\Form\Element\Collection::class);
$factoryCollection->expects($this->any())->method('create')->willReturn($elementCollection);
$rendererMock = $this->createMock(\Magento\Framework\Data\Form\Element\Renderer\RendererInterface::class);
$this->urlModelMock = $this->createMock(\Magento\Backend\Model\Url::class);
$this->layoutMock = $this->createMock(\Magento\Framework\View\Layout::class);
$this->groupMock = $this->createMock(\Magento\Config\Model\Config\Structure\Element\Group::class);
$this->groupMock->expects($this->any())->method('getFieldsetCss')->will($this->returnValue($this->testFieldSetCss));
$this->context = $this->createMock(\Magento\Backend\Block\Context::class);
$this->context->expects($this->any())->method('getRequest')->willReturn($this->requestMock);
$this->context->expects($this->any())->method('getUrlBuilder')->willReturn($this->urlModelMock);
$this->layoutMock->expects($this->any())->method('getBlockSingleton')->willReturn($rendererMock);
$this->helperMock = $this->createMock(\Magento\Framework\View\Helper\Js::class);
$this->form = $this->createPartialMock(\Magento\Config\Block\System\Config\Form::class, ['getElements', 'getRequest']);
$this->form->expects($this->any())->method('getElements')->willReturn($elementCollection);
$this->form->expects($this->any())->method('getRequest')->willReturn($this->requestMock);
}
}

View File

@ -1,17 +1,9 @@
<?php <?php
namespace Retailcrm\Retailcrm\Test\Unit\Block\Adminhtml\System\Config\Form\Field; namespace Retailcrm\Retailcrm\Test\Unit\Block\Adminhtml\System\Config\Form\Fieldset;
class PaymentTest extends \PHPUnit\Framework\TestCase class PaymentTest extends \Retailcrm\Retailcrm\Test\Helpers\FieldsetTest
{ {
private $objectManager;
private $testElementId = 'test_element_id';
public function setUp()
{
$this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this);
}
/** /**
* @param boolean $isSuccessful * @param boolean $isSuccessful
* @param boolean $isConfigured * @param boolean $isConfigured
@ -19,15 +11,6 @@ class PaymentTest extends \PHPUnit\Framework\TestCase
*/ */
public function testRender($isSuccessful, $isConfigured) public function testRender($isSuccessful, $isConfigured)
{ {
// element mock
$elementMock = $this->getMockBuilder(\Magento\Framework\Data\Form\Element\AbstractElement::class)
->disableOriginalConstructor()
->setMethods(['getId'])
->getMock();
$elementMock->expects($this->any())
->method('getId')
->willReturn($this->testElementId);
// response // response
$response = $this->objectManager->getObject( $response = $this->objectManager->getObject(
\RetailCrm\Response\ApiResponse::class, \RetailCrm\Response\ApiResponse::class,
@ -62,26 +45,35 @@ class PaymentTest extends \PHPUnit\Framework\TestCase
->method('getActiveMethods') ->method('getActiveMethods')
->willReturn($this->getTestActiveMethods()); ->willReturn($this->getTestActiveMethods());
$payment = $this->objectManager->getObject( $data = [
\Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Field\Payment::class, 'authSession' => $this->authSessionMock,
[ 'jsHelper' => $this->helperMock,
'data' => ['group' => $this->groupMock],
'client' => $client, 'client' => $client,
'paymentConfig' => $paymentConfig 'paymentConfig' => $paymentConfig,
] 'context' => $this->context
];
$payment = $this->objectManager->getObject(
\Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Fieldset\Payment::class,
$data
); );
$html = $payment->render($elementMock); $payment->setForm($this->form);
$payment->setLayout($this->layoutMock);
if (!$isConfigured || !$isSuccessful) { $html = $payment->render($this->elementMock);
$this->assertEquals($html, $this->getHtml(true));
}
if ($isConfigured && $isSuccessful) { $this->assertContains($this->testElementId, $html);
$this->assertEquals($html, $this->getHtml(false)); $this->assertContains($this->testFieldSetCss, $html);
if (!$isConfigured) {
$expected = '<div style="margin-left: 15px;"><b><i>Please check your API Url & API Key</i></b></div>';
$this->assertContains($expected, $html);
} }
} }
private function getTestActiveMethods() protected function getTestActiveMethods()
{ {
$payment = $this->getMockBuilder(\Magento\Payment\Model\MethodInterface::class) $payment = $this->getMockBuilder(\Magento\Payment\Model\MethodInterface::class)
->disableOriginalConstructor() ->disableOriginalConstructor()
@ -107,35 +99,6 @@ class PaymentTest extends \PHPUnit\Framework\TestCase
]; ];
} }
private function getHtml($error)
{
$html = '';
$paymentTypes = $this->getTestResponse();
foreach ($this->getTestActiveMethods() as $code => $paymentType) {
$html .= '<table id="' . $this->testElementId . '_table">';
$html .= '<tr id="row_retailcrm_payment_' . $code . '">';
$html .= '<td class="label">' . $paymentType->getTitle() . '</td>';
$html .= '<td>';
$html .= '<select id="1" name="groups[Payment][fields][' . $code . '][value]">';
foreach ($paymentTypes['paymentTypes'] as $k => $value) {
$html .= '<option value="' . $value['code'] . '"> ' . $value['name'] . '</option>';
}
$html .= '</select>';
$html .= '</td>';
$html .= '</tr>';
$html .= '</table>';
}
if ($error) {
return '<div style="margin-left: 15px;"><b><i>Please check your API Url & API Key</i></b></div>';
}
return $html;
}
public function dataProvider() public function dataProvider()
{ {
return [ return [

View File

@ -1,17 +1,9 @@
<?php <?php
namespace Retailcrm\Retailcrm\Test\Unit\Block\Adminhtml\System\Config\Form\Field; namespace Retailcrm\Retailcrm\Test\Unit\Block\Adminhtml\System\Config\Form\Fieldset;
class ShippingTest extends \PHPUnit\Framework\TestCase class ShippingTest extends \Retailcrm\Retailcrm\Test\Helpers\FieldsetTest
{ {
private $objectManager;
private $testElementId = 'test_element_id';
public function setUp()
{
$this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this);
}
/** /**
* @param $isSuccessful * @param $isSuccessful
* @param $isConfigured * @param $isConfigured
@ -19,15 +11,6 @@ class ShippingTest extends \PHPUnit\Framework\TestCase
*/ */
public function testRender($isSuccessful, $isConfigured) public function testRender($isSuccessful, $isConfigured)
{ {
// element mock
$elementMock = $this->getMockBuilder(\Magento\Framework\Data\Form\Element\AbstractElement::class)
->disableOriginalConstructor()
->setMethods(['getId'])
->getMock();
$elementMock->expects($this->any())
->method('getId')
->willReturn($this->testElementId);
// response // response
$response = $this->objectManager->getObject( $response = $this->objectManager->getObject(
\RetailCrm\Response\ApiResponse::class, \RetailCrm\Response\ApiResponse::class,
@ -62,26 +45,35 @@ class ShippingTest extends \PHPUnit\Framework\TestCase
->method('getActiveCarriers') ->method('getActiveCarriers')
->willReturn($this->getTestActiveCarriers()); ->willReturn($this->getTestActiveCarriers());
$shipping = $this->objectManager->getObject( $data = [
\Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Field\Shipping::class, 'authSession' => $this->authSessionMock,
[ 'jsHelper' => $this->helperMock,
'data' => ['group' => $this->groupMock],
'client' => $client, 'client' => $client,
'shippingConfig' => $shippingConfig 'shippingConfig' => $shippingConfig,
] 'context' => $this->context
];
$shipping = $this->objectManager->getObject(
\Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Fieldset\Shipping::class,
$data
); );
$html = $shipping->render($elementMock); $shipping->setForm($this->form);
$shipping->setLayout($this->layoutMock);
if (!$isConfigured || !$isSuccessful) { $html = $shipping->render($this->elementMock);
$this->assertEquals($html, $this->getHtml(true));
}
if ($isConfigured && $isSuccessful) { $this->assertContains($this->testElementId, $html);
$this->assertEquals($html, $this->getHtml(false)); $this->assertContains($this->testFieldSetCss, $html);
if (!$isConfigured) {
$expected = '<div style="margin-left: 15px;"><b><i>Please check your API Url & API Key</i></b></div>';
$this->assertContains($expected, $html);
} }
} }
private function getTestActiveCarriers() protected function getTestActiveCarriers()
{ {
$shipping = $this->getMockBuilder(\Magento\Shipping\Model\Carrier\AbstractCarrierInterface::class) $shipping = $this->getMockBuilder(\Magento\Shipping\Model\Carrier\AbstractCarrierInterface::class)
->disableOriginalConstructor() ->disableOriginalConstructor()
@ -108,35 +100,6 @@ class ShippingTest extends \PHPUnit\Framework\TestCase
]; ];
} }
private function getHtml($error)
{
$html = '';
$deliveryTypes = $this->getTestResponse();
foreach ($this->getTestActiveCarriers() as $code => $deliveryType) {
$html .= '<table id="' . $this->testElementId . '_table">';
$html .= '<tr id="row_retailcrm_shipping_' . $code . '">';
$html .= '<td class="label">' . $deliveryType->getConfigData('title') . '</td>';
$html .= '<td>';
$html .= '<select id="1" name="groups[Shipping][fields][' . $code . '][value]">';
foreach ($deliveryTypes['deliveryTypes'] as $k => $value) {
$html .= '<option value="' . $value['code'] . '"> ' . $value['name'] . '</option>';
}
$html .= '</select>';
$html .= '</td>';
$html .= '</tr>';
$html .= '</table>';
}
if ($error) {
return '<div style="margin-left: 15px;"><b><i>Please check your API Url & API Key</i></b></div>';
}
return $html;
}
public function dataProvider() public function dataProvider()
{ {
return [ return [

View File

@ -0,0 +1,101 @@
<?php
namespace Retailcrm\Retailcrm\Test\Unit\Block\Adminhtml\System\Config\Form\Fieldset;
class SiteTest extends \Retailcrm\Retailcrm\Test\Helpers\FieldsetTest
{
/**
* @param boolean $isSuccessful
* @param boolean $isConfigured
* @dataProvider dataProvider
*/
public function testRender($isSuccessful, $isConfigured)
{
// response
$response = $this->objectManager->getObject(
\RetailCrm\Response\ApiResponse::class,
[
'statusCode' => $isSuccessful ? 200 : 404,
'responseBody' => json_encode($this->getTestResponse())
]
);
// api client mock
$client = $this->getMockBuilder(\Retailcrm\Retailcrm\Helper\Proxy::class)
->disableOriginalConstructor()
->setMethods(
[
'isConfigured',
'sitesList'
]
)
->getMock();
$client->expects($this->any())
->method('isConfigured')
->willReturn($isConfigured);
$client->expects($this->any())
->method('sitesList')
->willReturn($response);
$data = [
'authSession' => $this->authSessionMock,
'jsHelper' => $this->helperMock,
'data' => ['group' => $this->groupMock],
'client' => $client,
'context' => $this->context
];
$site = $this->objectManager->getObject(
\Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Fieldset\Site::class,
$data
);
$site->setForm($this->form);
$site->setLayout($this->layoutMock);
$html = $site->render($this->elementMock);
$this->assertContains($this->testElementId, $html);
$this->assertContains($this->testFieldSetCss, $html);
if (!$isConfigured) {
$expected = '<div style="margin-left: 15px;"><b><i>Please check your API Url & API Key</i></b></div>';
$this->assertContains($expected, $html);
}
}
private function getTestResponse()
{
return [
'success' => true,
'sites' => [
[
'code' => 'payment',
'name' => 'Test site'
]
]
];
}
public function dataProvider()
{
return [
[
'is_successful' => true,
'is_configured' => true
],
[
'is_successful' => false,
'is_configured' => false
],
[
'is_successful' => true,
'is_configured' => false
],
[
'is_successful' => false,
'is_configured' => true
]
];
}
}

View File

@ -0,0 +1,130 @@
<?php
namespace Retailcrm\Retailcrm\Test\Unit\Block\Adminhtml\System\Config\Form\Fieldset;
class SitesTest extends \Retailcrm\Retailcrm\Test\Helpers\FieldsetTest
{
/**
* @param boolean $isSuccessful
* @param boolean $isConfigured
* @dataProvider dataProvider
*/
public function testRender($isSuccessful, $isConfigured)
{
// response
$response = $this->objectManager->getObject(
\RetailCrm\Response\ApiResponse::class,
[
'statusCode' => $isSuccessful ? 200 : 404,
'responseBody' => json_encode($this->getTestResponse())
]
);
// api client mock
$client = $this->getMockBuilder(\Retailcrm\Retailcrm\Helper\Proxy::class)
->disableOriginalConstructor()
->setMethods(
[
'isConfigured',
'sitesList'
]
)
->getMock();
$client->expects($this->any())
->method('isConfigured')
->willReturn($isConfigured);
$client->expects($this->any())
->method('sitesList')
->willReturn($response);
$websiteMock = $this->createMock(\Magento\Store\Model\Website::class);
$websiteMock->expects($this->any())->method('getStores')->willReturn($this->getTestStores());
// payment config mock
$storeManager = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class)
->disableOriginalConstructor()
->getMockForAbstractClass();
$storeManager->expects($this->any())
->method('getWebsite')
->willReturn($websiteMock);
$data = [
'authSession' => $this->authSessionMock,
'jsHelper' => $this->helperMock,
'data' => ['group' => $this->groupMock],
'client' => $client,
'storeManager' => $storeManager,
'context' => $this->context
];
$sites = $this->objectManager->getObject(
\Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Fieldset\Sites::class,
$data
);
$sites->setForm($this->form);
$sites->setLayout($this->layoutMock);
$html = $sites->render($this->elementMock);
$this->assertContains($this->testElementId, $html);
$this->assertContains($this->testFieldSetCss, $html);
if (!$isConfigured) {
$expected = '<div style="margin-left: 15px;"><b><i>Please check your API Url & API Key</i></b></div>';
$this->assertContains($expected, $html);
}
}
protected function getTestStores()
{
$store = $this->getMockBuilder(\Magento\Store\Model\Store::class)
->disableOriginalConstructor()
->getMock();
$store->expects($this->any())
->method('getName')
->willReturn('Test Store');
$store->expects($this->any())
->method('getCode')
->willReturn('test_store_code');
return ['test_site' => $store];
}
private function getTestResponse()
{
return [
'success' => true,
'sites' => [
[
'code' => 'payment',
'name' => 'Test site'
]
]
];
}
public function dataProvider()
{
return [
[
'is_successful' => true,
'is_configured' => true
],
[
'is_successful' => false,
'is_configured' => false
],
[
'is_successful' => true,
'is_configured' => false
],
[
'is_successful' => false,
'is_configured' => true
]
];
}
}

View File

@ -1,17 +1,9 @@
<?php <?php
namespace Retailcrm\Retailcrm\Test\Unit\Block\Adminhtml\System\Config\Form\Field; namespace Retailcrm\Retailcrm\Test\Unit\Block\Adminhtml\System\Config\Form\Fieldset;
class StatusTest extends \PHPUnit\Framework\TestCase class StatusTest extends \Retailcrm\Retailcrm\Test\Helpers\FieldsetTest
{ {
private $objectManager;
private $testElementId = 'test_element_id';
public function setUp()
{
$this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this);
}
/** /**
* @param boolean $isSuccessful * @param boolean $isSuccessful
* @param boolean $isConfigured * @param boolean $isConfigured
@ -19,15 +11,6 @@ class StatusTest extends \PHPUnit\Framework\TestCase
*/ */
public function testRender($isSuccessful, $isConfigured) public function testRender($isSuccessful, $isConfigured)
{ {
// element mock
$elementMock = $this->getMockBuilder(\Magento\Framework\Data\Form\Element\AbstractElement::class)
->disableOriginalConstructor()
->setMethods(['getId'])
->getMock();
$elementMock->expects($this->any())
->method('getId')
->willReturn($this->testElementId);
// response // response
$response = $this->objectManager->getObject( $response = $this->objectManager->getObject(
\RetailCrm\Response\ApiResponse::class, \RetailCrm\Response\ApiResponse::class,
@ -62,26 +45,35 @@ class StatusTest extends \PHPUnit\Framework\TestCase
->method('toOptionArray') ->method('toOptionArray')
->willReturn($this->getTestStatuses()); ->willReturn($this->getTestStatuses());
$status = $this->objectManager->getObject( $data = [
\Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Field\Status::class, 'authSession' => $this->authSessionMock,
[ 'jsHelper' => $this->helperMock,
'data' => ['group' => $this->groupMock],
'client' => $client, 'client' => $client,
'statusCollection' => $statusCollection 'statusCollection' => $statusCollection,
] 'context' => $this->context
];
$status = $this->objectManager->getObject(
\Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Fieldset\Status::class,
$data
); );
$html = $status->render($elementMock); $status->setForm($this->form);
$status->setLayout($this->layoutMock);
if (!$isConfigured || !$isSuccessful) { $html = $status->render($this->elementMock);
$this->assertEquals($html, $this->getHtml(true));
}
if ($isConfigured && $isSuccessful) { $this->assertContains($this->testElementId, $html);
$this->assertEquals($html, $this->getHtml(false)); $this->assertContains($this->testFieldSetCss, $html);
if (!$isConfigured) {
$expected = '<div style="margin-left: 15px;"><b><i>Please check your API Url & API Key</i></b></div>';
$this->assertContains($expected, $html);
} }
} }
private function getTestStatuses() protected function getTestStatuses()
{ {
$status = [ $status = [
'label' => 'Test Status', 'label' => 'Test Status',
@ -104,37 +96,6 @@ class StatusTest extends \PHPUnit\Framework\TestCase
]; ];
} }
private function getHtml($error)
{
$html = '';
$statuses = $this->getTestResponse();
foreach ($this->getTestStatuses() as $code => $status) {
$html .= '<table id="' . $this->testElementId . '_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]">';
$html .= '<option value=""> Select status </option>';
foreach ($statuses['statuses'] as $k => $value) {
$html .= '<option value="' . $value['code'] . '"> ' . $value['name'] . '</option>';
}
$html .= '</select>';
$html .= '</td>';
$html .= '</tr>';
$html .= '</table>';
}
if ($error) {
return '<div style="margin-left: 15px;"><b><i>Please check your API Url & API Key</i></b></div>';
}
return $html;
}
public function dataProvider() public function dataProvider()
{ {
return [ return [

View File

@ -11,6 +11,7 @@ class CustomerTest extends \PHPUnit\Framework\TestCase
private $mockEvent; private $mockEvent;
private $mockCustomer; private $mockCustomer;
private $unit; private $unit;
private $helper;
public function setUp() public function setUp()
{ {
@ -19,7 +20,8 @@ class CustomerTest extends \PHPUnit\Framework\TestCase
->setMethods([ ->setMethods([
'customersEdit', 'customersEdit',
'customersCreate', 'customersCreate',
'isConfigured' 'isConfigured',
'setSite'
]) ])
->getMock(); ->getMock();
@ -48,12 +50,16 @@ class CustomerTest extends \PHPUnit\Framework\TestCase
'getEmail', 'getEmail',
'getFirstname', 'getFirstname',
'getMiddlename', 'getMiddlename',
'getLastname' 'getLastname',
'getStore'
]) ])
->getMock(); ->getMock();
$this->helper = $this->createMock(\Retailcrm\Retailcrm\Helper\Data::class);
$this->unit = new \Retailcrm\Retailcrm\Model\Observer\Customer( $this->unit = new \Retailcrm\Retailcrm\Model\Observer\Customer(
$this->registry, $this->registry,
$this->helper,
$this->mockApi $this->mockApi
); );
} }
@ -110,6 +116,12 @@ class CustomerTest extends \PHPUnit\Framework\TestCase
->method('getLastname') ->method('getLastname')
->willReturn($testData['lastname']); ->willReturn($testData['lastname']);
$store = $this->createMock(\Magento\Store\Model\Store::class);
$this->mockCustomer->expects($this->any())
->method('getStore')
->willReturn($store);
// mock Event // mock Event
$this->mockEvent->expects($this->any()) $this->mockEvent->expects($this->any())
->method('getCustomer') ->method('getCustomer')
@ -120,7 +132,7 @@ class CustomerTest extends \PHPUnit\Framework\TestCase
->method('getEvent') ->method('getEvent')
->willReturn($this->mockEvent); ->willReturn($this->mockEvent);
$this->unit->execute($this->mockObserver); $customerObserver = $this->unit->execute($this->mockObserver);
if ($isConfigured) { if ($isConfigured) {
$this->assertNotEmpty($this->unit->getCustomer()); $this->assertNotEmpty($this->unit->getCustomer());
@ -130,6 +142,7 @@ class CustomerTest extends \PHPUnit\Framework\TestCase
$this->assertArrayHasKey('lastName', $this->unit->getCustomer()); $this->assertArrayHasKey('lastName', $this->unit->getCustomer());
$this->assertArrayHasKey('patronymic', $this->unit->getCustomer()); $this->assertArrayHasKey('patronymic', $this->unit->getCustomer());
$this->assertArrayHasKey('createdAt', $this->unit->getCustomer()); $this->assertArrayHasKey('createdAt', $this->unit->getCustomer());
$this->assertInstanceOf(\RetailCrm\Retailcrm\Model\Observer\Customer::class, $customerObserver);
} else { } else {
$this->assertEmpty($this->unit->getCustomer()); $this->assertEmpty($this->unit->getCustomer());
} }

View File

@ -33,7 +33,8 @@ class OrderCreateTest extends \PHPUnit\Framework\TestCase
'customersCreate', 'customersCreate',
'customersList', 'customersList',
'getVersion', 'getVersion',
'isConfigured' 'isConfigured',
'setSite'
]) ])
->getMock(); ->getMock();
@ -119,11 +120,14 @@ class OrderCreateTest extends \PHPUnit\Framework\TestCase
->disableOriginalConstructor() ->disableOriginalConstructor()
->getMock(); ->getMock();
$helper = $this->createMock(\Retailcrm\Retailcrm\Helper\Data::class);
$this->unit = new \Retailcrm\Retailcrm\Model\Observer\OrderCreate( $this->unit = new \Retailcrm\Retailcrm\Model\Observer\OrderCreate(
$this->config, $this->config,
$this->registry, $this->registry,
$this->logger, $this->logger,
$product, $product,
$helper,
$this->mockApi $this->mockApi
); );
} }
@ -304,7 +308,7 @@ class OrderCreateTest extends \PHPUnit\Framework\TestCase
->method('getEvent') ->method('getEvent')
->willReturn($this->mockEvent); ->willReturn($this->mockEvent);
$this->unit->execute($this->mockObserver); $orderCreateObserver = $this->unit->execute($this->mockObserver);
if ($isConfigured && !$isSuccessful) { if ($isConfigured && !$isSuccessful) {
$this->assertNotEmpty($this->unit->getOrder()); $this->assertNotEmpty($this->unit->getOrder());
@ -325,6 +329,8 @@ class OrderCreateTest extends \PHPUnit\Framework\TestCase
} else { } else {
$this->assertArrayHasKey('paymentType', $this->unit->getOrder()); $this->assertArrayHasKey('paymentType', $this->unit->getOrder());
} }
$this->assertInstanceOf(\Retailcrm\Retailcrm\Model\Observer\OrderCreate::class, $orderCreateObserver);
} elseif (!$isConfigured || $isSuccessful) { } elseif (!$isConfigured || $isSuccessful) {
$this->assertEmpty($this->unit->getOrder()); $this->assertEmpty($this->unit->getOrder());
} }

View File

@ -22,7 +22,8 @@ class OrderUpdateTest extends \PHPUnit\Framework\TestCase
'ordersEdit', 'ordersEdit',
'ordersPaymentsEdit', 'ordersPaymentsEdit',
'getVersion', 'getVersion',
'isConfigured' 'isConfigured',
'setSite'
]) ])
->getMock(); ->getMock();
@ -38,12 +39,14 @@ class OrderUpdateTest extends \PHPUnit\Framework\TestCase
$this->objectManager = $this->getMockBuilder(\Magento\Framework\ObjectManagerInterface::class) $this->objectManager = $this->getMockBuilder(\Magento\Framework\ObjectManagerInterface::class)
->getMockForAbstractClass(); ->getMockForAbstractClass();
$this->mockOrder = $this->getMockBuilder(\Magento\Sales\Order::class) $this->mockOrder = $this->getMockBuilder(\Magento\Sales\Model\Order::class)
->disableOriginalConstructor()
->setMethods([ ->setMethods([
'getId', 'getId',
'getPayment', 'getPayment',
'getBaseTotalDue', 'getBaseTotalDue',
'getStatus' 'getStatus',
'getStore'
]) ])
->getMock(); ->getMock();
@ -59,9 +62,12 @@ class OrderUpdateTest extends \PHPUnit\Framework\TestCase
->disableOriginalConstructor() ->disableOriginalConstructor()
->getMock(); ->getMock();
$helper = $this->createMock(\Retailcrm\Retailcrm\Helper\Data::class);
$this->unit = new \Retailcrm\Retailcrm\Model\Observer\OrderUpdate( $this->unit = new \Retailcrm\Retailcrm\Model\Observer\OrderUpdate(
$this->config, $this->config,
$this->registry, $this->registry,
$helper,
$this->mockApi $this->mockApi
); );
} }
@ -101,6 +107,12 @@ class OrderUpdateTest extends \PHPUnit\Framework\TestCase
->method('getPayment') ->method('getPayment')
->willReturn($this->mockPayment); ->willReturn($this->mockPayment);
$store = $this->createMock(\Magento\Store\Model\Store::class);
$this->mockOrder->expects($this->any())
->method('getStore')
->willReturn($store);
// mock Api // mock Api
$this->mockApi->expects($this->any()) $this->mockApi->expects($this->any())
->method('getVersion') ->method('getVersion')
@ -120,12 +132,16 @@ class OrderUpdateTest extends \PHPUnit\Framework\TestCase
->method('getEvent') ->method('getEvent')
->willReturn($this->mockEvent); ->willReturn($this->mockEvent);
$this->unit->execute($this->mockObserver); $updateOrderObserver = $this->unit->execute($this->mockObserver);
if ($isConfigured) { if ($isConfigured) {
$this->assertNotEmpty($this->unit->getOrder()); $this->assertNotEmpty($this->unit->getOrder());
$this->assertArrayHasKey('externalId', $this->unit->getOrder()); $this->assertArrayHasKey('externalId', $this->unit->getOrder());
$this->assertArrayHasKey('status', $this->unit->getOrder()); $this->assertArrayHasKey('status', $this->unit->getOrder());
$this->assertInstanceOf(
\Retailcrm\Retailcrm\Model\Observer\OrderUpdate::class,
$updateOrderObserver
);
} else { } else {
$this->assertEmpty($this->unit->getOrder()); $this->assertEmpty($this->unit->getOrder());
} }

View File

@ -36,42 +36,25 @@
<label>Attributes to export into icml</label> <label>Attributes to export into icml</label>
<comment>Attributes to export into icml</comment> <comment>Attributes to export into icml</comment>
<source_model>Retailcrm\Retailcrm\Model\Setting\Attribute</source_model> <source_model>Retailcrm\Retailcrm\Model\Setting\Attribute</source_model>
<!--
<frontend_model>Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Field\Attributes</frontend_model>
-->
</field> </field>
</group> </group>
<group id="Shipping" translate="label" type="text" sortOrder="30" showInDefault="1" showInWebsite="1" showInStore="1"> <group id="shipping" translate="label" type="select" sortOrder="30" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Shipping</label> <label>Shipping</label>
<field id="Shipping" translate="label" type="select" sortOrder="3" showInDefault="1" showInWebsite="1" showInStore="1"> <frontend_model>Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Fieldset\Shipping</frontend_model>
<label>Shipping</label>
<!-- <source_model>Retailcrm\Retailcrm\Model\Setting\Shipping</source_model>
-->
<frontend_model>Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Field\Shipping</frontend_model>
</field>
</group> </group>
<group id="Payment" translate="label comment" type="text" sortOrder="40" showInDefault="1" showInWebsite="1" showInStore="1"> <group id="payment" translate="label comment" type="select" sortOrder="40" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Payment method</label> <label>Payment method</label>
<field id="display_text" translate="label" type="text" sortOrder="5" showInDefault="1" showInWebsite="1" showInStore="1"> <frontend_model>Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Fieldset\Payment</frontend_model>
<label>Payment</label>
<frontend_model>Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Field\Payment</frontend_model>
<comment>This text will display on the frontend.</comment>
</field>
</group> </group>
<group id="Status" translate="label" type="text" sortOrder="50" showInDefault="5" showInWebsite="1" showInStore="1"> <group id="status" translate="label" type="select" sortOrder="50" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Order Status</label> <label>Order Status</label>
<field id="status_text" translate="label" type="text" sortOrder="5" showInDefault="1" showInWebsite="1" showInStore="1"> <frontend_model>Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Fieldset\Status</frontend_model>
<label>Status</label>
<frontend_model>Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Field\Status</frontend_model>
<comment>This text will display on the frontend.</comment>
</field>
</group> </group>
<group id="Load" translate="label" type="text" sortOrder="60" showInDefault="6" showInWebsite="1" showInStore="1"> <group id="Load" translate="label" type="text" sortOrder="80" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Order Load</label> <label>Order Load</label>
<field id="number_order" translate="label" type="text" sortOrder="6" showInDefault="1" showInWebsite="1" showInStore="1"> <field id="number_order" translate="label" type="text" sortOrder="6" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Order number</label> <label>Order number</label>
@ -82,6 +65,15 @@
</field> </field>
</group> </group>
<group id="site" translate="label" type="select" sortOrder="60" showInDefault="1" showInWebsite="0" showInStore="0">
<label>Site</label>
<frontend_model>Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Fieldset\Site</frontend_model>
</group>
<group id="sites" translate="label" type="select" sortOrder="70" showInDefault="0" showInWebsite="1" showInStore="0">
<label>Sites</label>
<frontend_model>Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Fieldset\Sites</frontend_model>
</group>
</section> </section>
</system> </system>
</config> </config>