1
0
mirror of synced 2024-11-25 06:26:07 +03:00
This commit is contained in:
Alex Lushpai 2017-05-31 15:24:46 +03:00
parent f838099bb0
commit f4000c9874
71 changed files with 2892 additions and 3221 deletions

View File

@ -0,0 +1,75 @@
<?php
namespace Retailcrm\Retailcrm\Block\Adminhtml\System\Config;
class Button extends \Magento\Config\Block\System\Config\Form\Field
{
/**
* @var string
*/
protected $_template = 'Retailcrm_Retailcrm::system/config/button.phtml';
/**
* @param \Magento\Backend\Block\Template\Context $context
* @param array $data
*/
public function __construct(
\Magento\Backend\Block\Template\Context $context,
array $data = []
) {
parent::__construct($context, $data);
}
/**
* Remove scope label
*
* @param \Magento\Framework\Data\Form\Element\AbstractElement $element
* @return string
*/
public function render(\Magento\Framework\Data\Form\Element\AbstractElement $element)
{
$element->unsScope()->unsCanUseWebsiteValue()->unsCanUseDefaultValue();
return parent::render($element);
}
/**
* Return element html
*
* @param \Magento\Framework\Data\Form\Element\AbstractElement $element
* @return string
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
protected function _getElementHtml(\Magento\Framework\Data\Form\Element\AbstractElement $element)
{
return $this->_toHtml();
}
/**
* Return ajax url for synchronize button
*
* @return string
*/
public function getAjaxSyncUrl()
{
return $this->getUrl('retailcrm_retailcrm/system_config/button');
}
/**
* Generate synchronize button html
*
* @return string
*/
public function getButtonHtml()
{
$button = $this->getLayout()->createBlock(
'Magento\Backend\Block\Widget\Button'
)->setData(
[
'id' => 'order_button',
'label' => __('Run'),
]
);
return $button->toHtml();
}
}

View File

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

View File

@ -0,0 +1,72 @@
<?php
namespace Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Field;
class Base extends \Magento\Framework\Model\AbstractModel
{
public $_apiKey;
public $_apiUrl;
public $_isCredentialCorrect;
protected $logger;
protected $_cacheTypeList;
protected $_resourceConfig;
public function __construct()
{
$om = \Magento\Framework\App\ObjectManager::getInstance();
$config = $om->get('\Magento\Framework\App\Config\ScopeConfigInterface');
$logger = $om->get('\Psr\Log\LoggerInterface');
$cacheTypeList = $om->get('\Magento\Framework\App\Cache\TypeListInterface');
$resourceConfig = $om->get('Magento\Config\Model\ResourceModel\Config');
$this->_resourceConfig = $resourceConfig;
$this->_cacheTypeList = $cacheTypeList;
$this->logger = $logger;
$this->_apiUrl = $config->getValue('retailcrm/general/api_url');
$this->_apiKey = $config->getValue('retailcrm/general/api_key');
$this->_isCredentialCorrect = false;
if (!empty($this->_apiUrl) && !empty($this->_apiKey)) {
if (false === stripos($this->_apiUrl, 'https://')) {
$this->_apiUrl = str_replace("http://", "https://", $this->_apiUrl);
$this->_resourceConfig->saveConfig('retailcrm/general/api_url', $this->_apiUrl, 'default', 0);
$this->_cacheTypeList->cleanType('config');
}
if (!$this->is_url($this->_apiUrl)){
echo 'URL not valid<br>';
echo 'Please check your Url and Reload page<br>';
$this->_resourceConfig->saveConfig('retailcrm/general/api_url', '', 'default', 0);
$this->_cacheTypeList->cleanType('config');
}
$client = new \Retailcrm\Retailcrm\Model\ApiClient\ApiClient(
$this->_apiUrl,
$this->_apiKey
);
try {
$response = $client->sitesList();
} catch (\Retailcrm\Retailcrm\Model\ApiClient\Exception\CurlException $e) {
$this->_logger->addDebug($e->getMessage());
}
if ($response->isSuccessful()) {
$this->_isCredentialCorrect = true;
if($response['success'] != 1) {
$this->_resourceConfig->saveConfig('retailcrm/general/api_url', '', 'default', 0);
$this->_cacheTypeList->cleanType('config');
}
}
}
}
public function is_url($url) {
return preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $url);
}
}

View File

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

View File

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

View File

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

17
Block/Display.php Normal file
View File

@ -0,0 +1,17 @@
<?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');
}
}

View File

@ -0,0 +1,30 @@
<?php
namespace Retailcrm\Retailcrm\Controller\Adminhtml\System\Config;
class Button extends \Magento\Backend\App\Action
{
/**
* @var \Psr\Log\LoggerInterface
*/
protected $_logger;
/**
* @param \Magento\Backend\App\Action\Context $context
* @param \Psr\Log\LoggerInterface $logger
*/
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Psr\Log\LoggerInterface $logger
) {
$this->_logger = $logger;
parent::__construct($context);
}
public function execute()
{
$order = new \Retailcrm\Retailcrm\Model\Order\OrderNumber();
$order->ExportOrderNumber();
}
}

View File

@ -0,0 +1,19 @@
<?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);
}
public function execute()
{
return $this->_pageFactory->create();
}
}

38
Controller/Index/Test.php Normal file
View File

@ -0,0 +1,38 @@
<?php
namespace Retailcrm\Retailcrm\Controller\Index;
use Magento\Framework\App\Helper\Context;
use Psr\Log\LoggerInterface;
class Test extends \Magento\Framework\App\Action\Action
{
protected $logger;
public function __construct(
LoggerInterface $logger
,\Magento\Framework\App\Action\Context $context
,\Magento\Framework\View\Page\Config $pageConfig
,\Magento\Framework\App\Config\ScopeConfigInterface $config
)
{
$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);
}
public function execute()
{
//
exit;
}
}

20
Cron/Icml.php Normal file
View File

@ -0,0 +1,20 @@
<?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;
}
public function execute() {
$Icml = new \Retailcrm\Retailcrm\Model\Icml\Icml();
$Icml->generate();
$this->_logger->addDebug('Cron Works: create icml');
}
}

20
Cron/OrderHistory.php Normal file
View File

@ -0,0 +1,20 @@
<?php
namespace Retailcrm\Retailcrm\Cron;
class OrderHistory {
protected $_logger;
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');
}
}

67
Helper/Data.php Normal file
View File

@ -0,0 +1,67 @@
<?php
namespace Retailcrm\Retailcrm\Helper;
use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\App\Helper\Context;
use Magento\Store\Model\ScopeInterface;
class Data extends AbstractHelper
{
protected $storeManager;
protected $objectManager;
const XML_PATH_RETAILCRM = 'retailcrm/';
public function __construct(Context $context,
ObjectManagerInterface $objectManager,
StoreManagerInterface $storeManager
) {
$this->objectManager = $objectManager;
$this->storeManager = $storeManager;
parent::__construct($context);
}
public function getConfigValue($field, $storeId = null)
{
return $this->scopeConfig->getValue(
$field, ScopeInterface::SCOPE_STORE, $storeId
);
}
public function getGeneralConfig($code, $storeId = null)
{
return $this->getConfigValue(self::XML_PATH_RETAILCRM . $code, $storeId);
}
/**
* Recursive array filter
*
* @param array $haystack input array
*
* @SuppressWarnings(PHPMD.StaticAccess)
* @SuppressWarnings(PHPMD.ElseExpression)
*
* @return array
*/
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;
}
}

0
Log/.gitkeep Normal file
View File

View File

@ -0,0 +1,30 @@
<?php
/**
* PHP version 5.3
*
* Class CurlException
*
* @category RetailCrm
* @package RetailCrm
* @author RetailCrm <integration@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
* @link http://www.retailcrm.ru/docs/Developers/ApiVersion4
*/
namespace Retailcrm\Retailcrm\Model\ApiClient\Exception;
/**
* PHP version 5.3
*
* Class CurlException
*
* @category RetailCrm
* @package RetailCrm
* @author RetailCrm <integration@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
* @link http://www.retailcrm.ru/docs/Developers/ApiVersion4
*/
class CurlException extends \RuntimeException
{
}

View File

@ -0,0 +1,30 @@
<?php
/**
* PHP version 5.3
*
* Class InvalidJsonException
*
* @category RetailCrm
* @package RetailCrm
* @author RetailCrm <integration@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
* @link http://www.retailcrm.ru/docs/Developers/ApiVersion4
*/
namespace Retailcrm\Retailcrm\Model\ApiClient\Exception;
/**
* PHP version 5.3
*
* Class InvalidJsonException
*
* @category RetailCrm
* @package RetailCrm
* @author RetailCrm <integration@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
* @link http://www.retailcrm.ru/docs/Developers/ApiVersion4
*/
class InvalidJsonException extends \DomainException
{
}

View File

