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 new file mode 100644 index 0000000..953135f --- /dev/null +++ b/app/code/community/Retailcrm/Retailcrm/Block/Adminhtml/System/Config/Form/Button.php @@ -0,0 +1,51 @@ +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 index 8ef4e1e..7540e40 100644 --- 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 @@ -6,30 +6,37 @@ class Retailcrm_Retailcrm_Block_Adminhtml_System_Config_Form_Fieldset_Base exten protected $_apiKey; protected $_apiUrl; protected $_isCredentialCorrect; - + public function __construct() { parent::__construct(); $this->_apiUrl = Mage::getStoreConfig('retailcrm/general/api_url'); $this->_apiKey = Mage::getStoreConfig('retailcrm/general/api_key'); - $this->_isCredentialCorrect = false; - if (!empty($this->_apiUrl) && !empty($this->_apiKey)) { - $client = Mage::getModel( - 'retailcrm/ApiClient', - array('url' => $this->_apiUrl, 'key' => $this->_apiKey, 'site' => null) - ); - - try { - $response = $client->sitesList(); - } catch (Retailcrm_Retailcrm_Model_Exception_CurlException $e) { - Mage::log($e->getMessage()); + 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 new file mode 100644 index 0000000..dc77449 --- /dev/null +++ b/app/code/community/Retailcrm/Retailcrm/Block/Adminhtml/System/Config/Form/Fieldset/Order.php @@ -0,0 +1,10 @@ +_fieldRenderer)) { $this->_fieldRenderer = Mage::getBlockSingleton('adminhtml/system_config_form_field'); } + return $this->_fieldRenderer; } @@ -34,9 +35,9 @@ class Retailcrm_Retailcrm_Block_Adminhtml_System_Config_Form_Fieldset_Payment ex protected function _getValues() { if(!empty($this->_apiUrl) && !empty($this->_apiKey) && $this->_isCredentialCorrect) { - $client = Mage::getModel( - 'retailcrm/ApiClient', - array('url' => $this->_apiUrl, 'key' => $this->_apiKey, 'site' => null) + $client = new Retailcrm_Retailcrm_Model_ApiClient( + $this->_apiUrl, + $this->_apiKey ); try { @@ -70,8 +71,8 @@ class Retailcrm_Retailcrm_Block_Adminhtml_System_Config_Form_Fieldset_Payment ex $inherit = true; } - - $field = $fieldset->addField('payment_' . $group->getId(), 'select', + $field = $fieldset->addField( + 'payment_' . $group->getId(), 'select', array( 'name' => 'groups[payment][fields]['.$group->getId().'][value]', 'label' => Mage::getStoreConfig('payment/'.$group->getId().'/title'), @@ -80,7 +81,8 @@ class Retailcrm_Retailcrm_Block_Adminhtml_System_Config_Form_Fieldset_Payment ex 'inherit' => $inherit, 'can_use_default_value' => 1, 'can_use_website_value' => 1 - ))->setRenderer($this->_getFieldRenderer()); + ) + )->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 index 20eea5a..7a79dbb 100644 --- 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 @@ -4,7 +4,7 @@ class Retailcrm_Retailcrm_Block_Adminhtml_System_Config_Form_Fieldset_Shipping e public function render(Varien_Data_Form_Element_Abstract $element) { $html = $this->_getHeaderHtml($element); - + if(!empty($this->_apiUrl) && !empty($this->_apiKey) && $this->_isCredentialCorrect) { $groups = Mage::getSingleton('shipping/config')->getActiveCarriers(); @@ -25,6 +25,7 @@ class Retailcrm_Retailcrm_Block_Adminhtml_System_Config_Form_Fieldset_Shipping e if (empty($this->_fieldRenderer)) { $this->_fieldRenderer = Mage::getBlockSingleton('adminhtml/system_config_form_field'); } + return $this->_fieldRenderer; } @@ -34,9 +35,9 @@ class Retailcrm_Retailcrm_Block_Adminhtml_System_Config_Form_Fieldset_Shipping e protected function _getValues() { if(!empty($this->_apiUrl) && !empty($this->_apiKey) && $this->_isCredentialCorrect) { - $client = Mage::getModel( - 'retailcrm/ApiClient', - array('url' => $this->_apiUrl, 'key' => $this->_apiKey, 'site' => null) + $client = new Retailcrm_Retailcrm_Model_ApiClient( + $this->_apiUrl, + $this->_apiKey ); try { @@ -52,7 +53,6 @@ class Retailcrm_Retailcrm_Block_Adminhtml_System_Config_Form_Fieldset_Shipping e } } } - } return $this->_values; @@ -71,8 +71,8 @@ class Retailcrm_Retailcrm_Block_Adminhtml_System_Config_Form_Fieldset_Shipping e $inherit = true; } - - $field = $fieldset->addField('shipping_' . $group->getId(), 'select', + $field = $fieldset->addField( + 'shipping_' . $group->getId(), 'select', array( 'name' => 'groups[shipping][fields]['.$group->getId().'][value]', 'label' => Mage::getStoreConfig('carriers/'.$group->getId().'/title'), @@ -81,7 +81,8 @@ class Retailcrm_Retailcrm_Block_Adminhtml_System_Config_Form_Fieldset_Shipping e 'inherit' => $inherit, 'can_use_default_value' => 1, 'can_use_website_value' => 1 - ))->setRenderer($this->_getFieldRenderer()); + ) + )->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 index 50e8187..e2f71c5 100644 --- 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 @@ -1,13 +1,11 @@ _getHeaderHtml($element); if(!empty($this->_apiUrl) && !empty($this->_apiKey) && $this->_isCredentialCorrect) { - $statuses = Mage::getModel('sales/order_status')->getResourceCollection()->getData(); foreach ($statuses as $status) { @@ -27,6 +25,7 @@ class Retailcrm_Retailcrm_Block_Adminhtml_System_Config_Form_Fieldset_Status ext if (empty($this->_fieldRenderer)) { $this->_fieldRenderer = Mage::getBlockSingleton('adminhtml/system_config_form_field'); } + return $this->_fieldRenderer; } @@ -36,9 +35,9 @@ class Retailcrm_Retailcrm_Block_Adminhtml_System_Config_Form_Fieldset_Status ext protected function _getValues() { if(!empty($this->_apiUrl) && !empty($this->_apiKey) && $this->_isCredentialCorrect) { - $client = Mage::getModel( - 'retailcrm/ApiClient', - array('url' => $this->_apiUrl, 'key' => $this->_apiKey, 'site' => null) + $client = new Retailcrm_Retailcrm_Model_ApiClient( + $this->_apiUrl, + $this->_apiKey ); try { @@ -54,7 +53,6 @@ class Retailcrm_Retailcrm_Block_Adminhtml_System_Config_Form_Fieldset_Status ext } } } - } return $this->_values; @@ -73,7 +71,8 @@ class Retailcrm_Retailcrm_Block_Adminhtml_System_Config_Form_Fieldset_Status ext $inherit = true; } - $field = $fieldset->addField('status_' . $group['status'], 'select', + $field = $fieldset->addField( + 'status_' . $group['status'], 'select', array( 'name' => 'groups[status][fields]['.$group['status'].'][value]', 'label' => $group['label'], @@ -82,7 +81,8 @@ class Retailcrm_Retailcrm_Block_Adminhtml_System_Config_Form_Fieldset_Status ext 'inherit' => $inherit, 'can_use_default_value' => 1, 'can_use_website_value' => 1 - ))->setRenderer($this->_getFieldRenderer()); + ) + )->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 index f239fce..b22b438 100644 --- a/app/code/community/Retailcrm/Retailcrm/Helper/Data.php +++ b/app/code/community/Retailcrm/Retailcrm/Helper/Data.php @@ -78,18 +78,13 @@ class Retailcrm_Retailcrm_Helper_Data extends Mage_Core_Helper_Abstract * * @return string */ - public function rewrittenProductUrl( - $baseUrl, - $coreUrl, - $productId, - $storeId, - $categoryId = null - ) + 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); @@ -165,6 +160,7 @@ class Retailcrm_Retailcrm_Helper_Data extends Mage_Core_Helper_Abstract if (is_array($value)) { $haystack[$key] = self::filterRecursive($haystack[$key]); } + if (is_null($haystack[$key]) || $haystack[$key] === '' || count($haystack[$key]) == 0 diff --git a/app/code/community/Retailcrm/Retailcrm/Model/ApiClient.php b/app/code/community/Retailcrm/Retailcrm/Model/ApiClient.php index 52be0fe..72599ec 100644 --- a/app/code/community/Retailcrm/Retailcrm/Model/ApiClient.php +++ b/app/code/community/Retailcrm/Retailcrm/Model/ApiClient.php @@ -1,11 +1,20 @@ + * @license https://opensource.org/licenses/MIT MIT License + * @link http://www.retailcrm.ru/docs/Developers/ApiVersion4 */ class Retailcrm_Retailcrm_Model_ApiClient { - const VERSION = 'v3'; + + const VERSION = 'v4'; protected $client; @@ -15,537 +24,1063 @@ class Retailcrm_Retailcrm_Model_ApiClient protected $siteCode; /** - * Retailcrm_Retailcrm_Model_Http_Client init + * Client creating * - * @param string $url - * @param string $apiKey - * @param string $siteCode - * @return mixed + * @param string $url api url + * @param string $apiKey api key + * @param string $site site code + * + * @throws \InvalidArgumentException */ - public function __construct($params) + public function __construct($url, $apiKey, $site = null) { - $url = $params['url']; - - if ('/' != substr($url, strlen($url) - 1, 1)) { + if ('/' !== $url[strlen($url) - 1]) { $url .= '/'; } $url = $url . 'api/' . self::VERSION; - $this->client = new Retailcrm_Retailcrm_Model_Http_Client($url, array('apiKey' => $params['key'])); - $this->siteCode = $params['site']; + $this->client = new Retailcrm_Retailcrm_Model_Http_Client($url, array('apiKey' => $apiKey)); + $this->siteCode = $site; + } /** - * Create a order + * Returns users list + * + * @param array $filter + * @param null $page + * @param null $limit + * + * @throws \RetailCrm\Exception\InvalidJsonException + * @throws \RetailCrm\Exception\CurlException + * @throws \InvalidArgumentException * - * @param array $order - * @param string $site (default: null) * @return ApiResponse */ - public function ordersCreate(array $order, $site = null) + public function usersList(array $filter = array(), $page = null, $limit = null) { - if (!sizeof($order)) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException('Parameter `order` must contains a data'); + $parameters = array(); + + if (count($filter)) { + $parameters['filter'] = $filter; } - - return $this->client->makeRequest("/orders/create", Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, $this->fillSite($site, array( - 'order' => json_encode($order) - ))); - } - - /** - * Edit a order - * - * @param array $order - * @param string $site (default: null) - * @return ApiResponse - */ - public function ordersEdit(array $order, $by = 'externalId', $site = null) - { - if (!sizeof($order)) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException('Parameter `order` must contains a data'); + + if (null !== $page) { + $parameters['page'] = (int) $page; } - - $this->checkIdParameter($by); - - if (!isset($order[$by])) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException(sprintf('Order array must contain the "%s" parameter.', $by)); + + if (null !== $limit) { + $parameters['limit'] = (int) $limit; } - + return $this->client->makeRequest( - "/orders/" . $order[$by] . "/edit", - Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, - $this->fillSite($site, array( - 'order' => json_encode($order), - 'by' => $by, - )) + '/users', + Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET, + $parameters ); } /** - * Upload array of the orders + * Get user groups + * + * @param null $page + * @param null $limit + * + * @throws \RetailCrm\Exception\InvalidJsonException + * @throws \RetailCrm\Exception\CurlException * - * @param array $orders - * @param string $site (default: null) * @return ApiResponse */ - public function ordersUpload(array $orders, $site = null) + public function usersGroups($page = null, $limit = null) { - if (!sizeof($orders)) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException('Parameter `orders` must contains array of the orders'); - } - - return $this->client->makeRequest("/orders/upload", Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, $this->fillSite($site, array( - 'orders' => json_encode($orders), - ))); - } - - /** - * Get order by id or externalId - * - * @param string $id - * @param string $by (default: 'externalId') - * @param string $site (default: null) - * @return ApiResponse - */ - public function ordersGet($id, $by = 'externalId', $site = null) - { - $this->checkIdParameter($by); - - return $this->client->makeRequest("/orders/$id", Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET, $this->fillSite($site, array( - 'by' => $by - ))); - } - - /** - * Returns a orders history - * - * @param DateTime $startDate (default: null) - * @param DateTime $endDate (default: null) - * @param int $limit (default: 100) - * @param int $offset (default: 0) - * @param bool $skipMyChanges (default: true) - * @return ApiResponse - */ - public function ordersHistory( - DateTime $startDate = null, - DateTime $endDate = null, - $limit = 100, - $offset = 0, - $skipMyChanges = true - ) { $parameters = array(); - if ($startDate) { - $parameters['startDate'] = $startDate->format('Y-m-d H:i:s'); + if (null !== $page) { + $parameters['page'] = (int) $page; } - if ($endDate) { - $parameters['endDate'] = $endDate->format('Y-m-d H:i:s'); - } - if ($limit) { + + if (null !== $limit) { $parameters['limit'] = (int) $limit; } - if ($offset) { - $parameters['offset'] = (int) $offset; - } - if ($skipMyChanges) { - $parameters['skipMyChanges'] = (bool) $skipMyChanges; - } - return $this->client->makeRequest('/orders/history', Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET, $parameters); + return $this->client->makeRequest( + '/user-groups', + Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET, + $parameters + ); + } + + /** + * Returns user data + * + * @param integer $id user ID + * + * @throws \RetailCrm\Exception\InvalidJsonException + * @throws \RetailCrm\Exception\CurlException + * @throws \InvalidArgumentException + * + * @return ApiResponse + */ + public function usersGet($id) + { + return $this->client->makeRequest("/users/$id", Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET); } /** * Returns filtered orders list * - * @param array $filter (default: array()) - * @param int $page (default: null) - * @param int $limit (default: null) + * @param array $filter (default: array()) + * @param int $page (default: null) + * @param int $limit (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * * @return ApiResponse */ public function ordersList(array $filter = array(), $page = null, $limit = null) { $parameters = array(); - if (sizeof($filter)) { + 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, + $parameters + ); + } - return $this->client->makeRequest('/orders', Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET, $parameters); + /** + * Create a order + * + * @param array $order order data + * @param string $site (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function ordersCreate(array $order, $site = null) + { + if (!count($order)) { + throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + 'Parameter `order` must contains a data' + ); + } + + return $this->client->makeRequest( + '/orders/create', + Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, + $this->fillSite($site, array('order' => json_encode($order))) + ); + } + + /** + * Save order IDs' (id and externalId) association in the CRM + * + * @param array $ids order identificators + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function ordersFixExternalIds(array $ids) + { + if (! count($ids)) { + throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + 'Method parameter must contains at least one IDs pair' + ); + } + + return $this->client->makeRequest( + '/orders/fix-external-ids', + Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, + array('orders' => json_encode($ids) + ) + ); } /** * Returns statuses of the orders * - * @param array $ids (default: array()) - * @param array $externalIds (default: array()) + * @param array $ids (default: array()) + * @param array $externalIds (default: array()) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * * @return ApiResponse */ public function ordersStatuses(array $ids = array(), array $externalIds = array()) { $parameters = array(); - if (sizeof($ids)) { + if (count($ids)) { $parameters['ids'] = $ids; } - if (sizeof($externalIds)) { + + if (count($externalIds)) { $parameters['externalIds'] = $externalIds; } - - return $this->client->makeRequest('/orders/statuses', Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET, $parameters); + + return $this->client->makeRequest( + '/orders/statuses', + Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET, + $parameters + ); } /** - * Save order IDs' (id and externalId) association in the CRM + * Upload array of the orders + * + * @param array $orders array of orders + * @param string $site (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException * - * @param array $ids * @return ApiResponse */ - public function ordersFixExternalIds(array $ids) + public function ordersUpload(array $orders, $site = null) { - if (!sizeof($ids)) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException('Method parameter must contains at least one IDs pair'); + if (!count($orders)) { + throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + 'Parameter `orders` must contains array of the orders' + ); } - return $this->client->makeRequest("/orders/fix-external-ids", Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, array( - 'orders' => json_encode($ids), - )); + return $this->client->makeRequest( + '/orders/upload', + Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, + $this->fillSite($site, array('orders' => json_encode($orders))) + ); } /** - * Get orders assembly history + * Get order by id or externalId + * + * @param string $id order identificator + * @param string $by (default: 'externalId') + * @param string $site (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException * - * @param array $filter (default: array()) - * @param int $page (default: null) - * @param int $limit (default: null) * @return ApiResponse */ - public function ordersPacksHistory(array $filter = array(), $page = null, $limit = null) + public function ordersGet($id, $by = 'externalId', $site = null) { - $parameters = array(); + $this->checkIdParameter($by); - if (sizeof($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, $parameters); + return $this->client->makeRequest( + "/orders/$id", + Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET, + $this->fillSite($site, array('by' => $by)) + ); } /** - * Create a customer + * Edit a order + * + * @param array $order order data + * @param string $by (default: 'externalId') + * @param string $site (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException * - * @param array $customer - * @param string $site (default: null) * @return ApiResponse */ - public function customersCreate(array $customer, $site = null) + public function ordersEdit(array $order, $by = 'externalId', $site = null) { - if (!sizeof($customer)) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException('Parameter `customer` must contains a data'); - } - - return $this->client->makeRequest("/customers/create", Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, $this->fillSite($site, array( - 'customer' => json_encode($customer) - ))); - } - - /** - * Edit a customer - * - * @param array $customer - * @param string $by (default: 'externalId') - * @param string $site (default: null) - * @return ApiResponse - */ - public function customersEdit(array $customer, $by = 'externalId', $site = null) - { - if (!sizeof($customer)) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException('Parameter `customer` must contains a data'); + if (!count($order)) { + throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + 'Parameter `order` must contains a data' + ); } $this->checkIdParameter($by); - if (!isset($customer[$by])) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException(sprintf('Customer array must contain the "%s" parameter.', $by)); + if (!array_key_exists($by, $order)) { + throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + sprintf('Order array must contain the "%s" parameter.', $by) + ); } return $this->client->makeRequest( - "/customers/" . $customer[$by] . "/edit", + sprintf('/orders/%s/edit', $order[$by]), Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, $this->fillSite( $site, - array( - 'customer' => json_encode($customer), - 'by' => $by - ) + array('order' => json_encode($order), 'by' => $by) ) ); } /** - * Upload array of the customers + * Get orders history + * @param array $filter + * @param null $page + * @param null $limit * - * @param array $customers - * @param string $site (default: null) * @return ApiResponse */ - public function customersUpload(array $customers, $site = null) + public function ordersHistory(array $filter = array(), $page = null, $limit = null) { - if (!sizeof($customers)) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException('Parameter `customers` must contains array of the customers'); + $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("/customers/upload", Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, $this->fillSite($site, array( - 'customers' => json_encode($customers), - ))); - } - - /** - * Get customer by id or externalId - * - * @param string $id - * @param string $by (default: 'externalId') - * @param string $site (default: null) - * @return ApiResponse - */ - public function customersGet($id, $by = 'externalId', $site = null) - { - $this->checkIdParameter($by); - - return $this->client->makeRequest("/customers/$id", Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET, $this->fillSite($site, array( - 'by' => $by - ))); + return $this->client->makeRequest( + '/orders/history', + Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET, + $parameters + ); } /** * Returns filtered customers list * - * @param array $filter (default: array()) - * @param int $page (default: null) - * @param int $limit (default: null) + * @param array $filter (default: array()) + * @param int $page (default: null) + * @param int $limit (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * * @return ApiResponse */ public function customersList(array $filter = array(), $page = null, $limit = null) { $parameters = array(); - if (sizeof($filter)) { + 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, $parameters); + return $this->client->makeRequest( + '/customers', + Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET, + $parameters + ); + } + + /** + * Create a customer + * + * @param array $customer customer data + * @param string $site (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function customersCreate(array $customer, $site = null) + { + if (! count($customer)) { + throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + 'Parameter `customer` must contains a data' + ); + } + + return $this->client->makeRequest( + '/customers/create', + Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, + $this->fillSite($site, array('customer' => json_encode($customer))) + ); } /** * Save customer IDs' (id and externalId) association in the CRM * - * @param array $ids + * @param array $ids ids mapping + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * * @return ApiResponse */ public function customersFixExternalIds(array $ids) { - if (!sizeof($ids)) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException('Method parameter must contains at least one IDs pair'); + if (! count($ids)) { + throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + 'Method parameter must contains at least one IDs pair' + ); } - return $this->client->makeRequest("/customers/fix-external-ids", Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, array( - 'customers' => json_encode($ids), - )); + return $this->client->makeRequest( + '/customers/fix-external-ids', + Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, + array('customers' => json_encode($ids)) + ); + } + + /** + * Upload array of the customers + * + * @param array $customers array of customers + * @param string $site (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function customersUpload(array $customers, $site = null) + { + if (! count($customers)) { + throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + 'Parameter `customers` must contains array of the customers' + ); + } + + return $this->client->makeRequest( + '/customers/upload', + Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, + $this->fillSite($site, array('customers' => json_encode($customers))) + ); + } + + /** + * Get customer by id or externalId + * + * @param string $id customer identificator + * @param string $by (default: 'externalId') + * @param string $site (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function customersGet($id, $by = 'externalId', $site = null) + { + $this->checkIdParameter($by); + + return $this->client->makeRequest( + "/customers/$id", + Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET, + $this->fillSite($site, array('by' => $by)) + ); + } + + /** + * Edit a customer + * + * @param array $customer customer data + * @param string $by (default: 'externalId') + * @param string $site (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function customersEdit(array $customer, $by = 'externalId', $site = null) + { + if (!count($customer)) { + throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + 'Parameter `customer` must contains a data' + ); + } + + $this->checkIdParameter($by); + + if (!array_key_exists($by, $customer)) { + throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + 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, + $this->fillSite( + $site, + array('customer' => json_encode($customer), 'by' => $by) + ) + ); + } + + /** + * Get customers history + * @param array $filter + * @param null $page + * @param null $limit + * + * @return ApiResponse + */ + public function customersHistory(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( + '/customers/history', + Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET, + $parameters + ); + } + + /** + * Get orders assembly list + * + * @param array $filter (default: array()) + * @param int $page (default: null) + * @param int $limit (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function ordersPacksList(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( + '/orders/packs', + Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET, + $parameters + ); + } + + /** + * Create orders assembly + * + * @param array $pack pack data + * @param string $site (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function ordersPacksCreate(array $pack, $site = null) + { + if (!count($pack)) { + throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + 'Parameter `pack` must contains a data' + ); + } + + return $this->client->makeRequest( + '/orders/packs/create', + Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, + $this->fillSite($site, array('pack' => json_encode($pack))) + ); + } + + /** + * Get orders assembly history + * + * @param array $filter (default: array()) + * @param int $page (default: null) + * @param int $limit (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function ordersPacksHistory(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( + '/orders/packs/history', + Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET, + $parameters + ); + } + + /** + * Get orders assembly by id + * + * @param string $id pack identificator + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function ordersPacksGet($id) + { + if (empty($id)) { + throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException('Parameter `id` must be set'); + } + + return $this->client->makeRequest( + "/orders/packs/$id", + Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET + ); + } + + /** + * Delete orders assembly by id + * + * @param string $id pack identificator + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function ordersPacksDelete($id) + { + if (empty($id)) { + throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException('Parameter `id` must be set'); + } + + return $this->client->makeRequest( + sprintf('/orders/packs/%s/delete', $id), + Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST + ); + } + + /** + * Edit orders assembly + * + * @param array $pack pack data + * @param string $site (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function ordersPacksEdit(array $pack, $site = null) + { + if (!count($pack) || empty($pack['id'])) { + throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + '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, + $this->fillSite($site, array('pack' => json_encode($pack))) + ); } /** * Get purchace prices & stock balance * - * @param array $filter (default: array()) - * @param int $page (default: null) - * @param int $limit (default: null) - * @param string $site (default: null) + * @param array $filter (default: array()) + * @param int $page (default: null) + * @param int $limit (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * * @return ApiResponse */ - public function storeInventories(array $filter = array(), $page = null, $limit = null, $site = null) + public function storeInventories(array $filter = array(), $page = null, $limit = null) { $parameters = array(); - if (sizeof($filter)) { + 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_GET, $this->fillSite($site, $parameters)); + return $this->client->makeRequest( + '/store/inventories', + Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, + $parameters + ); + } + + /** + * Get store settings + * + * @param string $code get settings code + * + * @return ApiResponse + * @throws \RetailCrm\Exception\InvalidJsonException + * @throws \RetailCrm\Exception\CurlException + * @throws \InvalidArgumentException + * + * @return ApiResponse + */ + public function storeSettingsGet($code) + { + if (empty($code)) { + throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException('Parameter `code` must be set'); + } + + return $this->client->makeRequest( + "/store/setting/$code", + Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET + ); + } + + /** + * Edit store configuration + * + * @param array $configuration + * + * @throws \RetailCrm\Exception\InvalidJsonException + * @throws \RetailCrm\Exception\CurlException + * @throws \InvalidArgumentException + * + * @return ApiResponse + */ + public function storeSettingsEdit(array $configuration) + { + if (!count($configuration) || empty($configuration['code'])) { + throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + '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, + array('configuration' => json_encode($configuration)) + ); } /** * Upload store inventories * - * @param array $offers - * @param string $site (default: null) + * @param array $offers offers data + * @param string $site (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * * @return ApiResponse */ public function storeInventoriesUpload(array $offers, $site = null) { - if (!sizeof($offers)) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException('Parameter `offers` must contains array of the customers'); + if (!count($offers)) { + throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + 'Parameter `offers` must contains array of the offers' + ); } return $this->client->makeRequest( - "/store/inventories/upload", + '/store/inventories/upload', Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, $this->fillSite($site, array('offers' => json_encode($offers))) ); } + /** + * Upload store prices + * + * @param array $prices prices data + * @param string $site default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function storePricesUpload(array $prices, $site = null) + { + if (!count($prices)) { + throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + 'Parameter `prices` must contains array of the prices' + ); + } + + return $this->client->makeRequest( + '/store/prices/upload', + Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, + $this->fillSite($site, array('prices' => json_encode($prices))) + ); + } + + /** + * Get products + * + * @param array $filter (default: array()) + * @param int $page (default: null) + * @param int $limit (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function storeProducts(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( + '/store/products', + Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, + $parameters + ); + } + + /** + * Get delivery settings + * + * @param string $code + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function deliverySettingsGet($code) + { + if (empty($code)) { + throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException('Parameter `code` must be set'); + } + + return $this->client->makeRequest( + "/delivery/generic/setting/$code", + Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST + ); + } + + /** + * Edit delivery configuration + * + * @param array $configuration + * + * @throws \RetailCrm\Exception\InvalidJsonException + * @throws \RetailCrm\Exception\CurlException + * @throws \InvalidArgumentException + * + * @return ApiResponse + */ + public function deliverySettingsEdit(array $configuration) + { + if (!count($configuration) || empty($configuration['code'])) { + throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + '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, + array('configuration' => json_encode($configuration)) + ); + } + + /** + * Delivery tracking update + * + * @param string $code + * @param array $statusUpdate + * + * @throws \RetailCrm\Exception\InvalidJsonException + * @throws \RetailCrm\Exception\CurlException + * @throws \InvalidArgumentException + * + * @return ApiResponse + */ + public function deliveryTracking($code, array $statusUpdate) + { + if (empty($code)) { + throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException('Parameter `code` must be set'); + } + + if (!count($statusUpdate)) { + throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + 'Parameter `statusUpdate` must contains a data' + ); + } + + return $this->client->makeRequest( + sprintf('/delivery/generic/%s/tracking', $code), + Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, + $statusUpdate + ); + } + + /** + * Returns available county list + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function countriesList() + { + return $this->client->makeRequest( + '/reference/countries', + Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST + ); + } + /** * Returns deliveryServices list * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * * @return ApiResponse */ public function deliveryServicesList() { - return $this->client->makeRequest('/reference/delivery-services', Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET); - } - - /** - * Returns deliveryTypes list - * - * @return ApiResponse - */ - public function deliveryTypesList() - { - return $this->client->makeRequest('/reference/delivery-types', Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET); - } - - /** - * Returns orderMethods list - * - * @return ApiResponse - */ - public function orderMethodsList() - { - return $this->client->makeRequest('/reference/order-methods', Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET); - } - - /** - * Returns orderTypes list - * - * @return ApiResponse - */ - public function orderTypesList() - { - return $this->client->makeRequest('/reference/order-types', Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET); - } - - /** - * Returns paymentStatuses list - * - * @return ApiResponse - */ - public function paymentStatusesList() - { - return $this->client->makeRequest('/reference/payment-statuses', Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET); - } - - /** - * Returns paymentTypes list - * - * @return ApiResponse - */ - public function paymentTypesList() - { - return $this->client->makeRequest('/reference/payment-types', Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET); - } - - /** - * Returns productStatuses list - * - * @return ApiResponse - */ - public function productStatusesList() - { - return $this->client->makeRequest('/reference/product-statuses', Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET); - } - - /** - * Returns statusGroups list - * - * @return ApiResponse - */ - public function statusGroupsList() - { - return $this->client->makeRequest('/reference/status-groups', Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET); - } - - /** - * Returns statuses list - * - * @return ApiResponse - */ - public function statusesList() - { - return $this->client->makeRequest('/reference/statuses', Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET); - } - - /** - * Returns sites list - * - * @return ApiResponse - */ - public function sitesList() - { - return $this->client->makeRequest('/reference/sites', Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET); - } - - /** - * Returns stores list - * - * @return ApiResponse - */ - public function storesList() - { - return $this->client->makeRequest('/reference/stores', Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET); + return $this->client->makeRequest( + '/reference/delivery-services', + Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST + ); } /** * Edit deliveryService * * @param array $data delivery service data + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * * @return ApiResponse */ public function deliveryServicesEdit(array $data) { - if (!isset($data['code'])) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException('Data must contain "code" parameter.'); + if (!array_key_exists('code', $data)) { + throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + 'Data must contain "code" parameter.' + ); } return $this->client->makeRequest( - '/reference/delivery-services/' . $data['code'] . '/edit', + sprintf('/reference/delivery-services/%s/edit', $data['code']), Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, - array( - 'deliveryService' => json_encode($data) - ) + array('deliveryService' => json_encode($data)) + ); + } + + /** + * Returns deliveryTypes list + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function deliveryTypesList() + { + return $this->client->makeRequest( + '/reference/delivery-types', + Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET ); } @@ -553,20 +1088,42 @@ class Retailcrm_Retailcrm_Model_ApiClient * Edit deliveryType * * @param array $data delivery type data + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * * @return ApiResponse */ public function deliveryTypesEdit(array $data) { - if (!isset($data['code'])) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException('Data must contain "code" parameter.'); + if (!array_key_exists('code', $data)) { + throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + 'Data must contain "code" parameter.' + ); } return $this->client->makeRequest( - '/reference/delivery-types/' . $data['code'] . '/edit', + sprintf('/reference/delivery-types/%s/edit', $data['code']), Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, - array( - 'deliveryType' => json_encode($data) - ) + array('deliveryType' => json_encode($data)) + ); + } + + /** + * Returns orderMethods list + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function orderMethodsList() + { + return $this->client->makeRequest( + '/reference/order-methods', + Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST ); } @@ -574,20 +1131,42 @@ class Retailcrm_Retailcrm_Model_ApiClient * Edit orderMethod * * @param array $data order method data + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * * @return ApiResponse */ public function orderMethodsEdit(array $data) { - if (!isset($data['code'])) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException('Data must contain "code" parameter.'); + if (!array_key_exists('code', $data)) { + throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + 'Data must contain "code" parameter.' + ); } return $this->client->makeRequest( - '/reference/order-methods/' . $data['code'] . '/edit', - Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, - array( - 'orderMethod' => json_encode($data) - ) + sprintf('/reference/order-methods/%s/edit', $data['code']), + Retailcrm_Retailcrm_Model_Http_Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, + array('orderMethod' => json_encode($data)) + ); + } + + /** + * Returns orderTypes list + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function orderTypesList() + { + return $this->client->makeRequest( + '/reference/order-types', + Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST ); } @@ -595,20 +1174,42 @@ class Retailcrm_Retailcrm_Model_ApiClient * Edit orderType * * @param array $data order type data + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * * @return ApiResponse */ public function orderTypesEdit(array $data) { - if (!isset($data['code'])) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException('Data must contain "code" parameter.'); + if (!array_key_exists('code', $data)) { + throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + 'Data must contain "code" parameter.' + ); } return $this->client->makeRequest( - '/reference/order-types/' . $data['code'] . '/edit', + sprintf('/reference/order-types/%s/edit', $data['code']), Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, - array( - 'orderType' => json_encode($data) - ) + array('orderType' => json_encode($data)) + ); + } + + /** + * Returns paymentStatuses list + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function paymentStatusesList() + { + return $this->client->makeRequest( + '/reference/payment-statuses', + Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET ); } @@ -616,20 +1217,42 @@ class Retailcrm_Retailcrm_Model_ApiClient * Edit paymentStatus * * @param array $data payment status data + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * * @return ApiResponse */ public function paymentStatusesEdit(array $data) { - if (!isset($data['code'])) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException('Data must contain "code" parameter.'); + if (!array_key_exists('code', $data)) { + throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + 'Data must contain "code" parameter.' + ); } return $this->client->makeRequest( - '/reference/payment-statuses/' . $data['code'] . '/edit', + sprintf('/reference/payment-statuses/%s/edit', $data['code']), Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, - array( - 'paymentStatus' => json_encode($data) - ) + array('paymentStatus' => json_encode($data)) + ); + } + + /** + * Returns paymentTypes list + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function paymentTypesList() + { + return $this->client->makeRequest( + '/reference/payment-types', + Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET ); } @@ -637,20 +1260,42 @@ class Retailcrm_Retailcrm_Model_ApiClient * Edit paymentType * * @param array $data payment type data + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * * @return ApiResponse */ public function paymentTypesEdit(array $data) { - if (!isset($data['code'])) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException('Data must contain "code" parameter.'); + if (!array_key_exists('code', $data)) { + throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + 'Data must contain "code" parameter.' + ); } return $this->client->makeRequest( - '/reference/payment-types/' . $data['code'] . '/edit', + sprintf('/reference/payment-types/%s/edit', $data['code']), Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, - array( - 'paymentType' => json_encode($data) - ) + array('paymentType' => json_encode($data)) + ); + } + + /** + * Returns productStatuses list + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function productStatusesList() + { + return $this->client->makeRequest( + '/reference/product-statuses', + Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST ); } @@ -658,41 +1303,42 @@ class Retailcrm_Retailcrm_Model_ApiClient * Edit productStatus * * @param array $data product status data + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * * @return ApiResponse */ public function productStatusesEdit(array $data) { - if (!isset($data['code'])) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException('Data must contain "code" parameter.'); + if (!array_key_exists('code', $data)) { + throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + 'Data must contain "code" parameter.' + ); } return $this->client->makeRequest( - '/reference/product-statuses/' . $data['code'] . '/edit', + sprintf('/reference/product-statuses/%s/edit', $data['code']), Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, - array( - 'productStatus' => json_encode($data) - ) + array('productStatus' => json_encode($data)) ); } /** - * Edit order status + * Returns sites list + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException * - * @param array $data status data * @return ApiResponse */ - public function statusesEdit(array $data) + public function sitesList() { - if (!isset($data['code'])) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException('Data must contain "code" parameter.'); - } - return $this->client->makeRequest( - '/reference/statuses/' . $data['code'] . '/edit', - Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, - array( - 'status' => json_encode($data) - ) + '/reference/sites', + Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET ); } @@ -700,20 +1346,102 @@ class Retailcrm_Retailcrm_Model_ApiClient * Edit site * * @param array $data site data + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * * @return ApiResponse */ public function sitesEdit(array $data) { - if (!isset($data['code'])) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException('Data must contain "code" parameter.'); + if (!array_key_exists('code', $data)) { + throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + 'Data must contain "code" parameter.' + ); } return $this->client->makeRequest( - '/reference/sites/' . $data['code'] . '/edit', + sprintf('/reference/sites/%s/edit', $data['code']), Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, - array( - 'site' => json_encode($data) - ) + array('site' => json_encode($data)) + ); + } + + /** + * Returns statusGroups list + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function statusGroupsList() + { + return $this->client->makeRequest( + '/reference/status-groups', + Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET + ); + } + + /** + * Returns statuses list + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function statusesList() + { + return $this->client->makeRequest( + '/reference/statuses', + Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET + ); + } + + /** + * Edit order status + * + * @param array $data status data + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function statusesEdit(array $data) + { + if (!array_key_exists('code', $data)) { + throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + 'Data must contain "code" parameter.' + ); + } + + return $this->client->makeRequest( + sprintf('/reference/statuses/%s/edit', $data['code']), + Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, + array('status' => json_encode($data)) + ); + } + + /** + * Returns stores list + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function storesList() + { + return $this->client->makeRequest( + '/reference/stores', + Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET ); } @@ -721,35 +1449,309 @@ class Retailcrm_Retailcrm_Model_ApiClient * Edit store * * @param array $data site data + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * * @return ApiResponse */ public function storesEdit(array $data) { - if (!isset($data['code'])) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException('Data must contain "code" parameter.'); + if (!array_key_exists('code', $data)) { + throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + 'Data must contain "code" parameter.' + ); } - if (!isset($data['name'])) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException('Data must contain "name" parameter.'); + if (!array_key_exists('name', $data)) { + throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + 'Data must contain "name" parameter.' + ); } return $this->client->makeRequest( - '/reference/stores/' . $data['code'] . '/edit', + sprintf('/reference/stores/%s/edit', $data['code']), Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, - array( - 'store' => json_encode($data) - ) + array('store' => json_encode($data)) + ); + } + + /** + * Get prices types + * + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function pricesTypes() + { + return $this->client->makeRequest( + '/reference/price-types', + Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET + ); + } + + /** + * Edit price type + * + * @param array $data + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function pricesEdit(array $data) + { + if (!array_key_exists('code', $data)) { + throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + 'Data must contain "code" parameter.' + ); + } + + if (!array_key_exists('name', $data)) { + throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + 'Data must contain "name" parameter.' + ); + } + + return $this->client->makeRequest( + sprintf('/reference/price-types/%s/edit', $data['code']), + Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, + array('priceType' => json_encode($data)) + ); + } + + /** + * Get telephony settings + * + * @param string $code + * + * @throws \RetailCrm\Exception\InvalidJsonException + * @throws \RetailCrm\Exception\CurlException + * @throws \InvalidArgumentException + * + * @return ApiResponse + */ + public function telephonySettingsGet($code) + { + if (empty($code)) { + throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException('Parameter `code` must be set'); + } + + return $this->client->makeRequest( + "/telephony/setting/$code", + Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST + ); + } + + /** + * Edit telephony settings + * + * @param string $code symbolic code + * @param string $clientId client id + * @param boolean $active telephony activity + * @param mixed $name service name + * @param mixed $makeCallUrl service init url + * @param mixed $image service logo url(svg file) + * + * @param array $additionalCodes + * @param array $externalPhones + * @param bool $allowEdit + * @param bool $inputEventSupported + * @param bool $outputEventSupported + * @param bool $hangupEventSupported + * @param bool $changeUserStatusUrl + * + * @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) + { + if (!isset($code)) { + throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException('Code must be set'); + } + + $parameters['code'] = $code; + + if (!isset($clientId)) { + throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException('client id must be set'); + } + + $parameters['clientId'] = $clientId; + + if (!isset($active)) { + $parameters['active'] = false; + } else { + $parameters['active'] = $active; + } + + if (!isset($name)) { + throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException('name must be set'); + } + + if (isset($name)) { + $parameters['name'] = $name; + } + + if (isset($makeCallUrl)) { + $parameters['makeCallUrl'] = $makeCallUrl; + } + + if (isset($image)) { + $parameters['image'] = $image; + } + + if (isset($additionalCodes)) { + $parameters['additionalCodes'] = $additionalCodes; + } + + if (isset($externalPhones)) { + $parameters['externalPhones'] = $externalPhones; + } + + if (isset($allowEdit)) { + $parameters['allowEdit'] = $allowEdit; + } + + if (isset($inputEventSupported)) { + $parameters['inputEventSupported'] = $inputEventSupported; + } + + if (isset($outputEventSupported)) { + $parameters['outputEventSupported'] = $outputEventSupported; + } + + if (isset($hangupEventSupported)) { + $parameters['hangupEventSupported'] = $hangupEventSupported; + } + + if (isset($changeUserStatusUrl)) { + $parameters['changeUserStatusUrl'] = $changeUserStatusUrl; + } + + return $this->client->makeRequest( + "/telephony/setting/$code/edit", + Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, + array('configuration' => json_encode($parameters)) + ); + } + + /** + * Call event + * + * @param string $phone phone number + * @param string $type call type + * @param array $codes + * @param string $hangupStatus + * @param string $externalPhone + * @param array $webAnalyticsData + * + * @return ApiResponse + * @internal param string $code additional phone code + * @internal param string $status call status + * + */ + 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'); + } + + if (!isset($type)) { + throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException('Type must be set (in|out|hangup)'); + } + + if (empty($codes)) { + throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException('Codes array must be set'); + } + + $parameters['phone'] = $phone; + $parameters['type'] = $type; + $parameters['codes'] = $codes; + $parameters['hangupStatus'] = $hangupStatus; + $parameters['callExternalId'] = $externalPhone; + $parameters['webAnalyticsData'] = $webAnalyticsData; + + + return $this->client->makeRequest( + '/telephony/call/event', + Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, + array('event' => json_encode($parameters)) + ); + } + + /** + * Upload calls + * + * @param array $calls calls data + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function telephonyCallsUpload(array $calls) + { + if (!count($calls)) { + throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + 'Parameter `calls` must contains array of the calls' + ); + } + + return $this->client->makeRequest( + '/telephony/calls/upload', + Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, + array('calls' => json_encode($calls)) + ); + } + + /** + * Get call manager + * + * @param string $phone phone number + * @param bool $details detailed information + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function telephonyCallManager($phone, $details) + { + if (!isset($phone)) { + throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException('Phone number must be set'); + } + + $parameters['phone'] = $phone; + $parameters['details'] = isset($details) ? $details : 0; + + return $this->client->makeRequest( + '/telephony/manager', + Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST, + $parameters ); } /** * Update CRM basic statistic * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * * @return ApiResponse */ public function statisticUpdate() { - return $this->client->makeRequest('/statistic/update', Retailcrm_Retailcrm_Model_Http_Client::METHOD_GET); + return $this->client->makeRequest( + '/statistic/update', + Retailcrm_Retailcrm_Model_Http_Client::METHOD_POST + ); } /** @@ -765,7 +1767,8 @@ class Retailcrm_Retailcrm_Model_ApiClient /** * Set site * - * @param string $site + * @param string $site site code + * * @return void */ public function setSite($site) @@ -776,18 +1779,27 @@ class Retailcrm_Retailcrm_Model_ApiClient /** * Check ID parameter * - * @param string $by + * @param string $by identify by + * + * @throws \InvalidArgumentException + * * @return bool */ protected function checkIdParameter($by) { - $allowedForBy = array('externalId', 'id'); - if (!in_array($by, $allowedForBy)) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException(sprintf( - 'Value "%s" for parameter "by" is not valid. Allowed values are %s.', - $by, - implode(', ', $allowedForBy) - )); + $allowedForBy = array( + 'externalId', + 'id' + ); + + if (!in_array($by, $allowedForBy, false)) { + throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + sprintf( + 'Value "%s" for "by" param is not valid. Allowed values are %s.', + $by, + implode(', ', $allowedForBy) + ) + ); } return true; @@ -796,8 +1808,9 @@ class Retailcrm_Retailcrm_Model_ApiClient /** * Fill params by site value * - * @param string $site - * @param array $params + * @param string $site site code + * @param array $params input parameters + * * @return array */ protected function fillSite($site, array $params) diff --git a/app/code/community/Retailcrm/Retailcrm/Model/Customer.php b/app/code/community/Retailcrm/Retailcrm/Model/Customer.php index e643490..13716df 100644 --- a/app/code/community/Retailcrm/Retailcrm/Model/Customer.php +++ b/app/code/community/Retailcrm/Retailcrm/Model/Customer.php @@ -29,9 +29,8 @@ class Retailcrm_Retailcrm_Model_Customer extends Retailcrm_Retailcrm_Model_Excha 'firstName' => $data->getFirstname(), 'patronymic' => $data->getMiddlename(), 'lastName' => $data->getLastname(), - 'createdAt' => date('Y-m-d H:i:s', strtotime($data->getCreatedAt())) + 'createdAt' => Mage::getSingleton('core/date')->date() ); - $this->_api->customersEdit($customer); } @@ -51,8 +50,7 @@ class Retailcrm_Retailcrm_Model_Customer extends Retailcrm_Retailcrm_Model_Excha ->addAttributeToSelect('email') ->addAttributeToSelect('firstname') ->addAttributeToSelect('lastname'); - foreach ($customerCollection as $customerData) - { + foreach ($customerCollection as $customerData) { $customer = array( 'externalId' => $customerData->getId(), 'email' => $customerData->getData('email'), @@ -61,15 +59,17 @@ class Retailcrm_Retailcrm_Model_Customer extends Retailcrm_Retailcrm_Model_Excha ); $customers[] = $customer; } + unset($customerCollection); $chunked = array_chunk($customers, 50); unset($customers); - foreach ($chunked as $chunk) { -//file_put_contents('/var/www/konzeptual/data/www/konzeptual.ru/tempC.txt', var_export($chunk,true)); die(); + 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/Exchange.php b/app/code/community/Retailcrm/Retailcrm/Model/Exchange.php index 2e8ac10..aa61d79 100644 --- a/app/code/community/Retailcrm/Retailcrm/Model/Exchange.php +++ b/app/code/community/Retailcrm/Retailcrm/Model/Exchange.php @@ -6,55 +6,76 @@ class Retailcrm_Retailcrm_Model_Exchange protected $_apiUrl; protected $_config; protected $_api; - + public function __construct() { $this->_apiUrl = Mage::getStoreConfig('retailcrm/general/api_url'); $this->_apiKey = Mage::getStoreConfig('retailcrm/general/api_key'); if(!empty($this->_apiUrl) && !empty($this->_apiKey)) { - $this->_api = Mage::getModel( - 'retailcrm/ApiClient', - array('url' => $this->_apiUrl, 'key' => $this->_apiKey, 'site' => null) + $this->_api = new Retailcrm_Retailcrm_Model_ApiClient( + $this->_apiUrl, + $this->_apiKey ); } } - - /** - * Get orders history & modify orders into shop - * - */ + +/** + * Get orders history & modify orders into shop + * + */ public function ordersHistory() { $runTime = $this->getExchangeTime($this->_config['general']['history']); - - try { - $response = $this->_api->ordersHistory($runTime); - if ( - $response->isSuccessful() - && - 200 === $response->getStatusCode() - ) { - $nowTime = $response->getGeneratedAt(); - $this->processOrders($response->orders, $nowTime); - } else { - Mage::log( - sprintf( - "Orders history 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()); + $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 */ @@ -66,28 +87,28 @@ class Retailcrm_Retailcrm_Model_Exchange ); foreach ($orders as $order) { - if(!empty($order['externalId'])) { + 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() - ) { + + if ($response->isSuccessful() && 200 === $response->getStatusCode()) { $order = $response->order; } else { Mage::log( @@ -105,34 +126,33 @@ class Retailcrm_Retailcrm_Model_Exchange } 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 - $_store = Mage::getModel("core/store")->load($order['site']); - $_siteId = Mage::getModel('core/store')->load($_store->getId())->getWebsiteId(); $_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->setWebsiteId($siteid); $customer->loadByEmail($order['email']); - - if (!is_numeric($customer->getId())) { + + if (!is_numeric($customer->getId())) { $customer ->setGropuId(1) - ->setWebsiteId($_siteId) - ->setStore($_store) + ->setWebsiteId($siteid) + ->setStore($storeId) ->setEmail($order['email']) ->setFirstname($order['firstName']) ->setLastname($order['lastName']) ->setMiddleName($order['patronymic']) - ->setPassword(uniqid()) - ; - + ->setPassword(uniqid()); + try { $customer->save(); $customer->setConfirmation(null); @@ -149,6 +169,7 @@ class Retailcrm_Retailcrm_Model_Exchange ->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') @@ -169,11 +190,7 @@ class Retailcrm_Retailcrm_Model_Exchange 'externalId' => $customer->getId() ) ); - if ( - !$response->isSuccessful() - || - 200 !== $response->getStatusCode() - ) { + if (!$response->isSuccessful() || 200 !== $response->getStatusCode()) { Mage::log( sprintf( "Orders fix error: [HTTP status %s] %s", @@ -189,18 +206,17 @@ class Retailcrm_Retailcrm_Model_Exchange } 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' => $_store->getId(), + 'store_id' => $storeId, ), 'payment' => array( 'method' => $payments[$order['paymentType']], @@ -215,11 +231,11 @@ class Retailcrm_Retailcrm_Model_Exchange 'firstname' => $order['firstName'], 'middlename' => $order['patronymic'], 'lastname' => $order['lastName'], - 'street' => $order['customer']['address']['street'], - 'city' => $order['customer']['address']['city'], + 'street' => $order['delivery']['address']['street'], + 'city' => $order['delivery']['address']['city'], 'country_id' => $this->getCountryCode($order['customer']['address']['country']), - 'region' => $order['customer']['address']['region'], - 'postcode' => $order['customer']['address']['index'], + 'region' => $order['delivery']['address']['region'], + 'postcode' => $order['delivery']['address']['index'], 'telephone' => $order['phone'], ), 'shipping_address' => array( @@ -244,44 +260,49 @@ class Retailcrm_Retailcrm_Model_Exchange Mage::unregister('sales_order_place_after'); Mage::register('sales_order_place_after', 1); - $quote = Mage::getModel('sales/quote')->setStoreId($_store->getId()); + $quote = Mage::getModel('sales/quote')->setStoreId($storeId); $quote->assignCustomer($customer); $quote->setSendCconfirmation($_sendConfirmation); - - foreach($_products as $idx => $val) { + + foreach($products as $idx => $val) { $product = Mage::getModel('catalog/product')->load($idx); $quote->addProduct($product, new Varien_Object($val)); } - - $quote->getBillingAddress()->addData($orderData['order']['billing_address']); - + + $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 - ->collectTotals() - ->setCollectShippingRates(true) + + $shippingAddress->setCollectShippingRates(true) ->collectShippingRates() - ->setShippingMethod($orderData['order']['shipping_method']) - ->setpaymentMethod($orderData['payment']['method']) - ; - + ->setShippingMethod($shipping_method) + ->setPaymentMethod($orderData['payment']['method']); + $quote->getPayment()->importData($orderData['payment']); - $quote->setTotalsCollectedFlag(false)->collectTotals()->save(); - + $quote->collectTotals(); + $quote->reserveOrderId(); + $quote->save(); + $service = Mage::getModel('sales/service_quote', $quote); - $service->submitAll(); - + + try{ + $service->submitAll(); + } + catch (Exception $e) { + Mage::log($e->getMessage()); + } + try { $response = $this->_api->ordersFixExternalIds( array( - 'id' => $order['id'], - 'externalId' => $service->getOrder()->getId() + array( + 'id' => $order['id'], + 'externalId' =>$service->getOrder()->getRealOrderId() + ) ) ); - if ( - !$response->isSuccessful() - || - 200 !== $response->getStatusCode() - ) { + + if (!$response->isSuccessful() || 200 !== $response->getStatusCode()) { Mage::log( sprintf( "Orders fix error: [HTTP status %s] %s", @@ -296,75 +317,377 @@ class Retailcrm_Retailcrm_Model_Exchange } } catch (Retailcrm_Retailcrm_Model_Exception_CurlException $e) { Mage::log($e->getMessage()); - } - - Mage::log("Create: " . $order['externalId'], null, 'history.log'); + } } /** * @param array $order */ - private function doUpdate($order) + private function doCreateUp($order) { - $magentoOrder = Mage::getModel('sales/order')->load($order['externalId']); - - if (!empty($order['status'])) { - try { - $response = $this->_api->statusesList(); - if ( - $response->isSuccessful() - && - 200 === $response->getStatusCode() - ) { - $code = $order['status']; - $group = $response->statuses[$code]['group']; - - if (in_array($group, array('approval', 'assembling', 'delivery'))) { - $magentoOrder->setState(Mage_Sales_Model_Order::STATE_PROCESSING, true); - $magentoOrder->save(); - - $invoice = $magentoOrder->prepareInvoice() - ->setTransactionId($magentoOrder->getId()) - ->register() - ->pay(); - - $transaction_save = Mage::getModel('core/resource_transaction') - ->addObject($invoice) - ->addObject($invoice->getOrder()); - - $transaction_save->save(); - } - - if (in_array($group, array('complete'))) { - $itemQty = $magentoOrder->getItemsCollection()->count(); - Mage::getModel('sales/service_order', $magentoOrder)->prepareShipment($itemQty); - $shipment = new Mage_Sales_Model_Order_Shipment_Api(); - $shipment->create($order['externalId']); - } - - if (in_array($group, array('cancel'))) { - $magentoOrder->setState(Mage_Sales_Model_Order::STATE_CANCELED, true); - $magentoOrder->save(); - } - - Mage::log("Update: " . $order['externalId'], null, 'history.log'); - } else { + 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( - "Statuses list error: [HTTP status %s] %s", + "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(); + } + } /** @@ -497,4 +820,162 @@ class Retailcrm_Retailcrm_Model_Exchange 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/Http/Client.php b/app/code/community/Retailcrm/Retailcrm/Model/Http/Client.php index 42bd8e3..5a5527f 100644 --- a/app/code/community/Retailcrm/Retailcrm/Model/Http/Client.php +++ b/app/code/community/Retailcrm/Retailcrm/Model/Http/Client.php @@ -1,7 +1,15 @@ + * @license https://opensource.org/licenses/MIT MIT License + * @link http://www.retailcrm.ru/docs/Developers/ApiVersion4 */ class Retailcrm_Retailcrm_Model_Http_Client { @@ -11,78 +19,84 @@ class Retailcrm_Retailcrm_Model_Http_Client protected $url; protected $defaultParameters; + /** + * Client constructor. + * + * @param string $url api url + * @param array $defaultParameters array of parameters + * + * @throws \InvalidArgumentException + */ public function __construct($url, array $defaultParameters = array()) { if (false === stripos($url, 'https://')) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException('API schema requires HTTPS protocol'); + throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + 'API schema requires HTTPS protocol' + ); } $this->url = $url; $this->defaultParameters = $defaultParameters; - $this->retry = 0; } /** * Make HTTP request * - * @param string $path - * @param string $method (default: 'GET') - * @param array $parameters (default: array()) - * @param int $timeout - * @return Retailcrm_Retailcrm_Model_Response_ApiResponse + * @param string $path request url + * @param string $method (default: 'GET') + * @param array $parameters (default: array()) + * + * @SuppressWarnings(PHPMD.ExcessiveParameterList) + * + * @throws \InvalidArgumentException + * @throws CurlException + * @throws InvalidJsonException + * + * @return ApiResponse */ - public function makeRequest($path, $method, array $parameters = array(), $timeout = 90) + public function makeRequest($path,$method,array $parameters = array()) { $allowedMethods = array(self::METHOD_GET, self::METHOD_POST); - if (!in_array($method, $allowedMethods)) { - throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException(sprintf( - 'Method "%s" is not valid. Allowed methods are %s', - $method, - implode(', ', $allowedMethods) - )); + + if (!in_array($method, $allowedMethods, false)) { + throw new Retailcrm_Retailcrm_Model_Exception_InvalidJsonException( + sprintf( + 'Method "%s" is not valid. Allowed methods are %s', + $method, + implode(', ', $allowedMethods) + ) + ); } $parameters = array_merge($this->defaultParameters, $parameters); $url = $this->url . $path; - if (self::METHOD_GET === $method && sizeof($parameters)) { - $url .= '?' . http_build_query($parameters); + if (self::METHOD_GET === $method && count($parameters)) { + $url .= '?' . http_build_query($parameters, '', '&'); } - $ch = curl_init(); - curl_setopt($ch, CURLOPT_URL, $url); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); - curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); - curl_setopt($ch, CURLOPT_FAILONERROR, false); - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); - curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); - curl_setopt($ch, CURLOPT_TIMEOUT, (int) $timeout); - curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, (int) $timeout); + $curlHandler = curl_init(); + curl_setopt($curlHandler, CURLOPT_URL, $url); + curl_setopt($curlHandler, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($curlHandler, CURLOPT_FOLLOWLOCATION, 1); + curl_setopt($curlHandler, CURLOPT_FAILONERROR, false); + curl_setopt($curlHandler, CURLOPT_SSL_VERIFYPEER, false); + curl_setopt($curlHandler, CURLOPT_SSL_VERIFYHOST, false); + curl_setopt($curlHandler, CURLOPT_TIMEOUT, 30); + curl_setopt($curlHandler, CURLOPT_CONNECTTIMEOUT, 30); if (self::METHOD_POST === $method) { - curl_setopt($ch, CURLOPT_POST, true); - curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters); + curl_setopt($curlHandler, CURLOPT_POST, true); + curl_setopt($curlHandler, CURLOPT_POSTFIELDS, $parameters); } - $responseBody = curl_exec($ch); - $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); - $errno = curl_errno($ch); - $error = curl_error($ch); + $responseBody = curl_exec($curlHandler); + $statusCode = curl_getinfo($curlHandler, CURLINFO_HTTP_CODE); + $errno = curl_errno($curlHandler); + $error = curl_error($curlHandler); - curl_close($ch); - - if ($errno && in_array($errno, array(6, 7, 28, 34, 35)) && $this->retry < 3) { - $errno = null; - $error = null; - $this->retry += 1; - $this->makeRequest( - $path, - $method, - $parameters, - $timeout - ); - } + curl_close($curlHandler); if ($errno) { throw new Retailcrm_Retailcrm_Model_Exception_CurlException($error, $errno); diff --git a/app/code/community/Retailcrm/Retailcrm/Model/Icml.php b/app/code/community/Retailcrm/Retailcrm/Model/Icml.php index 1b3e0bf..8b79b47 100644 --- a/app/code/community/Retailcrm/Retailcrm/Model/Icml.php +++ b/app/code/community/Retailcrm/Retailcrm/Model/Icml.php @@ -10,7 +10,7 @@ class Retailcrm_Retailcrm_Model_Icml public function generate($shop) { $this->_shop = $shop; - + $string = ' @@ -43,6 +43,7 @@ class Retailcrm_Retailcrm_Model_Icml $baseDir = Mage::getBaseDir(); $shopCode = Mage::app()->getStore($shop)->getCode(); $this->_dd->save($baseDir . DS . 'retailcrm_' . $shopCode . '.xml'); + } private function addCategories() @@ -82,14 +83,15 @@ class Retailcrm_Retailcrm_Model_Icml $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); @@ -97,8 +99,11 @@ class Retailcrm_Retailcrm_Model_Icml ->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(); @@ -109,13 +114,8 @@ class Retailcrm_Retailcrm_Model_Icml $offer['name'] = $product->getName(); $offer['productName'] = $product->getName(); $offer['initialPrice'] = (float) $product->getPrice(); - - $offer['url'] = $helper->rewrittenProductUrl( - $product->getId(), $product->getCategoryId(), $this->_shop - ); - + $offer['url'] = $product->getProductUrl(); $offer['picture'] = $picUrl.'catalog/product'.$product->getImage(); - $offer['quantity'] = Mage::getModel('cataloginventory/stock_item') ->loadByProduct($product)->getQty(); @@ -188,6 +188,7 @@ class Retailcrm_Retailcrm_Model_Icml foreach($attributes AS $attributeName=>$attributeValue) { $attributesString[] = $attributeName.': '.$attributeValue; } + $attributesString = ' (' . implode(', ', $attributesString) . ')'; $offer = array(); @@ -198,13 +199,8 @@ class Retailcrm_Retailcrm_Model_Icml $offer['name'] = $associatedProduct->getName().$attributesString; $offer['productName'] = $product->getName(); $offer['initialPrice'] = (float) $associatedProduct->getFinalPrice(); - - $offer['url'] = $helper->rewrittenProductUrl( - $associatedProduct->getId(), $associatedProduct->getCategoryId(), $this->_shop - ); - + $offer['url'] = $associatedProduct->getProductUrl(); $offer['picture'] = $picUrl.'catalog/product'.$associatedProduct->getImage(); - $offer['quantity'] = Mage::getModel('cataloginventory/stock_item') ->loadByProduct($associatedProduct)->getQty(); @@ -273,7 +269,6 @@ class Retailcrm_Retailcrm_Model_Icml } foreach ($offers as $offer) { - $e = $this->_eOffers->appendChild( $this->_dd->createElement('offer') ); @@ -322,9 +317,8 @@ class Retailcrm_Retailcrm_Model_Icml if (!empty($offer['purchasePrice'])) { $e->appendChild($this->_dd->createElement('purchasePrice')) ->appendChild( - $this->_dd->createTextNode($offer['purchasePrice'] - ) - ); + $this->_dd->createTextNode($offer['purchasePrice']) + ); } if (!empty($offer['picture'])) { @@ -337,17 +331,15 @@ class Retailcrm_Retailcrm_Model_Icml if (!empty($offer['url'])) { $e->appendChild($this->_dd->createElement('url')) ->appendChild( - $this->_dd->createTextNode($offer['url'] - ) - ); + $this->_dd->createTextNode($offer['url']) + ); } if (!empty($offer['vendor'])) { $e->appendChild($this->_dd->createElement('vendor')) ->appendChild( - $this->_dd->createTextNode($offer['vendor'] - ) - ); + $this->_dd->createTextNode($offer['vendor']) + ); } if(!empty($offer['params'])) { diff --git a/app/code/community/Retailcrm/Retailcrm/Model/Observer.php b/app/code/community/Retailcrm/Retailcrm/Model/Observer.php index 1cda209..332499c 100644 --- a/app/code/community/Retailcrm/Retailcrm/Model/Observer.php +++ b/app/code/community/Retailcrm/Retailcrm/Model/Observer.php @@ -21,14 +21,22 @@ class Retailcrm_Retailcrm_Model_Observer 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 * @@ -47,7 +55,7 @@ class Retailcrm_Retailcrm_Model_Observer return true; } - + public function exportCatalog() { foreach (Mage::app()->getWebsites() as $website) { diff --git a/app/code/community/Retailcrm/Retailcrm/Model/Order.php b/app/code/community/Retailcrm/Retailcrm/Model/Order.php index 7d0ddd9..2fb17e0 100644 --- a/app/code/community/Retailcrm/Retailcrm/Model/Order.php +++ b/app/code/community/Retailcrm/Retailcrm/Model/Order.php @@ -24,32 +24,43 @@ class Retailcrm_Retailcrm_Model_Order extends Retailcrm_Retailcrm_Model_Exchange */ public function orderPay($orderId) { - //file_put_contents('/home/user/sites/magento.local/temp1.txt', var_export(1,true)); - //Mage::log($order->getId(), null, 'events.log', true); - //file_put_contents('/home/user/sites/magento.local/temp2.txt', var_export(1,true)); - //$orderId = $observer->getPayment()->getOrder()->getId(); - //file_put_contents('/home/user/sites/magento.local/temp2.txt', var_export($order,true)); $order = Mage::getModel('sales/order')->load($orderId); - //$config = Mage::getModel('retailcrm/settings', $order->getStoreId()); - //file_put_contents('/home/user/sites/magento.local/temp.txt', var_export(1,true)); - //file_put_contents('/home/user/sites/magento.local/tempE1.txt', var_export($order->getBaseGrandTotal(),true)); - //file_put_contents('/home/user/sites/magento.local/tempE2.txt', var_export($order->getTotalPaid(),true)); - + if((string)$order->getBaseGrandTotal() == (string)$order->getTotalPaid()){ - //file_put_contents('/home/user/sites/magento.local/temp1.txt', var_export(2,true)); $preparedOrder = array( - 'externalId' => $order->getId(), + 'externalId' => $order->getRealOrderId(),//getId(), 'paymentStatus' => 'paid', - //'paymentType' => $config->getMapping($order->getPayment()->getMethodInstance()->getCode(), 'payment'), - //'status' => $config->getMapping($order->getStatus(), 'status'), ); - //file_put_contents('/home/user/sites/magento.local/temp2.txt', var_export($preparedOrder,true)); $preparedOrder = Mage::helper('retailcrm')->filterRecursive($preparedOrder); - //file_put_contents('/home/user/sites/magento.local/temp3.txt', var_export($preparedOrder,true)); $this->_api->ordersEdit($preparedOrder); } - //file_put_contents('/home/user/sites/magento.local/temp.txt', var_export($preparedOrder,true)); } + + 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( @@ -59,25 +70,24 @@ class Retailcrm_Retailcrm_Model_Order extends Retailcrm_Retailcrm_Model_Exchange ) ); $preparedOrder = array( - 'externalId' => $order->getId(), + 'externalId' => $order->getRealOrderId(),//getId(), 'status' => $config->getMapping($order->getStatus(), 'status'), ); - if((float)$order->getBaseGrandTotal() == (float)$order->getTotalPaid()){ + if((float)$order->getBaseGrandTotal() == (float)$order->getTotalPaid()) { $preparedOrder['paymentStatus'] = 'paid'; + $preparedOrder = Mage::helper('retailcrm')->filterRecursive($preparedOrder); + $this->_api->ordersEdit($preparedOrder); } - - $preparedOrder = Mage::helper('retailcrm')->filterRecursive($preparedOrder); - $this->_api->ordersEdit($preparedOrder); + } + public function orderCreate($order) { - $config = Mage::getModel('retailcrm/settings', [ - 'storeId' => $order->getStoreId() - ]); + $config = Mage::getModel('retailcrm/settings', ['storeId' => $order->getStoreId()]); $address = $order->getShippingAddress()->getData(); $orderItems = $order->getItemsCollection() ->addAttributeToSelect('*') - //->addAttributeToFilter('product_type', array('eq'=>'simple')) + ->addAttributeToFilter('product_type', array('eq'=>'simple')) ->load(); $items = array(); @@ -91,7 +101,10 @@ class Retailcrm_Retailcrm_Model_Order extends Retailcrm_Retailcrm_Model_Exchange '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() + 'initialPrice' => !isset($parent) ? $item->getPrice() : $parent->getPrice(), + 'offer'=>array( + 'externalId'=>$item->getProductId() + ) ); unset($parent); @@ -101,7 +114,10 @@ class Retailcrm_Retailcrm_Model_Order extends Retailcrm_Retailcrm_Model_Exchange 'productId' => $item->getProductId(), 'productName' => $item->getName(), 'quantity' => $item->getQtyOrdered(), - 'initialPrice' => $item->getPrice() + 'initialPrice' => $item->getPrice(), + 'offer'=>array( + 'externalId'=>$item->getProductId() + ) ); $items[] = $product; @@ -112,9 +128,9 @@ class Retailcrm_Retailcrm_Model_Order extends Retailcrm_Retailcrm_Model_Exchange $preparedOrder = array( 'site' => $order->getStore()->getCode(), - 'externalId' => $order->getId(), + 'externalId' => $order->getRealOrderId(), 'number' => $order->getRealOrderId(), - 'createdAt' => date_create_from_format("Y-m-d H:i:s", $order->getCreatedAt())->modify('+3 hour')->format("Y-m-d H:i:s"), + 'createdAt' => Mage::getModel('core/date')->date(), 'lastName' => $order->getCustomerLastname(), 'firstName' => $order->getCustomerFirstname(), 'patronymic' => $order->getCustomerMiddlename(), @@ -137,34 +153,45 @@ class Retailcrm_Retailcrm_Model_Order extends Retailcrm_Retailcrm_Model_Exchange 'text' => trim( ',', implode( - ',', - array( - $address['postcode'], - $address['city'], - $address['street'] + ',', + 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) { - if ($this->_api->customersGet($order->getCustomerId())) { + $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()) { @@ -187,6 +214,57 @@ class Retailcrm_Retailcrm_Model_Order extends Retailcrm_Retailcrm_Model_Exchange } } + 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 * @@ -224,24 +302,28 @@ class Retailcrm_Retailcrm_Model_Order extends Retailcrm_Retailcrm_Model_Exchange ->setPageSize(1000) ->setCurPage(1) ->load(); + foreach ($ordersList as $order) { $orders[] = $this->prepareOrder($order); } + $chunked = array_chunk($orders, 50); unset($orders); foreach ($chunked as $chunk) { -//file_put_contents('/var/www/konzeptual/data/www/konzeptual.ru/tempO.txt', var_export($chunk,true)); die(); $this->_api->ordersUpload($chunk); time_nanosleep(0, 250000000); } + unset($chunked); + return true; } protected function prepareOrder($order) { $config = Mage::getModel('retailcrm/settings', $order->getStoreId()); - $address = $order->getShippingAddress()->getData(); + $address = $order->getShippingAddress(); + $orderItems = $order->getItemsCollection() ->addAttributeToSelect('*') ->addAttributeToFilter('product_type', array('eq'=>'simple')) @@ -252,6 +334,7 @@ class Retailcrm_Retailcrm_Model_Order extends Retailcrm_Retailcrm_Model_Exchange if ($item->getParentItemId()) { $parent = Mage::getModel('sales/order_item')->load($item->getParentItemId()); } + $product = array( 'productId' => $item->getProductId(), 'productName' => !isset($parent) ? $item->getName() : $parent->getName(), @@ -262,9 +345,10 @@ class Retailcrm_Retailcrm_Model_Order extends Retailcrm_Retailcrm_Model_Exchange $items[] = $product; } } + $shipping = $this->getShippingCode($order->getShippingMethod()); $preparedOrder = array( - 'externalId' => $order->getId(), + 'externalId' => $order->getRealOrderId(), 'number' => $order->getRealOrderId(), 'createdAt' => $order->getCreatedAt(), 'lastName' => $order->getCustomerLastname(), @@ -300,18 +384,23 @@ class Retailcrm_Retailcrm_Model_Order extends Retailcrm_Retailcrm_Model_Exchange ), ) ); + 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); } diff --git a/app/code/community/Retailcrm/Retailcrm/Model/Response/ApiResponse.php b/app/code/community/Retailcrm/Retailcrm/Model/Response/ApiResponse.php index 6ab32ed..a7208f3 100644 --- a/app/code/community/Retailcrm/Retailcrm/Model/Response/ApiResponse.php +++ b/app/code/community/Retailcrm/Retailcrm/Model/Response/ApiResponse.php @@ -1,7 +1,15 @@ + * @license https://opensource.org/licenses/MIT MIT License + * @link http://www.retailcrm.ru/docs/Developers/ApiVersion4 */ class Retailcrm_Retailcrm_Model_Response_ApiResponse implements ArrayAccess { @@ -11,6 +19,14 @@ class Retailcrm_Retailcrm_Model_Response_ApiResponse implements ArrayAccess // response assoc array protected $response; + /** + * ApiResponse constructor. + * + * @param int $statusCode HTTP status code + * @param mixed $responseBody HTTP body + * + * @throws InvalidJsonException + */ public function __construct($statusCode, $responseBody = null) { $this->statusCode = (int) $statusCode; @@ -52,7 +68,11 @@ class Retailcrm_Retailcrm_Model_Response_ApiResponse implements ArrayAccess /** * Allow to access for the property throw class method * - * @param string $name + * @param string $name method name + * @param mixed $arguments method parameters + * + * @throws \InvalidArgumentException + * * @return mixed */ public function __call($name, $arguments) @@ -70,7 +90,10 @@ class Retailcrm_Retailcrm_Model_Response_ApiResponse implements ArrayAccess /** * Allow to access for the property throw object property * - * @param string $name + * @param string $name property name + * + * @throws \InvalidArgumentException + * * @return mixed */ public function __get($name) @@ -83,8 +106,13 @@ class Retailcrm_Retailcrm_Model_Response_ApiResponse implements ArrayAccess } /** - * @param mixed $offset - * @param mixed $value + * Offset set + * + * @param mixed $offset offset + * @param mixed $value value + * + * @throws \BadMethodCallException + * @return void */ public function offsetSet($offset, $value) { @@ -92,7 +120,12 @@ class Retailcrm_Retailcrm_Model_Response_ApiResponse implements ArrayAccess } /** - * @param mixed $offset + * Offset unset + * + * @param mixed $offset offset + * + * @throws \BadMethodCallException + * @return void */ public function offsetUnset($offset) { @@ -100,7 +133,10 @@ class Retailcrm_Retailcrm_Model_Response_ApiResponse implements ArrayAccess } /** - * @param mixed $offset + * Check offset + * + * @param mixed $offset offset + * * @return bool */ public function offsetExists($offset) @@ -109,7 +145,12 @@ class Retailcrm_Retailcrm_Model_Response_ApiResponse implements ArrayAccess } /** - * @param mixed $offset + * Get offset + * + * @param mixed $offset offset + * + * @throws \InvalidArgumentException + * * @return mixed */ public function offsetGet($offset) diff --git a/app/code/community/Retailcrm/Retailcrm/controllers/Adminhtml/RetailcrmbuttonController.php b/app/code/community/Retailcrm/Retailcrm/controllers/Adminhtml/RetailcrmbuttonController.php new file mode 100644 index 0000000..d2149b3 --- /dev/null +++ b/app/code/community/Retailcrm/Retailcrm/controllers/Adminhtml/RetailcrmbuttonController.php @@ -0,0 +1,24 @@ +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 index 39e9bb2..359f131 100644 --- a/app/code/community/Retailcrm/Retailcrm/etc/config.xml +++ b/app/code/community/Retailcrm/Retailcrm/etc/config.xml @@ -45,6 +45,7 @@ SOFTWARE. + @@ -54,6 +55,8 @@ SOFTWARE. + + @@ -63,6 +66,19 @@ SOFTWARE. + + + + + + singleton + Retailcrm_Retailcrm_Model_Observer + orderStatusHistoryCheck + + + + + @@ -72,8 +88,21 @@ SOFTWARE. + + + + + + + + Retailcrm_Retailcrm + + + + + diff --git a/app/code/community/Retailcrm/Retailcrm/etc/system.xml b/app/code/community/Retailcrm/Retailcrm/etc/system.xml index 593308b..292274a 100644 --- a/app/code/community/Retailcrm/Retailcrm/etc/system.xml +++ b/app/code/community/Retailcrm/Retailcrm/etc/system.xml @@ -121,6 +121,39 @@ SOFTWARE. 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 new file mode 100644 index 0000000..98de835 --- /dev/null +++ b/app/design/adminhtml/default/default/template/retailcrm/system/config/button.phtml @@ -0,0 +1,16 @@ + + +getButtonHtml() ?> \ No newline at end of file diff --git a/tests/unit/autoload.php b/tests/unit/autoload.php new file mode 100644 index 0000000..8d04aba --- /dev/null +++ b/tests/unit/autoload.php @@ -0,0 +1,12 @@ + + + + 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 new file mode 100644 index 0000000..de9e754 --- /dev/null +++ b/tests/unit/testsuite/Retailcrm/Retailcrm/Model/IcmlTest.php @@ -0,0 +1,22 @@ +_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 new file mode 100644 index 0000000..f54b152 --- /dev/null +++ b/tests/unit/testsuite/Retailcrm/Retailcrm/Model/OrderTest.php @@ -0,0 +1,27 @@ +_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