diff --git a/Block/Adminhtml/System/Config/Button.php b/Block/Adminhtml/System/Config/Button.php new file mode 100644 index 0000000..872c540 --- /dev/null +++ b/Block/Adminhtml/System/Config/Button.php @@ -0,0 +1,75 @@ +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(); + } +} \ No newline at end of file diff --git a/Block/Adminhtml/System/Config/Form/Field/Attributes.php b/Block/Adminhtml/System/Config/Form/Field/Attributes.php new file mode 100644 index 0000000..d7c933e --- /dev/null +++ b/Block/Adminhtml/System/Config/Form/Field/Attributes.php @@ -0,0 +1,61 @@ +getValues(); + $html = ''; + $html .= ''; + $html .= '
    '; + + $selected = explode(',', $element->getValue()); + foreach ($selected as $value) { + if ($key = array_search($value, array_column($values, 'value'))) { + $html .= '
  • '; + $html .= isset($values[$key]['label'])?$values[$key]['label']:'n/a'; + $html .= '
  • '; + $values[$key]['selected'] = TRUE; + } + } + + $html .= '
'; + $html .= '
    '; + if ($values) { + foreach ($values as $option) { + if (!isset($option['selected'])) { + $html .= '
  • '; + $html .= isset($option['label'])?$option['label']:'n/a'; + $html .= '
  • '; + } + } + } + + $html .= '