@ -11,7 +11,25 @@
* @license https://opensource.org/licenses/MIT MIT License
* @link http://www.retailcrm.ru/docs/Developers/ApiVersion4
*/
class Retailcrm_Retailcrm_Model_Http_Client
namespace Retailcrm\Retailcrm\Model\ApiClient\Http;
use Retailcrm\Retailcrm\Model\ApiClient\Exception\CurlException;
use Retailcrm\Retailcrm\Model\ApiClient\Exception\InvalidJsonException;
use Retailcrm\Retailcrm\Model\ApiClient\Response\ApiResponse;
/**
* PHP version 5.3
*
* HTTP client
*
* @category RetailCrm
* @package RetailCrm
* @author RetailCrm <integration@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
* @link http://www.retailcrm.ru/docs/Developers/ApiVersion4
*/
class Client
{
const METHOD_GET = 'GET';
const METHOD_POST = 'POST';
@ -30,7 +48,7 @@ class Retailcrm_Retailcrm_Model_Http_Client
public function __construct($url, array $defaultParameters = array())
{
if (false === stripos($url, 'https://')) {
throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException(
throw new \InvalidArgumentException(
'API schema requires HTTPS protocol'
);
}
@ -54,12 +72,15 @@ class Retailcrm_Retailcrm_Model_Http_Client
*
* @return ApiResponse
*/
public function makeRequest($path,$method,array $parameters = array())
{
public function makeRequest(
$path,
$method,
array $parameters = array()
) {
$allowedMethods = array(self::METHOD_GET, self::METHOD_POST);
if (!in_array($method, $allowedMethods, false)) {
throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException(
throw new \InvalidArgumentException(
sprintf(
'Method "%s" is not valid. Allowed methods are %s',
$method,
@ -99,9 +120,9 @@ class Retailcrm_Retailcrm_Model_Http_Client
curl_close($curlHandler);
if ($errno) {
throw new Retailcrm_Retailcrm_Model_Exception_CurlException($error, $errno);
throw new CurlException($error, $errno);
}
return new Retailcrm_Retailcrm_Model_Response_ApiResponse($statusCode, $responseBody);
return new ApiResponse($statusCode, $responseBody);
}
}

View File

@ -11,7 +11,23 @@
* @license https://opensource.org/licenses/MIT MIT License
* @link http://www.retailcrm.ru/docs/Developers/ApiVersion4
*/
class Retailcrm_Retailcrm_Model_Response_ApiResponse implements ArrayAccess
namespace Retailcrm\Retailcrm\Model\ApiClient\Response;
use Retailcrm\Retailcrm\Model\ApiClient\Exception\InvalidJsonException;
/**
* PHP version 5.3
*
* Response from retailCRM API
*
* @category RetailCrm
* @package RetailCrm
* @author RetailCrm <integration@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
* @link http://www.retailcrm.ru/docs/Developers/ApiVersion4
*/
class ApiResponse implements \ArrayAccess
{
// HTTP response status code
protected $statusCode;
@ -35,7 +51,7 @@ class Retailcrm_Retailcrm_Model_Response_ApiResponse implements ArrayAccess
$response = json_decode($responseBody, true);
if (!$response && JSON_ERROR_NONE !== ($error = json_last_error())) {
throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException(
throw new InvalidJsonException(
"Invalid JSON in the API response body. Error code #$error",
$error
);
@ -81,7 +97,7 @@ class Retailcrm_Retailcrm_Model_Response_ApiResponse implements ArrayAccess
$propertyName = strtolower(substr($name, 3, 1)) . substr($name, 4);
if (!isset($this->response[$propertyName])) {
throw new InvalidArgumentException("Method \"$name\" not found");
throw new \InvalidArgumentException("Method \"$name\" not found");
}
return $this->response[$propertyName];
@ -99,7 +115,7 @@ class Retailcrm_Retailcrm_Model_Response_ApiResponse implements ArrayAccess
public function __get($name)
{
if (!isset($this->response[$name])) {
throw new InvalidArgumentException("Property \"$name\" not found");
throw new \InvalidArgumentException("Property \"$name\" not found");
}
return $this->response[$name];
@ -116,7 +132,7 @@ class Retailcrm_Retailcrm_Model_Response_ApiResponse implements ArrayAccess
*/
public function offsetSet($offset, $value)
{
throw new BadMethodCallException('This activity not allowed');
throw new \BadMethodCallException('This activity not allowed');
}
/**
@ -129,7 +145,7 @@ class Retailcrm_Retailcrm_Model_Response_ApiResponse implements ArrayAccess
*/
public function offsetUnset($offset)
{
throw new BadMethodCallException('This call not allowed');
throw new \BadMethodCallException('This call not allowed');
}
/**
@ -156,7 +172,7 @@ class Retailcrm_Retailcrm_Model_Response_ApiResponse implements ArrayAccess
public function offsetGet($offset)
{
if (!isset($this->response[$offset])) {
throw new InvalidArgumentException("Property \"$offset\" not found");
throw new \InvalidArgumentException("Property \"$offset\" not found");
}
return $this->response[$offset];

762
Model/History/Exchange.php Normal file
View File

@ -0,0 +1,762 @@
<?php
namespace Retailcrm\Retailcrm\Model\History;
class Exchange
{
protected $_api;
protected $_config;
protected $_helper;
protected $_logger;
protected $_resourceConfig;
protected $_customerFactory;
protected $_quote;
protected $_customerRepository;
protected $_product;
protected $_shipconfig;
protected $_quoteManagement;
protected $_registry;
protected $_cacheTypeList;
protected $_order;
protected $_orderManagement;
//protected $_transaction;
//protected $_invoiceService;
protected $_eventManager;
public function __construct()
{
$om = \Magento\Framework\App\ObjectManager::getInstance();
$helper = $om->get('\Retailcrm\Retailcrm\Helper\Data');
$logger = $om->get('\Psr\Log\LoggerInterface');
$config = $om->get('\Magento\Framework\App\Config\ScopeConfigInterface');
$resourceConfig = $om->get('Magento\Config\Model\ResourceModel\Config');
$customerFactory = $om->get('\Magento\Customer\Model\CustomerFactory');
$quote = $om->get('\Magento\Quote\Model\QuoteFactory');
$customerRepository = $om->get('\Magento\Customer\Api\CustomerRepositoryInterface');
$product = $om->get('\Magento\Catalog\Model\Product');
$shipconfig = $om->get('\Magento\Shipping\Model\Config');
$quoteManagement = $om->get('\Magento\Quote\Model\QuoteManagement');
$registry = $om->get('\Magento\Framework\Registry');
$cacheTypeList = $om->get('\Magento\Framework\App\Cache\TypeListInterface');
$order = $om->get('\Magento\Sales\Api\Data\OrderInterface');
$orderManagement = $om->get('\Magento\Sales\Api\OrderManagementInterface');
//$invoiceService = $om->get('\Magento\Sales\Model\Service\InvoiceService');
//$transaction = $om->get('\Magento\Framework\DB\Transaction');
$eventManager = $om->get('\Magento\Framework\Event\Manager');
$this->_shipconfig = $shipconfig;
$this->_logger = $logger;
$this->_helper = $helper;
$this->_config = $config;
$this->_resourceConfig = $resourceConfig;
$this->_customerFactory = $customerFactory;
$this->_quote = $quote;
$this->_customerRepository = $customerRepository;
$this->_product = $product;
$this->_quoteManagement = $quoteManagement;
$this->_registry = $registry;
$this->_cacheTypeList = $cacheTypeList;
$this->_order = $order;
$this->_orderManagement = $orderManagement;
//$this->_transaction = $transaction;
//$this->_invoiceService = $invoiceService;
$this->_eventManager = $eventManager;
$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 ordersHistory()
{
$historyFilter = array();
$historiOrder = array();
$historyStart = $this->_config->getValue('retailcrm/general/filter_history');
if($historyStart && $historyStart > 0) {
$historyFilter['sinceId'] = $historyStart;
}
while(true) {
try {
$response = $this->_api->ordersHistory($historyFilter);
if ($response->isSuccessful()&&200 === $response->getStatusCode()) {
$nowTime = $response->getGeneratedAt();
} else {
$this->_logger->addDebug(
sprintf("Orders history error: [HTTP status %s] %s", $response->getStatusCode(), $response->getErrorMsg())
);
if (isset($response['errors'])) {
$this->_logger->addDebug(implode(' :: ', $response['errors']));
}
return false;
}
} catch (\Retailcrm\Retailcrm\Model\ApiClient\Exception\CurlException $e) {
$this->_logger->addDebug($e->getMessage());
return false;
}
$orderH = isset($response['history']) ? $response['history'] : array();
if(count($orderH) == 0) {
return true;
}
$historiOrder = array_merge($historiOrder, $orderH);
$end = array_pop($response->history);
$historyFilter['sinceId'] = $end['id'];
if($response['pagination']['totalPageCount'] == 1) {
$this->_resourceConfig->saveConfig('retailcrm/general/filter_history', $historyFilter['sinceId'], 'default', 0);
$this->_cacheTypeList->cleanType('config');
$orders = self::assemblyOrder($historiOrder);
$logger = new \Retailcrm\Retailcrm\Model\Logger\Logger();
$logger->write($orders,'OrderHistory');
$this->processOrders($orders, $nowTime);
return true;
}
}//endwhile
}
/**
* @param array $orders
*/
private function processOrders($orders, $time)
{
$logger = new \Retailcrm\Retailcrm\Model\Logger\Logger();
$logger->write($orders,'processOrders');
if(!empty($orders)) {
foreach ($orders as $order) {
if(!empty($order['externalId'])) {
$this->doUpdate($order);
} else {
$this->doCreate($order);
}
}
die();
}
}
/**
* @param array $order
*/
private function doCreate($order)
{
$logger = new \Retailcrm\Retailcrm\Model\Logger\Logger();
$logger->write($order,'doCreate');
$payments = $this->_config->getValue('retailcrm/Payment');
$shippings = $this->_config->getValue('retailcrm/Shipping');
$om = \Magento\Framework\App\ObjectManager::getInstance();
$manager = $om->get('Magento\Store\Model\StoreManagerInterface');
$store = $manager->getStore();
$websiteId = $manager->getStore()->getWebsiteId();
$customer = $this->_customerFactory->create();
$customer->setWebsiteId($websiteId);
$customer->loadByEmail($order['email']);// load customet by email address
if(!$customer->getEntityId()){
//If not avilable then create this customer
$customer->setWebsiteId($websiteId)
->setStore($store)
->setFirstname($order['firstName'])
->setLastname($order['lastName'])
->setEmail($order['email'])
->setPassword($order['email']);
try {
$customer->save();
} catch (Exception $e) {
$this->_logger->addDebug($e->getMessage());
}
}
//Create object of quote
$quote = $this->_quote->create();
//set store for which you create quote
$quote->setStore($store);
// if you have allready buyer id then you can load customer directly
$customer = $this->_customerRepository->getById($customer->getEntityId());
$quote->setCurrency();
$quote->assignCustomer($customer); //Assign quote to customer
//add items in quote
foreach($order['items'] as $item){
$product = $this->_product->load($item['offer']['externalId']);
$product->setPrice($item['initialPrice']);
$quote->addProduct(
$product,
intval($item['quantity'])
);
}
$products = array();
foreach ($order['items'] as $item) {
$products[$item['offer']['externalId']] = array('qty' => $item['quantity']);
}
$orderData = array(
'currency_id' => 'USD',
'email' => $order['email'],
'shipping_address' =>array(
'firstname' => $order['firstName'],
'lastname' => $order['lastName'],
'street' => $order['delivery']['address']['street'],
'city' => $order['delivery']['address']['city'],
'country_id' => $order['delivery']['address']['countryIso'],//US
'region' => $order['delivery']['address']['region'],
'postcode' => $order['delivery']['address']['index'],
'telephone' => $order['phone'],
'save_in_address_book' => 1
),
'items'=> $products
);
$shippings = array_flip(array_filter($shippings));
$payments = array_flip(array_filter($payments));
$ShippingMethods = $this->getAllShippingMethodsCode($shippings[$order['delivery']['code']]);
//Set Address to quote
$quote->getBillingAddress()->addData($orderData['shipping_address']);
$quote->getShippingAddress()->addData($orderData['shipping_address']);
$shippingAddress=$quote->getShippingAddress();
$shippingAddress->setCollectShippingRates(true)
->collectShippingRates()
->setShippingMethod($ShippingMethods);
$quote->setPaymentMethod($payments[$order['paymentType']]);
$quote->setInventoryProcessed(false);
$quote->save();
// Set Sales Order Payment
$quote->getPayment()->importData(['method' => $payments[$order['paymentType']]]);
// Collect Totals & Save Quote
$quote->collectTotals()->save();
// Create Order From Quote
$magentoOrder = $this->_quoteManagement->submit($quote);
try {
$increment_id = $magentoOrder->getRealOrderId();
} catch (\Retailcrm\Retailcrm\Model\ApiClient\Exception\CurlException $e) {
$this->_logger->addDebug($e->getMessage());
}
try {
$response = $this->_api->ordersFixExternalIds(
array(
array(
'id' => $order['id'],
'externalId' =>$increment_id
)
)
);
if (!$response->isSuccessful() || 200 !== $response->getStatusCode()) {
$this->_logger->addDebug(
sprintf(
"Orders fix error: [HTTP status %s] %s",
$response->getStatusCode(),
$response->getErrorMsg()
)
);
if (isset($response['errors'])) {
$this->_logger->addDebug(implode(' :: ', $response['errors']));
}
}
} catch (\Retailcrm\Retailcrm\Model\ApiClient\Exception\CurlException $e) {
$this->_logger->addDebug($e->getMessage());
}
}
/**
* @param array $order
*/
private function doCreateUp($order)
{
$logger = new \Retailcrm\Retailcrm\Model\Logger\Logger();
$logger->write($order,'doCreateUp');
try {
$response = $this->_api->ordersGet($order['id'], $by = 'id');
if ($response->isSuccessful() && 200 === $response->getStatusCode()) {
$order = $response->order;
} else {
$this->_logger->addDebug(
sprintf(
"Orders get error: [HTTP status %s] %s",
$response->getStatusCode(),
$response->getErrorMsg()
)
);
if (isset($response['errors'])) {
$this->_logger->addDebug(implode(' :: ', $response['errors']));
}
}
} catch (Retailcrm_Retailcrm_Model_Exception_CurlException $e) {
$this->_logger->addDebug($e->getMessage());
}
$payments = $this->_config->getValue('retailcrm/Payment');
$shippings = $this->_config->getValue('retailcrm/Shipping');
$om = \Magento\Framework\App\ObjectManager::getInstance();
$manager = $om->get('Magento\Store\Model\StoreManagerInterface');
$store = $manager->getStore();
$websiteId = $manager->getStore()->getWebsiteId();
$customer = $this->_customerFactory->create();
$customer->setWebsiteId($websiteId);
$customer->loadByEmail($order['email']);// load customet by email address
if(!$customer->getEntityId()){
//If not avilable then create this customer
$customer->setWebsiteId($websiteId)
->setStore($store)
->setFirstname($order['firstName'])
->setLastname($order['lastName'])
->setEmail($order['email'])
->setPassword($order['email']);
try {
$customer->save();
} catch (Exception $e) {
$this->_logger->addDebug($e->getMessage());
}
}
//Create object of quote
$quote = $this->_quote->create();
//set store for which you create quote
$quote->setStore($store);
// if you have allready buyer id then you can load customer directly
$customer = $this->_customerRepository->getById($customer->getEntityId());
$quote->setCurrency();
$quote->assignCustomer($customer); //Assign quote to customer
//add items in quote
foreach($order['items'] as $item){
$product = $this->_product->load($item['offer']['externalId']);
$product->setPrice($item['initialPrice']);
$quote->addProduct(
$product,
intval($item['quantity'])
);
}
$products = array();
foreach ($order['items'] as $item) {
$products[$item['offer']['externalId']] = array('qty' => $item['quantity']);
}
$orderData = array(
'currency_id' => 'USD',
'email' => $order['email'],
'shipping_address' =>array(
'firstname' => $order['firstName'],
'lastname' => $order['lastName'],
'street' => $order['delivery']['address']['street'],
'city' => $order['delivery']['address']['city'],
'country_id' => $order['delivery']['address']['countryIso'],//US
'region' => $order['delivery']['address']['region'],
'postcode' => $order['delivery']['address']['index'],
'telephone' => $order['phone'],
'save_in_address_book' => 1
),
'items'=> $products
);
$shippings = array_flip(array_filter($shippings));
$payments = array_flip(array_filter($payments));
$ShippingMethods = $this->getAllShippingMethodsCode($shippings[$order['delivery']['code']]);
//Set Address to quote
$quote->getBillingAddress()->addData($orderData['shipping_address']);
$quote->getShippingAddress()->addData($orderData['shipping_address']);
$shippingAddress=$quote->getShippingAddress();
$shippingAddress->setCollectShippingRates(true)
->collectShippingRates()
->setShippingMethod($ShippingMethods);
$quote->setPaymentMethod($payments[$order['paymentType']]);
$quote->setInventoryProcessed(false);
$originalId = $order['externalId'];
$oldOrder = $this->_order->loadByIncrementId($originalId);
$oldOrderArr = $oldOrder->getData();
if(!empty($oldOrderArr['original_increment_id'])) {
$originalId = $oldOrderArr['original_increment_id'];
}
$orderDataUp = array(
'original_increment_id' => $originalId,
'relation_parent_id' => $oldOrder->getId(),
'relation_parent_real_id' => $oldOrder->getIncrementId(),
'edit_increment' => $oldOrder->getEditIncrement()+1,
'increment_id' => $originalId.'-'.($oldOrder->getEditIncrement()+1)
);
print_r($orderDataUp);
$quote->setReservedOrderId($orderDataUp['increment_id']);
$quote->save();
// Set Sales Order Payment
$quote->getPayment()->importData(['method' => $payments[$order['paymentType']]]);
// Collect Totals & Save Quote
$quote->collectTotals()->save();
// Create Order From Quote
$magentoOrder = $this->_quoteManagement->submit($quote,$orderDataUp);
try {
$increment_id = $magentoOrder->getRealOrderId();
} catch (\Retailcrm\Retailcrm\Model\ApiClient\Exception\CurlException $e) {
$this->_logger->addDebug($e->getMessage());
}
try {
$response = $this->_api->ordersFixExternalIds(
array(
array(
'id' => $order['id'],
'externalId' =>$increment_id
)
)
);
if (!$response->isSuccessful() || 200 !== $response->getStatusCode()) {
$this->_logger->addDebug(
sprintf(
"Orders fix error: [HTTP status %s] %s",
$response->getStatusCode(),
$response->getErrorMsg()
)
);
if (isset($response['errors'])) {
$this->_logger->addDebug(implode(' :: ', $response['errors']));
}
}
} catch (\Retailcrm\Retailcrm\Model\ApiClient\Exception\CurlException $e) {
$this->_logger->addDebug($e->getMessage());
}
}
/**
* @param array $order
*/
private function doUpdate($order)
{
$logger = new \Retailcrm\Retailcrm\Model\Logger\Logger();
$logger->write($order,'doUpdate');
$Status = $this->_config->getValue('retailcrm/Status');
$Status = array_flip(array_filter($Status));
$magentoOrder = $this->_order->loadByIncrementId($order['externalId']);
$magentoOrderArr = $magentoOrder->getData();
$logger->write($magentoOrderArr,'magentoOrderArr');
$logger->write($Status,'status');
if((!empty($order['order_edit']))&&($order['order_edit'] == 1)) {
$this->doCreateUp($order);
}
if (!empty($order['status'])) {
$change = $Status[$order['status']];
if($change == 'canceled'){
$this->_orderManagement->cancel($magentoOrderArr['entity_id']);
}
if($change == 'holded'){
$om = \Magento\Framework\App\ObjectManager::getInstance();
$order_status = $om->get('Magento\Sales\Model\Order')->load($magentoOrder->getId());
$order_status->setStatus('holded');
$order_status->save();
}
if(($change == 'complete')||($order['status']== 'complete')){
$om = \Magento\Framework\App\ObjectManager::getInstance();
$order_status = $om->get('Magento\Sales\Model\Order')->load($magentoOrder->getId());
$order_status->setStatus('complete');
$order_status->save();
}
if($change == 'closed'){
$om = \Magento\Framework\App\ObjectManager::getInstance();
$order_status = $om->get('Magento\Sales\Model\Order')->load($magentoOrder->getId());
$order_status->setStatus('closed');
$order_status->save();
}
if($change == 'processing'){
$om = \Magento\Framework\App\ObjectManager::getInstance();
$order_status = $om->get('Magento\Sales\Model\Order')->load($magentoOrder->getId());
$order_status->setStatus('processing');
$order_status->save();
}
if($change == 'fraud'){
$om = \Magento\Framework\App\ObjectManager::getInstance();
$order_status = $om->get('Magento\Sales\Model\Order')->load($magentoOrder->getId());
$order_status->setStatus('fraud');
$order_status->save();
}
if($change == 'payment_review'){
$om = \Magento\Framework\App\ObjectManager::getInstance();
$order_status = $om->get('Magento\Sales\Model\Order')->load($magentoOrder->getId());
$order_status->setStatus('payment_review');
$order_status->save();
}
if($change == 'paypal_canceled_reversal'){
$om = \Magento\Framework\App\ObjectManager::getInstance();
$order_status = $om->get('Magento\Sales\Model\Order')->load($magentoOrder->getId());
$order_status->setStatus('paypal_canceled_reversal');
$order_status->save();
}
if($change == 'paypal_reversed'){
$om = \Magento\Framework\App\ObjectManager::getInstance();
$order_status = $om->get('Magento\Sales\Model\Order')->load($magentoOrder->getId());
$order_status->setStatus('paypal_reversed');
$order_status->save();
}
if($change == 'pending_payment'){
$om = \Magento\Framework\App\ObjectManager::getInstance();
$order_status = $om->get('Magento\Sales\Model\Order')->load($magentoOrder->getId());
$order_status->setStatus('pending_payment');
$order_status->save();
}
if($change == 'pending_paypal'){
$om = \Magento\Framework\App\ObjectManager::getInstance();
$order_status = $om->get('Magento\Sales\Model\Order')->load($magentoOrder->getId());
$order_status->setStatus('pending_paypal');
$order_status->save();
}
}
}
public static function assemblyOrder($orderHistory)
{
$orders = array();
foreach ($orderHistory as $change) {
$change['order'] = self::removeEmpty($change['order']);
if(isset($change['order']['items'])) {
$items = array();
foreach($change['order']['items'] as $item) {
if(isset($change['created'])) {
$item['create'] = 1;
}
$items[$item['id']] = $item;
}
$change['order']['items'] = $items;
}
$logger = new \Retailcrm\Retailcrm\Model\Logger\Logger();
$logger->write($change,'retailcrmHistoryAssemblyOrder');
if(isset($change['order']['contragent']['contragentType'])) {
$change['order']['contragentType'] = self::newValue($change['order']['contragent']['contragentType']);
unset($change['order']['contragent']);
}
if(isset($orders[$change['order']['id']])) {
$orders[$change['order']['id']] = array_merge($orders[$change['order']['id']], $change['order']);
}
else {
$orders[$change['order']['id']] = $change['order'];
}
if($change['field'] == 'manager_comment'){
$orders[$change['order']['id']][$change['field']] = $change['newValue'];
}
if(($change['field'] != 'status')&&
($change['field'] != 'country')&&
($change['field'] != 'manager_comment')&&
($change['field'] != 'order_product.status')&&
($change['field'] != 'payment_status')&&
($change['field'] != 'prepay_sum')
) {
$orders[$change['order']['id']]['order_edit'] = 1;
}
if(isset($change['item'])) {
if($orders[$change['order']['id']]['items'][$change['item']['id']]) {
$orders[$change['order']['id']]['items'][$change['item']['id']] = array_merge($orders[$change['order']['id']]['items'][$change['item']['id']], $change['item']);
}
else{
$orders[$change['order']['id']]['items'][$change['item']['id']] = $change['item'];
}
if(empty($change['oldValue']) && $change['field'] == 'order_product') {
$orders[$change['order']['id']]['items'][$change['item']['id']]['create'] = 1;
$orders[$change['order']['id']]['order_edit'] = 1;
unset($orders[$change['order']['id']]['items'][$change['item']['id']]['delete']);
}
if(empty($change['newValue']) && $change['field'] == 'order_product') {
$orders[$change['order']['id']]['items'][$change['item']['id']]['delete'] = 1;
$orders[$change['order']['id']]['order_edit'] = 1;
}
if(!empty($change['newValue']) && $change['field'] == 'order_product.quantity') {
$orders[$change['order']['id']]['order_edit'] = 1;
}
if(!$orders[$change['order']['id']]['items'][$change['item']['id']]['create'] && $fields['item'][$change['field']]) {
$orders[$change['order']['id']]['items'][$change['item']['id']][$fields['item'][$change['field']]] = $change['newValue'];
}
}
else {
if((isset($fields['delivery'][$change['field']]))&&($fields['delivery'][$change['field']] == 'service')) {
$orders[$change['order']['id']]['delivery']['service']['code'] = self::newValue($change['newValue']);
}
elseif(isset($fields['delivery'][$change['field']])) {
$orders[$change['order']['id']]['delivery'][$fields['delivery'][$change['field']]] = self::newValue($change['newValue']);
}
elseif(isset($fields['orderAddress'][$change['field']])) {
$orders[$change['order']['id']]['delivery']['address'][$fields['orderAddress'][$change['field']]] = $change['newValue'];
}
elseif(isset($fields['integrationDelivery'][$change['field']])) {
$orders[$change['order']['id']]['delivery']['service'][$fields['integrationDelivery'][$change['field']]] = self::newValue($change['newValue']);
}
elseif(isset($fields['customerContragent'][$change['field']])) {
$orders[$change['order']['id']][$fields['customerContragent'][$change['field']]] = self::newValue($change['newValue']);
}
elseif(strripos($change['field'], 'custom_') !== false) {
$orders[$change['order']['id']]['customFields'][str_replace('custom_', '', $change['field'])] = self::newValue($change['newValue']);
}
elseif(isset($fields['order'][$change['field']])) {
$orders[$change['order']['id']][$fields['order'][$change['field']]] = self::newValue($change['newValue']);
}
if(isset($change['created'])) {
$orders[$change['order']['id']]['create'] = 1;
}
if(isset($change['deleted'])) {
$orders[$change['order']['id']]['deleted'] = 1;
}
}
}
return $orders;
}
public static function removeEmpty($inputArray)
{
$outputArray = array();
if (!empty($inputArray)) {
foreach ($inputArray as $key => $element) {
if(!empty($element) || $element === 0 || $element === '0') {
if (is_array($element)) {
$element = self::removeEmpty($element);
}
$outputArray[$key] = $element;
}
}
}
return $outputArray;
}
public static function newValue($value)
{
if(isset($value['code'])) {
return $value['code'];
} else{
return $value;
}
}
public function getAllShippingMethodsCode($mcode)
{
$activeCarriers = $this->_shipconfig->getActiveCarriers();
$storeScope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE;
foreach($activeCarriers as $carrierCode => $carrierModel)
{
$options = array();
if( $carrierMethods = $carrierModel->getAllowedMethods()) {
foreach ($carrierMethods as $methodCode => $method) {
$code= $carrierCode.'_'.$methodCode;
if($mcode == $carrierCode){
$methods[$mcode] = $code;
}
}
}
}
return $methods[$mcode];
}
}

292
Model/Icml/Icml.php Normal file
View File

@ -0,0 +1,292 @@
<?php
namespace Retailcrm\Retailcrm\Model\Icml;
class Icml
{
protected $_dd;
protected $_eCategories;
protected $_eOffers;
protected $_shop;
protected $_manager;
protected $_category;
protected $_product;
protected $_storeManager;
protected $_StockState;
protected $_configurable;
protected $_config;
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;
}
public function generate()
{
$this->_shop = $this->_manager->getStore()->getId();
$string = '<?xml version="1.0" encoding="UTF-8"?>
<yml_catalog date="'.date('Y-m-d H:i:s').'">
<shop>
<name>'.$this->_manager->getStore()->getName().'</name>
<categories/>
<offers/>
</shop>
</yml_catalog>
';
$xml = new \SimpleXMLElement(
$string,
LIBXML_NOENT | LIBXML_NOCDATA | LIBXML_COMPACT | LIBXML_PARSEHUGE
);
$this->_dd = new \DOMDocument();
$this->_dd->preserveWhiteSpace = false;
$this->_dd->formatOutput = true;
$this->_dd->loadXML($xml->asXML());
$this->_eCategories = $this->_dd->
getElementsByTagName('categories')->item(0);
$this->_eOffers = $this->_dd
->getElementsByTagName('offers')->item(0);
$this->addCategories();
$this->addOffers();
$this->_dd->saveXML();
$dirlist = new \Magento\Framework\Filesystem\DirectoryList('');
$baseDir = $dirlist->getRoot();
$shopCode = $this->_manager->getStore()->getCode();
$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());
}
}
}
}
private function addOffers()
{
$offers = array();
$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);
}
}
}
}
}

29
Model/Logger/Logger.php Normal file
View File

@ -0,0 +1,29 @@
<?php
namespace Retailcrm\Retailcrm\Model\Logger;
class Logger
{
private $logPath;
private $files;
public function __construct(
$logPath = '/app/code/Retailcrm/Retailcrm/Log/'
)
{
$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);
}
}

View File

@ -0,0 +1,59 @@
<?php
namespace Retailcrm\Retailcrm\Model\Observer;
use Magento\Framework\Event\Observer;
class Customer implements \Magento\Framework\Event\ObserverInterface
{
protected $_api;
protected $_config;
protected $_helper;
protected $_logger;
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');
}
}

View File

@ -0,0 +1,180 @@
<?php
namespace Retailcrm\Retailcrm\Model\Observer;
use Magento\Framework\Event\Observer;
class OrderCreate implements \Magento\Framework\Event\ObserverInterface
{
protected $_api;
protected $_objectManager;
protected $_config;
protected $_helper;
protected $_logger;
protected $_configurable;
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(),
'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;
}
protected function getShippingCode($string)
{
$split = array_values(explode('_', $string));
$length = count($split);
$prepare = array_slice($split, 0, $length/2);
return implode('_', $prepare);
}
}

View File

@ -0,0 +1,56 @@
<?php
namespace Retailcrm\Retailcrm\Model\Observer;
use Magento\Framework\Event\Observer;
class OrderUpdate implements \Magento\Framework\Event\ObserverInterface
{
protected $_api;
protected $_config;
protected $_helper;
protected $_logger;
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);
}
}
}

168
Model/Order/OrderNumber.php Normal file
View File

@ -0,0 +1,168 @@
<?php
namespace Retailcrm\Retailcrm\Model\Order;
use \Retailcrm\Retailcrm\Observer;
//use Psr\Log\LoggerInterface;
class OrderNumber extends \Retailcrm\Retailcrm\Model\Observer\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;
$this->_searchCriteriaBuilder = $searchCriteriaBuilder;
$this->_config = $config;
$this->_filterBuilder = $filterBuilder;
$this->_order = $order;
$this->_helper = $helper;
$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 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);
}
}

View File

@ -0,0 +1,37 @@
<?php
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;
}
}

View File

@ -0,0 +1,48 @@
<?php
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;
}
}

20
Model/Setting/Status.php Normal file
View File

@ -0,0 +1,20 @@
<?php
namespace Retailcrm\Retailcrm\Model\Setting;
class Status extends \Magento\Config\Model\Config\Backend\Serialized\ArraySerialized
{
public function beforeSave()
{
// For value validations
$exceptions = $this->getValue();
// Validations
$this->setValue($exceptions);
return parent::beforeSave();
}
}

View File