'; + $html .= '
' . $element->getElementHtml() . '
'; + $html .= ''; + + return $html; + } + +} \ No newline at end of file diff --git a/Block/Adminhtml/System/Config/Form/Field/Base.php b/Block/Adminhtml/System/Config/Form/Field/Base.php new file mode 100644 index 0000000..9a7d11b --- /dev/null +++ b/Block/Adminhtml/System/Config/Form/Field/Base.php @@ -0,0 +1,72 @@ +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
'; + echo 'Please check your Url and Reload page
'; + + $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); + } + +} \ No newline at end of file diff --git a/Block/Adminhtml/System/Config/Form/Field/Payment.php b/Block/Adminhtml/System/Config/Form/Field/Payment.php new file mode 100644 index 0000000..567af4d --- /dev/null +++ b/Block/Adminhtml/System/Config/Form/Field/Payment.php @@ -0,0 +1,96 @@ +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 .=''; + $html .=''; + $html .=''; + $html .=''; + $html .=''; + $html .='
'.$payment.''; + $html .=''; + $html .='
'; + + } + + return $html; + }else{ + $html = '
Please check your API Url & API Key
'; + + return $html; + } + } + + +} \ No newline at end of file diff --git a/Block/Adminhtml/System/Config/Form/Field/Shipping.php b/Block/Adminhtml/System/Config/Form/Field/Shipping.php new file mode 100644 index 0000000..7fd896b --- /dev/null +++ b/Block/Adminhtml/System/Config/Form/Field/Shipping.php @@ -0,0 +1,99 @@ +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 .=''; + $html .=''; + $html .=''; + $html .=''; + $html .=''; + $html .='
'.$delivery.''; + $html .=''; + $html .='
'; + + } + + return $html; + + } else { + $html .= '
Please check your API Url & API Key
'; + } + + $html = ''; + + return $html; + + } + + +} \ No newline at end of file diff --git a/Block/Adminhtml/System/Config/Form/Field/Status.php b/Block/Adminhtml/System/Config/Form/Field/Status.php new file mode 100644 index 0000000..803a4f5 --- /dev/null +++ b/Block/Adminhtml/System/Config/Form/Field/Status.php @@ -0,0 +1,96 @@ +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 .=''; + $html .=''; + $html .=''; + $html .=''; + $html .=''; + $html .='
'.$status['label'].''; + $html .=''; + $html .='
'; + + } + + return $html; + + }else{ + $html = '
Please check your API Url & API Key
'; + + return $html; + } + } + + +} \ No newline at end of file diff --git a/Block/Display.php b/Block/Display.php new file mode 100644 index 0000000..02d3588 --- /dev/null +++ b/Block/Display.php @@ -0,0 +1,17 @@ +_logger = $logger; + parent::__construct($context); + } + + + public function execute() + { + $order = new \Retailcrm\Retailcrm\Model\Order\OrderNumber(); + $order->ExportOrderNumber(); + } +} \ No newline at end of file diff --git a/Controller/Index/Display.php b/Controller/Index/Display.php new file mode 100644 index 0000000..fa3938b --- /dev/null +++ b/Controller/Index/Display.php @@ -0,0 +1,19 @@ +_pageFactory = $pageFactory; + return parent::__construct($context); + } + + public function execute() + { + return $this->_pageFactory->create(); + } +} \ No newline at end of file diff --git a/Controller/Index/Test.php b/Controller/Index/Test.php new file mode 100644 index 0000000..5d46c4e --- /dev/null +++ b/Controller/Index/Test.php @@ -0,0 +1,38 @@ +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; + } + +} \ No newline at end of file diff --git a/Cron/Icml.php b/Cron/Icml.php new file mode 100644 index 0000000..cac587f --- /dev/null +++ b/Cron/Icml.php @@ -0,0 +1,20 @@ +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'); + } + +} diff --git a/Cron/OrderHistory.php b/Cron/OrderHistory.php new file mode 100644 index 0000000..b2d1229 --- /dev/null +++ b/Cron/OrderHistory.php @@ -0,0 +1,20 @@ +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'); + } + +} \ No newline at end of file diff --git a/Helper/Data.php b/Helper/Data.php new file mode 100644 index 0000000..d94655c --- /dev/null +++ b/Helper/Data.php @@ -0,0 +1,67 @@ +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; + } +} \ No newline at end of file diff --git a/Log/.gitkeep b/Log/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/app/code/community/Retailcrm/Retailcrm/Model/ApiClient.php b/Model/ApiClient/ApiClient.php similarity index 83% rename from app/code/community/Retailcrm/Retailcrm/Model/ApiClient.php rename to Model/ApiClient/ApiClient.php index 72599ec..49c7674 100644 --- a/app/code/community/Retailcrm/Retailcrm/Model/ApiClient.php +++ b/Model/ApiClient/ApiClient.php @@ -11,7 +11,24 @@ * @license https://opensource.org/licenses/MIT MIT License * @link http://www.retailcrm.ru/docs/Developers/ApiVersion4 */ -class Retailcrm_Retailcrm_Model_ApiClient + +namespace Retailcrm\Retailcrm\Model\ApiClient; + +use Retailcrm\Retailcrm\Model\ApiClient\Http\Client; +use Retailcrm\Retailcrm\Model\ApiClient\Response\ApiResponse; + +/** + * PHP version 5.3 + * + * API client class + * + * @category RetailCrm + * @package RetailCrm + * @author RetailCrm + * @license https://opensource.org/licenses/MIT MIT License + * @link http://www.retailcrm.ru/docs/Developers/ApiVersion4 + */ +class ApiClient { const VERSION = 'v4'; @@ -40,9 +57,8 @@ class Retailcrm_Retailcrm_Model_ApiClient $url = $url . 'api/' . self::VERSION; - $this->client = new Retailcrm_Retailcrm_Model_Http_Client($url, array('apiKey' => $apiKey)); + $this->client = new Client($url, array('apiKey' => $apiKey)); $this->siteCode = $site; - } /** @@ -61,22 +77,20 @@ class Retailcrm_Retailcrm_Model_ApiClient public function usersList(array $filter = array(), $page = null, $limit = null) { $parameters = array(); - + if (count($filter)) { $parameters['filter'] = $filter; } - if (null !== $page) { $parameters['page'] = (int) $page; } - if (null !== $limit) { $parameters['limit'] = (int) $limit; } - + return $this->client->makeRequest( '/users', - Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET, + Client::METHOD_GET, $parameters ); } @@ -99,14 +113,13 @@ class Retailcrm_Retailcrm_Model_ApiClient if (null !== $page) { $parameters['page'] = (int) $page; } - if (null !== $limit) { $parameters['limit'] = (int) $limit; } return $this->client->makeRequest( '/user-groups', - Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET, + Client::METHOD_GET, $parameters ); } @@ -124,7 +137,7 @@ class Retailcrm_Retailcrm_Model_ApiClient */ public function usersGet($id) { - return $this->client->makeRequest("/users/$id", Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET); + return $this->client->makeRequest("/users/$id", Client::METHOD_GET); } /** @@ -147,18 +160,16 @@ class Retailcrm_Retailcrm_Model_ApiClient if (count($filter)) { $parameters['filter'] = $filter; } - if (null !== $page) { $parameters['page'] = (int) $page; } - if (null !== $limit) { $parameters['limit'] = (int) $limit; } - + return $this->client->makeRequest( '/orders', - Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET, + Client::METHOD_GET, $parameters ); } @@ -178,14 +189,14 @@ class Retailcrm_Retailcrm_Model_ApiClient public function ordersCreate(array $order, $site = null) { if (!count($order)) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + throw new \InvalidArgumentException( 'Parameter `order` must contains a data' ); } return $this->client->makeRequest( '/orders/create', - Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, + Client::METHOD_POST, $this->fillSite($site, array('order' => json_encode($order))) ); } @@ -204,14 +215,14 @@ class Retailcrm_Retailcrm_Model_ApiClient public function ordersFixExternalIds(array $ids) { if (! count($ids)) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + throw new \InvalidArgumentException( 'Method parameter must contains at least one IDs pair' ); } return $this->client->makeRequest( '/orders/fix-external-ids', - Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, + Client::METHOD_POST, array('orders' => json_encode($ids) ) ); @@ -236,14 +247,13 @@ class Retailcrm_Retailcrm_Model_ApiClient if (count($ids)) { $parameters['ids'] = $ids; } - if (count($externalIds)) { $parameters['externalIds'] = $externalIds; } - + return $this->client->makeRequest( '/orders/statuses', - Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET, + Client::METHOD_GET, $parameters ); } @@ -263,14 +273,14 @@ class Retailcrm_Retailcrm_Model_ApiClient public function ordersUpload(array $orders, $site = null) { if (!count($orders)) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + throw new \InvalidArgumentException( 'Parameter `orders` must contains array of the orders' ); } return $this->client->makeRequest( '/orders/upload', - Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, + Client::METHOD_POST, $this->fillSite($site, array('orders' => json_encode($orders))) ); } @@ -294,7 +304,7 @@ class Retailcrm_Retailcrm_Model_ApiClient return $this->client->makeRequest( "/orders/$id", - Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET, + Client::METHOD_GET, $this->fillSite($site, array('by' => $by)) ); } @@ -315,7 +325,7 @@ class Retailcrm_Retailcrm_Model_ApiClient public function ordersEdit(array $order, $by = 'externalId', $site = null) { if (!count($order)) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + throw new \InvalidArgumentException( 'Parameter `order` must contains a data' ); } @@ -323,14 +333,14 @@ class Retailcrm_Retailcrm_Model_ApiClient $this->checkIdParameter($by); if (!array_key_exists($by, $order)) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + throw new \InvalidArgumentException( sprintf('Order array must contain the "%s" parameter.', $by) ); } return $this->client->makeRequest( sprintf('/orders/%s/edit', $order[$by]), - Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, + Client::METHOD_POST, $this->fillSite( $site, array('order' => json_encode($order), 'by' => $by) @@ -353,18 +363,16 @@ class Retailcrm_Retailcrm_Model_ApiClient if (count($filter)) { $parameters['filter'] = $filter; } - if (null !== $page) { $parameters['page'] = (int) $page; } - if (null !== $limit) { $parameters['limit'] = (int) $limit; } return $this->client->makeRequest( '/orders/history', - Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET, + Client::METHOD_GET, $parameters ); } @@ -389,18 +397,16 @@ class Retailcrm_Retailcrm_Model_ApiClient if (count($filter)) { $parameters['filter'] = $filter; } - if (null !== $page) { $parameters['page'] = (int) $page; } - if (null !== $limit) { $parameters['limit'] = (int) $limit; } return $this->client->makeRequest( '/customers', - Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET, + Client::METHOD_GET, $parameters ); } @@ -420,14 +426,14 @@ class Retailcrm_Retailcrm_Model_ApiClient public function customersCreate(array $customer, $site = null) { if (! count($customer)) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + throw new \InvalidArgumentException( 'Parameter `customer` must contains a data' ); } return $this->client->makeRequest( '/customers/create', - Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, + Client::METHOD_POST, $this->fillSite($site, array('customer' => json_encode($customer))) ); } @@ -446,14 +452,14 @@ class Retailcrm_Retailcrm_Model_ApiClient public function customersFixExternalIds(array $ids) { if (! count($ids)) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + throw new \InvalidArgumentException( 'Method parameter must contains at least one IDs pair' ); } return $this->client->makeRequest( '/customers/fix-external-ids', - Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, + Client::METHOD_POST, array('customers' => json_encode($ids)) ); } @@ -473,14 +479,14 @@ class Retailcrm_Retailcrm_Model_ApiClient public function customersUpload(array $customers, $site = null) { if (! count($customers)) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + throw new \InvalidArgumentException( 'Parameter `customers` must contains array of the customers' ); } return $this->client->makeRequest( '/customers/upload', - Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, + Client::METHOD_POST, $this->fillSite($site, array('customers' => json_encode($customers))) ); } @@ -504,7 +510,7 @@ class Retailcrm_Retailcrm_Model_ApiClient return $this->client->makeRequest( "/customers/$id", - Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET, + Client::METHOD_GET, $this->fillSite($site, array('by' => $by)) ); } @@ -525,7 +531,7 @@ class Retailcrm_Retailcrm_Model_ApiClient public function customersEdit(array $customer, $by = 'externalId', $site = null) { if (!count($customer)) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + throw new \InvalidArgumentException( 'Parameter `customer` must contains a data' ); } @@ -533,14 +539,14 @@ class Retailcrm_Retailcrm_Model_ApiClient $this->checkIdParameter($by); if (!array_key_exists($by, $customer)) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + throw new \InvalidArgumentException( sprintf('Customer array must contain the "%s" parameter.', $by) ); } return $this->client->makeRequest( sprintf('/customers/%s/edit', $customer[$by]), - Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, + Client::METHOD_POST, $this->fillSite( $site, array('customer' => json_encode($customer), 'by' => $by) @@ -563,18 +569,16 @@ class Retailcrm_Retailcrm_Model_ApiClient if (count($filter)) { $parameters['filter'] = $filter; } - if (null !== $page) { $parameters['page'] = (int) $page; } - if (null !== $limit) { $parameters['limit'] = (int) $limit; } return $this->client->makeRequest( '/customers/history', - Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET, + Client::METHOD_GET, $parameters ); } @@ -599,18 +603,16 @@ class Retailcrm_Retailcrm_Model_ApiClient if (count($filter)) { $parameters['filter'] = $filter; } - if (null !== $page) { $parameters['page'] = (int) $page; } - if (null !== $limit) { $parameters['limit'] = (int) $limit; } return $this->client->makeRequest( '/orders/packs', - Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET, + Client::METHOD_GET, $parameters ); } @@ -630,14 +632,14 @@ class Retailcrm_Retailcrm_Model_ApiClient public function ordersPacksCreate(array $pack, $site = null) { if (!count($pack)) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + throw new \InvalidArgumentException( 'Parameter `pack` must contains a data' ); } return $this->client->makeRequest( '/orders/packs/create', - Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, + Client::METHOD_POST, $this->fillSite($site, array('pack' => json_encode($pack))) ); } @@ -662,18 +664,16 @@ class Retailcrm_Retailcrm_Model_ApiClient if (count($filter)) { $parameters['filter'] = $filter; } - if (null !== $page) { $parameters['page'] = (int) $page; } - if (null !== $limit) { $parameters['limit'] = (int) $limit; } return $this->client->makeRequest( '/orders/packs/history', - Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET, + Client::METHOD_GET, $parameters ); } @@ -692,12 +692,12 @@ class Retailcrm_Retailcrm_Model_ApiClient public function ordersPacksGet($id) { if (empty($id)) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException('Parameter `id` must be set'); + throw new \InvalidArgumentException('Parameter `id` must be set'); } return $this->client->makeRequest( "/orders/packs/$id", - Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET + Client::METHOD_GET ); } @@ -715,12 +715,12 @@ class Retailcrm_Retailcrm_Model_ApiClient public function ordersPacksDelete($id) { if (empty($id)) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException('Parameter `id` must be set'); + throw new \InvalidArgumentException('Parameter `id` must be set'); } return $this->client->makeRequest( sprintf('/orders/packs/%s/delete', $id), - Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST + Client::METHOD_POST ); } @@ -739,14 +739,14 @@ class Retailcrm_Retailcrm_Model_ApiClient public function ordersPacksEdit(array $pack, $site = null) { if (!count($pack) || empty($pack['id'])) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + throw new \InvalidArgumentException( 'Parameter `pack` must contains a data & pack `id` must be set' ); } return $this->client->makeRequest( sprintf('/orders/packs/%s/edit', $pack['id']), - Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, + Client::METHOD_POST, $this->fillSite($site, array('pack' => json_encode($pack))) ); } @@ -771,18 +771,16 @@ class Retailcrm_Retailcrm_Model_ApiClient if (count($filter)) { $parameters['filter'] = $filter; } - if (null !== $page) { $parameters['page'] = (int) $page; } - if (null !== $limit) { $parameters['limit'] = (int) $limit; } return $this->client->makeRequest( '/store/inventories', - Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, + Client::METHOD_GET, $parameters ); } @@ -802,12 +800,12 @@ class Retailcrm_Retailcrm_Model_ApiClient public function storeSettingsGet($code) { if (empty($code)) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException('Parameter `code` must be set'); + throw new \InvalidArgumentException('Parameter `code` must be set'); } return $this->client->makeRequest( "/store/setting/$code", - Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET + Client::METHOD_GET ); } @@ -825,14 +823,14 @@ class Retailcrm_Retailcrm_Model_ApiClient public function storeSettingsEdit(array $configuration) { if (!count($configuration) || empty($configuration['code'])) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + throw new \InvalidArgumentException( 'Parameter `configuration` must contains a data & configuration `code` must be set' ); } return $this->client->makeRequest( sprintf('/store/setting/%s/edit', $configuration['code']), - Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, + Client::METHOD_POST, array('configuration' => json_encode($configuration)) ); } @@ -852,14 +850,14 @@ class Retailcrm_Retailcrm_Model_ApiClient public function storeInventoriesUpload(array $offers, $site = null) { if (!count($offers)) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + throw new \InvalidArgumentException( 'Parameter `offers` must contains array of the offers' ); } return $this->client->makeRequest( '/store/inventories/upload', - Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, + Client::METHOD_POST, $this->fillSite($site, array('offers' => json_encode($offers))) ); } @@ -879,14 +877,14 @@ class Retailcrm_Retailcrm_Model_ApiClient public function storePricesUpload(array $prices, $site = null) { if (!count($prices)) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + throw new \InvalidArgumentException( 'Parameter `prices` must contains array of the prices' ); } return $this->client->makeRequest( '/store/prices/upload', - Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, + Client::METHOD_POST, $this->fillSite($site, array('prices' => json_encode($prices))) ); } @@ -911,18 +909,16 @@ class Retailcrm_Retailcrm_Model_ApiClient if (count($filter)) { $parameters['filter'] = $filter; } - if (null !== $page) { $parameters['page'] = (int) $page; } - if (null !== $limit) { $parameters['limit'] = (int) $limit; } - + return $this->client->makeRequest( '/store/products', - Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, + Client::METHOD_GET, $parameters ); } @@ -941,12 +937,12 @@ class Retailcrm_Retailcrm_Model_ApiClient public function deliverySettingsGet($code) { if (empty($code)) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException('Parameter `code` must be set'); + throw new \InvalidArgumentException('Parameter `code` must be set'); } return $this->client->makeRequest( "/delivery/generic/setting/$code", - Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST + Client::METHOD_GET ); } @@ -964,14 +960,14 @@ class Retailcrm_Retailcrm_Model_ApiClient public function deliverySettingsEdit(array $configuration) { if (!count($configuration) || empty($configuration['code'])) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + throw new \InvalidArgumentException( 'Parameter `configuration` must contains a data & configuration `code` must be set' ); } return $this->client->makeRequest( sprintf('/delivery/generic/setting/%s/edit', $configuration['code']), - Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, + Client::METHOD_POST, array('configuration' => json_encode($configuration)) ); } @@ -991,18 +987,18 @@ class Retailcrm_Retailcrm_Model_ApiClient public function deliveryTracking($code, array $statusUpdate) { if (empty($code)) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException('Parameter `code` must be set'); + throw new \InvalidArgumentException('Parameter `code` must be set'); } if (!count($statusUpdate)) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + throw new \InvalidArgumentException( 'Parameter `statusUpdate` must contains a data' ); } return $this->client->makeRequest( sprintf('/delivery/generic/%s/tracking', $code), - Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, + Client::METHOD_POST, $statusUpdate ); } @@ -1020,7 +1016,7 @@ class Retailcrm_Retailcrm_Model_ApiClient { return $this->client->makeRequest( '/reference/countries', - Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST + Client::METHOD_GET ); } @@ -1037,7 +1033,7 @@ class Retailcrm_Retailcrm_Model_ApiClient { return $this->client->makeRequest( '/reference/delivery-services', - Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST + Client::METHOD_GET ); } @@ -1055,14 +1051,14 @@ class Retailcrm_Retailcrm_Model_ApiClient public function deliveryServicesEdit(array $data) { if (!array_key_exists('code', $data)) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + throw new \InvalidArgumentException( 'Data must contain "code" parameter.' ); } return $this->client->makeRequest( sprintf('/reference/delivery-services/%s/edit', $data['code']), - Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, + Client::METHOD_POST, array('deliveryService' => json_encode($data)) ); } @@ -1080,7 +1076,7 @@ class Retailcrm_Retailcrm_Model_ApiClient { return $this->client->makeRequest( '/reference/delivery-types', - Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET + Client::METHOD_GET ); } @@ -1098,14 +1094,14 @@ class Retailcrm_Retailcrm_Model_ApiClient public function deliveryTypesEdit(array $data) { if (!array_key_exists('code', $data)) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + throw new \InvalidArgumentException( 'Data must contain "code" parameter.' ); } return $this->client->makeRequest( sprintf('/reference/delivery-types/%s/edit', $data['code']), - Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, + Client::METHOD_POST, array('deliveryType' => json_encode($data)) ); } @@ -1123,7 +1119,7 @@ class Retailcrm_Retailcrm_Model_ApiClient { return $this->client->makeRequest( '/reference/order-methods', - Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST + Client::METHOD_GET ); } @@ -1141,14 +1137,14 @@ class Retailcrm_Retailcrm_Model_ApiClient public function orderMethodsEdit(array $data) { if (!array_key_exists('code', $data)) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + throw new \InvalidArgumentException( 'Data must contain "code" parameter.' ); } return $this->client->makeRequest( sprintf('/reference/order-methods/%s/edit', $data['code']), - Retailcrm_Retailcrm_Model_Http_Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, + Client::METHOD_POST, array('orderMethod' => json_encode($data)) ); } @@ -1166,7 +1162,7 @@ class Retailcrm_Retailcrm_Model_ApiClient { return $this->client->makeRequest( '/reference/order-types', - Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST + Client::METHOD_GET ); } @@ -1184,14 +1180,14 @@ class Retailcrm_Retailcrm_Model_ApiClient public function orderTypesEdit(array $data) { if (!array_key_exists('code', $data)) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + throw new \InvalidArgumentException( 'Data must contain "code" parameter.' ); } return $this->client->makeRequest( sprintf('/reference/order-types/%s/edit', $data['code']), - Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, + Client::METHOD_POST, array('orderType' => json_encode($data)) ); } @@ -1209,7 +1205,7 @@ class Retailcrm_Retailcrm_Model_ApiClient { return $this->client->makeRequest( '/reference/payment-statuses', - Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET + Client::METHOD_GET ); } @@ -1227,14 +1223,14 @@ class Retailcrm_Retailcrm_Model_ApiClient public function paymentStatusesEdit(array $data) { if (!array_key_exists('code', $data)) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + throw new \InvalidArgumentException( 'Data must contain "code" parameter.' ); } return $this->client->makeRequest( sprintf('/reference/payment-statuses/%s/edit', $data['code']), - Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, + Client::METHOD_POST, array('paymentStatus' => json_encode($data)) ); } @@ -1252,7 +1248,7 @@ class Retailcrm_Retailcrm_Model_ApiClient { return $this->client->makeRequest( '/reference/payment-types', - Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET + Client::METHOD_GET ); } @@ -1270,14 +1266,14 @@ class Retailcrm_Retailcrm_Model_ApiClient public function paymentTypesEdit(array $data) { if (!array_key_exists('code', $data)) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + throw new \InvalidArgumentException( 'Data must contain "code" parameter.' ); } return $this->client->makeRequest( sprintf('/reference/payment-types/%s/edit', $data['code']), - Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, + Client::METHOD_POST, array('paymentType' => json_encode($data)) ); } @@ -1295,7 +1291,7 @@ class Retailcrm_Retailcrm_Model_ApiClient { return $this->client->makeRequest( '/reference/product-statuses', - Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST + Client::METHOD_GET ); } @@ -1313,14 +1309,14 @@ class Retailcrm_Retailcrm_Model_ApiClient public function productStatusesEdit(array $data) { if (!array_key_exists('code', $data)) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + throw new \InvalidArgumentException( 'Data must contain "code" parameter.' ); } return $this->client->makeRequest( sprintf('/reference/product-statuses/%s/edit', $data['code']), - Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, + Client::METHOD_POST, array('productStatus' => json_encode($data)) ); } @@ -1338,7 +1334,7 @@ class Retailcrm_Retailcrm_Model_ApiClient { return $this->client->makeRequest( '/reference/sites', - Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET + Client::METHOD_GET ); } @@ -1356,14 +1352,14 @@ class Retailcrm_Retailcrm_Model_ApiClient public function sitesEdit(array $data) { if (!array_key_exists('code', $data)) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + throw new \InvalidArgumentException( 'Data must contain "code" parameter.' ); } return $this->client->makeRequest( sprintf('/reference/sites/%s/edit', $data['code']), - Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, + Client::METHOD_POST, array('site' => json_encode($data)) ); } @@ -1381,7 +1377,7 @@ class Retailcrm_Retailcrm_Model_ApiClient { return $this->client->makeRequest( '/reference/status-groups', - Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET + Client::METHOD_GET ); } @@ -1398,7 +1394,7 @@ class Retailcrm_Retailcrm_Model_ApiClient { return $this->client->makeRequest( '/reference/statuses', - Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET + Client::METHOD_GET ); } @@ -1416,14 +1412,14 @@ class Retailcrm_Retailcrm_Model_ApiClient public function statusesEdit(array $data) { if (!array_key_exists('code', $data)) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + throw new \InvalidArgumentException( 'Data must contain "code" parameter.' ); } return $this->client->makeRequest( sprintf('/reference/statuses/%s/edit', $data['code']), - Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, + Client::METHOD_POST, array('status' => json_encode($data)) ); } @@ -1441,7 +1437,7 @@ class Retailcrm_Retailcrm_Model_ApiClient { return $this->client->makeRequest( '/reference/stores', - Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET + Client::METHOD_GET ); } @@ -1459,20 +1455,20 @@ class Retailcrm_Retailcrm_Model_ApiClient public function storesEdit(array $data) { if (!array_key_exists('code', $data)) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + throw new \InvalidArgumentException( 'Data must contain "code" parameter.' ); } if (!array_key_exists('name', $data)) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + throw new \InvalidArgumentException( 'Data must contain "name" parameter.' ); } return $this->client->makeRequest( sprintf('/reference/stores/%s/edit', $data['code']), - Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, + Client::METHOD_POST, array('store' => json_encode($data)) ); } @@ -1489,7 +1485,7 @@ class Retailcrm_Retailcrm_Model_ApiClient { return $this->client->makeRequest( '/reference/price-types', - Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET + Client::METHOD_GET ); } @@ -1507,20 +1503,20 @@ class Retailcrm_Retailcrm_Model_ApiClient public function pricesEdit(array $data) { if (!array_key_exists('code', $data)) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + throw new \InvalidArgumentException( 'Data must contain "code" parameter.' ); } if (!array_key_exists('name', $data)) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + throw new \InvalidArgumentException( 'Data must contain "name" parameter.' ); } return $this->client->makeRequest( sprintf('/reference/price-types/%s/edit', $data['code']), - Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, + Client::METHOD_POST, array('priceType' => json_encode($data)) ); } @@ -1539,12 +1535,12 @@ class Retailcrm_Retailcrm_Model_ApiClient public function telephonySettingsGet($code) { if (empty($code)) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException('Parameter `code` must be set'); + throw new \InvalidArgumentException('Parameter `code` must be set'); } return $this->client->makeRequest( "/telephony/setting/$code", - Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST + Client::METHOD_GET ); } @@ -1568,16 +1564,30 @@ class Retailcrm_Retailcrm_Model_ApiClient * * @return ApiResponse */ - public function telephonySettingsEdit($code,$clientId,$active = false,$name = false,$makeCallUrl = false,$image = false,$additionalCodes = array(),$externalPhones = array(),$allowEdit = false,$inputEventSupported = false,$outputEventSupported = false,$hangupEventSupported = false,$changeUserStatusUrl = false) + public function telephonySettingsEdit( + $code, + $clientId, + $active = false, + $name = false, + $makeCallUrl = false, + $image = false, + $additionalCodes = array(), + $externalPhones = array(), + $allowEdit = false, + $inputEventSupported = false, + $outputEventSupported = false, + $hangupEventSupported = false, + $changeUserStatusUrl = false + ) { if (!isset($code)) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException('Code must be set'); + throw new \InvalidArgumentException('Code must be set'); } $parameters['code'] = $code; if (!isset($clientId)) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException('client id must be set'); + throw new \InvalidArgumentException('client id must be set'); } $parameters['clientId'] = $clientId; @@ -1589,7 +1599,7 @@ class Retailcrm_Retailcrm_Model_ApiClient } if (!isset($name)) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException('name must be set'); + throw new \InvalidArgumentException('name must be set'); } if (isset($name)) { @@ -1634,7 +1644,7 @@ class Retailcrm_Retailcrm_Model_ApiClient return $this->client->makeRequest( "/telephony/setting/$code/edit", - Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, + Client::METHOD_POST, array('configuration' => json_encode($parameters)) ); } @@ -1654,18 +1664,25 @@ class Retailcrm_Retailcrm_Model_ApiClient * @internal param string $status call status * */ - public function telephonyCallEvent($phone,$type,$codes,$hangupStatus,$externalPhone = null,$webAnalyticsData = array()) + public function telephonyCallEvent( + $phone, + $type, + $codes, + $hangupStatus, + $externalPhone = null, + $webAnalyticsData = array() + ) { if (!isset($phone)) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException('Phone number must be set'); + throw new \InvalidArgumentException('Phone number must be set'); } if (!isset($type)) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException('Type must be set (in|out|hangup)'); + throw new \InvalidArgumentException('Type must be set (in|out|hangup)'); } if (empty($codes)) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException('Codes array must be set'); + throw new \InvalidArgumentException('Codes array must be set'); } $parameters['phone'] = $phone; @@ -1678,7 +1695,7 @@ class Retailcrm_Retailcrm_Model_ApiClient return $this->client->makeRequest( '/telephony/call/event', - Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, + Client::METHOD_POST, array('event' => json_encode($parameters)) ); } @@ -1697,14 +1714,14 @@ class Retailcrm_Retailcrm_Model_ApiClient public function telephonyCallsUpload(array $calls) { if (!count($calls)) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + throw new \InvalidArgumentException( 'Parameter `calls` must contains array of the calls' ); } return $this->client->makeRequest( '/telephony/calls/upload', - Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, + Client::METHOD_POST, array('calls' => json_encode($calls)) ); } @@ -1724,7 +1741,7 @@ class Retailcrm_Retailcrm_Model_ApiClient public function telephonyCallManager($phone, $details) { if (!isset($phone)) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException('Phone number must be set'); + throw new \InvalidArgumentException('Phone number must be set'); } $parameters['phone'] = $phone; @@ -1732,7 +1749,7 @@ class Retailcrm_Retailcrm_Model_ApiClient return $this->client->makeRequest( '/telephony/manager', - Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, + Client::METHOD_GET, $parameters ); } @@ -1750,7 +1767,7 @@ class Retailcrm_Retailcrm_Model_ApiClient { return $this->client->makeRequest( '/statistic/update', - Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST + Client::METHOD_GET ); } @@ -1793,7 +1810,7 @@ class Retailcrm_Retailcrm_Model_ApiClient ); if (!in_array($by, $allowedForBy, false)) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + throw new \InvalidArgumentException( sprintf( 'Value "%s" for "by" param is not valid. Allowed values are %s.', $by, diff --git a/Model/ApiClient/Exception/CurlException.php b/Model/ApiClient/Exception/CurlException.php new file mode 100644 index 0000000..d52de1d --- /dev/null +++ b/Model/ApiClient/Exception/CurlException.php @@ -0,0 +1,30 @@ + + * @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 + * @license https://opensource.org/licenses/MIT MIT License + * @link http://www.retailcrm.ru/docs/Developers/ApiVersion4 + */ +class CurlException extends \RuntimeException +{ +} diff --git a/Model/ApiClient/Exception/InvalidJsonException.php b/Model/ApiClient/Exception/InvalidJsonException.php new file mode 100644 index 0000000..cb9437a --- /dev/null +++ b/Model/ApiClient/Exception/InvalidJsonException.php @@ -0,0 +1,30 @@ + + * @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 + * @license https://opensource.org/licenses/MIT MIT License + * @link http://www.retailcrm.ru/docs/Developers/ApiVersion4 + */ +class InvalidJsonException extends \DomainException +{ +} diff --git a/app/code/community/Retailcrm/Retailcrm/Model/Http/Client.php b/Model/ApiClient/Http/Client.php similarity index 77% rename from app/code/community/Retailcrm/Retailcrm/Model/Http/Client.php rename to Model/ApiClient/Http/Client.php index 5a5527f..4cd3b6a 100644 --- a/app/code/community/Retailcrm/Retailcrm/Model/Http/Client.php +++ b/Model/ApiClient/Http/Client.php @@ -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 + * @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); } } diff --git a/app/code/community/Retailcrm/Retailcrm/Model/Response/ApiResponse.php b/Model/ApiClient/Response/ApiResponse.php similarity index 78% rename from app/code/community/Retailcrm/Retailcrm/Model/Response/ApiResponse.php rename to Model/ApiClient/Response/ApiResponse.php index a7208f3..f62b2f6 100644 --- a/app/code/community/Retailcrm/Retailcrm/Model/Response/ApiResponse.php +++ b/Model/ApiClient/Response/ApiResponse.php @@ -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 + * @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]; diff --git a/Model/History/Exchange.php b/Model/History/Exchange.php new file mode 100644 index 0000000..e80ec3d --- /dev/null +++ b/Model/History/Exchange.php @@ -0,0 +1,762 @@ +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]; + } + +} \ No newline at end of file diff --git a/Model/Icml/Icml.php b/Model/Icml/Icml.php new file mode 100644 index 0000000..ebb79bb --- /dev/null +++ b/Model/Icml/Icml.php @@ -0,0 +1,292 @@ +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 = ' + + + '.$this->_manager->getStore()->getName().' + + + + + '; + + $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); + } + } + } + + } + +} \ No newline at end of file diff --git a/Model/Logger/Logger.php b/Model/Logger/Logger.php new file mode 100644 index 0000000..98058cf --- /dev/null +++ b/Model/Logger/Logger.php @@ -0,0 +1,29 @@ +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); + + } + +} diff --git a/Model/Observer/Customer.php b/Model/Observer/Customer.php new file mode 100644 index 0000000..4e07dca --- /dev/null +++ b/Model/Observer/Customer.php @@ -0,0 +1,59 @@ +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'); + + } + + + +} \ No newline at end of file diff --git a/Model/Observer/OrderCreate.php b/Model/Observer/OrderCreate.php new file mode 100644 index 0000000..e4e99e7 --- /dev/null +++ b/Model/Observer/OrderCreate.php @@ -0,0 +1,180 @@ +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); + } +} diff --git a/Model/Observer/OrderUpdate.php b/Model/Observer/OrderUpdate.php new file mode 100644 index 0000000..7adb56f --- /dev/null +++ b/Model/Observer/OrderUpdate.php @@ -0,0 +1,56 @@ +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); + + } + + + } + +} \ No newline at end of file diff --git a/Model/Order/OrderNumber.php b/Model/Order/OrderNumber.php new file mode 100644 index 0000000..8b7dbbd --- /dev/null +++ b/Model/Order/OrderNumber.php @@ -0,0 +1,168 @@ +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); + + } + +} \ No newline at end of file diff --git a/Model/Setting/Attribute.php b/Model/Setting/Attribute.php new file mode 100644 index 0000000..ddf39de --- /dev/null +++ b/Model/Setting/Attribute.php @@ -0,0 +1,37 @@ +_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; + } + + +} diff --git a/Model/Setting/Shipping.php b/Model/Setting/Shipping.php new file mode 100644 index 0000000..68c5cb5 --- /dev/null +++ b/Model/Setting/Shipping.php @@ -0,0 +1,48 @@ +_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; + + } +} \ No newline at end of file diff --git a/Model/Setting/Status.php b/Model/Setting/Status.php new file mode 100644 index 0000000..e2f96c4 --- /dev/null +++ b/Model/Setting/Status.php @@ -0,0 +1,20 @@ +getValue(); + + // Validations + + $this->setValue($exceptions); + + return parent::beforeSave(); + } + + +} \ No newline at end of file diff --git a/README.md b/README.md index 144982f..e3f793c 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/app/code/community/Retailcrm/Retailcrm/Block/Adminhtml/System/Config/Form/Button.php b/app/code/community/Retailcrm/Retailcrm/Block/Adminhtml/System/Config/Form/Button.php deleted file mode 100644 index 953135f..0000000 --- a/app/code/community/Retailcrm/Retailcrm/Block/Adminhtml/System/Config/Form/Button.php +++ /dev/null @@ -1,51 +0,0 @@ -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(); - } -} diff --git a/app/code/community/Retailcrm/Retailcrm/Block/Adminhtml/System/Config/Form/Fieldset/Base.php b/app/code/community/Retailcrm/Retailcrm/Block/Adminhtml/System/Config/Form/Fieldset/Base.php deleted file mode 100644 index 7540e40..0000000 --- a/app/code/community/Retailcrm/Retailcrm/Block/Adminhtml/System/Config/Form/Fieldset/Base.php +++ /dev/null @@ -1,43 +0,0 @@ -_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', ''); - } - } - } - } -} diff --git a/app/code/community/Retailcrm/Retailcrm/Block/Adminhtml/System/Config/Form/Fieldset/Order.php b/app/code/community/Retailcrm/Retailcrm/Block/Adminhtml/System/Config/Form/Fieldset/Order.php deleted file mode 100644 index dc77449..0000000 --- a/app/code/community/Retailcrm/Retailcrm/Block/Adminhtml/System/Config/Form/Fieldset/Order.php +++ /dev/null @@ -1,10 +0,0 @@ -_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 .= '
Please check your API Url & API Key
'; - } - - $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(); - } -} diff --git a/app/code/community/Retailcrm/Retailcrm/Block/Adminhtml/System/Config/Form/Fieldset/Shipping.php b/app/code/community/Retailcrm/Retailcrm/Block/Adminhtml/System/Config/Form/Fieldset/Shipping.php deleted file mode 100644 index 7a79dbb..0000000 --- a/app/code/community/Retailcrm/Retailcrm/Block/Adminhtml/System/Config/Form/Fieldset/Shipping.php +++ /dev/null @@ -1,89 +0,0 @@ -_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 .= '
Please check your API Url & API Key
'; - } - - $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(); - } -} diff --git a/app/code/community/Retailcrm/Retailcrm/Block/Adminhtml/System/Config/Form/Fieldset/Status.php b/app/code/community/Retailcrm/Retailcrm/Block/Adminhtml/System/Config/Form/Fieldset/Status.php deleted file mode 100644 index e2f71c5..0000000 --- a/app/code/community/Retailcrm/Retailcrm/Block/Adminhtml/System/Config/Form/Fieldset/Status.php +++ /dev/null @@ -1,89 +0,0 @@ -_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 .= '
Please check your API Url & API Key
'; - } - - $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(); - } -} diff --git a/app/code/community/Retailcrm/Retailcrm/Helper/Data.php b/app/code/community/Retailcrm/Retailcrm/Helper/Data.php deleted file mode 100644 index b22b438..0000000 --- a/app/code/community/Retailcrm/Retailcrm/Helper/Data.php +++ /dev/null @@ -1,176 +0,0 @@ - - * @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 - * @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; - } -} diff --git a/app/code/community/Retailcrm/Retailcrm/Model/Attribute.php b/app/code/community/Retailcrm/Retailcrm/Model/Attribute.php deleted file mode 100644 index ad7bba3..0000000 --- a/app/code/community/Retailcrm/Retailcrm/Model/Attribute.php +++ /dev/null @@ -1,43 +0,0 @@ -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'), - ); - } -} diff --git a/app/code/community/Retailcrm/Retailcrm/Model/Customer.php b/app/code/community/Retailcrm/Retailcrm/Model/Customer.php deleted file mode 100644 index 13716df..0000000 --- a/app/code/community/Retailcrm/Retailcrm/Model/Customer.php +++ /dev/null @@ -1,75 +0,0 @@ - - * @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; - } -} diff --git a/app/code/community/Retailcrm/Retailcrm/Model/Exception/CurlException.php b/app/code/community/Retailcrm/Retailcrm/Model/Exception/CurlException.php deleted file mode 100644 index 49c6de5..0000000 --- a/app/code/community/Retailcrm/Retailcrm/Model/Exception/CurlException.php +++ /dev/null @@ -1,5 +0,0 @@ -_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]; - } - - -} - diff --git a/app/code/community/Retailcrm/Retailcrm/Model/Icml.php b/app/code/community/Retailcrm/Retailcrm/Model/Icml.php deleted file mode 100644 index c2f1e3a..0000000 --- a/app/code/community/Retailcrm/Retailcrm/Model/Icml.php +++ /dev/null @@ -1,364 +0,0 @@ -_shop = $shop; - - $string = ' - - - '.Mage::app()->getStore($shop)->getName().' - - - - - '; - - $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); - } - } - } - } -} - diff --git a/app/code/community/Retailcrm/Retailcrm/Model/Observer.php b/app/code/community/Retailcrm/Retailcrm/Model/Observer.php deleted file mode 100644 index 332499c..0000000 --- a/app/code/community/Retailcrm/Retailcrm/Model/Observer.php +++ /dev/null @@ -1,72 +0,0 @@ -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(); - } -} diff --git a/app/code/community/Retailcrm/Retailcrm/Model/Rugento b/app/code/community/Retailcrm/Retailcrm/Model/Rugento deleted file mode 100644 index 5706ca9..0000000 --- a/app/code/community/Retailcrm/Retailcrm/Model/Rugento +++ /dev/null @@ -1,431 +0,0 @@ - - * @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]; - } -} diff --git a/app/code/community/Retailcrm/Retailcrm/Model/Settings.php b/app/code/community/Retailcrm/Retailcrm/Model/Settings.php deleted file mode 100644 index f969533..0000000 --- a/app/code/community/Retailcrm/Retailcrm/Model/Settings.php +++ /dev/null @@ -1,92 +0,0 @@ - - * @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'); - } -} diff --git a/app/code/community/Retailcrm/Retailcrm/controllers/Adminhtml/RetailcrmbuttonController.php b/app/code/community/Retailcrm/Retailcrm/controllers/Adminhtml/RetailcrmbuttonController.php deleted file mode 100644 index d2149b3..0000000 --- a/app/code/community/Retailcrm/Retailcrm/controllers/Adminhtml/RetailcrmbuttonController.php +++ /dev/null @@ -1,24 +0,0 @@ -ordersExportNumber(); - } - - /** - * Check is allowed access to action - * - * @return bool - */ - protected function _isAllowed() - { - return Mage::getSingleton('admin/session')->isAllowed('system/config/retailcrm'); - } -} \ No newline at end of file diff --git a/app/code/community/Retailcrm/Retailcrm/etc/config.xml b/app/code/community/Retailcrm/Retailcrm/etc/config.xml deleted file mode 100644 index 359f131..0000000 --- a/app/code/community/Retailcrm/Retailcrm/etc/config.xml +++ /dev/null @@ -1,139 +0,0 @@ - - - - - - 1.0.0 - - - - - - Retailcrm_Retailcrm_Helper - - - - - Retailcrm_Retailcrm_Model - - - - - Retailcrm_Retailcrm_Block - - - - - - - - singleton - Retailcrm_Retailcrm_Model_Observer - orderCreate - - - - - - - - - singleton - Retailcrm_Retailcrm_Model_Observer - orderUpdate - - - - - - - - - singleton - Retailcrm_Retailcrm_Model_Observer - orderStatusHistoryCheck - - - - - - - - - singleton - Retailcrm_Retailcrm_Model_Observer - customerRegister - - - - - - - - - - - - - Retailcrm_Retailcrm - - - - - - - - - * */4 * * * - retailcrm/observer::exportCatalog - - - */5 * * * * - retailcrm/observer::importHistory - - - - - - - - - - - - - - Store RetailCRM Module Section - - - - - - - - - - - diff --git a/app/code/community/Retailcrm/Retailcrm/etc/system.xml b/app/code/community/Retailcrm/Retailcrm/etc/system.xml deleted file mode 100644 index 292274a..0000000 --- a/app/code/community/Retailcrm/Retailcrm/etc/system.xml +++ /dev/null @@ -1,160 +0,0 @@ - - - - - - - 1000 - - - - - - retailcrm-section - retailcrm_extension - text - 10 - 1 - 1 - 1 - - - 1 - - text - 10 - 1 - 1 - 1 - - - - text - 1 - 1 - 1 - 1 - YourCrmName.retailcrm.ru]]> - - - - text - 3 - 1 - 1 - 1 - Integration > API Keys]]> - - - - - 1 - - text - 11 - 1 - 1 - 1 - - - - multiselect - retailcrm/attributes_to_export_into_icml - 7 - retailcrm/attribute - 1 - 1 - 1 - 1 - - - - - 0 - - text - 12 - 1 - 1 - 1 - retailcrm/adminhtml_system_config_form_fieldset_shipping - - - 0 - - text - 13 - 1 - 1 - 1 - retailcrm/adminhtml_system_config_form_fieldset_payment - - - 0 - - text - 14 - 1 - 1 - 1 - retailcrm/adminhtml_system_config_form_fieldset_status - - - - 0 - - text - 15 - 1 - 1 - 1 - retailcrm/adminhtml_system_config_form_fieldset_order - - - - text - 1 - 1 - 1 - 1 - - - - - - - - - - - - diff --git a/app/design/adminhtml/default/default/template/retailcrm/system/config/button.phtml b/app/design/adminhtml/default/default/template/retailcrm/system/config/button.phtml deleted file mode 100644 index 98de835..0000000 --- a/app/design/adminhtml/default/default/template/retailcrm/system/config/button.phtml +++ /dev/null @@ -1,16 +0,0 @@ - - -getButtonHtml() ?> \ No newline at end of file diff --git a/app/etc/modules/Retailcrm_Retailcrm.xml b/app/etc/modules/Retailcrm_Retailcrm.xml deleted file mode 100644 index 5d7a042..0000000 --- a/app/etc/modules/Retailcrm_Retailcrm.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - true - community - - - diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..012b677 --- /dev/null +++ b/composer.json @@ -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\\": "" + } + } +} \ No newline at end of file diff --git a/etc/adminhtml/menu.xml b/etc/adminhtml/menu.xml new file mode 100644 index 0000000..7b3b325 --- /dev/null +++ b/etc/adminhtml/menu.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/etc/adminhtml/routes.xml b/etc/adminhtml/routes.xml new file mode 100644 index 0000000..0755229 --- /dev/null +++ b/etc/adminhtml/routes.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/etc/adminhtml/system.xml b/etc/adminhtml/system.xml new file mode 100644 index 0000000..11d8923 --- /dev/null +++ b/etc/adminhtml/system.xml @@ -0,0 +1,90 @@ + + + + + + +
+ separator-top + + retailcrm + Retailcrm_Retailcrm::retailcrm_configuration + + + + + + https://YourCrmName.retailcrm.ru + + + + + To generate an API Key, log in to RetailCRM then select Admin > Integration > API Keys + + + + + + + + attributes to export into icml + + Retailcrm\Retailcrm\Model\Setting\Attribute + + + + + + + + + + + + Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Field\Shipping + + + + + + + + Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Field\Payment + This text will display on the frontend. + + + + + + + + + + Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Field\Status + This text will display on the frontend. + + + + + + + + + Enter your order number, separated by commas + + + + + Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Button + + + + + +
+
+
+ diff --git a/etc/config.xml b/etc/config.xml new file mode 100644 index 0000000..886840b --- /dev/null +++ b/etc/config.xml @@ -0,0 +1,24 @@ + + + + + + + test + + +
+ + {value} + + + + +
+ +
+ + + +
+
\ No newline at end of file diff --git a/app/code/community/Retailcrm/Retailcrm/etc/country.xml b/etc/country.xml similarity index 100% rename from app/code/community/Retailcrm/Retailcrm/etc/country.xml rename to etc/country.xml diff --git a/etc/crontab.xml b/etc/crontab.xml new file mode 100644 index 0000000..fe8235d --- /dev/null +++ b/etc/crontab.xml @@ -0,0 +1,13 @@ + + + + + * */4 * * * + + + + */5 * * * * + + + + \ No newline at end of file diff --git a/etc/di.xml b/etc/di.xml new file mode 100644 index 0000000..53508f4 --- /dev/null +++ b/etc/di.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/etc/events.xml b/etc/events.xml new file mode 100644 index 0000000..7a6e8ff --- /dev/null +++ b/etc/events.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/etc/frontend/events.xml b/etc/frontend/events.xml new file mode 100644 index 0000000..663136b --- /dev/null +++ b/etc/frontend/events.xml @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/etc/frontend/routes.xml b/etc/frontend/routes.xml new file mode 100644 index 0000000..c0e9a6a --- /dev/null +++ b/etc/frontend/routes.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/etc/module.xml b/etc/module.xml new file mode 100644 index 0000000..3659d71 --- /dev/null +++ b/etc/module.xml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/registration.php b/registration.php new file mode 100644 index 0000000..b717086 --- /dev/null +++ b/registration.php @@ -0,0 +1,6 @@ + - - - testsuite - - - - ../../app/code/community - - - \ No newline at end of file diff --git a/tests/unit/testsuite/Retailcrm/Retailcrm/Model/IcmlTest.php b/tests/unit/testsuite/Retailcrm/Retailcrm/Model/IcmlTest.php deleted file mode 100644 index de9e754..0000000 --- a/tests/unit/testsuite/Retailcrm/Retailcrm/Model/IcmlTest.php +++ /dev/null @@ -1,22 +0,0 @@ -_block = new Retailcrm_Retailcrm_Model_Icml; - } - - protected function tearDown() - { - - } - - public function testFirstMethod() - { - $this->assertInstanceOf('Retailcrm_Retailcrm_Model_Icml',$this->_block); - } -} \ No newline at end of file diff --git a/tests/unit/testsuite/Retailcrm/Retailcrm/Model/OrderTest.php b/tests/unit/testsuite/Retailcrm/Retailcrm/Model/OrderTest.php deleted file mode 100644 index f54b152..0000000 --- a/tests/unit/testsuite/Retailcrm/Retailcrm/Model/OrderTest.php +++ /dev/null @@ -1,27 +0,0 @@ -_block = new Retailcrm_Retailcrm_Model_Order; - } - - protected function tearDown() - { - - } - - public function testFirstMethod() - { - $this->assertInstanceOf('Retailcrm_Retailcrm_Model_Order',$this->_block); - } - - public function testSecondMethod() - { - - } -} \ No newline at end of file diff --git a/view/adminhtml/templates/system/config/button.phtml b/view/adminhtml/templates/system/config/button.phtml new file mode 100644 index 0000000..e7d39dc --- /dev/null +++ b/view/adminhtml/templates/system/config/button.phtml @@ -0,0 +1,27 @@ + + + +getButtonHtml() ?> \ No newline at end of file diff --git a/view/frontend/layout/retailcrm_index_display.xml b/view/frontend/layout/retailcrm_index_display.xml new file mode 100644 index 0000000..368d1f7 --- /dev/null +++ b/view/frontend/layout/retailcrm_index_display.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/view/templates/.gitkeep b/view/templates/.gitkeep new file mode 100644 index 0000000..e69de29