@ -1,13 +1,13 @@
Magento module
==============
Magento module for interaction with [RetailCRM](http://www.retailcrm.ru) through [REST API](http://retailcrm.ru/docs/Разработчики).
Magento module for interaction with [RetailCRM](http://www.retailcrm.ru) through [REST API](http://www.retailcrm.ru/docs/Developers/Index).
Module allows:
* Exchange the orders with retailCRM
* Configure relations between dictionaries of RetailCRM and Magento (statuses, payments, delivery types and etc)
* Generate [ICML](http://docs.retailcrm.ru/index.php?n=Разработчики.ФорматICML) (Intaro Markup Language) for catalog loading by RetailCRM
* Generate [ICML](http://www.retailcrm.ru/docs/Developers/ICML) (Intaro Markup Language) for catalog loading by RetailCRM
ICML

View File

@ -1,51 +0,0 @@
<?php
class Retailcrm_Retailcrm_Block_Adminhtml_System_Config_Form_Button extends Mage_Adminhtml_Block_System_Config_Form_Field
{
/**
* Set template
*/
protected function _construct()
{
parent::_construct();
$this->setTemplate('retailcrm/system/config/button.phtml');
}
/**
* Return element html
*
* @param Varien_Data_Form_Element_Abstract $element
* @return string
*/
protected function _getElementHtml(Varien_Data_Form_Element_Abstract $element)
{
return $this->_toHtml();
}
/**
* Return ajax url for button
*
* @return string
*/
public function getAjaxCheckUrl()
{
return Mage::helper('adminhtml')->getUrl('adminhtml/adminhtml_Retailcrmbutton/check');
}
/**
* Generate button html
*
* @return string
*/
public function getButtonHtml()
{
$button = $this->getLayout()->createBlock('adminhtml/widget_button')
->setData(
array(
'id' => 'Retailcrmbutton_button',
'label' => $this->helper('adminhtml')->__('Run now'),
'onclick' => 'javascript:check(); return false;'
)
);
return $button->toHtml();
}
}

View File

@ -1,43 +0,0 @@
<?php
class Retailcrm_Retailcrm_Block_Adminhtml_System_Config_Form_Fieldset_Base extends Mage_Adminhtml_Block_System_Config_Form_Fieldset
{
protected $_fieldRenderer;
protected $_values;
protected $_apiKey;
protected $_apiUrl;
protected $_isCredentialCorrect;
public function __construct()
{
parent::__construct();
$this->_apiUrl = Mage::getStoreConfig('retailcrm/general/api_url');
$this->_apiKey = Mage::getStoreConfig('retailcrm/general/api_key');
$this->_isCredentialCorrect = false;
if (!empty($this->_apiUrl) && !empty($this->_apiKey)) {
if (false === stripos($this->_apiUrl, 'https://')) {
$this->_apiUrl = str_replace("http://", "https://", $this->_apiUrl);
Mage::getModel('core/config')->saveConfig('retailcrm/general/api_url', $this->_apiUrl);
}
$client = new Retailcrm_Retailcrm_Model_ApiClient(
$this->_apiUrl,
$this->_apiKey
);
try {
$response = $client->sitesList();
} catch (Retailcrm_Retailcrm_Model_Exception_CurlException $e) {
Mage::log($e->getMessage());
}
if ($response->isSuccessful()) {
$this->_isCredentialCorrect = true;
if($response['success'] != 1) {
Mage::getModel('core/config')->saveConfig('retailcrm/general/api_url', '');
}
}
}
}
}

View File

@ -1,10 +0,0 @@
<?php
class Retailcrm_Retailcrm_Block_Adminhtml_System_Config_Form_Fieldset_Order extends Mage_Adminhtml_Block_System_Config_Form_Fieldset
{
protected $_numberOrder;
public function __construct()
{
}
}

View File

@ -1,89 +0,0 @@
<?php
class Retailcrm_Retailcrm_Block_Adminhtml_System_Config_Form_Fieldset_Payment extends Retailcrm_Retailcrm_Block_Adminhtml_System_Config_Form_Fieldset_Base
{
public function render(Varien_Data_Form_Element_Abstract $element)
{
$html = $this->_getHeaderHtml($element);
if(!empty($this->_apiUrl) && !empty($this->_apiKey) && $this->_isCredentialCorrect) {
$groups = Mage::getSingleton('payment/config')->getActiveMethods();
foreach ($groups as $group) {
$html .= $this->_getFieldHtml($element, $group);
}
} else {
$html .= '<div style="margin-left: 15px;"><b><i>Please check your API Url & API Key</i></b></div>';
}
$html .= $this->_getFooterHtml($element);
return $html;
}
protected function _getFieldRenderer()
{
if (empty($this->_fieldRenderer)) {
$this->_fieldRenderer = Mage::getBlockSingleton('adminhtml/system_config_form_field');
}
return $this->_fieldRenderer;
}
/**
* @return array
*/
protected function _getValues()
{
if(!empty($this->_apiUrl) && !empty($this->_apiKey) && $this->_isCredentialCorrect) {
$client = new Retailcrm_Retailcrm_Model_ApiClient(
$this->_apiUrl,
$this->_apiKey
);
try {
$paymentTypes = $client->paymentTypesList();
} catch (Retailcrm_Retailcrm_Model_Exception_CurlException $e) {
Mage::log($e->getMessage());
}
if ($paymentTypes->isSuccessful()) {
if (empty($this->_values)) {
foreach ($paymentTypes['paymentTypes'] as $type) {
$this->_values[] = array('label' => Mage::helper('adminhtml')->__($type['name']), 'value' => $type['code']);
}
}
}
}
return $this->_values;
}
protected function _getFieldHtml($fieldset, $group)
{
$configData = $this->getConfigData();
$path = 'retailcrm/payment/' . $group->getId();
if (isset($configData[$path])) {
$data = $configData[$path];
$inherit = false;
} else {
$data = (int)(string)$this->getForm()->getConfigRoot()->descend($path);
$inherit = true;
}
$field = $fieldset->addField(
'payment_' . $group->getId(), 'select',
array(
'name' => 'groups[payment][fields]['.$group->getId().'][value]',
'label' => Mage::getStoreConfig('payment/'.$group->getId().'/title'),
'value' => $data,
'values' => $this->_getValues(),
'inherit' => $inherit,
'can_use_default_value' => 1,
'can_use_website_value' => 1
)
)->setRenderer($this->_getFieldRenderer());
return $field->toHtml();
}
}

View File

@ -1,89 +0,0 @@
<?php
class Retailcrm_Retailcrm_Block_Adminhtml_System_Config_Form_Fieldset_Shipping extends Retailcrm_Retailcrm_Block_Adminhtml_System_Config_Form_Fieldset_Base
{
public function render(Varien_Data_Form_Element_Abstract $element)
{
$html = $this->_getHeaderHtml($element);
if(!empty($this->_apiUrl) && !empty($this->_apiKey) && $this->_isCredentialCorrect) {
$groups = Mage::getSingleton('shipping/config')->getActiveCarriers();
foreach ($groups as $group) {
$html .= $this->_getFieldHtml($element, $group);
}
} else {
$html .= '<div style="margin-left: 15px;"><b><i>Please check your API Url & API Key</i></b></div>';
}
$html .= $this->_getFooterHtml($element);
return $html;
}
protected function _getFieldRenderer()
{
if (empty($this->_fieldRenderer)) {
$this->_fieldRenderer = Mage::getBlockSingleton('adminhtml/system_config_form_field');
}
return $this->_fieldRenderer;
}
/**
* @return array
*/
protected function _getValues()
{
if(!empty($this->_apiUrl) && !empty($this->_apiKey) && $this->_isCredentialCorrect) {
$client = new Retailcrm_Retailcrm_Model_ApiClient(
$this->_apiUrl,
$this->_apiKey
);
try {
$deliveryTypes = $client->deliveryTypesList();
} catch (Retailcrm_Retailcrm_Model_Exception_CurlException $e) {
Mage::log($e->getMessage());
}
if ($deliveryTypes->isSuccessful()) {
if (empty($this->_values)) {
foreach ($deliveryTypes['deliveryTypes'] as $type) {
$this->_values[] = array('label'=>Mage::helper('adminhtml')->__($type['name']), 'value'=>$type['code']);
}
}
}
}
return $this->_values;
}
protected function _getFieldHtml($fieldset, $group)
{
$configData = $this->getConfigData();
$path = 'retailcrm/shipping/' . $group->getId();
if (isset($configData[$path])) {
$data = $configData[$path];
$inherit = false;
} else {
$data = (int)(string)$this->getForm()->getConfigRoot()->descend($path);
$inherit = true;
}
$field = $fieldset->addField(
'shipping_' . $group->getId(), 'select',
array(
'name' => 'groups[shipping][fields]['.$group->getId().'][value]',
'label' => Mage::getStoreConfig('carriers/'.$group->getId().'/title'),
'value' => $data,
'values' => $this->_getValues(),
'inherit' => $inherit,
'can_use_default_value' => 1,
'can_use_website_value' => 1
)
)->setRenderer($this->_getFieldRenderer());
return $field->toHtml();
}
}

View File

@ -1,89 +0,0 @@
<?php
class Retailcrm_Retailcrm_Block_Adminhtml_System_Config_Form_Fieldset_Status extends Retailcrm_Retailcrm_Block_Adminhtml_System_Config_Form_Fieldset_Base
{
public function render(Varien_Data_Form_Element_Abstract $element)
{
$html = $this->_getHeaderHtml($element);
if(!empty($this->_apiUrl) && !empty($this->_apiKey) && $this->_isCredentialCorrect) {
$statuses = Mage::getModel('sales/order_status')->getResourceCollection()->getData();
foreach ($statuses as $status) {
$html .= $this->_getFieldHtml($element, $status);
}
} else {
$html .= '<div style="margin-left: 15px;"><b><i>Please check your API Url & API Key</i></b></div>';
}
$html .= $this->_getFooterHtml($element);
return $html;
}
protected function _getFieldRenderer()
{
if (empty($this->_fieldRenderer)) {
$this->_fieldRenderer = Mage::getBlockSingleton('adminhtml/system_config_form_field');
}
return $this->_fieldRenderer;
}
/**
* @return array
*/
protected function _getValues()
{
if(!empty($this->_apiUrl) && !empty($this->_apiKey) && $this->_isCredentialCorrect) {
$client = new Retailcrm_Retailcrm_Model_ApiClient(
$this->_apiUrl,
$this->_apiKey
);
try {
$statuses = $client->statusesList();
} catch (Retailcrm_Retailcrm_Model_Exception_CurlException $e) {
Mage::log($e->getMessage());
}
if ($statuses->isSuccessful()) {
if (empty($this->_values)) {
foreach ($statuses['statuses'] as $status) {
$this->_values[] = array('label'=>Mage::helper('adminhtml')->__($status['name']), 'value'=>$status['code']);
}
}
}
}
return $this->_values;
}
protected function _getFieldHtml($fieldset, $group)
{
$configData = $this->getConfigData();
$path = 'retailcrm/status/' . $group['status'];
if (isset($configData[$path])) {
$data = $configData[$path];
$inherit = false;
} else {
$data = (int)(string)$this->getForm()->getConfigRoot()->descend($path);
$inherit = true;
}
$field = $fieldset->addField(
'status_' . $group['status'], 'select',
array(
'name' => 'groups[status][fields]['.$group['status'].'][value]',
'label' => $group['label'],
'value' => $data,
'values' => $this->_getValues(),
'inherit' => $inherit,
'can_use_default_value' => 1,
'can_use_website_value' => 1
)
)->setRenderer($this->_getFieldRenderer());
return $field->toHtml();
}
}

View File

@ -1,176 +0,0 @@
<?php
/**
* Default extension helper class
* PHP version 5.3
*
* @category Model
* @package RetailCrm\Model
* @author RetailDriver LLC <integration@retailcrm.ru>
* @license http://opensource.org/licenses/MIT MIT License
* @link http://www.magentocommerce.com/magento-connect/retailcrm-1.html
*/
/**
* Data helper class
*
* @category Model
* @package RetailCrm\Model
* @author RetailDriver LLC <integration@retailcrm.ru>
* @license http://opensource.org/licenses/MIT MIT License
* @link http://www.magentocommerce.com/magento-connect/retailcrm-1.html
*
* @SuppressWarnings(PHPMD.CamelCaseClassName)
*/
class Retailcrm_Retailcrm_Helper_Data extends Mage_Core_Helper_Abstract
{
/**
* Path to store config if front-end output is enabled
*
* @var string
*/
const XML_API_URL = 'retailcrm/general/api_url';
/**
* Path to store config where count of news posts per page is stored
*
* @var string
*/
const XML_API_KEY = 'retailcrm/general/api_key';
/**
* Get api url
*
* @param Mage_Core_Model_Store $store store instance
*
* @SuppressWarnings(PHPMD.StaticAccess)
*
* @return int
*/
public function getApiUrl($store = null)
{
return abs((int)Mage::getStoreConfig(self::XML_API_URL, $store));
}
/**
* Get api key
*
* @param Mage_Core_Model_Store $store store instance
*
* @SuppressWarnings(PHPMD.StaticAccess)
*
* @return int
*/
public function getApiKey($store = null)
{
return abs((int)Mage::getStoreConfig(self::XML_API_KEY, $store));
}
/**
* Get api key
*
* @param string $baseUrl base url
* @param mixed $coreUrl url rewritte
* @param integer $productId product id
* @param integer $storeId product store id
* @param integer $categoryId product category id
*
* @SuppressWarnings(PHPMD.StaticAccess)
*
* @return string
*/
public function rewrittenProductUrl($baseUrl,$coreUrl,$productId,$storeId,$categoryId = null)
{
$idPath = sprintf('product/%d', $productId);
if ($categoryId) {
$idPath = sprintf('%s/%d', $idPath, $categoryId);
}
$coreUrl->setStoreId($storeId);
$coreUrl->loadByIdPath($idPath);
return $baseUrl . $coreUrl->getRequestPath();
}
/**
* Get country code
*
* @param string $string country iso code
*
* @SuppressWarnings(PHPMD.StaticAccess)
*
* @return string
*/
public function getCountryCode($string)
{
$country = empty($string) ? 'RU' : $string;
$xmlObj = new Varien_Simplexml_Config(
sprintf(
"%s%s%s",
Mage::getModuleDir('etc', 'Retailcrm_Retailcrm'),
DS,
'country.xml'
)
);
$xmlData = $xmlObj->getNode();
if ($country != 'RU') {
foreach ($xmlData as $elem) {
if ($elem->name == $country || $elem->english == $country) {
$country = $elem->alpha;
break;
}
}
}
return (string) $country;
}
/**
* Get exchage time
*
* @param string $datetime datetime string
*
* @return \DateTime
*/
public function getExchangeTime($datetime)
{
return $datetime = empty($datetime)
? new DateTime(
date(
'Y-m-d H:i:s',
strtotime('-1 days', strtotime(date('Y-m-d H:i:s')))
)
)
: new DateTime($datetime);
}
/**
* Recursive array filter
*
* @param array $haystack input array
*
* @SuppressWarnings(PHPMD.StaticAccess)
* @SuppressWarnings(PHPMD.ElseExpression)
*
* @return array
*/
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;
}
}

View File

@ -1,43 +0,0 @@
<?php
class Retailcrm_Retailcrm_Model_Attribute
{
/**
* Options getter
*
* @return array
*/
public function toOptionArray()
{
$attributes = Mage::getResourceModel('catalog/product_attribute_collection')
->getItems();
$data = array();
foreach($attributes as $attribute) {
if(empty($attribute->getFrontendLabel())) continue;
$data[] = array(
'label' => $attribute->getFrontendLabel(),
'value' => $attribute->getAttributeCode()
);
}
return $data;
}
/**
* Get options in "key-value" format
*
* @return array
*/
public function toArray()
{
return array();
return array(
0 => Mage::helper('adminhtml')->__('Data1'),
1 => Mage::helper('adminhtml')->__('Data2'),
2 => Mage::helper('adminhtml')->__('Data3'),
);
}
}

View File

@ -1,75 +0,0 @@
<?php
/**
* Customer class
*
* @category Model
* @package RetailCrm\Model
* @author RetailDriver LLC <integration@retailcrm.ru>
* @license http://opensource.org/licenses/MIT MIT License
* @link http://www.magentocommerce.com/magento-connect/retailcrm-1.html
*
* @SuppressWarnings(PHPMD.CamelCaseClassName)
*/
class Retailcrm_Retailcrm_Model_Customer extends Retailcrm_Retailcrm_Model_Exchange
{
/**
* Customer create
*
* @SuppressWarnings(PHPMD.StaticAccess)
* @SuppressWarnings(PHPMD.ElseExpression)
* @param mixed $data
*
* @return bool
*/
public function customerRegister($data)
{
$customer = array(
'externalId' => $data->getId(),
'email' => $data->getEmail(),
'firstName' => $data->getFirstname(),
'patronymic' => $data->getMiddlename(),
'lastName' => $data->getLastname(),
'createdAt' => Mage::getSingleton('core/date')->date()
);
$this->_api->customersEdit($customer);
}
/**
* Customers export
*
* @SuppressWarnings(PHPMD.StaticAccess)
* @SuppressWarnings(PHPMD.ElseExpression)
*
* @return bool
*/
public function customersExport()
{
$customers = array();
$customerCollection = Mage::getModel('customer/customer')
->getCollection()
->addAttributeToSelect('email')
->addAttributeToSelect('firstname')
->addAttributeToSelect('lastname');
foreach ($customerCollection as $customerData) {
$customer = array(
'externalId' => $customerData->getId(),
'email' => $customerData->getData('email'),
'firstName' => $customerData->getData('firstname'),
'lastName' => $customerData->getData('lastname')
);
$customers[] = $customer;
}
unset($customerCollection);
$chunked = array_chunk($customers, 50);
unset($customers);
foreach ($chunked as $chunk) {
$this->_api->customersUpload($chunk);
time_nanosleep(0, 250000000);
}
unset($chunked);
return true;
}
}

View File

@ -1,5 +0,0 @@
<?php
class Retailcrm_Retailcrm_Model_Exception_CurlException extends RuntimeException
{
}

View File

@ -1,5 +0,0 @@
<?php
class Retailcrm_Retailcrm_Model_Exception_InvalidJsonException extends DomainException
{
}

View File

@ -1,981 +0,0 @@
<?php
class Retailcrm_Retailcrm_Model_Exchange
{
protected $_apiKey;
protected $_apiUrl;
protected $_config;
protected $_api;
public function __construct()
{
$this->_apiUrl = Mage::getStoreConfig('retailcrm/general/api_url');
$this->_apiKey = Mage::getStoreConfig('retailcrm/general/api_key');
if(!empty($this->_apiUrl) && !empty($this->_apiKey)) {
$this->_api = new Retailcrm_Retailcrm_Model_ApiClient(
$this->_apiUrl,
$this->_apiKey
);
}
}
/**
* Get orders history & modify orders into shop
*
*/
public function ordersHistory()
{
$runTime = $this->getExchangeTime($this->_config['general']['history']);
$historyFilter = array();
$historiOrder = array();
$historyStart = Mage::getStoreConfig('retailcrm/general/fhistory');
if($historyStart && $historyStart > 0) {
$historyFilter['sinceId'] = $historyStart;
}
while(true) {
try {
$response = $this->_api->ordersHistory($historyFilter);
if ($response->isSuccessful()&&200 === $response->getStatusCode()) {
$nowTime = $response->getGeneratedAt();
} else {
Mage::log(
sprintf("Orders history error: [HTTP status %s] %s", $response->getStatusCode(), $response->getErrorMsg())
);
if (isset($response['errors'])) {
Mage::log(implode(' :: ', $response['errors']));
}
return false;
}
} catch (Retailcrm_Retailcrm_Model_Exception_CurlException $e) {
Mage::log($e->getMessage());
return false;
}
$orderH = isset($response['history']) ? $response['history'] : array();
if(count($orderH) == 0) {
return true;
}
$historiOrder = array_merge($historiOrder, $orderH);
$end = array_pop($response->history);
$historyFilter['sinceId'] = $end['id'];
if($response['pagination']['totalPageCount'] == 1) {
Mage::getModel('core/config')->saveConfig('retailcrm/general/fhistory', $historyFilter['sinceId']);
$orders = self::assemblyOrder($historiOrder);
$this->processOrders($orders, $nowTime);
return true;
}
}//endwhile
}
/**
* @param array $orders
*/
private function processOrders($orders, $time)
{
if(!empty($orders)) {
Mage::getModel('core/config')->saveConfig(
'retailcrm/general/history', $time
);
foreach ($orders as $order) {
if(!empty($order['externalId'])) {
$this->doUpdate($order);
} else {
$this->doCreate($order);
}
}
die();
}
}
/**
* @param array $order
*/
private function doCreate($order)
{
Mage::log($order, null, 'retailcrmHistoriCreate.log', true);
try {
$response = $this->_api->ordersGet($order['id'], $by = 'id');
if ($response->isSuccessful() && 200 === $response->getStatusCode()) {
$order = $response->order;
} else {
Mage::log(
sprintf(
"Orders get error: [HTTP status %s] %s",
$response->getStatusCode(),
$response->getErrorMsg()
)
);
if (isset($response['errors'])) {
Mage::log(implode(' :: ', $response['errors']));
}
}
} catch (Retailcrm_Retailcrm_Model_Exception_CurlException $e) {
Mage::log($e->getMessage());
}
// get references
$this->_config = Mage::getStoreConfig('retailcrm');
$payments = array_flip(array_filter($this->_config['payment']));
$shippings = array_flip(array_filter($this->_config['shipping']));
// get store
$_sendConfirmation = '0';
$storeId = Mage::app()->getStore()->getId();
$siteid = Mage::getModel('core/store')->load($storeId)->getWebsiteId();
// search or create customer
$customer = Mage::getSingleton('customer/customer');
$customer->setWebsiteId($siteid);
$customer->loadByEmail($order['email']);
if (!is_numeric($customer->getId())) {
$customer
->setGropuId(1)
->setWebsiteId($siteid)
->setStore($storeId)
->setEmail($order['email'])
->setFirstname($order['firstName'])
->setLastname($order['lastName'])
->setMiddleName($order['patronymic'])
->setPassword(uniqid());
try {
$customer->save();
$customer->setConfirmation(null);
$customer->save();
} catch (Exception $e) {
Mage::log($e->getMessage());
}
$address = Mage::getModel("customer/address");
$address->setCustomerId($customer->getId())
->setFirstname($customer->getFirstname())
->setMiddleName($customer->getMiddlename())
->setLastname($customer->getLastname())
->setCountryId($this->getCountryCode($order['customer']['address']['country']))
->setPostcode($order['delivery']['address']['index'])
->setCity($order['delivery']['address']['city'])
->setRegion($order['delivery']['address']['region'])
->setTelephone($order['phone'])
->setStreet($order['delivery']['address']['street'])
->setIsDefaultBilling('1')
->setIsDefaultShipping('1')
->setSaveInAddressBook('1');
try{
$address->save();
}
catch (Exception $e) {
Mage::log($e->getMessage());
}
try {
$response = $this->_api->customersFixExternalIds(
array(
'id' => $order['customer']['id'],
'externalId' => $customer->getId()
)
);
if (!$response->isSuccessful() || 200 !== $response->getStatusCode()) {
Mage::log(
sprintf(
"Orders fix error: [HTTP status %s] %s",
$response->getStatusCode(),
$response->getErrorMsg()
)
);
if (isset($response['errors'])) {
Mage::log(implode(' :: ', $response['errors']));
}
}
} catch (Retailcrm_Retailcrm_Model_Exception_CurlException $e) {
Mage::log($e->getMessage());
}
}
$products = array();
foreach ($order['items'] as $item) {
$products[$item['offer']['externalId']] = array('qty' => $item['quantity']);
}
$orderData = array(
'session' => array(
'customer_id' => $customer->getId(),
'store_id' => $storeId,
),
'payment' => array(
'method' => $payments[$order['paymentType']],
),
'add_products' => $products,
'order' => array(
'account' => array(
'group_id' => $customer->getGroupId(),
'email' => $order['email']
),
'billing_address' => array(
'firstname' => $order['firstName'],
'middlename' => $order['patronymic'],
'lastname' => $order['lastName'],
'street' => $order['delivery']['address']['street'],
'city' => $order['delivery']['address']['city'],
'country_id' => $this->getCountryCode($order['customer']['address']['country']),
'region' => $order['delivery']['address']['region'],
'postcode' => $order['delivery']['address']['index'],
'telephone' => $order['phone'],
),
'shipping_address' => array(
'firstname' => $order['firstName'],
'middlename' => $order['patronymic'],
'lastname' => $order['lastName'],
'street' => $order['delivery']['address']['street'],
'city' => $order['delivery']['address']['city'],
'country_id' => $this->getCountryCode($order['customer']['address']['country']),
'region' => $order['delivery']['address']['region'],
'postcode' => $order['delivery']['address']['index'],
'telephone' => $order['phone'],
),
'shipping_method' => $shippings[$order['delivery']['code']],
'comment' => array(
'customer_note' => $order['customerComment'],
),
'send_confirmation' => $_sendConfirmation
)
);
Mage::unregister('sales_order_place_after');
Mage::register('sales_order_place_after', 1);
$quote = Mage::getModel('sales/quote')->setStoreId($storeId);
$quote->assignCustomer($customer);
$quote->setSendCconfirmation($_sendConfirmation);
foreach($products as $idx => $val) {
$product = Mage::getModel('catalog/product')->load($idx);
$quote->addProduct($product, new Varien_Object($val));
}
$shipping_method = self::getAllShippingMethodsCode($orderData['order']['shipping_method']);
$billingAddress = $quote->getBillingAddress()->addData($orderData['order']['billing_address']);
$shippingAddress = $quote->getShippingAddress()->addData($orderData['order']['shipping_address']);
$shippingAddress->setCollectShippingRates(true)
->collectShippingRates()
->setShippingMethod($shipping_method)
->setPaymentMethod($orderData['payment']['method']);
$quote->getPayment()->importData($orderData['payment']);
$quote->collectTotals();
$quote->reserveOrderId();
$quote->save();
$service = Mage::getModel('sales/service_quote', $quote);
try{
$service->submitAll();
}
catch (Exception $e) {
Mage::log($e->getMessage());
}
try {
$response = $this->_api->ordersFixExternalIds(
array(
array(
'id' => $order['id'],
'externalId' =>$service->getOrder()->getRealOrderId()
)
)
);
if (!$response->isSuccessful() || 200 !== $response->getStatusCode()) {
Mage::log(
sprintf(
"Orders fix error: [HTTP status %s] %s",
$response->getStatusCode(),
$response->getErrorMsg()
)
);
if (isset($response['errors'])) {
Mage::log(implode(' :: ', $response['errors']));
}
}
} catch (Retailcrm_Retailcrm_Model_Exception_CurlException $e) {
Mage::log($e->getMessage());
}
}
/**
* @param array $order
*/
private function doCreateUp($order)
{
Mage::log($order, null, 'retailcrmHistoriCreateUp.log', true);
try {
$response = $this->_api->ordersGet($order['id'], $by = 'id');
if ($response->isSuccessful() && 200 === $response->getStatusCode()) {
$order = $response->order;
} else {
Mage::log(
sprintf(
"Orders get error: [HTTP status %s] %s",
$response->getStatusCode(),
$response->getErrorMsg()
)
);
if (isset($response['errors'])) {
Mage::log(implode(' :: ', $response['errors']));
}
}
} catch (Retailcrm_Retailcrm_Model_Exception_CurlException $e) {
Mage::log($e->getMessage());
}
// get references
$this->_config = Mage::getStoreConfig('retailcrm');
$payments = array_flip(array_filter($this->_config['payment']));
$shippings = array_flip(array_filter($this->_config['shipping']));
// get store
$_sendConfirmation = '0';
$storeId = Mage::app()->getStore()->getId();
$siteid = Mage::getModel('core/store')->load($storeId)->getWebsiteId();
// search or create customer
$customer = Mage::getSingleton('customer/customer');
$customer->setWebsiteId($siteid);
$customer->loadByEmail($order['email']);
if (!is_numeric($customer->getId())) {
$customer
->setGropuId(1)
->setWebsiteId($siteid)
->setStore($storeId)
->setEmail($order['email'])
->setFirstname($order['firstName'])
->setLastname($order['lastName'])
->setMiddleName($order['patronymic'])
->setPassword(uniqid());
try {
$customer->save();
$customer->setConfirmation(null);
$customer->save();
} catch (Exception $e) {
Mage::log($e->getMessage());
}
$address = Mage::getModel("customer/address");
$address->setCustomerId($customer->getId())
->setFirstname($customer->getFirstname())
->setMiddleName($customer->getMiddlename())
->setLastname($customer->getLastname())
->setCountryId($this->getCountryCode($order['customer']['address']['country']))
->setPostcode($order['delivery']['address']['index'])
->setCity($order['delivery']['address']['city'])
->setRegion($order['delivery']['address']['region'])
->setTelephone($order['phone'])
->setStreet($order['delivery']['address']['street'])
->setIsDefaultBilling('1')
->setIsDefaultShipping('1')
->setSaveInAddressBook('1');
try{
$address->save();
}
catch (Exception $e) {
Mage::log($e->getMessage());
}
try {
$response = $this->_api->customersFixExternalIds(
array(
'id' => $order['customer']['id'],
'externalId' => $customer->getId()
)
);
if (!$response->isSuccessful() || 200 !== $response->getStatusCode()) {
Mage::log(
sprintf(
"Orders fix error: [HTTP status %s] %s",
$response->getStatusCode(),
$response->getErrorMsg()
)
);
if (isset($response['errors'])) {
Mage::log(implode(' :: ', $response['errors']));
}
}
} catch (Retailcrm_Retailcrm_Model_Exception_CurlException $e) {
Mage::log($e->getMessage());
}
}
$products = array();
foreach ($order['items'] as $item) {
$products[$item['offer']['externalId']] = array('qty' => $item['quantity']);
}
$orderData = array(
'session' => array(
'customer_id' => $customer->getId(),
'store_id' => $storeId,
),
'payment' => array(
'method' => $payments[$order['paymentType']],
),
'add_products' => $products,
'order' => array(
'account' => array(
'group_id' => $customer->getGroupId(),
'email' => $order['email']
),
'billing_address' => array(
'firstname' => $order['firstName'],
'middlename' => $order['patronymic'],
'lastname' => $order['lastName'],
'street' => $order['delivery']['address']['street'],
'city' => $order['delivery']['address']['city'],
'country_id' => $this->getCountryCode($order['customer']['address']['country']),
'region' => $order['delivery']['address']['region'],
'postcode' => $order['delivery']['address']['index'],
'telephone' => $order['phone'],
),
'shipping_address' => array(
'firstname' => $order['firstName'],
'middlename' => $order['patronymic'],
'lastname' => $order['lastName'],
'street' => $order['delivery']['address']['street'],
'city' => $order['delivery']['address']['city'],
'country_id' => $this->getCountryCode($order['customer']['address']['country']),
'region' => $order['delivery']['address']['region'],
'postcode' => $order['delivery']['address']['index'],
'telephone' => $order['phone'],
),
'shipping_method' => $shippings[$order['delivery']['code']],
'comment' => array(
'customer_note' => $order['customerComment'],
),
'send_confirmation' => $_sendConfirmation
)
);
$quote = Mage::getModel('sales/quote')->setStoreId($storeId);
$quote->assignCustomer($customer);
$quote->setSendCconfirmation($_sendConfirmation);
foreach($products as $idx => $val) {
$product = Mage::getModel('catalog/product')->load($idx);
$quote->addProduct($product, new Varien_Object($val));
}
$shipping_method = self::getAllShippingMethodsCode($orderData['order']['shipping_method']);
$billingAddress = $quote->getBillingAddress()->addData($orderData['order']['billing_address']);
$shippingAddress = $quote->getShippingAddress()->addData($orderData['order']['shipping_address']);
$shippingAddress->setCollectShippingRates(true)
->collectShippingRates()
->setShippingMethod($shipping_method)
->setPaymentMethod($orderData['payment']['method']);
$quote->getPayment()->importData($orderData['payment']);
$quote->collectTotals();
$originalId = $order['externalId'];
$oldOrder = Mage::getModel('sales/order')->loadByIncrementId($originalId);
$oldOrderArr = $oldOrder->getData();
if(!empty($oldOrderArr['original_increment_id'])) {
$originalId = $oldOrderArr['original_increment_id'];
}
$orderDataUp = array(
'original_increment_id' => $originalId,
'relation_parent_id' => $oldOrder->getId(),
'relation_parent_real_id' => $oldOrder->getIncrementId(),
'edit_increment' => $oldOrder->getEditIncrement()+1,
'increment_id' => $originalId.'-'.($oldOrder->getEditIncrement()+1)
);
$quote->setReservedOrderId($orderDataUp['increment_id']);
$quote->save();
$service = Mage::getModel('sales/service_quote', $quote);
$service->setOrderData($orderDataUp);
try{
$service->submitAll();
}
catch (Exception $e) {
Mage::log($e->getMessage());
}
$magentoOrder = Mage::getModel('sales/order')->loadByIncrementId($orderDataUp['relation_parent_real_id']);
$magentoOrder->setState(Mage_Sales_Model_Order::STATE_CANCELED, true)->save();
try {
$response = $this->_api->ordersFixExternalIds(
array(
array(
'id' => $order['id'],
'externalId' =>$service->getOrder()->getRealOrderId()
)
)
);
if (!$response->isSuccessful() || 200 !== $response->getStatusCode()) {
Mage::log(
sprintf(
"Orders fix error: [HTTP status %s] %s",
$response->getStatusCode(),
$response->getErrorMsg()
)
);
if (isset($response['errors'])) {
Mage::log(implode(' :: ', $response['errors']));
}
}
} catch (Retailcrm_Retailcrm_Model_Exception_CurlException $e) {
Mage::log($e->getMessage());
}
}
/**
* @param array $order
*/
private function doUpdate($order)
{
$magentoOrder = Mage::getModel('sales/order')->loadByIncrementId($order['externalId']);
$magentoOrderArr = $magentoOrder->getData();
$config = Mage::getStoreConfig('retailcrm');
Mage::log($order, null, 'retailcrmHistoriUpdate.log', true);
if((!empty($order['order_edit']))&&($order['order_edit'] == 1)) {
$this->doCreateUp($order);
}
if (!empty($order['status'])) {
try {
$response = $this->_api->statusesList();
if ($response->isSuccessful() && 200 === $response->getStatusCode()) {
$code = $order['status'];
$group = $response->statuses[$code]['group'];
if ($magentoOrder->hasInvoices()) {
$invIncrementIDs = array();
foreach ($magentoOrder->getInvoiceCollection() as $inv) {
$invIncrementIDs[] = $inv->getIncrementId();
}
}
if (in_array($group, array('approval', 'assembling', 'delivery'))) {
if(empty($invIncrementIDs)) {
$magentoOrder->setState(Mage_Sales_Model_Order::STATE_PROCESSING, true);
$magentoOrder->save();
$invoice = $magentoOrder->prepareInvoice()
->setTransactionId($magentoOrder->getRealOrderId())
->addComment("Add status on CRM")
->register()
->pay();
$transaction_save = Mage::getModel('core/resource_transaction')
->addObject($invoice)
->addObject($invoice->getOrder());
$transaction_save->save();
}
}
if (in_array($group, array('complete'))) {
if(empty($invIncrementIDs)){
$invoice = $magentoOrder->prepareInvoice()
->setTransactionId($magentoOrder->getRealOrderId())
->addComment("Add status on CRM")
->register()
->pay();
$transaction_save = Mage::getModel('core/resource_transaction')
->addObject($invoice)
->addObject($invoice->getOrder());
$transaction_save->save();
$magentoOrder->setState(Mage_Sales_Model_Order::STATE_PROCESSING, true)->save();
}
if($magentoOrder->canShip()) {
$itemQty = $magentoOrder->getItemsCollection()->count();
$shipment = Mage::getModel('sales/service_order', $magentoOrder)->prepareShipment($itemQty);
$shipment = new Mage_Sales_Model_Order_Shipment_Api();
$shipmentId = $shipment->create($order['externalId']);
}
}
if($code == $config['status']['canceled']) {
$magentoOrder->setState(Mage_Sales_Model_Order::STATE_CANCELED, true)->save();
}
if($code == $config['status']['holded']) {
if($magentoOrder->canHold()){
$magentoOrder->hold()->save();
}
}
if($code == $config['status']['unhold']) {
if($magentoOrder->canUnhold()) {
$magentoOrder->unhold()->save();
}
}
if($code == $config['status']['closed']) {
if($magentoOrder->canCreditmemo()) {
$orderItem = $magentoOrder->getItemsCollection();
foreach ($orderItem as $item) {
$data['qtys'][$item->getid()] = $item->getQtyOrdered();
}
$service = Mage::getModel('sales/service_order', $magentoOrder);
$creditMemo = $service->prepareCreditmemo($data)->register()->save();
$magentoOrder->addStatusToHistory(Mage_Sales_Model_Order::STATE_CLOSED, 'Add status on CRM', false);
$magentoOrder->save();
}
}
Mage::log("Update: " . $order['externalId'], null, 'history.log');
} else {
Mage::log(
sprintf(
"Statuses list error: [HTTP status %s] %s",
$response->getStatusCode(),
$response->getErrorMsg()
)
);
if (isset($response['errors'])) {
Mage::log(implode(' :: ', $response['errors']));
}
}
} catch (Retailcrm_Retailcrm_Model_Exception_CurlException $e) {
Mage::log($e->getMessage());
}
}
if(!empty($order['manager_comment'])) {
$magentoOrder->addStatusHistoryComment($order['manager_comment']);
$magentoOrder->save();
}
}
/**
* @param $customer
* @return mixed
*/
private function setCustomerId($customer)
{
$customerId = $this->searchCustomer($customer);
if (is_array($customerId) && !empty($customerId)) {
if ($customerId['success']) {
return $customerId['result'];
} else {
$this->fixCustomer($customerId['result'], $customer['externalId']);
return $customer['externalId'];
}
} else {
$this->createCustomer(
array(
'externalId' => $customer['externalId'],
'firstName' => $customer['firstName'],
'lastName' => isset($customer['lastName']) ? $customer['lastName'] : '',
'patronymic' => isset($customer['patronymic']) ? $customer['patronymic'] : '',
'phones' => isset($customer['phone']) ? array($customer['phone']) : array(),
)
);
return $customer['externalId'];
}
}
/**
* @param $data
* @return array|bool
*/
private function searchCustomer($data)
{
try {
$customers = $this->_api->customersList(
array(
'name' => isset($data['phone']) ? $data['phone'] : $data['name'],
'email' => $data['email']
),
1,
100
);
} catch (Retailcrm_Retailcrm_Model_Exception_CurlException $e) {
Mage::log($e->getMessage());
}
if ($customers->isSuccessful()) {
return (count($customers['customers']) > 0)
? $this->defineCustomer($customers['customers'])
: false
;
}
}
private function createCustomer($customer)
{
try {
$this->_api->customersCreate($customer);
} catch (Retailcrm_Retailcrm_Model_Exception_CurlException $e) {
Mage::log('RestApi::CustomersCreate::Curl: ' . $e->getMessage());
}
}
private function fixCustomer($id, $extId)
{
try {
$this->_api->customersFixExternalIds(
array(
array(
'id' => $id,
'externalId' => $extId
)
)
);
} catch (Retailcrm_Retailcrm_Model_Exception_CurlException $e) {
Mage::log('RestApi::CustomersFixExternalIds::Curl: ' . $e->getMessage());
}
}
private function defineCustomer($searchResult)
{
$result = '';
foreach ($searchResult as $customer) {
if (isset($customer['externalId']) && $customer['externalId'] != '') {
$result = $customer['externalId'];
break;
}
}
return ($result != '')
? array('success' => true, 'result' => $result)
: array('success' => false, 'result' => $searchResult[0]['id']);
}
private function getExchangeTime($datetime)
{
if (empty($datetime)) {
$datetime = new DateTime(
date(
'Y-m-d H:i:s',
strtotime('-1 days', strtotime(date('Y-m-d H:i:s')))
)
);
} else {
$datetime = new DateTime($datetime);
}
return $datetime;
}
private function getCountryCode($string)
{
$country = empty($string) ? 'RU' : $string;
$xmlObj = new Varien_Simplexml_Config(Mage::getModuleDir('etc', 'Retailcrm_Retailcrm').DS.'country.xml');
$xmlData = $xmlObj->getNode();
if ($country != 'RU') {
foreach ($xmlData as $elem) {
if ($elem->name == $country || $elem->english == $country) {
$country = $elem->alpha2;
break;
}
}
}
return (string) $country;
}
public static function assemblyOrder($orderHistory)
{
$orders = array();
foreach ($orderHistory as $change) {
$change['order'] = self::removeEmpty($change['order']);
if($change['order']['items']) {
$items = array();
foreach($change['order']['items'] as $item) {
if(isset($change['created'])) {
$item['create'] = 1;
}
$items[$item['id']] = $item;
}
$change['order']['items'] = $items;
}
Mage::log($change, null, 'retailcrmHistoryAssemblyOrder.log', true);
if($change['order']['contragent']['contragentType']) {
$change['order']['contragentType'] = self::newValue($change['order']['contragent']['contragentType']);
unset($change['order']['contragent']);
}
if($orders[$change['order']['id']]) {
$orders[$change['order']['id']] = array_merge($orders[$change['order']['id']], $change['order']);
}
else {
$orders[$change['order']['id']] = $change['order'];
}
if($change['field'] == 'manager_comment'){
$orders[$change['order']['id']][$change['field']] = $change['newValue'];
}
if(($change['field'] != 'status')&&
($change['field'] != 'country')&&
($change['field'] != 'manager_comment')&&
($change['field'] != 'order_product.status')&&
($change['field'] != 'payment_status')&&
($change['field'] != 'prepay_sum')
) {
$orders[$change['order']['id']]['order_edit'] = 1;
}
if($change['item']) {
if($orders[$change['order']['id']]['items'][$change['item']['id']]) {
$orders[$change['order']['id']]['items'][$change['item']['id']] = array_merge($orders[$change['order']['id']]['items'][$change['item']['id']], $change['item']);
}
else{
$orders[$change['order']['id']]['items'][$change['item']['id']] = $change['item'];
}
if(empty($change['oldValue']) && $change['field'] == 'order_product') {
$orders[$change['order']['id']]['items'][$change['item']['id']]['create'] = 1;
$orders[$change['order']['id']]['order_edit'] = 1;
unset($orders[$change['order']['id']]['items'][$change['item']['id']]['delete']);
}
if(empty($change['newValue']) && $change['field'] == 'order_product') {
$orders[$change['order']['id']]['items'][$change['item']['id']]['delete'] = 1;
$orders[$change['order']['id']]['order_edit'] = 1;
}
if(!empty($change['newValue']) && $change['field'] == 'order_product.quantity') {
$orders[$change['order']['id']]['order_edit'] = 1;
}
if(!$orders[$change['order']['id']]['items'][$change['item']['id']]['create'] && $fields['item'][$change['field']]) {
$orders[$change['order']['id']]['items'][$change['item']['id']][$fields['item'][$change['field']]] = $change['newValue'];
}
}
else {
if($fields['delivery'][$change['field']] == 'service') {
$orders[$change['order']['id']]['delivery']['service']['code'] = self::newValue($change['newValue']);
}
elseif($fields['delivery'][$change['field']]) {
$orders[$change['order']['id']]['delivery'][$fields['delivery'][$change['field']]] = self::newValue($change['newValue']);
}
elseif($fields['orderAddress'][$change['field']]) {
$orders[$change['order']['id']]['delivery']['address'][$fields['orderAddress'][$change['field']]] = $change['newValue'];
}
elseif($fields['integrationDelivery'][$change['field']]) {
$orders[$change['order']['id']]['delivery']['service'][$fields['integrationDelivery'][$change['field']]] = self::newValue($change['newValue']);
}
elseif($fields['customerContragent'][$change['field']]) {
$orders[$change['order']['id']][$fields['customerContragent'][$change['field']]] = self::newValue($change['newValue']);
}
elseif(strripos($change['field'], 'custom_') !== false) {
$orders[$change['order']['id']]['customFields'][str_replace('custom_', '', $change['field'])] = self::newValue($change['newValue']);
}
elseif($fields['order'][$change['field']]) {
$orders[$change['order']['id']][$fields['order'][$change['field']]] = self::newValue($change['newValue']);
}
if(isset($change['created'])) {
$orders[$change['order']['id']]['create'] = 1;
}
if(isset($change['deleted'])) {
$orders[$change['order']['id']]['deleted'] = 1;
}
}
}
return $orders;
}
public static function removeEmpty($inputArray)
{
$outputArray = array();
if (!empty($inputArray)) {
foreach ($inputArray as $key => $element) {
if(!empty($element) || $element === 0 || $element === '0') {
if (is_array($element)) {
$element = self::removeEmpty($element);
}
$outputArray[$key] = $element;
}
}
}
return $outputArray;
}
public static function newValue($value)
{
if(isset($value['code'])) {
return $value['code'];
} else{
return $value;
}
}
public static function getAllShippingMethodsCode($code)
{
$methods = Mage::getSingleton('shipping/config')->getActiveCarriers();
$options = array();
foreach($methods as $_ccode => $_carrier) {
if($_methods = $_carrier->getAllowedMethods()) {
foreach($_methods as $_mcode => $_method) {
$_code = $_ccode . '_' . $_mcode;
$options[$_ccode] = $_code;
}
}
}
return $options[$code];
}
}

View File

@ -1,364 +0,0 @@
<?php
class Retailcrm_Retailcrm_Model_Icml
{
protected $_dd;
protected $_eCategories;
protected $_eOffers;
protected $_shop;
public function generate($shop)
{
$this->_shop = $shop;
$string = '<?xml version="1.0" encoding="UTF-8"?>
<yml_catalog date="'.date('Y-m-d H:i:s').'">
<shop>
<name>'.Mage::app()->getStore($shop)->getName().'</name>
<categories/>
<offers/>
</shop>
</yml_catalog>
';
$xml = new SimpleXMLElement(
$string,
LIBXML_NOENT | LIBXML_NOCDATA | LIBXML_COMPACT | LIBXML_PARSEHUGE
);
$this->_dd = new DOMDocument();
$this->_dd->preserveWhiteSpace = false;
$this->_dd->formatOutput = true;
$this->_dd->loadXML($xml->asXML());
$this->_eCategories = $this->_dd->
getElementsByTagName('categories')->item(0);
$this->_eOffers = $this->_dd
->getElementsByTagName('offers')->item(0);
$this->addCategories();
$this->addOffers();
$this->_dd->saveXML();
$baseDir = Mage::getBaseDir();
$shopCode = Mage::app()->getStore($shop)->getCode();
$this->_dd->save($baseDir . DS . 'retailcrm_' . $shopCode . '.xml');
}
private function addCategories()
{
$category = Mage::getModel('catalog/category');
$treeModel = $category->getTreeModel();
$treeModel->load();
$ids = $treeModel->getCollection()->getAllIds();
$categories = array();
if (!empty($ids))
{
foreach ($ids as $id)
{
if ($id > 1) {
$category = Mage::getModel('catalog/category');
$category->load($id);
$categoryData = array(
'id' => $category->getId(),
'name'=> $category->getName(),
'parentId' => $category->getParentId()
);
array_push($categories, $categoryData);
}
}
}
foreach($categories as $category) {
$e = $this->_eCategories->appendChild(
$this->_dd->createElement('category')
);
$e->appendChild($this->_dd->createTextNode($category['name']));
$e->setAttribute('id', $category['id']);
if ($category['parentId'] > 1) {
$e->setAttribute('parentId', $category['parentId']);
}
}
}
private function addOffers()
{
$offers = array();
$helper = Mage::helper('retailcrm');
$picUrl = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA);
$baseUrl = Mage::getBaseUrl();
$customAdditionalAttributes = Mage::getStoreConfig('retailcrm/attributes_to_export_into_icml');
$customAdditionalAttributes = explode(',', $customAdditionalAttributes);
$collection = Mage::getModel('catalog/product')
->getCollection()
->addAttributeToSelect('*')
->addUrlRewrite();
$collection->addFieldToFilter('status', Mage_Catalog_Model_Product_Status::STATUS_ENABLED);
$collection->addFieldToFilter('visibility', Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH);
$collection->addAttributeToFilter('type_id', array('eq' => 'simple'));
foreach ($collection as $product) {
/** @var Mage_Catalog_Model_Product $product */
$offer = array();
$offer['id'] = $product->getTypeId() != 'configurable' ? $product->getId() : null;
$offer['productId'] = $product->getId();
$offer['productActivity'] = $product->isAvailable() ? 'Y' : 'N';
$offer['name'] = $product->getName();
$offer['productName'] = $product->getName();
$offer['initialPrice'] = (float) $product->getPrice();
if($product->hasCost())
$offer['purchasePrice'] = (float) $product->getCost();
$offer['url'] = $product->getProductUrl();
$offer['picture'] = $picUrl.'catalog/product'.$product->getImage();
$offer['quantity'] = Mage::getModel('cataloginventory/stock_item')
->loadByProduct($product)->getQty();
foreach ($product->getCategoryIds() as $category_id) {
$offer['categoryId'][] = $category_id;
}
$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)) {
foreach($customAdditionalAttributes as $customAdditionalAttribute) {
$alreadyExists = false;
foreach($offer['params'] as $param) {
if($param['code'] == $customAdditionalAttribute) {
$alreadyExists = true;
break;
}
}
if($alreadyExists) continue;
$attribute = $product->getAttributeText($customAdditionalAttribute);
if(!empty($attribute)) {
$offer['params'][] = array(
'name' => $customAdditionalAttribute,
'code' => $customAdditionalAttribute,
'value' => $attribute
);
}
}
}
$offers[] = $offer;
if($product->getTypeId() == 'configurable') {
/** @var Mage_Catalog_Model_Product_Type_Configurable $product */
$associatedProducts = Mage::getModel('catalog/product_type_configurable')->getUsedProducts(null, $product);
$productAttributeOptions = $product->getTypeInstance(true)->getConfigurableAttributesAsArray($product);
foreach($associatedProducts as $associatedProduct) {
$associatedProduct = Mage::getModel('catalog/product')->load($associatedProduct->getId());
$attributes = array();
foreach($productAttributeOptions as $productAttributeOption) {
$attributes[$productAttributeOption['label']] = $associatedProduct->getAttributeText($productAttributeOption['attribute_code']);
}
$attributesString = array();
foreach($attributes AS $attributeName=>$attributeValue) {
$attributesString[] = $attributeName.': '.$attributeValue;
}
$attributesString = ' (' . implode(', ', $attributesString) . ')';
$offer = array();
$offer['id'] = $associatedProduct->getId();
$offer['productId'] = $product->getId();
$offer['productActivity'] = $associatedProduct->isAvailable() ? 'Y' : 'N';
$offer['name'] = $associatedProduct->getName().$attributesString;
$offer['productName'] = $product->getName();
$offer['initialPrice'] = (float) $associatedProduct->getFinalPrice();
if($associatedProduct->hasCost())
$offer['purchasePrice'] = (float) $associatedProduct->getCost();
$offer['url'] = $associatedProduct->getProductUrl();
$offer['picture'] = $picUrl.'catalog/product'.$associatedProduct->getImage();
$offer['quantity'] = Mage::getModel('cataloginventory/stock_item')
->loadByProduct($associatedProduct)->getQty();
foreach ($associatedProduct->getCategoryIds() as $category_id) {
$offer['categoryId'][] = $category_id;
}
$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
);
}
if(!empty($attributes)) {
foreach($attributes as $attributeName => $attributeValue) {
$offer['params'][] = array(
'name' => $attributeName,
'code' => str_replace(' ', '_', strtolower($attributeName)),
'value' => $attributeValue
);
}
}
if(!empty($customAdditionalAttributes)) {
foreach($customAdditionalAttributes as $customAdditionalAttribute) {
$alreadyExists = false;
foreach($offer['params'] as $param) {
if($param['code'] == $customAdditionalAttribute) {
$alreadyExists = true;
break;
}
}
if($alreadyExists) continue;
$attribute = $associatedProduct->getAttributeText($customAdditionalAttribute);
if(!empty($attribute)) {
$offer['params'][] = array(
'name' => $customAdditionalAttribute,
'code' => $customAdditionalAttribute,
'value' => $attribute
);
}
}
}
$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);
}
}
}
}
}

View File

@ -1,72 +0,0 @@
<?php
/**
* Observer
*
* @author RetailDriver LLC
*/
class Retailcrm_Retailcrm_Model_Observer
{
/**
* Event after order created
*
* @param Varien_Event_Observer $observer
* @return bool
*/
public function orderCreate(Varien_Event_Observer $observer)
{
if (Mage::registry('sales_order_place_after') != 1){//do nothing if the event was dispatched
$order = $observer->getEvent()->getOrder();
Mage::getModel('retailcrm/order')->orderCreate($order);
}
return true;
}
public function orderUpdate(Varien_Event_Observer $observer)
{
$order = $observer->getEvent()->getOrder();
Mage::getModel('retailcrm/order')->orderUpdate($order);
return true;
}
public function orderStatusHistoryCheck(Varien_Event_Observer $observer)
{
$order = $observer->getEvent()->getOrder();
Mage::getModel('retailcrm/order')->orderStatusHistoryCheck($order);
return true;
}
/**
* Event after customer created
*
* @param Varien_Event_Observer $observer
*
* @SuppressWarnings(PHPMD.StaticAccess)
*
* @return bool
*/
public function customerRegister(Varien_Event_Observer $observer)
{
if (Mage::registry('customer_save_after') != 1) {
$customer = $observer->getEvent()->getCustomer();
Mage::getModel('retailcrm/customer')->customerRegister($customer);
}
return true;
}
public function exportCatalog()
{
foreach (Mage::app()->getWebsites() as $website) {
foreach ($website->getGroups() as $group) {
Mage::getModel('retailcrm/icml')->generate((int)$group->getId());
}
}
}
public function importHistory()
{
Mage::getModel('retailcrm/exchange')->ordersHistory();
}
}

View File

@ -1,431 +0,0 @@
<?php
/**
* Order class
*
* @category Model
* @package RetailCrm\Model
* @author RetailDriver LLC <integration@retailcrm.ru>
* @license http://opensource.org/licenses/MIT MIT License
* @link http://www.magentocommerce.com/magento-connect/retailcrm-1.html
*
* @SuppressWarnings(PHPMD.CamelCaseClassName)
* @SuppressWarnings(PHPMD.CamelCasePropertyName)
*/
class Retailcrm_Retailcrm_Model_Order extends Retailcrm_Retailcrm_Model_Exchange
{
/**
* Order create
*
* @SuppressWarnings(PHPMD.StaticAccess)
* @SuppressWarnings(PHPMD.ElseExpression)
* @param mixed $order
*
* @return bool
*/
public function orderPay($orderId)
{
$order = Mage::getModel('sales/order')->load($orderId);
if((string)$order->getBaseGrandTotal() == (string)$order->getTotalPaid()){
$preparedOrder = array(
'externalId' => $order->getRealOrderId(),//getId(),
'paymentStatus' => 'paid',
);
$preparedOrder = Mage::helper('retailcrm')->filterRecursive($preparedOrder);
$this->_api->ordersEdit($preparedOrder);
}
}
public function orderStatusHistoryCheck($order)
{
$config = Mage::getModel(
'retailcrm/settings',
array(
'storeId' =>$order->getStoreId()
)
);
$preparedOrder = array(
'externalId' => $order->getRealOrderId(),//getId(),
'status' => $config->getMapping($order->getStatus(), 'status'),
);
$comment = $order->getStatusHistoryCollection()->getData();
if(!empty($comment[0]['comment'])) {
$preparedOrder['managerComment'] = $comment[0]['comment'];
}
$preparedOrder = Mage::helper('retailcrm')->filterRecursive($preparedOrder);
$this->_api->ordersEdit($preparedOrder);
}
public function orderUpdate($order)
{
$config = Mage::getModel(
'retailcrm/settings',
array(
'storeId' =>$order->getStoreId()
)
);
$preparedOrder = array(
'externalId' => $order->getRealOrderId(),//getId(),
'status' => $config->getMapping($order->getStatus(), 'status'),
);
if((float)$order->getBaseGrandTotal() == (float)$order->getTotalPaid()) {
$preparedOrder['paymentStatus'] = 'paid';
$preparedOrder = Mage::helper('retailcrm')->filterRecursive($preparedOrder);
$this->_api->ordersEdit($preparedOrder);
}
}
public function orderCreate($order)
{
$config = Mage::getModel('retailcrm/settings', ['storeId' => $order->getStoreId()]);
$address = $order->getShippingAddress()->getData();
$orderItems = $order->getItemsCollection()
->addAttributeToSelect('*')
->addAttributeToFilter('product_type', array('eq'=>'simple'))
->load();
$items = array();
foreach ($orderItems as $item) {
if ($item->getProductType() == "simple") {
if ($item->getParentItemId()) {
$parent = Mage::getModel('sales/order_item')->load($item->getParentItemId());
}
$product = array(
'productId' => $item->getProductId(),
'productName' => !isset($parent) ? $item->getName() : $parent->getName(),
'quantity' => !isset($parent) ? intval($item->getQtyOrdered()) : intval($parent->getQtyOrdered()),
'initialPrice' => !isset($parent) ? $item->getPrice() : $parent->getPrice(),
'offer'=>array(
'externalId'=>$item->getProductId()
)
);
unset($parent);
$items[] = $product;
} elseif($item->getProductType() == "grouped") {
$product = array(
'productId' => $item->getProductId(),
'productName' => $item->getName(),
'quantity' => $item->getQtyOrdered(),
'initialPrice' => $item->getPrice(),
'offer'=>array(
'externalId'=>$item->getProductId()
)
);
$items[] = $product;
}
}
$shipping = $this->getShippingCode($order->getShippingMethod());
$preparedOrder = array(
'site' => $order->getStore()->getCode(),
'externalId' => $order->getRealOrderId(),
'number' => $order->getRealOrderId(),
'createdAt' => Mage::getModel('core/date')->date(),
'lastName' => $order->getCustomerLastname(),
'firstName' => $order->getCustomerFirstname(),
'patronymic' => $order->getCustomerMiddlename(),
'email' => $order->getCustomerEmail(),
'phone' => $address['telephone'],
'paymentType' => $config->getMapping($order->getPayment()->getMethodInstance()->getCode(), 'payment'),
'status' => $config->getMapping($order->getStatus(), 'status'),
'discount' => abs($order->getDiscountAmount()),
'items' => $items,
'customerComment' => $order->getStatusHistoryCollection()->getFirstItem()->getComment(),
'delivery' => array(
'code' => $config->getMapping($shipping, 'shipping'),
'cost' => $order->getShippingAmount(),
'address' => array(
'index' => $address['postcode'],
'city' => $address['city'],
'country' => $address['country_id'],
'street' => $address['street'],
'region' => $address['region'],
'text' => trim(
',',
implode(
',',
array(
$address['postcode'],
$address['city'],
$address['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();
}
}
$preparedOrder = Mage::helper('retailcrm')->filterRecursive($preparedOrder);
Mage::log($preparedOrder, null, 'retailcrmCreatePreparedOrder.log', true);
try {
$response = $this->_api->ordersCreate($preparedOrder);
if ($response->isSuccessful() && 201 === $response->getStatusCode()) {
Mage::log($response->id);
} else {
Mage::log(
sprintf(
"Order create error: [HTTP status %s] %s",
$response->getStatusCode(),
$response->getErrorMsg()
)
);
if (isset($response['errors'])) {
Mage::log(implode(' :: ', $response['errors']));
}
}
} catch (Retailcrm_Retailcrm_Model_Exception_CurlException $e) {
Mage::log($e->getMessage());
}
}
public function ordersExportNumber()
{
$config = Mage::getStoreConfig('retailcrm');
$ordersId = explode(",", $config['load_order']['numberOrder']);
$orders = array();
$ordersList = Mage::getResourceModel('sales/order_collection')
->addAttributeToSelect('*')
->joinAttribute('billing_firstname', 'order_address/firstname', 'billing_address_id', null, 'left')
->joinAttribute('billing_lastname', 'order_address/lastname', 'billing_address_id', null, 'left')
->joinAttribute('billing_street', 'order_address/street', 'billing_address_id', null, 'left')
->joinAttribute('billing_company', 'order_address/company', 'billing_address_id', null, 'left')
->joinAttribute('billing_city', 'order_address/city', 'billing_address_id', null, 'left')
->joinAttribute('billing_region', 'order_address/region', 'billing_address_id', null, 'left')
->joinAttribute('billing_country', 'order_address/country_id', 'billing_address_id', null, 'left')
->joinAttribute('billing_postcode', 'order_address/postcode', 'billing_address_id', null, 'left')
->joinAttribute('billing_telephone', 'order_address/telephone', 'billing_address_id', null, 'left')
->joinAttribute('billing_fax', 'order_address/fax', 'billing_address_id', null, 'left')
->joinAttribute('shipping_firstname', 'order_address/firstname', 'shipping_address_id', null, 'left')
->joinAttribute('shipping_lastname', 'order_address/lastname', 'shipping_address_id', null, 'left')
->joinAttribute('shipping_street', 'order_address/street', 'shipping_address_id', null, 'left')
->joinAttribute('shipping_company', 'order_address/company', 'shipping_address_id', null, 'left')
->joinAttribute('shipping_city', 'order_address/city', 'shipping_address_id', null, 'left')
->joinAttribute('shipping_region', 'order_address/region', 'shipping_address_id', null, 'left')
->joinAttribute('shipping_country', 'order_address/country_id', 'shipping_address_id', null, 'left')
->joinAttribute('shipping_postcode', 'order_address/postcode', 'shipping_address_id', null, 'left')
->joinAttribute('shipping_telephone', 'order_address/telephone', 'shipping_address_id', null, 'left')
->joinAttribute('shipping_fax', 'order_address/fax', 'shipping_address_id', null, 'left')
->addAttributeToSort('created_at', 'asc')
->setPageSize(1000)
->setCurPage(1)
->addAttributeToFilter('increment_id', $ordersId)
->load();
foreach ($ordersList as $order) {
$orders[] = $this->prepareOrder($order);
}
$chunked = array_chunk($orders, 50);
unset($orders);
foreach ($chunked as $chunk) {
$this->_api->ordersUpload($chunk);
time_nanosleep(0, 250000000);
}
unset($chunked);
return true;
}
/**
* Orders export
*
* @SuppressWarnings(PHPMD.StaticAccess)
* @SuppressWarnings(PHPMD.ElseExpression)
*
* @return bool
*/
public function ordersExport()
{
$orders = array();
$ordersList = Mage::getResourceModel('sales/order_collection')
->addAttributeToSelect('*')
->joinAttribute('billing_firstname', 'order_address/firstname', 'billing_address_id', null, 'left')
->joinAttribute('billing_lastname', 'order_address/lastname', 'billing_address_id', null, 'left')
->joinAttribute('billing_street', 'order_address/street', 'billing_address_id', null, 'left')
->joinAttribute('billing_company', 'order_address/company', 'billing_address_id', null, 'left')
->joinAttribute('billing_city', 'order_address/city', 'billing_address_id', null, 'left')
->joinAttribute('billing_region', 'order_address/region', 'billing_address_id', null, 'left')
->joinAttribute('billing_country', 'order_address/country_id', 'billing_address_id', null, 'left')
->joinAttribute('billing_postcode', 'order_address/postcode', 'billing_address_id', null, 'left')
->joinAttribute('billing_telephone', 'order_address/telephone', 'billing_address_id', null, 'left')
->joinAttribute('billing_fax', 'order_address/fax', 'billing_address_id', null, 'left')
->joinAttribute('shipping_firstname', 'order_address/firstname', 'shipping_address_id', null, 'left')
->joinAttribute('shipping_lastname', 'order_address/lastname', 'shipping_address_id', null, 'left')
->joinAttribute('shipping_street', 'order_address/street', 'shipping_address_id', null, 'left')
->joinAttribute('shipping_company', 'order_address/company', 'shipping_address_id', null, 'left')
->joinAttribute('shipping_city', 'order_address/city', 'shipping_address_id', null, 'left')
->joinAttribute('shipping_region', 'order_address/region', 'shipping_address_id', null, 'left')
->joinAttribute('shipping_country', 'order_address/country_id', 'shipping_address_id', null, 'left')
->joinAttribute('shipping_postcode', 'order_address/postcode', 'shipping_address_id', null, 'left')
->joinAttribute('shipping_telephone', 'order_address/telephone', 'shipping_address_id', null, 'left')
->joinAttribute('shipping_fax', 'order_address/fax', 'shipping_address_id', null, 'left')
->addAttributeToSort('created_at', 'asc')
->setPageSize(1000)
->setCurPage(1)
->load();
foreach ($ordersList as $order) {
$orders[] = $this->prepareOrder($order);
}
$chunked = array_chunk($orders, 50);
unset($orders);
foreach ($chunked as $chunk) {
$this->_api->ordersUpload($chunk);
time_nanosleep(0, 250000000);
}
unset($chunked);
return true;
}
protected function prepareOrder($order)
{
$config = Mage::getModel('retailcrm/settings', ['storeId' => $order->getStoreId()]);
$address = $order->getShippingAddress();
$orderItems = $order->getItemsCollection()
->addAttributeToSelect('*')
->addAttributeToFilter('product_type', array('eq'=>'simple'))
->load();
$items = array();
foreach ($orderItems as $item) {
if ($item->getProductType() == "simple") {
if ($item->getParentItemId()) {
$parent = Mage::getModel('sales/order_item')->load($item->getParentItemId());
}
$product = array(
'productId' => $item->getProductId(),
'productName' => !isset($parent) ? $item->getName() : $parent->getName(),
'quantity' => !isset($parent) ? intval($item->getQtyOrdered()) : intval($parent->getQtyOrdered()),
'initialPrice' => !isset($parent) ? $item->getPrice() : $parent->getPrice()
);
unset($parent);
$items[] = $product;
}
}
$shipping = $this->getShippingCode($order->getShippingMethod());
$preparedOrder = array(
'externalId' => $order->getRealOrderId(),
'number' => $order->getRealOrderId(),
'createdAt' => $order->getCreatedAt(),
'lastName' => $order->getCustomerLastname(),
'firstName' => $order->getCustomerFirstname(),
'patronymic' => $order->getCustomerMiddlename(),
'email' => $order->getCustomerEmail(),
'phone' => $address['telephone'],
'paymentType' => $config->getMapping($order->getPayment()->getMethodInstance()->getCode(), 'payment'),
'status' => $config->getMapping($order->getStatus(), 'status'),
'discount' => abs($order->getDiscountAmount()),
'items' => $items,
'customerComment' => $order->getStatusHistoryCollection()->getFirstItem()->getComment(),
'delivery' => array(
'code' => $config->getMapping($shipping, 'shipping'),
'cost' => $order->getShippingAmount(),
'address' => array(
'index' => $address['postcode'],
'city' => $address['city'],
'country' => $address['country_id'],
'street' => $address['street'],
'region' => $address['region'],
'text' => trim(
',',
implode(
',',
array(
$address['postcode'],
$address['city'],
$address['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) {
$preparedOrder['customer']['externalId'] = $order->getCustomerId();
}
return Mage::helper('retailcrm')->filterRecursive($preparedOrder);
}
protected function getShippingCode($string)
{
$split = array_values(explode('_', $string));
$length = count($split);
$prepare = array_slice($split, 0, $length/2);
return implode('_', $prepare);
}
protected function getLocale($code)
{
$this->_locale = Mage::app()->getLocale()->getLocaleCode();
if (!in_array($this->_locale, array('ru_RU', 'en_US'))) {
$this->_locale = 'en_US';
}
$this->_dict = array(
'ru_RU' => array('sku' => 'Артикул', 'weight' => 'Вес', 'offer' => 'Вариант'),
'en_US' => array('sku' => 'Sku', 'weight' => 'Weight', 'offer' => 'Offer'),
);
return $this->_dict[$this->_locale][$code];
}
}

View File

@ -1,92 +0,0 @@
<?php
/**
* Settings class
*
* @category Model
* @package RetailCrm\Model
* @author RetailDriver LLC <integration@retailcrm.ru>
* @license http://opensource.org/licenses/MIT MIT License
* @link http://www.magentocommerce.com/magento-connect/retailcrm-1.html
*
* @SuppressWarnings(PHPMD.CamelCaseClassName)
* @SuppressWarnings(PHPMD.CamelCasePropertyName)
*/
class Retailcrm_Retailcrm_Model_Settings
{
protected $_config;
protected $_storeDefined;
/**
* Constructor
*
* @param array $params
*
* @SuppressWarnings(PHPMD.StaticAccess)
* @SuppressWarnings(PHPMD.ElseExpression)
*
* @return bool
*/
public function __construct(array $params = array())
{
$this->_config = empty($params)
? $this->setConfigWithoutStoreId()
: $this->setConfigWithStoreId($params['storeId']);
}
/**
* Get mapping values
*
* @param string $code
* @param string $type (default: status, values: status, payment, shipping)
* @param bool $reverse
*
* @SuppressWarnings(PHPMD.StaticAccess)
* @SuppressWarnings(PHPMD.BooleanArgumentFlag)
*
* @return mixed
*/
public function getMapping($code, $type, $reverse = false)
{
if (!in_array($type, array('status', 'payment', 'shipping'))) {
throw new \InvalidArgumentException(
"Parameter 'type' must be 'status', 'payment' or 'shipping'"
);
}
$array = ($reverse)
? array_flip(array_filter($this->_config[$type]))
: array_filter($this->_config[$type]);
return array_key_exists($code, $array)
? $array[$code]
: false;
}
/**
* Set config with orderStoreId
*
* @param string $storeId
*
* @SuppressWarnings(PHPMD.StaticAccess)
*
* @return mixed
*/
protected function setConfigWithStoreId($storeId)
{
$this->_storeDefined = true;
return Mage::getStoreConfig('retailcrm', $storeId);
}
/**
* Set config without orderStoreId
*
* @SuppressWarnings(PHPMD.StaticAccess)
*
* @return mixed
*/
protected function setConfigWithoutStoreId()
{
$this->_storeDefined = false;
return Mage::getStoreConfig('retailcrm');
}
}

View File

@ -1,24 +0,0 @@
<?php
class Retailcrm_Retailcrm_Adminhtml_RetailcrmbuttonController extends Mage_Adminhtml_Controller_Action
{
/**
* Return some checking result
*
* @return void
*/
public function checkAction()
{
$orders = Mage::getModel('retailcrm/order');
$orders ->ordersExportNumber();
}
/**
* Check is allowed access to action
*
* @return bool
*/
protected function _isAllowed()
{
return Mage::getSingleton('admin/session')->isAllowed('system/config/retailcrm');
}
}

View File

@ -1,139 +0,0 @@
<?xml version="1.0"?>
<!--
The MIT License (MIT)
Copyright (c) 2015 RetailDriver LLC
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-->
<config>
<modules>
<Retailcrm_Retailcrm>
<version>1.0.0</version>
</Retailcrm_Retailcrm>
</modules>
<global>
<helpers>
<retailcrm>
<class>Retailcrm_Retailcrm_Helper</class>
</retailcrm>
</helpers>
<models>
<retailcrm>
<class>Retailcrm_Retailcrm_Model</class>
</retailcrm>
</models>
<blocks>
<retailcrm>
<class>Retailcrm_Retailcrm_Block</class>
</retailcrm>
</blocks>
<events>
<sales_order_place_after>
<observers>
<retailcrm_retailcrm_model_observer>
<type>singleton</type>
<class>Retailcrm_Retailcrm_Model_Observer</class>
<method>orderCreate</method>
</retailcrm_retailcrm_model_observer>
</observers>
</sales_order_place_after>
<sales_order_save_commit_after>
<observers>
<retailcrm_retailcrm_model_observer>
<type>singleton</type>
<class>Retailcrm_Retailcrm_Model_Observer</class>
<method>orderUpdate</method>
</retailcrm_retailcrm_model_observer>
</observers>
</sales_order_save_commit_after>
<sales_order_save_after>
<observers>
<retailcrm_retailcrm_model_observer>
<type>singleton</type>
<class>Retailcrm_Retailcrm_Model_Observer</class>
<method>orderStatusHistoryCheck</method>
</retailcrm_retailcrm_model_observer>
</observers>
</sales_order_save_after>
<customer_save_after>
<observers>
<retailcrm_retailcrm_model_observer>
<type>singleton</type>
<class>Retailcrm_Retailcrm_Model_Observer</class>
<method>customerRegister</method>
</retailcrm_retailcrm_model_observer>
</observers>
</customer_save_after>
</events>
</global>
<admin>
<routers>
<adminhtml>
<args>
<modules>
<Retailcrmbutton after="Mage_Adminhtml">Retailcrm_Retailcrm</Retailcrmbutton>
</modules>
</args>
</adminhtml>
</routers>
</admin>
<crontab>
<jobs>
<icml>
<schedule><cron_expr>* */4 * * *</cron_expr></schedule>
<run><model>retailcrm/observer::exportCatalog</model></run>
</icml>
<history>
<schedule><cron_expr>*/5 * * * *</cron_expr></schedule>
<run><model>retailcrm/observer::importHistory</model></run>
</history>
</jobs>
</crontab>
<adminhtml>
<acl>
<resources>
<admin>
<children>
<system>
<children>
<config>
<children>
<retailcrm>
<title>Store RetailCRM Module Section</title>
</retailcrm>
</children>
</config>
</children>
</system>
</children>
</admin>
</resources>
</acl>
</adminhtml>
</config>

View File

@ -1,160 +0,0 @@
<?xml version="1.0"?>
<!--
The MIT License (MIT)
Copyright (c) 2015 RetailDriver LLC
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-->
<config>
<tabs>
<retailcrm_extension>
<label>RetailCRM</label>
<sort_order>1000</sort_order>
</retailcrm_extension>
</tabs>
<sections>
<retailcrm translate="label" module="retailcrm">
<label>Settings</label>
<class>retailcrm-section</class>
<tab>retailcrm_extension</tab>
<frontend_type>text</frontend_type>
<sort_order>10</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
<groups>
<general translate="label comment" module="retailcrm">
<expanded>1</expanded>
<label>General</label>
<frontend_type>text</frontend_type>
<sort_order>10</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
<fields>
<api_url translate="label comment">
<label>API URL</label>
<frontend_type>text</frontend_type>
<sort_order>1</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
<tooltip><![CDATA[https://<i><b>YourCrmName</b></i>.retailcrm.ru]]></tooltip>
</api_url>
<api_key translate="label comment">
<label>API Key</label>
<frontend_type>text</frontend_type>
<sort_order>3</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
<tooltip><![CDATA[To generate an API Key, log in to RetailCRM then select Admin > Integration > API Keys]]></tooltip>
</api_key>
</fields>
</general>
<misc>
<expanded>1</expanded>
<label>Misc</label>
<frontend_type>text</frontend_type>
<sort_order>11</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
<fields>
<attributes_to_export_into_icml translate="label">
<label>Custom attributes to export into ICML</label>
<frontend_type>multiselect</frontend_type>
<config_path>retailcrm/attributes_to_export_into_icml</config_path>
<sort_order>7</sort_order>
<source_model>retailcrm/attribute</source_model>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
<can_be_empty>1</can_be_empty>
</attributes_to_export_into_icml>
</fields>
</misc>
<shipping translate="label comment" module="retailcrm">
<expanded>0</expanded>
<label>Shipping</label>
<frontend_type>text</frontend_type>
<sort_order>12</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
<frontend_model>retailcrm/adminhtml_system_config_form_fieldset_shipping</frontend_model>
</shipping>
<payment translate="label comment" module="retailcrm">
<expanded>0</expanded>
<label>Payment Method</label>
<frontend_type>text</frontend_type>
<sort_order>13</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
<frontend_model>retailcrm/adminhtml_system_config_form_fieldset_payment</frontend_model>
</payment>
<status translate="label comment" module="retailcrm">
<expanded>0</expanded>
<label>Order Statuses</label>
<frontend_type>text</frontend_type>
<sort_order>14</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
<frontend_model>retailcrm/adminhtml_system_config_form_fieldset_status</frontend_model>
</status>
<load_order translate="label comment" module="retailcrm">
<expanded>0</expanded>
<label>Order Load</label>
<frontend_type>text</frontend_type>
<sort_order>15</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
<frontend_model>retailcrm/adminhtml_system_config_form_fieldset_order</frontend_model>
<fields>
<numberOrder translate="label comment">
<label>Number orders</label>
<frontend_type>text</frontend_type>
<sort_order>1</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
<tooltip><![CDATA[Enter your order number, separated by commas]]></tooltip>
</numberOrder>
<button translate="label comment">
<frontend_type>button</frontend_type>
<frontend_model>retailcrm/adminhtml_system_config_form_button</frontend_model>
<sort_order>2</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
</button>
</fields>
</load_order>
</groups>
</retailcrm>
</sections>
</config>

View File

@ -1,16 +0,0 @@
<script type="text/javascript">
//<![CDATA[
function check() {
new Ajax.Request('<?php echo $this->getAjaxCheckUrl() ?>', {
method: 'get',
onSuccess: function(transport){
if (transport.responseText){
alert('Completed');
}
}
});
}
//]]>
</script>
<?php echo $this->getButtonHtml() ?>

View File

@ -1,32 +0,0 @@
<?xml version="1.0"?>
<!--
The MIT License (MIT)
Copyright (c) 2015 RetailDriver LLC
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-->
<config>
<modules>
<Retailcrm_Retailcrm>
<active>true</active>
<codePool>community</codePool>
</Retailcrm_Retailcrm>
</modules>
</config>

29
composer.json Normal file
View File

@ -0,0 +1,29 @@
{
"name": "retailcrm/retailcrm",
"description": "Retailcrm",
"require": {
"php": "~5.5.0|~5.6.0|~7.0.0"
},
"type": "magento2-module",
"version": "1.0.0",
"license": [
"OSL-3.0",
"AFL-3.0"
],
"authors": [
{
"name": "Retailcrm",
"email": "gorokh@retailcrm.ru",
"homepage": "https://www.retailcrm.ru",
"role": "Developer"
}
],
"autoload": {
"files": [
"registration.php"
],
"psr-4": {
"Retailcrm\\Retailcrm\\": ""
}
}
}

5
etc/adminhtml/menu.xml Normal file
View File

@ -0,0 +1,5 @@
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Backend:etc/menu.xsd">
<menu>
</menu>
</config>

9
etc/adminhtml/routes.xml Normal file
View File

@ -0,0 +1,9 @@
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
<router id="admin">
<route id="retailcrm_retailcrm" frontName="retailcrm_retailcrm">
<module name="Retailcrm_Retailcrm" before="Magento_Backend" />
</route>
</router>
</config>

90
etc/adminhtml/system.xml Normal file
View File

@ -0,0 +1,90 @@
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
<system>
<tab id="retailcrm" translate="label" sortOrder="10">
<label>Retailcrm</label>
</tab>
<section id="retailcrm" translate="label" sortOrder="130" showInDefault="1" showInWebsite="1" showInStore="1">
<class>separator-top</class>
<label>Setting</label>
<tab>retailcrm</tab>
<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">
<label>API URL</label>
<comment>https://YourCrmName.retailcrm.ru</comment>
</field>
<field id="api_key" translate="label" type="text" sortOrder="1" 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>
</group>
<group id="Misc" translate="label" type="text" sortOrder="20" showInDefault="2" showInWebsite="0" showInStore="0">
<label>Misc</label>
<field id="attributes_to_export_into_icml" translate="label" type="multiselect" sortOrder="2" showInDefault="1" showInWebsite="0" showInStore="0">
<label>attributes to export into icml</label>
<comment>attributes to export into icml</comment>
<source_model>Retailcrm\Retailcrm\Model\Setting\Attribute</source_model>
<!--
<frontend_model>Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Field\Attributes</frontend_model>
-->
</field>
</group>
<group id="Shipping" translate="label" type="text" sortOrder="30" showInDefault="3" showInWebsite="0" showInStore="0">
<label>Shipping</label>
<field id="Shipping" translate="label" type="select" sortOrder="3" showInDefault="1" showInWebsite="0" showInStore="0">
<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 id="Payment" translate="label comment" type="text" sortOrder="40" showInDefault="4" showInWebsite="0" showInStore="0">
<label>Payment method</label>
<field id="display_text" translate="label" type="text" sortOrder="5" showInDefault="1" showInWebsite="0" showInStore="0">
<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 id="Status" translate="label" type="text" sortOrder="50" showInDefault="5" showInWebsite="0" showInStore="0">
<label>Order Status</label>
<field id="status_text" translate="label" type="text" sortOrder="5" showInDefault="1" showInWebsite="0" showInStore="0">
<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 id="Load" translate="label" type="text" sortOrder="60" showInDefault="6" showInWebsite="0" showInStore="0">
<label>Order Load</label>
<field id="number_order" translate="label" type="text" sortOrder="6" showInDefault="1" showInWebsite="0" showInStore="0">
<label>Order number</label>
<comment>Enter your order number, separated by commas</comment>
</field>
<field id="button_order" translate="label comment" type="button" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="0">
<frontend_model>Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Button</frontend_model>
</field>
</group>
</section>
</system>
</config>

24
etc/config.xml Normal file
View File

@ -0,0 +1,24 @@
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/config.xsd">
<default>
<retailcrm>
<general>
<api_url>test</api_url>
</general>
<section>
<general>
<api_key>{value}</api_key>
</general>
</section>
</retailcrm>
</default>
</config>

13
etc/crontab.xml Normal file
View File

@ -0,0 +1,13 @@
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Cron:etc/crontab.xsd">
<group id="default">
<job name="create_icml" instance="Retailcrm\Retailcrm\Cron\Icml" method="execute">
<schedule>* */4 * * *</schedule>
</job>
<job name="order_hystory" instance="Retailcrm\Retailcrm\Cron\OrderHistory" method="execute">
<schedule>*/5 * * * *</schedule>
</job>
</group>
</config>

5
etc/di.xml Normal file
View File

@ -0,0 +1,5 @@
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
</config>

25
etc/events.xml Normal file
View File

@ -0,0 +1,25 @@
<?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>
</config>

12
etc/frontend/events.xml Normal file
View File

@ -0,0 +1,12 @@
<?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" disabled="true"/>
</event>
</config>

8
etc/frontend/routes.xml Normal file
View File

@ -0,0 +1,8 @@
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
<router id="standard">
<route id="retailcrm" frontName="retailcrm">
<module name="Retailcrm_Retailcrm" />
</route>
</router>
</config>

4
etc/module.xml Normal file
View File

@ -0,0 +1,4 @@
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Retailcrm_Retailcrm" setup_version="0.0.1"/>
</config>

6
registration.php Normal file
View File

@ -0,0 +1,6 @@
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Retailcrm_Retailcrm',
__DIR__
);

View File

@ -1,12 +0,0 @@
<?php
ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR
. dirname(__FILE__) . '/../../app' . PATH_SEPARATOR . dirname(__FILE__));
//Set custom memory limit
ini_set('memory_limit', '512M');
//Include Magento libraries
require_once 'Mage.php';
//Start the Magento application
Mage::app('default');
//Avoid issues "Headers already send"
session_start();

View File

@ -1,20 +0,0 @@
<?xml version="1.0" encoding="UTF-8" ?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
syntaxCheck="true"
bootstrap="./autoload.php">
<testsuite name="Magento Unit Test">
<directory>testsuite</directory>
</testsuite>
<filter>
<whitelist>
<directory>../../app/code/community</directory>
</whitelist>
</filter>
</phpunit>

View File

@ -1,22 +0,0 @@
<?php
class Retailcrm_Retailcrm_Model_IcmlTest extends PHPUnit_Framework_TestCase
{
public function setUp()
{
Mage::reset ();
$app = Mage::app('default');
Mage::dispatchEvent('controller_front_init_before');
$this->_block = new Retailcrm_Retailcrm_Model_Icml;
}
protected function tearDown()
{
}
public function testFirstMethod()
{
$this->assertInstanceOf('Retailcrm_Retailcrm_Model_Icml',$this->_block);
}
}

View File

@ -1,27 +0,0 @@
<?php
class Retailcrm_Retailcrm_Model_OrderTest extends PHPUnit_Framework_TestCase
{
protected function setUp()
{
Mage::reset ();
Mage::app ('default');
Mage::dispatchEvent('controller_front_init_before');
$this->_block = new Retailcrm_Retailcrm_Model_Order;
}
protected function tearDown()
{
}
public function testFirstMethod()
{
$this->assertInstanceOf('Retailcrm_Retailcrm_Model_Order',$this->_block);
}
public function testSecondMethod()
{
}
}

View File

@ -0,0 +1,27 @@
<script>
require([
'jquery',
'prototype',
], function(jQuery){
function syncronize() {
params = {
};
new Ajax.Request('<?php echo $block->getAjaxSyncUrl() ?>', {
loaderArea: false,
asynchronous: true,
parameters: params,
onSuccess: function(transport) {
var response = JSON.parse(transport.responseText);
}
});
}
jQuery('#order_button').click(function () {
syncronize();
});
});
</script>
<?php echo $block->getButtonHtml() ?>

View File

@ -0,0 +1,6 @@
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<referenceContainer name="content">
<block class="Retailcrm\Retailcrm\Block\Display" name="retailcrm_display" template="Retailcrm_Retailcrm::sayhello.phtml" />
</referenceContainer>
</page>

0
view/templates/.gitkeep Normal file
View File