diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..14bc68c --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/nbproject/private/ \ No newline at end of file diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..ac55bf4 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,40 @@ +language: php + +sudo: false + +env: + global: + - DB_USER=root + - DB_HOST=localhost + - DB_NAME=magento2_test + - ADMIN_FIRSTNAME=admin_firstname + - ADMIN_LASTNAME=admin_lastname + - ADMIN_EMAIL=example@email.com + - ADMIN_USER=admin + - ADMIN_PASS=admin123 + +matrix: + include: + - php: 7.0 + env: BRANCH=2.2-develop + - php: 7.1 + env: BRANCH=2.2-develop + - php: 7.1 + env: BRANCH=2.3-develop + - php: 7.2 + env: BRANCH=2.3-develop + +before_script: + - bash bin/install.sh + +script: + - bash bin/script.sh + +deploy: + skip_cleanup: true + provider: script + script: make + on: + php: 7.2 + branch: master + condition: "$DEPLOY = true" \ No newline at end of file diff --git a/Block/Adminhtml/System/Config/Form/Field/Attributes.php b/Block/Adminhtml/System/Config/Form/Field/Attributes.php deleted file mode 100644 index 0b872e7..0000000 --- a/Block/Adminhtml/System/Config/Form/Field/Attributes.php +++ /dev/null @@ -1,63 +0,0 @@ -getValues(); - $html = ''; - $html .= ''; - $html .= '
    '; - - $selected = explode(',', $element->getValue()); - - foreach ($selected as $value) { - if ($key = array_search($value, array_column($values, 'value'))) { - $html .= '
  • '; - $html .= isset($values[$key]['label'])?$values[$key]['label']:'n/a'; - $html .= '
  • '; - $values[$key]['selected'] = TRUE; - } - } - - $html .= '
'; - $html .= '
    '; - - if ($values) { - foreach ($values as $option) { - if (!isset($option['selected'])) { - $html .= '
  • '; - $html .= isset($option['label'])?$option['label']:'n/a'; - $html .= '
  • '; - } - } - } - - $html .= '
'; - $html .= '
' . $element->getElementHtml() . '
'; - $html .= ''; - - return $html; - } -} diff --git a/Block/Adminhtml/System/Config/Form/Field/Base.php b/Block/Adminhtml/System/Config/Form/Field/Base.php deleted file mode 100644 index 9a7d11b..0000000 --- a/Block/Adminhtml/System/Config/Form/Field/Base.php +++ /dev/null @@ -1,72 +0,0 @@ -get('\Magento\Framework\App\Config\ScopeConfigInterface'); - $logger = $om->get('\Psr\Log\LoggerInterface'); - $cacheTypeList = $om->get('\Magento\Framework\App\Cache\TypeListInterface'); - $resourceConfig = $om->get('Magento\Config\Model\ResourceModel\Config'); - - $this->_resourceConfig = $resourceConfig; - $this->_cacheTypeList = $cacheTypeList; - $this->logger = $logger; - $this->_apiUrl = $config->getValue('retailcrm/general/api_url'); - $this->_apiKey = $config->getValue('retailcrm/general/api_key'); - $this->_isCredentialCorrect = false; - - if (!empty($this->_apiUrl) && !empty($this->_apiKey)) { - if (false === stripos($this->_apiUrl, 'https://')) { - $this->_apiUrl = str_replace("http://", "https://", $this->_apiUrl); - $this->_resourceConfig->saveConfig('retailcrm/general/api_url', $this->_apiUrl, 'default', 0); - $this->_cacheTypeList->cleanType('config'); - } - - if (!$this->is_url($this->_apiUrl)){ - echo 'URL not valid
'; - echo 'Please check your Url and Reload page
'; - - $this->_resourceConfig->saveConfig('retailcrm/general/api_url', '', 'default', 0); - $this->_cacheTypeList->cleanType('config'); - } - - $client = new \Retailcrm\Retailcrm\Model\ApiClient\ApiClient( - $this->_apiUrl, - $this->_apiKey - ); - - try { - $response = $client->sitesList(); - - } catch (\Retailcrm\Retailcrm\Model\ApiClient\Exception\CurlException $e) { - $this->_logger->addDebug($e->getMessage()); - } - - if ($response->isSuccessful()) { - $this->_isCredentialCorrect = true; - if($response['success'] != 1) { - $this->_resourceConfig->saveConfig('retailcrm/general/api_url', '', 'default', 0); - $this->_cacheTypeList->cleanType('config'); - } - } - } - - } - - - public function is_url($url) { - return preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $url); - } - -} \ No newline at end of file diff --git a/Block/Adminhtml/System/Config/Form/Field/ListMode.php b/Block/Adminhtml/System/Config/Form/Field/ListMode.php deleted file mode 100644 index 4f36103..0000000 --- a/Block/Adminhtml/System/Config/Form/Field/ListMode.php +++ /dev/null @@ -1,16 +0,0 @@ - 'grid', 'label' => __('Grid Only')], - ['value' => 'list', 'label' => __('List Only')], - ['value' => 'grid-list', 'label' => __('Grid (default) / List')], - ['value' => 'list-grid', 'label' => __('List (default) / Grid')] - ]; - } -} \ No newline at end of file diff --git a/Block/Adminhtml/System/Config/Form/Field/Payment.php b/Block/Adminhtml/System/Config/Form/Field/Payment.php deleted file mode 100644 index bc1c6f9..0000000 --- a/Block/Adminhtml/System/Config/Form/Field/Payment.php +++ /dev/null @@ -1,87 +0,0 @@ -get('\Magento\Framework\App\Config\ScopeConfigInterface'); - $this->_apiUrl = $config->getValue('retailcrm/general/api_url'); - $this->_apiKey = $config->getValue('retailcrm/general/api_key'); - $this->_apiVersion = $config->getValue('retailcrm/general/api_version'); - $this->_systemStore = $systemStore; - $this->_formFactory = $formFactory; - } - - public function render(AbstractElement $element) - { - $html = ''; - $htmlError = '
Please check your API Url & API Key
'; - - if ((!empty($this->_apiUrl)) && (!empty($this->_apiKey))) { - $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); - $paymentConfig = $objectManager->get('Magento\Payment\Model\Config'); - $activePaymentMethods = $paymentConfig->getActiveMethods(); - - $client = new ApiClient($this->_apiUrl, $this->_apiKey, $this->_apiVersion); - - $response = $client->paymentTypesList(); - - if ($response === false) { - return $htmlError; - } - - if ($response->isSuccessful()) { - $paymentTypes = $response['paymentTypes']; - } else { - return $htmlError; - } - - $config = \Magento\Framework\App\ObjectManager::getInstance()->get( - 'Magento\Framework\App\Config\ScopeConfigInterface' - ); - - foreach (array_keys($activePaymentMethods) as $k=>$payment){ - $html .=''; - $html .=''; - $html .=''; - $html .=''; - $html .= ''; - $html .= '
'.$payment.''; - $html .=''; - $html .= '
'; - } - - return $html; - } else { - return $htmlError; - } - } -} diff --git a/Block/Adminhtml/System/Config/Form/Field/Shipping.php b/Block/Adminhtml/System/Config/Form/Field/Shipping.php deleted file mode 100644 index 6cdb525..0000000 --- a/Block/Adminhtml/System/Config/Form/Field/Shipping.php +++ /dev/null @@ -1,88 +0,0 @@ -get('\Magento\Framework\App\Config\ScopeConfigInterface'); - $this->_apiUrl = $config->getValue('retailcrm/general/api_url'); - $this->_apiKey = $config->getValue('retailcrm/general/api_key'); - $this->_apiVersion = $config->getValue('retailcrm/general/api_version'); - $this->_systemStore = $systemStore; - $this->_formFactory = $formFactory; - $this->_objectManager = $objectManager; - } - - public function render(AbstractElement $element) - { - $html = ''; - $htmlError = '
Please check your API Url & API Key
'; - - if (!empty($this->_apiUrl) && !empty($this->_apiKey)) { - $shipConfig = $this->_objectManager->get('Magento\Shipping\Model\Config'); - $deliveryMethods = $shipConfig->getActiveCarriers(); - - $client = new ApiClient($this->_apiUrl, $this->_apiKey, $this->_apiVersion); - - $response = $client->deliveryTypesList(); - - if ($response === false) { - return $htmlError; - } - - if ($response->isSuccessful()) { - $deliveryTypes = $response['deliveryTypes']; - } else { - return $htmlError; - } - - $config = \Magento\Framework\App\ObjectManager::getInstance()->get( - 'Magento\Framework\App\Config\ScopeConfigInterface' - ); - - foreach (array_keys($deliveryMethods) as $k => $delivery) { - $html .=''; - $html .=''; - $html .=''; - $html .=''; - $html .=''; - $html .='
'.$delivery.''; - $html .=''; - $html .='
'; - } - - return $html; - } else { - return $htmlError; - } - } -} diff --git a/Block/Adminhtml/System/Config/Form/Field/Status.php b/Block/Adminhtml/System/Config/Form/Field/Status.php deleted file mode 100644 index f02d7f3..0000000 --- a/Block/Adminhtml/System/Config/Form/Field/Status.php +++ /dev/null @@ -1,91 +0,0 @@ -get('\Magento\Framework\App\Config\ScopeConfigInterface'); - $this->_apiUrl = $config->getValue('retailcrm/general/api_url'); - $this->_apiKey = $config->getValue('retailcrm/general/api_key'); - $this->_apiVersion = $config->getValue('retailcrm/general/api_version'); - $this->_systemStore = $systemStore; - $this->_formFactory = $formFactory; - $this->_objectManager = $objectManager; - } - - public function render(AbstractElement $element) - { - $html = ''; - $htmlError = '
Please check your API Url & API Key
'; - - if ((!empty($this->_apiUrl)) && (!empty($this->_apiKey))) { - $statusCollection = $this->_objectManager->create('Magento\Sales\Model\ResourceModel\Order\Status\Collection'); - $statuses = $statusCollection->toOptionArray(); - - $client = new ApiClient($this->_apiUrl, $this->_apiKey, $this->_apiVersion); - - $response = $client->statusesList(); - - if ($response === false) { - return $htmlError; - } - - if ($response->isSuccessful()) { - $statusTypes = $response['statuses']; - } else { - return $htmlError; - } - - $config = $this->_objectManager->get('Magento\Framework\App\Config\ScopeConfigInterface'); - - foreach ($statuses as $k => $status){ - $html .= ''; - $html .= ''; - $html .= ''; - $html .= ''; - $html .= ''; - $html .= '
' . $status['label'] . ''; - $html .= ''; - $html .= '
'; - } - - return $html; - } else { - return $htmlError; - } - } -} diff --git a/Block/Display.php b/Block/Display.php deleted file mode 100644 index 507ce62..0000000 --- a/Block/Display.php +++ /dev/null @@ -1,16 +0,0 @@ -logger = $logger; - - $api_url = $config->getValue('retailcrm/general/api_url'); - $api_key = $config->getValue('retailcrm/general/api_key'); - - var_dump($api_key); - var_dump($api_url); - - //$this->logger->debug($api_url); - - parent::__construct($context); - } - - public function execute() - { - // - exit; - } -} diff --git a/Cron/Icml.php b/Cron/Icml.php deleted file mode 100644 index c526cef..0000000 --- a/Cron/Icml.php +++ /dev/null @@ -1,19 +0,0 @@ -_logger = $logger; - } - - public function execute() - { - $Icml = new \Retailcrm\Retailcrm\Model\Icml\Icml(); - $Icml->generate(); - } -} diff --git a/Cron/OrderHistory.php b/Cron/OrderHistory.php deleted file mode 100644 index f46615f..0000000 --- a/Cron/OrderHistory.php +++ /dev/null @@ -1,23 +0,0 @@ -_logger = $logger; - } - - public function execute() - { - $history = new \Retailcrm\Retailcrm\Model\History\Exchange(); - $history->ordersHistory(); - - $this->_logger->writeRow('Cron Works: OrderHistory'); - } -} diff --git a/Helper/Data.php b/Helper/Data.php deleted file mode 100644 index d3e27ea..0000000 --- a/Helper/Data.php +++ /dev/null @@ -1,68 +0,0 @@ -objectManager = $objectManager; - $this->storeManager = $storeManager; - parent::__construct($context); - } - - public function getConfigValue($field, $storeId = null) - { - return $this->scopeConfig->getValue( - $field, ScopeInterface::SCOPE_STORE, $storeId - ); - } - - public function getGeneralConfig($code, $storeId = null) - { - return $this->getConfigValue(self::XML_PATH_RETAILCRM . $code, $storeId); - } - - /** - * Recursive array filter - * - * @param array $haystack input array - * - * @SuppressWarnings(PHPMD.StaticAccess) - * @SuppressWarnings(PHPMD.ElseExpression) - * - * @return array - */ - public function filterRecursive($haystack) - { - foreach ($haystack as $key => $value) { - if (is_array($value)) { - $haystack[$key] = self::filterRecursive($haystack[$key]); - } - - if (is_null($haystack[$key]) - || $haystack[$key] === '' - || count($haystack[$key]) == 0 - ) { - unset($haystack[$key]); - } elseif (!is_array($value)) { - $haystack[$key] = trim($value); - } - } - - return $haystack; - } -} \ No newline at end of file diff --git a/Helper/Proxy.php b/Helper/Proxy.php deleted file mode 100644 index 0ab24e0..0000000 --- a/Helper/Proxy.php +++ /dev/null @@ -1,81 +0,0 @@ -logger = new Logger($objectManager); - $this->apiClient = new ApiClient($url, $key, $apiVersion); - } - - public function __call($method, $arguments) - { - try { - $response = call_user_func_array([$this->apiClient->request, $method], $arguments); - - if (!$response->isSuccessful()) { - $this->logger->writeRow( - sprintf( - "[HTTP status %s] %s", - $response->getStatusCode(), - $response->getErrorMsg() - ) - ); - - if (isset($response['errors'])) { - $this->logger->writeRow(implode(' :: ', $response['errors'])); - } - } - } catch (\RetailCrm\Exception\CurlException $exception) { - $this->logger->writeRow($exception->getMessage()); - return false; - } catch (\RetailCrm\Exception\InvalidJsonException $exception) { - $this->logger->writeRow($exception->getMessage()); - return false; - } catch (\InvalidArgumentException $exception) { - $this->logger->writeRow($exception->getMessage()); - } - - return $response; - } - - /** - * Get API version - * - * @return string - */ - public function getVersion() - { - if (!is_object($this->apiClient)) { - return false; - } - - return $this->apiClient->getVersion(); - } - - /** - * Get error text message - * - * @param string $property - * - * @return string - */ - public function getErrorText($property) - { - return $this->{$property}; - } -} diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..957ab84 --- /dev/null +++ b/Makefile @@ -0,0 +1,14 @@ +FILE = $(TRAVIS_BUILD_DIR)/VERSION +VERSION = `cat $(FILE)` +ARCHIVE_NAME = '/tmp/retailcrm-retailcrm-'$(VERSION)'.zip' + +all: build_archive send_to_ftp delete_archive + +build_archive: + cd src; zip -r $(ARCHIVE_NAME) ./* + +send_to_ftp: + curl -T $(ARCHIVE_NAME) -u $(FTP_USER):$(FTP_PASSWORD) ftp://$(FTP_HOST) + +delete_archive: + rm -f $(ARCHIVE_NAME) diff --git a/Model/ApiClient/ApiClient.php b/Model/ApiClient/ApiClient.php deleted file mode 100644 index 49c7674..0000000 --- a/Model/ApiClient/ApiClient.php +++ /dev/null @@ -1,1843 +0,0 @@ - - * @license https://opensource.org/licenses/MIT MIT License - * @link http://www.retailcrm.ru/docs/Developers/ApiVersion4 - */ - -namespace Retailcrm\Retailcrm\Model\ApiClient; - -use Retailcrm\Retailcrm\Model\ApiClient\Http\Client; -use Retailcrm\Retailcrm\Model\ApiClient\Response\ApiResponse; - -/** - * PHP version 5.3 - * - * API client class - * - * @category RetailCrm - * @package RetailCrm - * @author RetailCrm - * @license https://opensource.org/licenses/MIT MIT License - * @link http://www.retailcrm.ru/docs/Developers/ApiVersion4 - */ -class ApiClient -{ - - const VERSION = 'v4'; - - protected $client; - - /** - * Site code - */ - protected $siteCode; - - /** - * Client creating - * - * @param string $url api url - * @param string $apiKey api key - * @param string $site site code - * - * @throws \InvalidArgumentException - */ - public function __construct($url, $apiKey, $site = null) - { - if ('/' !== $url[strlen($url) - 1]) { - $url .= '/'; - } - - $url = $url . 'api/' . self::VERSION; - - $this->client = new Client($url, array('apiKey' => $apiKey)); - $this->siteCode = $site; - } - - /** - * Returns users list - * - * @param array $filter - * @param null $page - * @param null $limit - * - * @throws \RetailCrm\Exception\InvalidJsonException - * @throws \RetailCrm\Exception\CurlException - * @throws \InvalidArgumentException - * - * @return ApiResponse - */ - public function usersList(array $filter = array(), $page = null, $limit = null) - { - $parameters = array(); - - if (count($filter)) { - $parameters['filter'] = $filter; - } - if (null !== $page) { - $parameters['page'] = (int) $page; - } - if (null !== $limit) { - $parameters['limit'] = (int) $limit; - } - - return $this->client->makeRequest( - '/users', - Client::METHOD_GET, - $parameters - ); - } - - /** - * Get user groups - * - * @param null $page - * @param null $limit - * - * @throws \RetailCrm\Exception\InvalidJsonException - * @throws \RetailCrm\Exception\CurlException - * - * @return ApiResponse - */ - public function usersGroups($page = null, $limit = null) - { - $parameters = array(); - - if (null !== $page) { - $parameters['page'] = (int) $page; - } - if (null !== $limit) { - $parameters['limit'] = (int) $limit; - } - - return $this->client->makeRequest( - '/user-groups', - 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", Client::METHOD_GET); - } - - /** - * Returns filtered orders 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 ordersList(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', - 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 \InvalidArgumentException( - 'Parameter `order` must contains a data' - ); - } - - return $this->client->makeRequest( - '/orders/create', - 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 \InvalidArgumentException( - 'Method parameter must contains at least one IDs pair' - ); - } - - return $this->client->makeRequest( - '/orders/fix-external-ids', - Client::METHOD_POST, - array('orders' => json_encode($ids) - ) - ); - } - - /** - * Returns statuses of the orders - * - * @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 (count($ids)) { - $parameters['ids'] = $ids; - } - if (count($externalIds)) { - $parameters['externalIds'] = $externalIds; - } - - return $this->client->makeRequest( - '/orders/statuses', - Client::METHOD_GET, - $parameters - ); - } - - /** - * 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 - * - * @return ApiResponse - */ - public function ordersUpload(array $orders, $site = null) - { - if (!count($orders)) { - throw new \InvalidArgumentException( - 'Parameter `orders` must contains array of the orders' - ); - } - - return $this->client->makeRequest( - '/orders/upload', - Client::METHOD_POST, - $this->fillSite($site, array('orders' => json_encode($orders))) - ); - } - - /** - * 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 - * - * @return ApiResponse - */ - public function ordersGet($id, $by = 'externalId', $site = null) - { - $this->checkIdParameter($by); - - return $this->client->makeRequest( - "/orders/$id", - Client::METHOD_GET, - $this->fillSite($site, array('by' => $by)) - ); - } - - /** - * 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 - * - * @return ApiResponse - */ - public function ordersEdit(array $order, $by = 'externalId', $site = null) - { - if (!count($order)) { - throw new \InvalidArgumentException( - 'Parameter `order` must contains a data' - ); - } - - $this->checkIdParameter($by); - - if (!array_key_exists($by, $order)) { - throw new \InvalidArgumentException( - sprintf('Order array must contain the "%s" parameter.', $by) - ); - } - - return $this->client->makeRequest( - sprintf('/orders/%s/edit', $order[$by]), - Client::METHOD_POST, - $this->fillSite( - $site, - array('order' => json_encode($order), 'by' => $by) - ) - ); - } - - /** - * Get orders history - * @param array $filter - * @param null $page - * @param null $limit - * - * @return ApiResponse - */ - public function ordersHistory(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/history', - Client::METHOD_GET, - $parameters - ); - } - - /** - * Returns filtered customers 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 customersList(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', - 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 \InvalidArgumentException( - 'Parameter `customer` must contains a data' - ); - } - - return $this->client->makeRequest( - '/customers/create', - Client::METHOD_POST, - $this->fillSite($site, array('customer' => json_encode($customer))) - ); - } - - /** - * Save customer IDs' (id and externalId) association in the CRM - * - * @param array $ids ids mapping - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function customersFixExternalIds(array $ids) - { - if (! count($ids)) { - throw new \InvalidArgumentException( - 'Method parameter must contains at least one IDs pair' - ); - } - - return $this->client->makeRequest( - '/customers/fix-external-ids', - 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 \InvalidArgumentException( - 'Parameter `customers` must contains array of the customers' - ); - } - - return $this->client->makeRequest( - '/customers/upload', - 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", - 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 \InvalidArgumentException( - 'Parameter `customer` must contains a data' - ); - } - - $this->checkIdParameter($by); - - if (!array_key_exists($by, $customer)) { - throw new \InvalidArgumentException( - sprintf('Customer array must contain the "%s" parameter.', $by) - ); - } - - return $this->client->makeRequest( - sprintf('/customers/%s/edit', $customer[$by]), - 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', - 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', - 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 \InvalidArgumentException( - 'Parameter `pack` must contains a data' - ); - } - - return $this->client->makeRequest( - '/orders/packs/create', - 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', - 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 \InvalidArgumentException('Parameter `id` must be set'); - } - - return $this->client->makeRequest( - "/orders/packs/$id", - 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 \InvalidArgumentException('Parameter `id` must be set'); - } - - return $this->client->makeRequest( - sprintf('/orders/packs/%s/delete', $id), - 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 \InvalidArgumentException( - 'Parameter `pack` must contains a data & pack `id` must be set' - ); - } - - return $this->client->makeRequest( - sprintf('/orders/packs/%s/edit', $pack['id']), - 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) - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function storeInventories(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/inventories', - Client::METHOD_GET, - $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 \InvalidArgumentException('Parameter `code` must be set'); - } - - return $this->client->makeRequest( - "/store/setting/$code", - 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 \InvalidArgumentException( - 'Parameter `configuration` must contains a data & configuration `code` must be set' - ); - } - - return $this->client->makeRequest( - sprintf('/store/setting/%s/edit', $configuration['code']), - Client::METHOD_POST, - array('configuration' => json_encode($configuration)) - ); - } - - /** - * Upload store inventories - * - * @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 (!count($offers)) { - throw new \InvalidArgumentException( - 'Parameter `offers` must contains array of the offers' - ); - } - - return $this->client->makeRequest( - '/store/inventories/upload', - 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 \InvalidArgumentException( - 'Parameter `prices` must contains array of the prices' - ); - } - - return $this->client->makeRequest( - '/store/prices/upload', - 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', - Client::METHOD_GET, - $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 \InvalidArgumentException('Parameter `code` must be set'); - } - - return $this->client->makeRequest( - "/delivery/generic/setting/$code", - Client::METHOD_GET - ); - } - - /** - * 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 \InvalidArgumentException( - 'Parameter `configuration` must contains a data & configuration `code` must be set' - ); - } - - return $this->client->makeRequest( - sprintf('/delivery/generic/setting/%s/edit', $configuration['code']), - 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 \InvalidArgumentException('Parameter `code` must be set'); - } - - if (!count($statusUpdate)) { - throw new \InvalidArgumentException( - 'Parameter `statusUpdate` must contains a data' - ); - } - - return $this->client->makeRequest( - sprintf('/delivery/generic/%s/tracking', $code), - 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', - Client::METHOD_GET - ); - } - - /** - * 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', - Client::METHOD_GET - ); - } - - /** - * 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 (!array_key_exists('code', $data)) { - throw new \InvalidArgumentException( - 'Data must contain "code" parameter.' - ); - } - - return $this->client->makeRequest( - sprintf('/reference/delivery-services/%s/edit', $data['code']), - Client::METHOD_POST, - 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', - Client::METHOD_GET - ); - } - - /** - * 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 (!array_key_exists('code', $data)) { - throw new \InvalidArgumentException( - 'Data must contain "code" parameter.' - ); - } - - return $this->client->makeRequest( - sprintf('/reference/delivery-types/%s/edit', $data['code']), - Client::METHOD_POST, - 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', - Client::METHOD_GET - ); - } - - /** - * 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 (!array_key_exists('code', $data)) { - throw new \InvalidArgumentException( - 'Data must contain "code" parameter.' - ); - } - - return $this->client->makeRequest( - sprintf('/reference/order-methods/%s/edit', $data['code']), - 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', - Client::METHOD_GET - ); - } - - /** - * 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 (!array_key_exists('code', $data)) { - throw new \InvalidArgumentException( - 'Data must contain "code" parameter.' - ); - } - - return $this->client->makeRequest( - sprintf('/reference/order-types/%s/edit', $data['code']), - Client::METHOD_POST, - 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', - Client::METHOD_GET - ); - } - - /** - * 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 (!array_key_exists('code', $data)) { - throw new \InvalidArgumentException( - 'Data must contain "code" parameter.' - ); - } - - return $this->client->makeRequest( - sprintf('/reference/payment-statuses/%s/edit', $data['code']), - Client::METHOD_POST, - 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', - Client::METHOD_GET - ); - } - - /** - * 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 (!array_key_exists('code', $data)) { - throw new \InvalidArgumentException( - 'Data must contain "code" parameter.' - ); - } - - return $this->client->makeRequest( - sprintf('/reference/payment-types/%s/edit', $data['code']), - Client::METHOD_POST, - 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', - Client::METHOD_GET - ); - } - - /** - * 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 (!array_key_exists('code', $data)) { - throw new \InvalidArgumentException( - 'Data must contain "code" parameter.' - ); - } - - return $this->client->makeRequest( - sprintf('/reference/product-statuses/%s/edit', $data['code']), - Client::METHOD_POST, - array('productStatus' => json_encode($data)) - ); - } - - /** - * Returns sites list - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function sitesList() - { - return $this->client->makeRequest( - '/reference/sites', - Client::METHOD_GET - ); - } - - /** - * 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 (!array_key_exists('code', $data)) { - throw new \InvalidArgumentException( - 'Data must contain "code" parameter.' - ); - } - - return $this->client->makeRequest( - sprintf('/reference/sites/%s/edit', $data['code']), - Client::METHOD_POST, - 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', - 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', - 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 \InvalidArgumentException( - 'Data must contain "code" parameter.' - ); - } - - return $this->client->makeRequest( - sprintf('/reference/statuses/%s/edit', $data['code']), - 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', - Client::METHOD_GET - ); - } - - /** - * 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 (!array_key_exists('code', $data)) { - throw new \InvalidArgumentException( - 'Data must contain "code" parameter.' - ); - } - - if (!array_key_exists('name', $data)) { - throw new \InvalidArgumentException( - 'Data must contain "name" parameter.' - ); - } - - return $this->client->makeRequest( - sprintf('/reference/stores/%s/edit', $data['code']), - Client::METHOD_POST, - 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', - 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 \InvalidArgumentException( - 'Data must contain "code" parameter.' - ); - } - - if (!array_key_exists('name', $data)) { - throw new \InvalidArgumentException( - 'Data must contain "name" parameter.' - ); - } - - return $this->client->makeRequest( - sprintf('/reference/price-types/%s/edit', $data['code']), - 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 \InvalidArgumentException('Parameter `code` must be set'); - } - - return $this->client->makeRequest( - "/telephony/setting/$code", - Client::METHOD_GET - ); - } - - /** - * 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 \InvalidArgumentException('Code must be set'); - } - - $parameters['code'] = $code; - - if (!isset($clientId)) { - throw new \InvalidArgumentException('client id must be set'); - } - - $parameters['clientId'] = $clientId; - - if (!isset($active)) { - $parameters['active'] = false; - } else { - $parameters['active'] = $active; - } - - if (!isset($name)) { - throw new \InvalidArgumentException('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", - 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 \InvalidArgumentException('Phone number must be set'); - } - - if (!isset($type)) { - throw new \InvalidArgumentException('Type must be set (in|out|hangup)'); - } - - if (empty($codes)) { - throw new \InvalidArgumentException('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', - 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 \InvalidArgumentException( - 'Parameter `calls` must contains array of the calls' - ); - } - - return $this->client->makeRequest( - '/telephony/calls/upload', - 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 \InvalidArgumentException('Phone number must be set'); - } - - $parameters['phone'] = $phone; - $parameters['details'] = isset($details) ? $details : 0; - - return $this->client->makeRequest( - '/telephony/manager', - Client::METHOD_GET, - $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', - Client::METHOD_GET - ); - } - - /** - * Return current site - * - * @return string - */ - public function getSite() - { - return $this->siteCode; - } - - /** - * Set site - * - * @param string $site site code - * - * @return void - */ - public function setSite($site) - { - $this->siteCode = $site; - } - - /** - * Check ID parameter - * - * @param string $by identify by - * - * @throws \InvalidArgumentException - * - * @return bool - */ - protected function checkIdParameter($by) - { - $allowedForBy = array( - 'externalId', - 'id' - ); - - if (!in_array($by, $allowedForBy, false)) { - throw new \InvalidArgumentException( - sprintf( - 'Value "%s" for "by" param is not valid. Allowed values are %s.', - $by, - implode(', ', $allowedForBy) - ) - ); - } - - return true; - } - - /** - * Fill params by site value - * - * @param string $site site code - * @param array $params input parameters - * - * @return array - */ - protected function fillSite($site, array $params) - { - if ($site) { - $params['site'] = $site; - } elseif ($this->siteCode) { - $params['site'] = $this->siteCode; - } - - return $params; - } -} diff --git a/Model/ApiClient/Exception/CurlException.php b/Model/ApiClient/Exception/CurlException.php deleted file mode 100644 index d52de1d..0000000 --- a/Model/ApiClient/Exception/CurlException.php +++ /dev/null @@ -1,30 +0,0 @@ - - * @license https://opensource.org/licenses/MIT MIT License - * @link http://www.retailcrm.ru/docs/Developers/ApiVersion4 - */ - -namespace Retailcrm\Retailcrm\Model\ApiClient\Exception; - -/** - * PHP version 5.3 - * - * Class CurlException - * - * @category RetailCrm - * @package RetailCrm - * @author RetailCrm - * @license https://opensource.org/licenses/MIT MIT License - * @link http://www.retailcrm.ru/docs/Developers/ApiVersion4 - */ -class CurlException extends \RuntimeException -{ -} diff --git a/Model/ApiClient/Exception/InvalidJsonException.php b/Model/ApiClient/Exception/InvalidJsonException.php deleted file mode 100644 index cb9437a..0000000 --- a/Model/ApiClient/Exception/InvalidJsonException.php +++ /dev/null @@ -1,30 +0,0 @@ - - * @license https://opensource.org/licenses/MIT MIT License - * @link http://www.retailcrm.ru/docs/Developers/ApiVersion4 - */ - -namespace Retailcrm\Retailcrm\Model\ApiClient\Exception; - -/** - * PHP version 5.3 - * - * Class InvalidJsonException - * - * @category RetailCrm - * @package RetailCrm - * @author RetailCrm - * @license https://opensource.org/licenses/MIT MIT License - * @link http://www.retailcrm.ru/docs/Developers/ApiVersion4 - */ -class InvalidJsonException extends \DomainException -{ -} diff --git a/Model/ApiClient/Http/Client.php b/Model/ApiClient/Http/Client.php deleted file mode 100644 index 4cd3b6a..0000000 --- a/Model/ApiClient/Http/Client.php +++ /dev/null @@ -1,128 +0,0 @@ - - * @license https://opensource.org/licenses/MIT MIT License - * @link http://www.retailcrm.ru/docs/Developers/ApiVersion4 - */ - -namespace Retailcrm\Retailcrm\Model\ApiClient\Http; - -use Retailcrm\Retailcrm\Model\ApiClient\Exception\CurlException; -use Retailcrm\Retailcrm\Model\ApiClient\Exception\InvalidJsonException; -use Retailcrm\Retailcrm\Model\ApiClient\Response\ApiResponse; - -/** - * PHP version 5.3 - * - * HTTP client - * - * @category RetailCrm - * @package RetailCrm - * @author RetailCrm - * @license https://opensource.org/licenses/MIT MIT License - * @link http://www.retailcrm.ru/docs/Developers/ApiVersion4 - */ -class Client -{ - const METHOD_GET = 'GET'; - const METHOD_POST = 'POST'; - - 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 \InvalidArgumentException( - 'API schema requires HTTPS protocol' - ); - } - - $this->url = $url; - $this->defaultParameters = $defaultParameters; - } - - /** - * Make HTTP request - * - * @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() - ) { - $allowedMethods = array(self::METHOD_GET, self::METHOD_POST); - - if (!in_array($method, $allowedMethods, false)) { - throw new \InvalidArgumentException( - 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 && count($parameters)) { - $url .= '?' . http_build_query($parameters, '', '&'); - } - - $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($curlHandler, CURLOPT_POST, true); - curl_setopt($curlHandler, CURLOPT_POSTFIELDS, $parameters); - } - - $responseBody = curl_exec($curlHandler); - $statusCode = curl_getinfo($curlHandler, CURLINFO_HTTP_CODE); - $errno = curl_errno($curlHandler); - $error = curl_error($curlHandler); - - curl_close($curlHandler); - - if ($errno) { - throw new CurlException($error, $errno); - } - - return new ApiResponse($statusCode, $responseBody); - } -} diff --git a/Model/ApiClient/Response/ApiResponse.php b/Model/ApiClient/Response/ApiResponse.php deleted file mode 100644 index f62b2f6..0000000 --- a/Model/ApiClient/Response/ApiResponse.php +++ /dev/null @@ -1,180 +0,0 @@ - - * @license https://opensource.org/licenses/MIT MIT License - * @link http://www.retailcrm.ru/docs/Developers/ApiVersion4 - */ - -namespace Retailcrm\Retailcrm\Model\ApiClient\Response; - -use Retailcrm\Retailcrm\Model\ApiClient\Exception\InvalidJsonException; - -/** - * PHP version 5.3 - * - * Response from retailCRM API - * - * @category RetailCrm - * @package RetailCrm - * @author RetailCrm - * @license https://opensource.org/licenses/MIT MIT License - * @link http://www.retailcrm.ru/docs/Developers/ApiVersion4 - */ -class ApiResponse implements \ArrayAccess -{ - // HTTP response status code - protected $statusCode; - - // 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; - - if (!empty($responseBody)) { - $response = json_decode($responseBody, true); - - if (!$response && JSON_ERROR_NONE !== ($error = json_last_error())) { - throw new InvalidJsonException( - "Invalid JSON in the API response body. Error code #$error", - $error - ); - } - - $this->response = $response; - } - } - - /** - * Return HTTP response status code - * - * @return int - */ - public function getStatusCode() - { - return $this->statusCode; - } - - /** - * HTTP request was successful - * - * @return bool - */ - public function isSuccessful() - { - return $this->statusCode < 400; - } - - /** - * Allow to access for the property throw class method - * - * @param string $name method name - * @param mixed $arguments method parameters - * - * @throws \InvalidArgumentException - * - * @return mixed - */ - public function __call($name, $arguments) - { - // convert getSomeProperty to someProperty - $propertyName = strtolower(substr($name, 3, 1)) . substr($name, 4); - - if (!isset($this->response[$propertyName])) { - throw new \InvalidArgumentException("Method \"$name\" not found"); - } - - return $this->response[$propertyName]; - } - - /** - * Allow to access for the property throw object property - * - * @param string $name property name - * - * @throws \InvalidArgumentException - * - * @return mixed - */ - public function __get($name) - { - if (!isset($this->response[$name])) { - throw new \InvalidArgumentException("Property \"$name\" not found"); - } - - return $this->response[$name]; - } - - /** - * Offset set - * - * @param mixed $offset offset - * @param mixed $value value - * - * @throws \BadMethodCallException - * @return void - */ - public function offsetSet($offset, $value) - { - throw new \BadMethodCallException('This activity not allowed'); - } - - /** - * Offset unset - * - * @param mixed $offset offset - * - * @throws \BadMethodCallException - * @return void - */ - public function offsetUnset($offset) - { - throw new \BadMethodCallException('This call not allowed'); - } - - /** - * Check offset - * - * @param mixed $offset offset - * - * @return bool - */ - public function offsetExists($offset) - { - return isset($this->response[$offset]); - } - - /** - * Get offset - * - * @param mixed $offset offset - * - * @throws \InvalidArgumentException - * - * @return mixed - */ - public function offsetGet($offset) - { - if (!isset($this->response[$offset])) { - throw new \InvalidArgumentException("Property \"$offset\" not found"); - } - - return $this->response[$offset]; - } -} diff --git a/Model/Icml/Icml.php b/Model/Icml/Icml.php deleted file mode 100644 index c16adc2..0000000 --- a/Model/Icml/Icml.php +++ /dev/null @@ -1,312 +0,0 @@ -get('Magento\Store\Model\StoreManagerInterface'); - $categoryCollectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Category\CollectionFactory'); - $product = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory'); - $storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface'); - $StockState = $objectManager->get('\Magento\CatalogInventory\Api\StockStateInterface'); - $configurable = $objectManager->get('Magento\ConfigurableProduct\Model\Product\Type\Configurable'); - $config = $objectManager->get('\Magento\Framework\App\Config\ScopeConfigInterface'); - - $this->_configurable = $configurable; - $this->_StockState = $StockState; - $this->_storeManager = $storeManager; - $this->_product = $product; - $this->_category = $categoryCollectionFactory; - $this->_manager = $manager; - $this->_config = $config; - } - - public function generate() - { - $this->_shop = $this->_manager->getStore()->getId(); - - $string = ' - - - '.$this->_manager->getStore()->getName().' - - - - - '; - - $xml = new \SimpleXMLElement( - $string, - LIBXML_NOENT | LIBXML_NOCDATA | LIBXML_COMPACT | LIBXML_PARSEHUGE - ); - - $this->_dd = new \DOMDocument(); - $this->_dd->preserveWhiteSpace = false; - $this->_dd->formatOutput = true; - $this->_dd->loadXML($xml->asXML()); - - $this->_eCategories = $this->_dd-> - getElementsByTagName('categories')->item(0); - $this->_eOffers = $this->_dd - ->getElementsByTagName('offers')->item(0); - - $this->addCategories(); - $this->addOffers(); - - $this->_dd->saveXML(); - $dirlist = new \Magento\Framework\Filesystem\DirectoryList(''); - $baseDir = $dirlist->getRoot(); - $shopCode = $this->_manager->getStore()->getCode(); - $this->_dd->save($baseDir . 'retailcrm_' . $shopCode . '.xml'); - } - - private function addCategories() - { - $collection = $this->_category->create(); - $collection->addAttributeToSelect('*'); - - foreach ($collection as $category) { - if ($category->getId() > 1){ - $e = $this->_eCategories->appendChild( - $this->_dd->createElement('category') - ); - $e->appendChild($this->_dd->createTextNode($category->getName())); - $e->setAttribute('id', $category->getId()); - - if ($category->getParentId() > 1) { - $e->setAttribute('parentId', $category->getParentId()); - } - } - } - } - - private function addOffers() - { - $offers = []; - - $collection = $this->_product->create(); - $collection->addFieldToFilter('visibility', 4);//catalog, search visible - $collection->addAttributeToSelect('*'); - - $picUrl = $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA); - $baseUrl = $this->_storeManager->getStore()->getBaseUrl(); - - $customAdditionalAttributes = []; - $customAdditionalAttributes = $this->_config->getValue('retailcrm/Misc/attributes_to_export_into_icml'); - - foreach ($collection as $product) { - if ($product->getTypeId() == 'simple') { - $offer['id'] = $product->getId(); - $offer['productId'] = $product->getId(); - $offer['productActivity'] = $product->isAvailable() ? 'Y' : 'N'; - $offer['name'] = $product->getName(); - $offer['productName'] = $product->getName(); - $offer['initialPrice'] = $product->getFinalPrice(); - $offer['url'] = $product->getProductUrl(); - $offer['picture'] = $picUrl.'catalog/product'.$product->getImage(); - $offer['quantity'] = $this->_StockState->getStockQty($product->getId(), $product->getStore()->getWebsiteId()); - $offer['categoryId'] = $product->getCategoryIds(); - $offer['vendor'] = $product->getAttributeText('manufacturer'); - $offer['params'] = []; - - $article = $product->getSku(); - - if(!empty($article)) { - $offer['params'][] = [ - 'name' => 'Article', - 'code' => 'article', - 'value' => $article - ]; - } - - $weight = $product->getWeight(); - - if(!empty($weight)) { - $offer['params'][] = [ - 'name' => 'Weight', - 'code' => 'weight', - 'value' => $weight - ]; - } - - if(!empty($customAdditionalAttributes)) { - //var_dump($customAdditionalAttributes); - } - - $offers[] = $offer; - } - - if ($product->getTypeId() == 'configurable') { - $associated_products = $this->_configurable - ->getUsedProductCollection($product) - ->addAttributeToSelect('*') - ->addFilterByRequiredOptions(); - - foreach ($associated_products as $associatedProduct) { - $offer['id'] = $associatedProduct->getId(); - $offer['productId'] = $product->getId(); - $offer['productActivity'] = $associatedProduct->isAvailable() ? 'Y' : 'N'; - $offer['name'] = $associatedProduct->getName(); - $offer['productName'] = $product->getName(); - $offer['initialPrice'] = $associatedProduct->getFinalPrice(); - $offer['url'] = $product->getProductUrl(); - $offer['picture'] = $picUrl.'catalog/product'.$associatedProduct->getImage(); - $offer['quantity'] = $this->_StockState->getStockQty($associatedProduct->getId(), $associatedProduct->getStore()->getWebsiteId()); - $offer['categoryId'] = $associatedProduct->getCategoryIds(); - $offer['vendor'] = $associatedProduct->getAttributeText('manufacturer'); - $offer['params'] = []; - - $article = $associatedProduct->getSku(); - - if ($associatedProduct->getResource()->getAttribute('color')) { - $colorAttribute = $associatedProduct->getResource()->getAttribute('color'); - $color = $colorAttribute->getSource()->getOptionText($associatedProduct->getColor()); - } - - if (isset($color)) { - $offer['params'][] = [ - 'name' => 'Color', - 'code' => 'color', - 'value' => $color - ]; - } - - if ($associatedProduct->getResource()->getAttribute('size')) { - $sizeAttribute = $associatedProduct->getResource()->getAttribute('size'); - $size = $sizeAttribute->getSource()->getOptionText($associatedProduct->getSize()); - } - - if (isset($size)) { - $offer['params'][] = [ - 'name' => 'Size', - 'code' => 'size', - 'value' => $size - ]; - } - - if (!empty($article)) { - $offer['params'][] = [ - 'name' => 'Article', - 'code' => 'article', - 'value' => $article - ]; - } - - $weight = $associatedProduct->getWeight(); - - if(!empty($weight)) { - $offer['params'][] = [ - 'name' => 'Weight', - 'code' => 'weight', - 'value' => $weight - ]; - } - - $offers[] = $offer; - } - } - } - - foreach ($offers as $offer) { - $e = $this->_eOffers->appendChild( - $this->_dd->createElement('offer') - ); - - $e->setAttribute('id', $offer['id']); - $e->setAttribute('productId', $offer['productId']); - - if (!empty($offer['quantity'])) { - $e->setAttribute('quantity', (int) $offer['quantity']); - } else { - $e->setAttribute('quantity', 0); - } - - if (!empty($offer['categoryId'])) { - foreach ($offer['categoryId'] as $categoryId) { - $e->appendChild( - $this->_dd->createElement('categoryId') - )->appendChild( - $this->_dd->createTextNode($categoryId) - ); - } - } else { - $e->appendChild($this->_dd->createElement('categoryId', 1)); - } - - $e->appendChild($this->_dd->createElement('productActivity')) - ->appendChild( - $this->_dd->createTextNode($offer['productActivity']) - ); - - $e->appendChild($this->_dd->createElement('name')) - ->appendChild( - $this->_dd->createTextNode($offer['name']) - ); - - $e->appendChild($this->_dd->createElement('productName')) - ->appendChild( - $this->_dd->createTextNode($offer['productName']) - ); - - $e->appendChild($this->_dd->createElement('price')) - ->appendChild( - $this->_dd->createTextNode($offer['initialPrice']) - ); - - if (!empty($offer['purchasePrice'])) { - $e->appendChild($this->_dd->createElement('purchasePrice')) - ->appendChild( - $this->_dd->createTextNode($offer['purchasePrice']) - ); - } - - if (!empty($offer['picture'])) { - $e->appendChild($this->_dd->createElement('picture')) - ->appendChild( - $this->_dd->createTextNode($offer['picture']) - ); - } - - if (!empty($offer['url'])) { - $e->appendChild($this->_dd->createElement('url')) - ->appendChild( - $this->_dd->createTextNode($offer['url']) - ); - } - - if (!empty($offer['vendor'])) { - $e->appendChild($this->_dd->createElement('vendor')) - ->appendChild( - $this->_dd->createTextNode($offer['vendor']) - ); - } - - if(!empty($offer['params'])) { - foreach($offer['params'] as $param) { - $paramNode = $this->_dd->createElement('param'); - $paramNode->setAttribute('name', $param['name']); - $paramNode->setAttribute('code', $param['code']); - $paramNode->appendChild( - $this->_dd->createTextNode($param['value']) - ); - $e->appendChild($paramNode); - } - } - } - } -} diff --git a/Model/Observer/Customer.php b/Model/Observer/Customer.php deleted file mode 100644 index 0ec8209..0000000 --- a/Model/Observer/Customer.php +++ /dev/null @@ -1,66 +0,0 @@ -get('\Retailcrm\Retailcrm\Helper\Data'); - $logger = $objectManager->get('\Retailcrm\Retailcrm\Model\Logger\Logger'); - - $this->_logger = $logger; - $this->_helper = $helper; - $this->_config = $config; - $this->_objectManager = $objectManager; - $this->registry = $registry; - - $url = $config->getValue('retailcrm/general/api_url'); - $key = $config->getValue('retailcrm/general/api_key'); - $version = $config->getValue('retailcrm/general/api_version'); - - if (!empty($url) && !empty($key)) { - $this->_api = new ApiClient($url, $key, $version); - } - } - - public function execute(\Magento\Framework\Event\Observer $observer) - { - if ($this->registry->registry('RETAILCRM_HISTORY') === true) { - return; - } - - $data = $observer->getEvent()->getCustomer(); - - $customer = [ - 'externalId' => $data->getId(), - 'email' => $data->getEmail(), - 'firstName' => $data->getFirstname(), - 'patronymic' => $data->getMiddlename(), - 'lastName' => $data->getLastname(), - 'createdAt' => date('Y-m-d H:i:s', strtotime($data->getCreatedAt())) - ]; - - $response = $this->_api->customersEdit($customer); - - if ($response === false) { - return; - } - - if (!$response->isSuccessful() && $response->errorMsg == $this->_api->getErrorText('errorNotFound')) { - $this->_api->customersCreate($customer); - } - } -} diff --git a/Model/Observer/OrderUpdate.php b/Model/Observer/OrderUpdate.php deleted file mode 100644 index 7a45135..0000000 --- a/Model/Observer/OrderUpdate.php +++ /dev/null @@ -1,79 +0,0 @@ -_helper = $objectManager->get('\Retailcrm\Retailcrm\Helper\Data'); - $this->_objectManager = $objectManager; - $this->_config = $config; - $this->registry = $registry; - - $url = $config->getValue('retailcrm/general/api_url'); - $key = $config->getValue('retailcrm/general/api_key'); - $apiVersion = $config->getValue('retailcrm/general/api_version'); - - if (!empty($url) && !empty($key)) { - $this->_api = new ApiClient($url, $key, $apiVersion); - } - } - - /** - * Execute update order in CRM - * - * @param Observer $observer - * - * @return void - */ - public function execute(Observer $observer) - { - if ($this->registry->registry('RETAILCRM_HISTORY') === true) { - return; - } - - $order = $observer->getEvent()->getOrder(); - - if ($order) { - $preparedOrder = [ - 'externalId' => $order->getId(), - 'status' => $this->_config->getValue('retailcrm/Status/' . $order->getStatus()) - ]; - - if ($order->getBaseTotalDue() == 0) { - if ($this->_api->getVersion() == 'v4') { - $preparedOrder['paymentStatus'] = 'paid'; - } elseif ($this->_api->getVersion() == 'v5') { - $payment = [ - 'externalId' => $order->getPayment()->getId(), - 'status' => 'paid' - ]; - - $this->_api->ordersPaymentsEdit($payment); - } - } - - $this->_helper->filterRecursive($preparedOrder); - $this->_api->ordersEdit($preparedOrder); - } - } -} diff --git a/Model/Order/OrderNumber.php b/Model/Order/OrderNumber.php deleted file mode 100644 index ce411b0..0000000 --- a/Model/Order/OrderNumber.php +++ /dev/null @@ -1,165 +0,0 @@ -get('Magento\Sales\Model\OrderRepository'); - $searchCriteriaBuilder = $objectManager->get('Magento\Framework\Api\SearchCriteriaBuilder'); - $config = $objectManager->get('Magento\Framework\App\Config\ScopeConfigInterface'); - $filterBuilder = $objectManager->get('Magento\Framework\Api\FilterBuilder'); - $order = $objectManager->get('\Magento\Sales\Api\Data\OrderInterface'); - $helper = $objectManager->get('\Retailcrm\Retailcrm\Helper\Data'); - - $this->_orderRepository = $orderRepository; - $this->_searchCriteriaBuilder = $searchCriteriaBuilder; - $this->_config = $config; - $this->_filterBuilder = $filterBuilder; - $this->_order = $order; - $this->_helper = $helper; - $this->_logger = $objectManager->get('\Retailcrm\Retailcrm\Model\Logger\Logger'); - - $url = $config->getValue('retailcrm/general/api_url'); - $key = $config->getValue('retailcrm/general/api_key'); - $version = $config->getValue('retailcrm/general/api_version'); - - if (!empty($url) && !empty($key)) { - $this->_api = new ApiClient($url, $key, $version); - } - } - - public function ExportOrderNumber() - { - $ordernumber = $this->_config->getValue('retailcrm/Load/number_order'); - $ordersId = explode(",", $ordernumber); - $orders = []; - - foreach ($ordersId as $id) { - $orders[] = $this->prepareOrder($id); - } - - $chunked = array_chunk($orders, 50); - unset($orders); - - foreach ($chunked as $chunk) { - $this->_api->ordersUpload($chunk); - time_nanosleep(0, 250000000); - } - - unset($chunked); - - return true; - } - - public function prepareOrder($id) - { - $magentoOrder = $this->_order->load($id); - - $items = []; - $addressObj = $magentoOrder->getBillingAddress(); - - foreach ($magentoOrder->getAllItems() as $item) { - if ($item->getProductType() == "simple") { - $price = $item->getPrice(); - - if ($price == 0){ - $om = \Magento\Framework\App\ObjectManager::getInstance(); - $omproduct = $om->get('Magento\Catalog\Model\ProductRepository') - ->getById($item->getProductId()); - $price = $omproduct->getPrice(); - } - - $product = [ - 'productId' => $item->getProductId(), - 'productName' => $item->getName(), - 'quantity' => $item->getQtyOrdered(), - 'initialPrice' => $price, - 'offer' => [ - 'externalId'=>$item->getProductId() - ] - ]; - - unset($om); - unset($omproduct); - unset($price); - - $items[] = $product; - } - } - - $ship = $this->getShippingCode($magentoOrder->getShippingMethod()); - - $preparedOrder = [ - 'site' => $magentoOrder->getStore()->getCode(), - 'externalId' => $magentoOrder->getRealOrderId(), - 'number' => $magentoOrder->getRealOrderId(), - 'createdAt' => date('Y-m-d H:i:s'), - 'lastName' => $magentoOrder->getCustomerLastname(), - 'firstName' => $magentoOrder->getCustomerFirstname(), - 'patronymic' => $magentoOrder->getCustomerMiddlename(), - 'email' => $magentoOrder->getCustomerEmail(), - 'phone' => $addressObj->getTelephone(), - 'paymentType' => $this->_config->getValue('retailcrm/Payment/'.$magentoOrder->getPayment()->getMethodInstance()->getCode()), - 'status' => $this->_config->getValue('retailcrm/Status/'.$magentoOrder->getStatus()), - 'discount' => abs($magentoOrder->getDiscountAmount()), - 'items' => $items, - 'delivery' => [ - 'code' => $this->_config->getValue('retailcrm/Shipping/'.$ship), - 'cost' => $magentoOrder->getShippingAmount(), - 'address' => [ - 'index' => $addressObj->getData('postcode'), - 'city' => $addressObj->getData('city'), - 'country' => $addressObj->getData('country_id'), - 'street' => $addressObj->getData('street'), - 'region' => $addressObj->getData('region'), - 'text' => trim( - ',', - implode( - ',', - [ - $addressObj->getData('postcode'), - $addressObj->getData('city'), - $addressObj->getData('street'), - ] - ) - ) - ] - ] - ]; - - if (trim($preparedOrder['delivery']['code']) == ''){ - unset($preparedOrder['delivery']['code']); - } - - if (trim($preparedOrder['paymentType']) == ''){ - unset($preparedOrder['paymentType']); - } - - if (trim($preparedOrder['status']) == ''){ - unset($preparedOrder['status']); - } - - if ($magentoOrder->getCustomerIsGuest() == 0) { - $preparedOrder['customer']['externalId'] = $magentoOrder->getCustomerId(); - } - - $this->_logger->writeDump($preparedOrder,'OrderNumber'); - - return $this->_helper->filterRecursive($preparedOrder); - } -} diff --git a/README.md b/README.md index c6ff888..20bf70c 100644 --- a/README.md +++ b/README.md @@ -9,14 +9,18 @@ Module allows: * Configure relations between dictionaries of retailCRM and Magento (statuses, payments, delivery types and etc) * Generate [ICML](http://www.retailcrm.ru/docs/Developers/ICML) (Intaro Markup Language) export file for catalog loading by retailCRM -### ICML +## ICML By default ICML file is being generated by module every 4 hours. You can find file in the web root folder with name "retailcrm_{{shop_code}}.xml". For example, http://example.org/retailcrm_default.xml ### Manual install - 1) Run into your project root directory: + +1) Unpack the archive with the module in the directory "app/code/Retailcrm/Retailcrm". In the file "app/etc/config.php" in array `modules` add an element `'Retailcrm_Retailcrm' => 1` + +2) Run into your project directory: + ```bash composer require retailcrm/api-client-php ~5.0 ``` @@ -25,5 +29,4 @@ composer require retailcrm/api-client-php ~5.0 3) Change `app/etc/config.php` file by adding `'Retailcrm_Retailcrm' => 1` line into `modules` array - This module is compatible with Magento up to version 2.2.3 diff --git a/README.ru.md b/README.ru.md index cd5fc51..f132f94 100644 --- a/README.ru.md +++ b/README.ru.md @@ -1,5 +1,4 @@ Magento module -============== Модуль Magento 2 для интеграции с [retailCRM](http://www.retailcrm.ru). @@ -17,6 +16,19 @@ Magento module 1) Находясь в корневой директории проекта выполните команду: +* Настроить соответствие справочников RetailCRM и Magento (статусы, оплаты, типы доставки и т.д.) +* Создать [ICML] (http://www.retailcrm.ru/docs/Developers/ICML) (Intaro Markup Language) для загрузки каталога товаров в RetailCRM + +## ICML + +По умолчанию ICML-файл генерируется модулем каждые 4 часа. Вы можете найти файл в корневой папке с именем «retailcrm_{{shop_code}}.xml". Например, http://retailcrm.ru/retailcrm_default.xml + +## Ручная установка + +1) Распакуйте архив с модулем в директорию "app/code/Retailcrm/Retailcrm". В файле "app/etc/config.php" в массив `modules` добавьте элемент `'Retailcrm_Retailcrm' => 1` + +2) Выполните в папке проекта: + ```bash composer require retailcrm/api-client-php ~5.0 ``` @@ -28,4 +40,5 @@ composer require retailcrm/api-client-php ~5.0 В конфигурационный файл `composer.json` вашего проекта будет добавлена библиотека [retailcrm/api-client-php](https://github.com/retailcrm/api-client-php), которая будет установлена в директорию `vendor/`. + Этот модуль совместим с Magento 2 до версии 2.2.3 diff --git a/VERSION b/VERSION new file mode 100644 index 0000000..afaf360 --- /dev/null +++ b/VERSION @@ -0,0 +1 @@ +1.0.0 \ No newline at end of file diff --git a/bin/install.sh b/bin/install.sh new file mode 100644 index 0000000..46abbb8 --- /dev/null +++ b/bin/install.sh @@ -0,0 +1,52 @@ +#!/usr/bin/env bash + +if [ -z $TRAVIS_BUILD_DIR ]; then + exit 0; +fi + +MAGE_ROOT=$TRAVIS_BUILD_DIR/../magento2 + +create_db() { + mysqladmin create $DB_NAME --user="$DB_USER" --password="$DB_PASS" +} + +magento_clone() { + cd .. + git clone https://github.com/magento/magento2 + cd magento2 + git checkout $BRANCH + composer install + composer require retailcrm/api-client-php +} + +magento_install() { + cd $MAGE_ROOT + + php bin/magento setup:install \ + --db-host="$DB_HOST" \ + --db-name="$DB_NAME" \ + --db-user="$DB_USER" \ + --admin-firstname="$ADMIN_FIRSTNAME" \ + --admin-lastname="$ADMIN_LASTNAME" \ + --admin-email="$ADMIN_EMAIL" \ + --admin-user="$ADMIN_USER" \ + --admin-password="$ADMIN_PASS" \ + --language="en_US" \ + --currency="USD" \ + --timezone="Europe/Moscow" +} + +module_install() { + cd $MAGE_ROOT + mkdir -p app/code/Retailcrm/Retailcrm + cp -R $TRAVIS_BUILD_DIR/src/* app/code/Retailcrm/Retailcrm + + php bin/magento module:enable Retailcrm_Retailcrm + php bin/magento setup:upgrade + php bin/magento setup:di:compile +} + +create_db +magento_clone +magento_install +module_install diff --git a/bin/script.sh b/bin/script.sh new file mode 100644 index 0000000..1e5ebe2 --- /dev/null +++ b/bin/script.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash + +if [ -z $TRAVIS_BUILD_DIR ]; then + exit 0; +fi + +MAGE_ROOT=$TRAVIS_BUILD_DIR/../magento2 +cd $MAGE_ROOT +php vendor/phpunit/phpunit/phpunit -c dev/tests/unit/phpunit.xml.dist app/code/Retailcrm/Retailcrm/Test/Unit diff --git a/etc/adminhtml/system.xml b/etc/adminhtml/system.xml deleted file mode 100644 index 657ec96..0000000 --- a/etc/adminhtml/system.xml +++ /dev/null @@ -1,97 +0,0 @@ - - - - - - -
- separator-top - - retailcrm - Retailcrm_Retailcrm::retailcrm_configuration - - - - - - https://YourCrmName.retailcrm.ru - Retailcrm\Retailcrm\Model\Config\Backend\ApiUrl - - - - - To generate an API Key, log in to RetailCRM then select Admin > Integration > API Keys - - - - - Retailcrm\Retailcrm\Model\Setting\ApiVersions - Retailcrm\Retailcrm\Model\Config\Backend\ApiVersion - - - - - - - - attributes to export into icml - - Retailcrm\Retailcrm\Model\Setting\Attribute - - - - - - - - - - - - Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Field\Shipping - - - - - - - - Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Field\Payment - This text will display on the frontend. - - - - - - - - - - Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Field\Status - This text will display on the frontend. - - - - - - - - - Enter your order number, separated by commas - - - - - Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Button - - - - - -
-
-
- diff --git a/etc/di.xml b/etc/di.xml deleted file mode 100644 index ec4579e..0000000 --- a/etc/di.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - Retailcrm\Retailcrm\Console\Command\Command - - - - diff --git a/registration.php b/registration.php deleted file mode 100644 index b717086..0000000 --- a/registration.php +++ /dev/null @@ -1,6 +0,0 @@ -_toHtml(); } diff --git a/src/Block/Adminhtml/System/Config/Form/Fieldset/Payment.php b/src/Block/Adminhtml/System/Config/Form/Fieldset/Payment.php new file mode 100644 index 0000000..014bf89 --- /dev/null +++ b/src/Block/Adminhtml/System/Config/Form/Fieldset/Payment.php @@ -0,0 +1,164 @@ +paymentConfig = $paymentConfig; + $this->client = $client; + + parent::__construct($context, $authSession, $jsHelper, $data); + } + + /** + * Get field renderer + * + * @return \Magento\Config\Block\System\Config\Form\Field + */ + protected function _getFieldRenderer() + { + if (empty($this->_fieldRenderer)) { + $this->_fieldRenderer = $this->getLayout()->getBlockSingleton( + \Magento\Config\Block\System\Config\Form\Field::class + ); + } + + return $this->_fieldRenderer; + } + + /** + * Get dummy element + * + * @return \Magento\Framework\DataObject + */ + protected function _getDummyElement() + { + if (empty($this->_dummyElement)) { + $this->_dummyElement = new \Magento\Framework\DataObject(['showInDefault' => 1, 'showInWebsite' => 1]); + } + + return $this->_dummyElement; + } + + public function render(AbstractElement $element) + { + $html = ''; + $htmlError = '
Please check your API Url & API Key
'; + $html .= $this->_getHeaderHtml($element); + + if ($this->client->isConfigured()) { + $paymentMethods = $this->paymentConfig->getActiveMethods(); + + foreach ($paymentMethods as $code => $payment) { + $html .= $this->_getFieldHtml($element, $payment); + } + } else { + $html .= $htmlError; + } + + $html .= $this->_getFooterHtml($element); + + return $html; + } + + /** + * Get options values + * + * @return array + */ + private function getValues() + { + $defaultValues = [ + [ + 'value' => '', + 'label' => '' + ] + ]; + + $values = []; + + $response = $this->client->paymentTypesList(); + + if ($response === false) { + return $defaultValues; + } + + if ($response->isSuccessful()) { + $paymentsTypes = $response['paymentTypes']; + } else { + return $defaultValues; + } + + foreach ($paymentsTypes as $paymentType) { + $values[] = [ + 'label' => $paymentType['name'], + 'value' => $paymentType['code'] + ]; + } + + return $values; + } + + /** + * Get field html + * + * @param \Magento\Framework\Data\Form\Element\AbstractElement $fieldset + * @param \Magento\Payment\Model\Method\AbstractMethod $payment + * + * @return string + */ + protected function _getFieldHtml($fieldset, $payment) + { + $configData = $this->getConfigData(); + $path = 'retailcrm/' . $fieldset->getId() . '/' . $payment->getCode(); + + $data = isset($configData[$path]) ? $configData[$path] : []; + + $e = $this->_getDummyElement(); + + $field = $fieldset->addField( + $payment->getCode(), + 'select', + [ + 'name' => 'groups[' . $fieldset->getId() . '][fields][' . $payment->getCode() . '][value]', + 'label' => $payment->getTitle(), + 'value' => isset($data) ? $data : '', + 'values' => $this->getValues(), + 'inherit' => true, + 'can_use_default_value' => $this->getForm()->canUseDefaultValue($e), + 'can_use_website_value' => $this->getForm()->canUseWebsiteValue($e) + ] + )->setRenderer( + $this->_getFieldRenderer() + ); + + return $field->toHtml(); + } +} diff --git a/src/Block/Adminhtml/System/Config/Form/Fieldset/Shipping.php b/src/Block/Adminhtml/System/Config/Form/Fieldset/Shipping.php new file mode 100644 index 0000000..1def2f3 --- /dev/null +++ b/src/Block/Adminhtml/System/Config/Form/Fieldset/Shipping.php @@ -0,0 +1,170 @@ +shippingConfig = $shippingConfig; + $this->client = $client; + + parent::__construct($context, $authSession, $jsHelper, $data); + } + + /** + * Get field renderer + * + * @return \Magento\Config\Block\System\Config\Form\Field + */ + protected function _getFieldRenderer() + { + if (empty($this->_fieldRenderer)) { + $this->_fieldRenderer = $this->getLayout()->getBlockSingleton( + \Magento\Config\Block\System\Config\Form\Field::class + ); + } + + return $this->_fieldRenderer; + } + + /** + * Get dummy element + * + * @return \Magento\Framework\DataObject + */ + protected function _getDummyElement() + { + if (empty($this->_dummyElement)) { + $this->_dummyElement = new \Magento\Framework\DataObject(['showInDefault' => 1, 'showInWebsite' => 1]); + } + + return $this->_dummyElement; + } + + /** + * Render element + * + * @param AbstractElement $element + * @return string + */ + public function render(AbstractElement $element) + { + $html = ''; + $htmlError = '
Please check your API Url & API Key
'; + $html .= $this->_getHeaderHtml($element); + + if ($this->client->isConfigured()) { + $deliveryMethods = $this->shippingConfig->getActiveCarriers(); + + foreach ($deliveryMethods as $code => $delivery) { + $html .= $this->_getFieldHtml($element, $delivery); + } + } else { + $html .= $htmlError; + } + + $html .= $this->_getFooterHtml($element); + + return $html; + } + + /** + * Get options values + * + * @return array + */ + private function getValues() + { + $defaultValues = [ + [ + 'value' => '', + 'label' => '' + ] + ]; + + $values = []; + + $response = $this->client->deliveryTypesList(); + + if ($response === false) { + return $defaultValues; + } + + if ($response->isSuccessful()) { + $deliveryTypes = $response['deliveryTypes']; + } else { + return $defaultValues; + } + + foreach ($deliveryTypes as $deliveryType) { + $values[] = [ + 'label' => $deliveryType['name'], + 'value' => $deliveryType['code'] + ]; + } + + return $values; + } + + /** + * Get field html + * + * @param \Magento\Framework\Data\Form\Element\AbstractElement $fieldset + * @param \Magento\Shipping\Model\Carrier\AbstractCarrier $shipping + * + * @return string + */ + protected function _getFieldHtml($fieldset, $shipping) + { + $configData = $this->getConfigData(); + $path = 'retailcrm/' . $fieldset->getId() . '/' . $shipping->getCarrierCode(); + + $data = isset($configData[$path]) ? $configData[$path] : []; + + $e = $this->_getDummyElement(); + + $field = $fieldset->addField( + $shipping->getCarrierCode(), + 'select', + [ + 'name' => 'groups[' . $fieldset->getId() . '][fields][' . $shipping->getCarrierCode() . '][value]', + 'label' => $shipping->getConfigData('title'), + 'value' => isset($data) ? $data : '', + 'values' => $this->getValues(), + 'inherit' => true, + 'can_use_default_value' => $this->getForm()->canUseDefaultValue($e), + 'can_use_website_value' => $this->getForm()->canUseWebsiteValue($e) + ] + )->setRenderer( + $this->_getFieldRenderer() + ); + + return $field->toHtml(); + } +} diff --git a/src/Block/Adminhtml/System/Config/Form/Fieldset/Site.php b/src/Block/Adminhtml/System/Config/Form/Fieldset/Site.php new file mode 100644 index 0000000..e27af0b --- /dev/null +++ b/src/Block/Adminhtml/System/Config/Form/Fieldset/Site.php @@ -0,0 +1,161 @@ +client = $client; + + parent::__construct($context, $authSession, $jsHelper, $data); + } + + /** + * Get field renderer + * + * @return \Magento\Config\Block\System\Config\Form\Field + */ + protected function _getFieldRenderer() + { + if (empty($this->_fieldRenderer)) { + $this->_fieldRenderer = $this->getLayout()->getBlockSingleton( + \Magento\Config\Block\System\Config\Form\Field::class + ); + } + + return $this->_fieldRenderer; + } + + /** + * Get dummy element + * + * @return \Magento\Framework\DataObject + */ + protected function _getDummyElement() + { + if (empty($this->_dummyElement)) { + $this->_dummyElement = new \Magento\Framework\DataObject(['showInDefault' => 1, 'showInWebsite' => 0]); + } + + return $this->_dummyElement; + } + + /** + * Render element + * + * @param AbstractElement $element + * @return string + */ + public function render(AbstractElement $element) + { + $html = ''; + $htmlError = '
Please check your API Url & API Key
'; + $html .= $this->_getHeaderHtml($element); + + if ($this->client->isConfigured()) { + $html .= $this->_getFieldHtml($element); + } else { + $html .= $htmlError; + } + + $html .= $this->_getFooterHtml($element); + + return $html; + } + + /** + * Get options values + * + * @return array + */ + private function getValues() + { + $defaultValues = [ + [ + 'value' => '', + 'label' => '' + ] + ]; + + $values = []; + + $response = $this->client->sitesList(); + + if ($response === false) { + return $defaultValues; + } + + if ($response->isSuccessful()) { + $sites = $response['sites']; + } else { + return $defaultValues; + } + + foreach ($sites as $site) { + $values[] = [ + 'label' => $site['name'], + 'value' => $site['code'] + ]; + } + + return $values; + } + + /** + * Get field html + * + * @param \Magento\Framework\Data\Form\Element\AbstractElement $fieldset + * @param \Magento\Shipping\Model\Carrier\AbstractCarrier $shipping + * + * @return string + */ + protected function _getFieldHtml($fieldset) + { + $configData = $this->getConfigData(); + $path = 'retailcrm/' . $fieldset->getId() . '/default'; + $data = isset($configData[$path]) ? $configData[$path] : []; + $e = $this->_getDummyElement(); + + $field = $fieldset->addField( + 'default', + 'select', + [ + 'name' => 'groups[' . $fieldset->getId() . '][fields][default][value]', + 'label' => 'Default site', + 'value' => isset($data) ? $data : '', + 'values' => $this->getValues(), + 'inherit' => isset($data['inherit']) ? $data['inherit'] : '', + 'can_use_default_value' => $this->getForm()->canUseDefaultValue($e), + 'can_use_website_value' => $this->getForm()->canUseWebsiteValue($e) + ] + )->setRenderer( + $this->_getFieldRenderer() + ); + + return $field->toHtml(); + } +} diff --git a/src/Block/Adminhtml/System/Config/Form/Fieldset/Sites.php b/src/Block/Adminhtml/System/Config/Form/Fieldset/Sites.php new file mode 100644 index 0000000..0d13cfe --- /dev/null +++ b/src/Block/Adminhtml/System/Config/Form/Fieldset/Sites.php @@ -0,0 +1,168 @@ +storeManager = $storeManager; + $this->client = $client; + + parent::__construct($context, $authSession, $jsHelper, $data); + } + + /** + * Get field renderer + * + * @return \Magento\Config\Block\System\Config\Form\Field + */ + protected function _getFieldRenderer() + { + if (empty($this->_fieldRenderer)) { + $this->_fieldRenderer = $this->getLayout()->getBlockSingleton( + \Magento\Config\Block\System\Config\Form\Field::class + ); + } + + return $this->_fieldRenderer; + } + + /** + * Get dummy element + * + * @return \Magento\Framework\DataObject + */ + protected function _getDummyElement() + { + if (empty($this->_dummyElement)) { + $this->_dummyElement = new \Magento\Framework\DataObject(['showInDefault' => 1, 'showInWebsite' => 0]); + } + + return $this->_dummyElement; + } + + /** + * Render element + * + * @param AbstractElement $element + * @return string + */ + public function render(AbstractElement $element) + { + $html = ''; + $htmlError = '
Please check your API Url & API Key
'; + $html .= $this->_getHeaderHtml($element); + + if ($this->client->isConfigured()) { + $website = $this->storeManager->getWebsite($this->getRequest()->getParam('website', 0)); + + foreach ($website->getStores() as $store) { + $html .= $this->_getFieldHtml($element, $store); + } + } else { + $html .= $htmlError; + } + + $html .= $this->_getFooterHtml($element); + + return $html; + } + + /** + * Get options values + * + * @return array + */ + private function getValues() + { + $defaultValues = [ + [ + 'value' => '', + 'label' => '' + ] + ]; + + $values = []; + + $response = $this->client->sitesList(); + + if ($response === false) { + return $defaultValues; + } + + if ($response->isSuccessful()) { + $sites = $response['sites']; + } else { + return $defaultValues; + } + + foreach ($sites as $site) { + $values[] = [ + 'label' => $site['name'], + 'value' => $site['code'] + ]; + } + + return $values; + } + + /** + * Get field html + * + * @param \Magento\Framework\Data\Form\Element\AbstractElement $fieldset + * @param \Magento\Shipping\Model\Carrier\AbstractCarrier $shipping + * + * @return string + */ + protected function _getFieldHtml($fieldset, $store) + { + $configData = $this->getConfigData(); + $path = 'retailcrm/' . $fieldset->getId() . '/' . $store->getCode(); + $data = isset($configData[$path]) ? $configData[$path] : []; + $e = $this->_getDummyElement(); + + $field = $fieldset->addField( + $store->getCode(), + 'select', + [ + 'name' => 'groups[' . $fieldset->getId() . '][fields][' . $store->getCode() . '][value]', + 'label' => $store->getName(), + 'value' => isset($data) ? $data : '', + 'values' => $this->getValues(), + 'inherit' => isset($data['inherit']) ? $data['inherit'] : '', + 'can_use_default_value' => $this->getForm()->canUseDefaultValue($e), + 'can_use_website_value' => $this->getForm()->canUseWebsiteValue($e) + ] + )->setRenderer( + $this->_getFieldRenderer() + ); + + return $field->toHtml(); + } +} diff --git a/src/Block/Adminhtml/System/Config/Form/Fieldset/Status.php b/src/Block/Adminhtml/System/Config/Form/Fieldset/Status.php new file mode 100644 index 0000000..7a4a669 --- /dev/null +++ b/src/Block/Adminhtml/System/Config/Form/Fieldset/Status.php @@ -0,0 +1,164 @@ +statusCollection = $statusCollection; + $this->client = $client; + + parent::__construct($context, $authSession, $jsHelper, $data); + } + + /** + * Get field renderer + * + * @return \Magento\Config\Block\System\Config\Form\Field + */ + protected function _getFieldRenderer() + { + if (empty($this->_fieldRenderer)) { + $this->_fieldRenderer = $this->getLayout()->getBlockSingleton( + \Magento\Config\Block\System\Config\Form\Field::class + ); + } + + return $this->_fieldRenderer; + } + + /** + * Get dummy element + * + * @return \Magento\Framework\DataObject + */ + protected function _getDummyElement() + { + if (empty($this->_dummyElement)) { + $this->_dummyElement = new \Magento\Framework\DataObject(['showInDefault' => 1, 'showInWebsite' => 1]); + } + + return $this->_dummyElement; + } + + public function render(AbstractElement $element) + { + $html = ''; + $htmlError = '
Please check your API Url & API Key
'; + $html .= $this->_getHeaderHtml($element); + + if ($this->client->isConfigured()) { + $statuses = $this->statusCollection->toOptionArray();; + + foreach ($statuses as $code => $status) { + $html .= $this->_getFieldHtml($element, $status); + } + } else { + $html .= $htmlError; + } + + $html .= $this->_getFooterHtml($element); + + return $html; + } + + /** + * Get options values + * + * @return array + */ + private function getValues() + { + $defaultValues = [ + [ + 'value' => '', + 'label' => '' + ] + ]; + + $values = []; + + $response = $this->client->statusesList(); + + if ($response === false) { + return $defaultValues; + } + + if ($response->isSuccessful()) { + $statuses = $response['statuses']; + } else { + return $defaultValues; + } + + foreach ($statuses as $status) { + $values[] = [ + 'label' => $status['name'], + 'value' => $status['code'] + ]; + } + + return $values; + } + + /** + * Get field html + * + * @param \Magento\Framework\Data\Form\Element\AbstractElement $fieldset + * @param array $status + * + * @return string + */ + protected function _getFieldHtml($fieldset, $status) + { + $configData = $this->getConfigData(); + $path = 'retailcrm/' . $fieldset->getId() . '/' . $status['value']; + + $data = isset($configData[$path]) ? $configData[$path] : []; + + $e = $this->_getDummyElement(); + + $field = $fieldset->addField( + $status['value'], + 'select', + [ + 'name' => 'groups[' . $fieldset->getId() . '][fields][' . $status['value'] . '][value]', + 'label' => $status['label'], + 'value' => isset($data) ? $data : '', + 'values' => $this->getValues(), + 'inherit' => true, + 'can_use_default_value' => $this->getForm()->canUseDefaultValue($e), + 'can_use_website_value' => $this->getForm()->canUseWebsiteValue($e) + ] + )->setRenderer( + $this->_getFieldRenderer() + ); + + return $field->toHtml(); + } +} diff --git a/src/Block/Display.php b/src/Block/Display.php new file mode 100644 index 0000000..9740a75 --- /dev/null +++ b/src/Block/Display.php @@ -0,0 +1,11 @@ +_logger = $logger; + $this->order = $order; + $this->logger = $logger; parent::__construct($context); } - public function execute() { - $order = new \Retailcrm\Retailcrm\Model\Order\OrderNumber(); - $order->ExportOrderNumber(); + $this->order->exportOrderNumber(); } -} \ No newline at end of file +} diff --git a/Controller/Index/Display.php b/src/Controller/Index/Display.php similarity index 66% rename from Controller/Index/Display.php rename to src/Controller/Index/Display.php index 0156cfd..7b0a6df 100644 --- a/Controller/Index/Display.php +++ b/src/Controller/Index/Display.php @@ -4,18 +4,18 @@ namespace Retailcrm\Retailcrm\Controller\Index; class Display extends \Magento\Framework\App\Action\Action { - protected $_pageFactory; + private $pageFactory; public function __construct( \Magento\Framework\App\Action\Context $context, \Magento\Framework\View\Result\PageFactory $pageFactory ) { - $this->_pageFactory = $pageFactory; - return parent::__construct($context); + $this->pageFactory = $pageFactory; + parent::__construct($context); } public function execute() { - return $this->_pageFactory->create(); + return $this->pageFactory->create(); } -} \ No newline at end of file +} diff --git a/src/Cron/Icml.php b/src/Cron/Icml.php new file mode 100644 index 0000000..70cc5e0 --- /dev/null +++ b/src/Cron/Icml.php @@ -0,0 +1,22 @@ +logger = $logger; + $this->icml = $icml; + } + + public function execute() + { + $this->icml->generate(); + } +} diff --git a/src/Cron/OrderHistory.php b/src/Cron/OrderHistory.php new file mode 100644 index 0000000..d968d71 --- /dev/null +++ b/src/Cron/OrderHistory.php @@ -0,0 +1,23 @@ +logger = $logger; + $this->history = $history; + } + + public function execute() + { + $this->history->ordersHistory(); + $this->logger->writeRow('Cron Works: OrderHistory'); + } +} diff --git a/src/Helper/Data.php b/src/Helper/Data.php new file mode 100644 index 0000000..fbbdb1d --- /dev/null +++ b/src/Helper/Data.php @@ -0,0 +1,120 @@ +storeManager = $storeManager; + parent::__construct($context); + } + + public function getConfigValue($field, $storeId = null) + { + return $this->scopeConfig->getValue( + $field, + ScopeInterface::SCOPE_STORE, + $storeId + ); + } + + public function getGeneralConfig($code, $storeId = null) + { + return $this->getConfigValue(self::XML_PATH_RETAILCRM . $code, $storeId); + } + + /** + * Get site code + * + * @param $store + * + * @return mixed|null + */ + public function getSite($store) + { + if (is_int($store)) { + $store = $this->storeManager->getStore($store); + } + + $websitesConfig = $this->scopeConfig->getValue( + self::XML_PATH_RETAILCRM . self::XML_PATH_SITES . $store->getCode(), + ScopeInterface::SCOPE_WEBSITES + ); + + if (!$websitesConfig) { + $defaultSite = $this->scopeConfig->getValue(self::XML_PATH_RETAILCRM . self::XML_PATH_DEFAULT_SITE); + + if (!$defaultSite) { + return null; + } + + return $defaultSite; + } + + return $websitesConfig; + } + + public function getMappingSites() + { + $sites = []; + + $websites = $this->storeManager->getWebsites(); + + foreach ($websites as $website) { + foreach ($website->getStores() as $store) { + $site = $this->scopeConfig->getValue( + self::XML_PATH_RETAILCRM . self::XML_PATH_SITES . $store->getCode(), + ScopeInterface::SCOPE_WEBSITES, + $website->getId() + ); + $sites[$site] = $store->getId(); + } + } + + return $sites; + } + + /** + * Recursive array filter + * + * @param array $haystack input array + * + * @SuppressWarnings(PHPMD.StaticAccess) + * @SuppressWarnings(PHPMD.ElseExpression) + * + * @return array + */ + public static function filterRecursive($haystack) + { + foreach ($haystack as $key => $value) { + if (is_array($value)) { + $haystack[$key] = self::filterRecursive($haystack[$key]); + } + + if ($haystack[$key] === null + || $haystack[$key] === '' + || (is_array($haystack[$key]) && empty($haystack[$key])) + ) { + unset($haystack[$key]); + } elseif (!is_array($value)) { + $haystack[$key] = trim($value); + } + } + + return $haystack; + } +} diff --git a/src/Helper/Proxy.php b/src/Helper/Proxy.php new file mode 100644 index 0000000..726bd86 --- /dev/null +++ b/src/Helper/Proxy.php @@ -0,0 +1,176 @@ +logger = $logger; + $this->url = $config->getConfigValue($pathUrl); + $this->apiKey = $config->getConfigValue($pathKey); + $this->version = $config->getConfigValue($pathVersion); + $this->apiClientFactory = $apiClientFactory; + + if ($this->isConfigured()) { + $this->init(); + } + } + + public function __call($method, $arguments) + { + try { + $response = call_user_func_array([$this->apiClient->request, $method], $arguments); + + if (!$response->isSuccessful()) { + $this->logger->writeRow( + sprintf( + "[HTTP status %s] %s - %s", + $response->getStatusCode(), + $method, + $response->getErrorMsg() + ) + ); + + if (isset($response['errors'])) { + $this->logger->writeRow(implode(' :: ', $response['errors'])); + } + } + } catch (\RetailCrm\Exception\CurlException $exception) { + $this->logger->writeRow($exception->getMessage()); + return false; + } catch (\RetailCrm\Exception\InvalidJsonException $exception) { + $this->logger->writeRow($exception->getMessage()); + return false; + } catch (\InvalidArgumentException $exception) { + $this->logger->writeRow($exception->getMessage()); + } + + return $response; + } + + /** + * Init retailcrm api client + */ + public function init() + { + $this->apiClient = $this->apiClientFactory->create( + $this->url, + $this->apiKey, + $this->version + ); + } + + /** + * @param $url + */ + public function setUrl($url) + { + $this->url = $url; + } + + /** + * @param $apiKey + */ + public function setApiKey($apiKey) + { + $this->apiKey = $apiKey; + } + + /** + * @param $version + */ + public function setVersion($version) + { + $this->version = $version; + } + + /** + * @return bool + */ + public function isConfigured() + { + return $this->url && $this->apiKey; + } + + /** + * Get API version + * + * @return string + */ + public function getVersion() + { + if (!is_object($this->apiClient)) { + return false; + } + + return $this->apiClient->getVersion(); + } + + /** + * Set site code + * + * @param $site + */ + public function setSite($site) + { + if ($this->isConfigured()) { + $this->apiClient->request->setSite($site); + } + } + + /** + * Get site code + * + * @return null | mixed + */ + public function getSite() + { + if ($this->isConfigured()) { + return $this->apiClient->request->getSite(); + } + + return null; + } + + /** + * Get error text message + * + * @param string $property + * + * @return string + */ + public function getErrorText($property) + { + return $this->{$property}; + } +} diff --git a/LICENSE b/src/LICENSE similarity index 100% rename from LICENSE rename to src/LICENSE diff --git a/Model/Config/Backend/ApiUrl.php b/src/Model/Config/Backend/ApiUrl.php similarity index 70% rename from Model/Config/Backend/ApiUrl.php rename to src/Model/Config/Backend/ApiUrl.php index e5e8b73..f61234a 100644 --- a/Model/Config/Backend/ApiUrl.php +++ b/src/Model/Config/Backend/ApiUrl.php @@ -6,15 +6,17 @@ use Retailcrm\Retailcrm\Helper\Proxy as ApiClient; class ApiUrl extends \Magento\Framework\App\Config\Value { + private $api; + /** + * ApiUrl constructor. * @param \Magento\Framework\Model\Context $context * @param \Magento\Framework\Registry $registry * @param \Magento\Framework\App\Config\ScopeConfigInterface $config * @param \Magento\Framework\App\Cache\TypeListInterface $cacheTypeList - * @param \Magento\Framework\App\Config\ValueFactory $configValueFactory - * @param \Magento\Framework\Model\ResourceModel\AbstractResource $resource - * @param \Magento\Framework\Data\Collection\AbstractDb $resourceCollection - * @param string $runModelPath + * @param \Magento\Framework\Model\ResourceModel\AbstractResource|null $resource + * @param \Magento\Framework\Data\Collection\AbstractDb|null $resourceCollection + * @param ApiClient $api * @param array $data */ public function __construct( @@ -22,68 +24,62 @@ class ApiUrl extends \Magento\Framework\App\Config\Value \Magento\Framework\Registry $registry, \Magento\Framework\App\Config\ScopeConfigInterface $config, \Magento\Framework\App\Cache\TypeListInterface $cacheTypeList, + ApiClient $api, \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null, \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null, array $data = [] ) { + $this->api = $api; parent::__construct($context, $registry, $config, $cacheTypeList, $resource, $resourceCollection, $data); } /** * Call before save api url - * + * + * @throws \Magento\Framework\Exception\ValidatorException + * * @return void */ public function beforeSave() { - $apiUrl = $this->getValue(); - $apiKey = $this->getFieldsetDataValue('api_key'); - $apiVersion = $this->getFieldsetDataValue('api_version'); + $this->setParams([ + 'url' => $this->getValue(), + 'apiKey' => $this->getFieldsetDataValue('api_key'), + 'version' => $this->getFieldsetDataValue('api_version') + ]); - if (!$this->isUrl($apiUrl)) { + if (!$this->isUrl($this->getValue())) { throw new \Magento\Framework\Exception\ValidatorException(__('Invalid CRM url')); } - if (!$this->isHttps($apiUrl)) { - $this->schemeEdit($apiUrl); + if (!$this->isHttps($this->getValue())) { + $this->schemeEdit($this->getValue()); } - $api = new ApiClient($apiUrl, $apiKey, $apiVersion); - - if ($this->validateApiUrl($api)) { - $this->setValue($apiUrl); + if ($this->validateApiUrl($this->api)) { + $this->setValue($this->getValue()); } parent::beforeSave(); } - /** - * Call after save api url - * - * @return void - */ - public function afterSave() - { - return parent::afterSave(); - } - /** * Validate selected api url - * + * * @param ApiClient $api * @param string $apiVersion - * + * * @throws \Magento\Framework\Exception\ValidatorException - * + * * @return boolean */ - protected function validateApiUrl(ApiClient $api) + private function validateApiUrl(ApiClient $api) { $response = $api->availableVersions(); if ($response === false) { throw new \Magento\Framework\Exception\ValidatorException(__('Verify that the data entered is correct')); - } elseif (!$response->isSuccessful() && $response['errorMsg'] == $api->getErrorText ('errorApiKey')) { + } elseif (!$response->isSuccessful() && $response['errorMsg'] == $api->getErrorText('errorApiKey')) { throw new \Magento\Framework\Exception\ValidatorException(__('Invalid CRM api key')); } elseif (isset($response['errorMsg']) && $response['errorMsg'] == $api->getErrorText('errorAccount')) { throw new \Magento\Framework\Exception\ValidatorException(__('Invalid CRM api url')); @@ -94,12 +90,12 @@ class ApiUrl extends \Magento\Framework\App\Config\Value /** * Check url scheme - * + * * @param string $url - * + * * @return boolean */ - protected function isHttps($url) + private function isHttps($url) { $url_array = parse_url($url); @@ -112,12 +108,12 @@ class ApiUrl extends \Magento\Framework\App\Config\Value /** * Edit scheme from http to https - * + * * @param string $url - * + * * @return string */ - protected function schemeEdit(&$url) + private function schemeEdit(&$url) { $url_array = parse_url($url); @@ -126,13 +122,24 @@ class ApiUrl extends \Magento\Framework\App\Config\Value /** * Check url - * + * * @param string $url - * + * * @return type */ public function isUrl($url) { return preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $url); } + + /** + * @param array $data + */ + private function setParams(array $data) + { + $this->api->setUrl($data['url']); + $this->api->setApiKey($data['apiKey']); + $this->api->setVersion($data['version']); + $this->api->init(); + } } diff --git a/Model/Config/Backend/ApiVersion.php b/src/Model/Config/Backend/ApiVersion.php similarity index 72% rename from Model/Config/Backend/ApiVersion.php rename to src/Model/Config/Backend/ApiVersion.php index d294f63..d99e1a1 100644 --- a/Model/Config/Backend/ApiVersion.php +++ b/src/Model/Config/Backend/ApiVersion.php @@ -6,15 +6,17 @@ use Retailcrm\Retailcrm\Helper\Proxy as ApiClient; class ApiVersion extends \Magento\Framework\App\Config\Value { + private $api; + /** + * ApiVersion constructor. * @param \Magento\Framework\Model\Context $context * @param \Magento\Framework\Registry $registry * @param \Magento\Framework\App\Config\ScopeConfigInterface $config * @param \Magento\Framework\App\Cache\TypeListInterface $cacheTypeList - * @param \Magento\Framework\App\Config\ValueFactory $configValueFactory - * @param \Magento\Framework\Model\ResourceModel\AbstractResource $resource - * @param \Magento\Framework\Data\Collection\AbstractDb $resourceCollection - * @param string $runModelPath + * @param \Magento\Framework\Model\ResourceModel\AbstractResource|null $resource + * @param \Magento\Framework\Data\Collection\AbstractDb|null $resourceCollection + * @param ApiClient $api * @param array $data */ public function __construct( @@ -22,52 +24,44 @@ class ApiVersion extends \Magento\Framework\App\Config\Value \Magento\Framework\Registry $registry, \Magento\Framework\App\Config\ScopeConfigInterface $config, \Magento\Framework\App\Cache\TypeListInterface $cacheTypeList, + ApiClient $api, \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null, \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null, array $data = [] ) { + $this->api = $api; parent::__construct($context, $registry, $config, $cacheTypeList, $resource, $resourceCollection, $data); } /** * Call before save api version - * + * * @return void */ public function beforeSave() { - $apiUrl = $this->getFieldsetDataValue('api_url'); - $apiKey = $this->getFieldsetDataValue('api_key'); - $apiVersion = $this->getValue(); + $this->setParams([ + 'url' => $this->getFieldsetDataValue('api_url'), + 'apiKey' => $this->getFieldsetDataValue('api_key'), + 'version' => $this->getValue() + ]); - $api = new ApiClient($apiUrl, $apiKey, $apiVersion); - - $this->validateApiVersion($api, $apiVersion); + $this->validateApiVersion($this->api, $this->getValue()); parent::beforeSave(); } - /** - * Call after save api version - * - * @return void - */ - public function afterSave() - { - return parent::afterSave(); - } - /** * Validate selected api version - * + * * @param ApiClient $api * @param string $apiVersion - * + * * @throws \Magento\Framework\Exception\ValidatorException - * + * * @return void */ - protected function validateApiVersion(ApiClient $api, $apiVersion) + private function validateApiVersion(ApiClient $api, $apiVersion) { $apiVersions = [ 'v4' => '4.0', @@ -90,4 +84,15 @@ class ApiVersion extends \Magento\Framework\App\Config\Value } } } + + /** + * @param array $data + */ + private function setParams(array $data) + { + $this->api->setUrl($data['url']); + $this->api->setApiKey($data['apiKey']); + $this->api->setVersion($data['version']); + $this->api->init(); + } } diff --git a/Model/History/Exchange.php b/src/Model/History/Exchange.php similarity index 54% rename from Model/History/Exchange.php rename to src/Model/History/Exchange.php index 2a7da17..c32d416 100644 --- a/Model/History/Exchange.php +++ b/src/Model/History/Exchange.php @@ -2,102 +2,100 @@ namespace Retailcrm\Retailcrm\Model\History; -use Retailcrm\Retailcrm\Helper\Proxy as ApiClient; - class Exchange { - protected $_api; - protected $_config; - protected $_helper; - protected $_logger; - protected $_resourceConfig; - protected $_customerFactory; - protected $_quote; - protected $_customerRepository; - protected $_product; - protected $_shipconfig; - protected $_quoteManagement; - protected $_registry; - protected $_cacheTypeList; - protected $_order; - protected $_orderManagement; - //protected $_transaction; - //protected $_invoiceService; - protected $_eventManager; - protected $_objectManager; + private $api; + private $config; + private $helper; + private $logger; + private $resourceConfig; + private $customerFactory; + private $quote; + private $customerRepository; + private $product; + private $shipconfig; + private $quoteManagement; + private $registry; + private $cacheTypeList; + private $order; + private $orderManagement; + private $eventManager; + private $objectManager; + private $orderInterface; + private $storeManager; + private $regionFactory; - public function __construct() - { - $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); - $helper = $objectManager->get('\Retailcrm\Retailcrm\Helper\Data'); - $config = $objectManager->get('\Magento\Framework\App\Config\ScopeConfigInterface'); - $resourceConfig = $objectManager->get('Magento\Config\Model\ResourceModel\Config'); - $customerFactory = $objectManager->get('\Magento\Customer\Model\CustomerFactory'); - $quote = $objectManager->get('\Magento\Quote\Model\QuoteFactory'); - $customerRepository = $objectManager->get('\Magento\Customer\Api\CustomerRepositoryInterface'); - $product = $objectManager->get('\Magento\Catalog\Model\Product'); - $shipconfig = $objectManager->get('\Magento\Shipping\Model\Config'); - $quoteManagement = $objectManager->get('\Magento\Quote\Model\QuoteManagement'); - $registry = $objectManager->get('\Magento\Framework\Registry'); - $cacheTypeList = $objectManager->get('\Magento\Framework\App\Cache\TypeListInterface'); - $order = $objectManager->get('\Magento\Sales\Api\Data\OrderInterface'); - $orderManagement = $objectManager->get('\Magento\Sales\Api\OrderManagementInterface'); - //$invoiceService = $objectManager->get('\Magento\Sales\Model\Service\InvoiceService'); - //$transaction = $objectManager->get('\Magento\Framework\DB\Transaction'); - $eventManager = $objectManager->get('\Magento\Framework\Event\Manager'); - $logger = new \Retailcrm\Retailcrm\Model\Logger\Logger($objectManager); - - $this->_shipconfig = $shipconfig; - $this->_logger = $logger; - $this->_helper = $helper; - $this->_config = $config; - $this->_resourceConfig = $resourceConfig; - $this->_customerFactory = $customerFactory; - $this->_quote = $quote; - $this->_customerRepository = $customerRepository; - $this->_product = $product; - $this->_quoteManagement = $quoteManagement; - $this->_registry = $registry; - $this->_cacheTypeList = $cacheTypeList; - $this->_order = $order; - $this->_orderManagement = $orderManagement; - //$this->_transaction = $transaction; - //$this->_invoiceService = $invoiceService; - $this->_eventManager = $eventManager; - $this->_objectManager = $objectManager; - - $url = $config->getValue('retailcrm/general/api_url'); - $key = $config->getValue('retailcrm/general/api_key'); - $version = $config->getValue('retailcrm/general/api_version'); - - if (!empty($url) && !empty($key)) { - $this->_api = new ApiClient($url, $key, $version); - } + public function __construct( + \Magento\Framework\App\ObjectManager $objectManager, + \Retailcrm\Retailcrm\Helper\Data $helper, + \Magento\Framework\App\Config\ScopeConfigInterface $config, + \Magento\Config\Model\ResourceModel\Config $resourceConfig, + \Magento\Customer\Model\CustomerFactory $customerFactory, + \Magento\Quote\Model\QuoteFactory $quote, + \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository, + \Magento\Catalog\Model\Product $product, + \Magento\Shipping\Model\Config $shipconfig, + \Magento\Quote\Model\QuoteManagement $quoteManagement, + \Magento\Framework\Registry $registry, + \Magento\Framework\App\Cache\TypeListInterface $cacheTypeList, + \Magento\Sales\Api\Data\OrderInterface $orderInterface, + \Magento\Sales\Api\OrderManagementInterface $orderManagement, + \Magento\Framework\Event\Manager $eventManager, + \Retailcrm\Retailcrm\Model\Logger\Logger $logger, + \Magento\Sales\Model\Order $order, + \Magento\Store\Model\StoreManagerInterface $storeManager, + \Magento\Directory\Model\RegionFactory $regionFactory, + \Retailcrm\Retailcrm\Helper\Proxy $api + ) { + $this->shipconfig = $shipconfig; + $this->logger = $logger; + $this->helper = $helper; + $this->config = $config; + $this->resourceConfig = $resourceConfig; + $this->customerFactory = $customerFactory; + $this->quote = $quote; + $this->customerRepository = $customerRepository; + $this->product = $product; + $this->quoteManagement = $quoteManagement; + $this->registry = $registry; + $this->cacheTypeList = $cacheTypeList; + $this->orderInterface = $orderInterface; + $this->orderManagement = $orderManagement; + $this->eventManager = $eventManager; + $this->objectManager = $objectManager; + $this->order = $order; + $this->storeManager = $storeManager; + $this->regionFactory = $regionFactory; + $this->api = $api; } /** * Get orders history from CRM - * + * * @return boolean */ public function ordersHistory() { - $this->_registry->register('RETAILCRM_HISTORY', true); + if (!$this->api->isConfigured()) { + return false; + } + + $this->registry->register('RETAILCRM_HISTORY', true); $historyFilter = []; $historyOrder = []; - $historyStart = $this->_config->getValue('retailcrm/general/filter_history'); + $historyStart = $this->config->getValue('retailcrm/general/filter_history'); if ($historyStart && $historyStart > 0) { $historyFilter['sinceId'] = $historyStart; } while (true) { - $response = $this->_api->ordersHistory($historyFilter); + $response = $this->api->ordersHistory($historyFilter); if ($response === false) { - return; + return false; } if (!$response->isSuccessful()) { @@ -106,7 +104,7 @@ class Exchange $orderH = isset($response['history']) ? $response['history'] : []; - if (count($orderH) == 0) { + if (empty($orderH)) { return true; } @@ -115,32 +113,37 @@ class Exchange $historyFilter['sinceId'] = $end['id']; if ($response['pagination']['totalPageCount'] == 1) { - $this->_resourceConfig->saveConfig('retailcrm/general/filter_history', $historyFilter['sinceId'], 'default', 0); - $this->_cacheTypeList->cleanType('config'); + $this->resourceConfig->saveConfig( + 'retailcrm/general/filter_history', + $historyFilter['sinceId'], + 'default', + 0 + ); + $this->cacheTypeList->cleanType('config'); $orders = self::assemblyOrder($historyOrder); - $this->_logger->writeDump($orders,'OrderHistory'); + $this->logger->writeDump($orders, 'OrderHistory'); $this->processOrders($orders); return true; } - }//endwhile + } - $this->_registry->register('RETAILCRM_HISTORY', false); + $this->registry->register('RETAILCRM_HISTORY', false); } /** * Process orders - * + * * @param array $orders - * + * * @return void */ private function processOrders($orders) { - $this->_logger->writeDump($orders,'processOrders'); + $this->logger->writeDump($orders, 'processOrders'); if (!empty($orders)) { foreach ($orders as $order) { @@ -155,24 +158,29 @@ class Exchange /** * Create new order from CRM - * + * * @param array $order - * + * * @return void */ private function doCreate($order) { - $this->_logger->writeDump($order,'doCreate'); + $this->logger->writeDump($order, 'doCreate'); - $payments = $this->_config->getValue('retailcrm/Payment'); - $shippings = $this->_config->getValue('retailcrm/Shipping'); + $payments = $this->config->getValue('retailcrm/retailcrm_payment'); + $shippings = $this->config->getValue('retailcrm/retailcrm_shipping'); + $sites = $this->helper->getMappingSites(); - $manager = $this->_objectManager->get('Magento\Store\Model\StoreManagerInterface'); - $region = $this->_objectManager->get('Magento\Directory\Model\RegionFactory')->create(); - $store = $manager->getStore(); - $websiteId = $manager->getStore()->getWebsiteId(); + if ($sites) { + $store = $this->storeManager->getStore($sites[$order['site']]); + $websiteId = $store->getWebsiteId(); + } else { + $store = $this->storeManager->getStore(); + $websiteId = $this->storeManager->getStore()->getWebsiteId(); + } - $customer = $this->_customerFactory->create(); + $region = $this->regionFactory->create(); + $customer = $this->customerFactory->create(); $customer->setWebsiteId($websiteId); if (isset($order['customer']['externalId'])) { @@ -190,10 +198,10 @@ class Exchange try { $customer->save(); } catch (\Exception $exception) { - $this->_logger->writeRow($exception->getMessage()); + $this->logger->writeRow($exception->getMessage()); } - $this->_api->customersFixExternalIds( + $this->api->customersFixExternalIds( [ [ 'id' => $order['customer']['id'], @@ -204,23 +212,23 @@ class Exchange } //Create object of quote - $quote = $this->_quote->create(); + $quote = $this->quote->create(); //set store for which you create quote - $quote->setStore($store); + $quote->setStore($store); // if you have allready buyer id then you can load customer directly - $customer = $this->_customerRepository->getById($customer->getId()); + $customer = $this->customerRepository->getById($customer->getId()); $quote->setCurrency(); $quote->assignCustomer($customer); //Assign quote to customer //add items in quote - foreach($order['items'] as $item){ - $product = $this->_product->load($item['offer']['externalId']); + foreach ($order['items'] as $item) { + $product = $this->product->load($item['offer']['externalId']); $product->setPrice($item['initialPrice']); $quote->addProduct( $product, - intval($item['quantity']) + (int)$item['quantity'] ); } @@ -231,7 +239,7 @@ class Exchange } $orderData = [ - 'currency_id' => $manager->getStore()->getCurrentCurrency()->getCode(), + 'currency_id' => $this->storeManager->getStore()->getCurrentCurrency()->getCode(), 'email' => $order['email'], 'shipping_address' => [ 'firstname' => $order['firstName'], @@ -267,9 +275,9 @@ class Exchange ->collectShippingRates() ->setShippingMethod($ShippingMethods); - if ($this->_api->getVersion() == 'v4') { + if ($this->api->getVersion() == 'v4') { $paymentType = $order['paymentType']; - } elseif ($this->_api->getVersion() == 'v5') { + } elseif ($this->api->getVersion() == 'v5') { if ($order['payments']) { $paymentType = $this->getPaymentMethod($order['payments']); } @@ -287,11 +295,11 @@ class Exchange $quote->collectTotals()->save(); // Create Order From Quote - $magentoOrder = $this->_quoteManagement->submit($quote); + $magentoOrder = $this->quoteManagement->submit($quote); $increment_id = $magentoOrder->getId(); - $this->_api->ordersFixExternalIds( + $this->api->ordersFixExternalIds( [ [ 'id' => $order['id'], @@ -303,16 +311,16 @@ class Exchange /** * Create old edited order - * + * * @param array $order - * + * * @return void */ private function doCreateUp($order) { - $this->_logger->writeDump($order,'doCreateUp'); + $this->logger->writeDump($order, 'doCreateUp'); - $response = $this->_api->ordersGet($order['id'], $by = 'id'); + $response = $this->api->ordersGet($order['id'], $by = 'id'); if (!$response->isSuccessful()) { return; @@ -322,31 +330,37 @@ class Exchange $order = $response['order']; } - $payments = $this->_config->getValue('retailcrm/Payment'); - $shippings = $this->_config->getValue('retailcrm/Shipping'); + $payments = $this->config->getValue('retailcrm/retailcrm_payment'); + $shippings = $this->config->getValue('retailcrm/retailcrm_shipping'); - $manager = $this->_objectManager->get('Magento\Store\Model\StoreManagerInterface'); - $region = $this->_objectManager->get('Magento\Directory\Model\RegionFactory')->create(); - $store = $manager->getStore(); - $websiteId = $manager->getStore()->getWebsiteId(); + $region = $this->regionFactory->create(); + $sites = $this->helper->getMappingSites(); - $customer = $this->_customerFactory->create(); + if ($sites) { + $store = $this->storeManager->getStore($sites[$order['site']]); + $websiteId = $store->getWebsiteId(); + } else { + $store = $this->storeManager->getStore(); + $websiteId = $this->storeManager->getStore()->getWebsiteId(); + } + + $customer = $this->customerFactory->create(); $customer->setWebsiteId($websiteId); if (isset($order['customer']['externalId'])) { - $customer->load($order['customer']['externalId']); // load customet by external id + $customer->load($order['customer']['externalId']); // load customer by external id } //Create object of quote - $quote = $this->_quote->create(); + $quote = $this->quote->create(); //set store for which you create quote $quote->setStore($store); $quote->setCurrency(); - // if you have allready buyer id then you can load customer directly + // if you have all ready buyer id then you can load customer directly if ($customer->getId()) { - $customer = $this->_customerRepository->getById($customer->getId()); + $customer = $this->customerRepository->getById($customer->getId()); $quote->assignCustomer($customer); //Assign quote to customer } else { $quote->setCustomerEmail($order['email']); @@ -354,12 +368,12 @@ class Exchange } //add items in quote - foreach($order['items'] as $item){ - $product = $this->_product->load($item['offer']['externalId']); + foreach ($order['items'] as $item) { + $product = $this->product->load($item['offer']['externalId']); $product->setPrice($item['initialPrice']); $quote->addProduct( $product, - intval($item['quantity']) + (int)$item['quantity'] ); } @@ -370,9 +384,9 @@ class Exchange } $orderData = [ - 'currency_id' => $manager->getStore()->getCurrentCurrency()->getCode(), + 'currency_id' => $this->storeManager->getStore()->getCurrentCurrency()->getCode(), 'email' => $order['email'], - 'shipping_address' =>array( + 'shipping_address' => [ 'firstname' => $order['firstName'], 'lastname' => $order['lastName'], 'street' => $order['delivery']['address']['street'], @@ -382,7 +396,7 @@ class Exchange 'postcode' => $order['delivery']['address']['index'], 'telephone' => $order['phone'], 'save_in_address_book' => 1 - ), + ], 'items'=> $products ]; @@ -406,18 +420,17 @@ class Exchange ->collectShippingRates() ->setShippingMethod($ShippingMethods); - if ($this->_api->getVersion() == 'v4') { + if ($this->api->getVersion() == 'v4') { $paymentType = $order['paymentType']; - } elseif ($this->_api->getVersion() == 'v5') { + } elseif ($this->api->getVersion() == 'v5') { $paymentType = $this->getPaymentMethod($order['payments'], false); } $quote->setPaymentMethod($payments[$paymentType]); $quote->setInventoryProcessed(false); - $originalId = $order['externalId']; - $oldOrder = $this->_order->load($originalId); + $oldOrder = $this->orderInterface->load($originalId); $orderDataUp = [ 'original_increment_id' => $oldOrder->getIncrementId(), @@ -437,11 +450,11 @@ class Exchange $quote->collectTotals()->save(); // Create Order From Quote - $magentoOrder = $this->_quoteManagement->submit($quote,$orderDataUp); + $magentoOrder = $this->quoteManagement->submit($quote, $orderDataUp); $oldOrder->setStatus('canceled')->save(); $increment_id = $magentoOrder->getId(); - $this->_api->ordersFixExternalIds( + $this->api->ordersFixExternalIds( [ [ 'id' => $order['id'], @@ -453,23 +466,23 @@ class Exchange /** * Edit order - * + * * @param array $order - * + * * @return void */ private function doUpdate($order) { - $this->_logger->writeDump($order,'doUpdate'); + $this->logger->writeDump($order, 'doUpdate'); - $Status = $this->_config->getValue('retailcrm/Status'); + $Status = $this->config->getValue('retailcrm/retailcrm_status'); $Status = array_flip(array_filter($Status)); - $magentoOrder = $this->_order->load($order['externalId']); + $magentoOrder = $this->order->load($order['externalId']); $magentoOrderArr = $magentoOrder->getData(); - $this->_logger->writeDump($magentoOrderArr, 'magentoOrderArr'); - $this->_logger->writeDump($Status, 'status'); + $this->logger->writeDump($magentoOrderArr, 'magentoOrderArr'); + $this->logger->writeDump($Status, 'status'); if ((!empty($order['order_edit'])) && ($order['order_edit'] == 1)) { $this->doCreateUp($order); @@ -478,88 +491,21 @@ class Exchange if (!empty($order['status'])) { $change = $Status[$order['status']]; - if($change == 'canceled'){ - $this->_orderManagement->cancel($magentoOrderArr['entity_id']); + if ($change == 'canceled') { + $this->orderManagement->cancel($magentoOrderArr['entity_id']); } - if($change == 'holded'){ - $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); - $order_status = $objectManager->get('Magento\Sales\Model\Order')->load($magentoOrder->getId()); - $order_status->setStatus('holded'); - $order_status->save(); - } - - if(($change == 'complete')||($order['status']== 'complete')){ - $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); - $order_status = $objectManager->get('Magento\Sales\Model\Order')->load($magentoOrder->getId()); - $order_status->setStatus('complete'); - $order_status->save(); - } - - if($change == 'closed'){ - $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); - $order_status = $objectManager->get('Magento\Sales\Model\Order')->load($magentoOrder->getId()); - $order_status->setStatus('closed'); - $order_status->save(); - } - - if($change == 'processing'){ - $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); - $order_status = $objectManager->get('Magento\Sales\Model\Order')->load($magentoOrder->getId()); - $order_status->setStatus('processing'); - $order_status->save(); - - } - - if($change == 'fraud'){ - $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); - $order_status = $objectManager->get('Magento\Sales\Model\Order')->load($magentoOrder->getId()); - $order_status->setStatus('fraud'); - $order_status->save(); - } - - if($change == 'payment_review'){ - $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); - $order_status = $objectManager->get('Magento\Sales\Model\Order')->load($magentoOrder->getId()); - $order_status->setStatus('payment_review'); - $order_status->save(); - } - - if($change == 'paypal_canceled_reversal'){ - $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); - $order_status = $objectManager->get('Magento\Sales\Model\Order')->load($magentoOrder->getId()); - $order_status->setStatus('paypal_canceled_reversal'); - $order_status->save(); - } - - if($change == 'paypal_reversed'){ - $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); - $order_status = $objectManager->get('Magento\Sales\Model\Order')->load($magentoOrder->getId()); - $order_status->setStatus('paypal_reversed'); - $order_status->save(); - } - - if($change == 'pending_payment'){ - $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); - $order_status = $objectManager->get('Magento\Sales\Model\Order')->load($magentoOrder->getId()); - $order_status->setStatus('pending_payment'); - $order_status->save(); - } - - if($change == 'pending_paypal'){ - $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); - $order_status = $objectManager->get('Magento\Sales\Model\Order')->load($magentoOrder->getId()); - $order_status->setStatus('pending_paypal'); - $order_status->save(); - } + $order_status = $this->order->load($magentoOrder->getId()); + $order_status->setStatus($change); + $order_status->save(); } } /** * Assembly orders from history - * + * * @param array $orderHistory - * + * * @return array $orders */ public static function assemblyOrder($orderHistory) @@ -567,6 +513,7 @@ class Exchange $orders = []; foreach ($orderHistory as $change) { + $orderId = $change['order']['id']; $change['order'] = self::removeEmpty($change['order']); if (isset($change['order']['items'])) { @@ -610,10 +557,13 @@ class Exchange if (isset($change['item'])) { if (isset($orders[$change['order']['id']]['items']) - && $orders[$change['order']['id']]['items'][$change['item']['id']] + && $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']] = array_merge( + $orders[$change['order']['id']]['items'][$change['item']['id']], + $change['item'] + ); + } else { $orders[$change['order']['id']]['items'][$change['item']['id']] = $change['item']; } @@ -631,33 +581,41 @@ class Exchange if (!empty($change['newValue']) && $change['field'] == 'order_product.quantity') { $orders[$change['order']['id']]['order_edit'] = 1; } - - if (!$orders[$change['order']['id']]['items'][$change['item']['id']]['create'] && $fields['item'][$change['field']]) { - $orders[$change['order']['id']]['items'][$change['item']['id']][$fields['item'][$change['field']]] = $change['newValue']; - } } else { - if ((isset($fields['delivery'][$change['field']]))&&($fields['delivery'][$change['field']] == 'service')) { - $orders[$change['order']['id']]['delivery']['service']['code'] = self::newValue($change['newValue']); + if (isset($fields['delivery'][$change['field']]) + && $fields['delivery'][$change['field']] == 'service' + ) { + $orders[$orderId]['delivery']['service']['code'] = self::newValue($change['newValue']); } elseif (isset($fields['delivery'][$change['field']])) { - $orders[$change['order']['id']]['delivery'][$fields['delivery'][$change['field']]] = self::newValue($change['newValue']); + $field = $fields['delivery'][$change['field']]; + $orders[$orderId]['delivery'][$field] = self::newValue($change['newValue']); + unset($field); } elseif (isset($fields['orderAddress'][$change['field']])) { - $orders[$change['order']['id']]['delivery']['address'][$fields['orderAddress'][$change['field']]] = $change['newValue']; + $field = $fields['orderAddress'][$change['field']]; + $orders[$orderId]['delivery']['address'][$field] = self::newValue($change['newValue']); + unset($field); } elseif (isset($fields['integrationDelivery'][$change['field']])) { - $orders[$change['order']['id']]['delivery']['service'][$fields['integrationDelivery'][$change['field']]] = self::newValue($change['newValue']); + $field = $fields['integrationDelivery'][$change['field']]; + $orders[$orderId]['delivery']['service'][$field] = self::newValue($change['newValue']); + unset($field); } elseif (isset($fields['customerContragent'][$change['field']])) { - $orders[$change['order']['id']][$fields['customerContragent'][$change['field']]] = self::newValue($change['newValue']); + $field = $fields['customerContragent'][$change['field']]; + $orders[$orderId][$field] = self::newValue($change['newValue']); + unset($field); } elseif (strripos($change['field'], 'custom_') !== false) { - $orders[$change['order']['id']]['customFields'][str_replace('custom_', '', $change['field'])] = self::newValue($change['newValue']); + $field = str_replace('custom_', '', $change['field']); + $orders[$orderId]['customFields'][$field] = self::newValue($change['newValue']); + unset($field); } elseif (isset($fields['order'][$change['field']])) { - $orders[$change['order']['id']][$fields['order'][$change['field']]] = self::newValue($change['newValue']); + $orders[$orderId][$fields['order'][$change['field']]] = self::newValue($change['newValue']); } if (isset($change['created'])) { - $orders[$change['order']['id']]['create'] = 1; + $orders[$orderId]['create'] = 1; } if (isset($change['deleted'])) { - $orders[$change['order']['id']]['deleted'] = 1; + $orders[$orderId]['deleted'] = 1; } } } @@ -667,9 +625,9 @@ class Exchange /** * Remove empty elements - * + * * @param array $inputArray - * + * * @return array $outputArray */ public static function removeEmpty($inputArray) @@ -678,7 +636,7 @@ class Exchange if (!empty($inputArray)) { foreach ($inputArray as $key => $element) { - if(!empty($element) || $element === 0 || $element === '0') { + if (!empty($element) || $element === 0 || $element === '0') { if (is_array($element)) { $element = self::removeEmpty($element); } @@ -700,28 +658,25 @@ class Exchange */ public static function newValue($value) { - if(isset($value['code'])) { + if (isset($value['code'])) { return $value['code']; - } else{ + } else { return $value; } } /** * Get shipping methods - * + * * @param string $mcode - * + * * @return string */ public function getAllShippingMethodsCode($mcode) { - $activeCarriers = $this->_shipconfig->getActiveCarriers(); - $storeScope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE; - - foreach($activeCarriers as $carrierCode => $carrierModel) { - $options = []; + $activeCarriers = $this->shipconfig->getActiveCarriers(); + foreach ($activeCarriers as $carrierCode => $carrierModel) { if ($carrierMethods = $carrierModel->getAllowedMethods()) { foreach ($carrierMethods as $methodCode => $method) { $code = $carrierCode . '_'. $methodCode; @@ -738,13 +693,13 @@ class Exchange /** * Get payment type for api v5 - * + * * @param array $payments * @param boolean $newOrder - * + * * @return mixed */ - protected function getPaymentMethod($payments, $newOrder = true) + private function getPaymentMethod($payments, $newOrder = true) { if (count($payments) == 1 || $newOrder) { $payment = reset($payments); diff --git a/src/Model/Icml/Icml.php b/src/Model/Icml/Icml.php new file mode 100644 index 0000000..d884b19 --- /dev/null +++ b/src/Model/Icml/Icml.php @@ -0,0 +1,394 @@ +configurable = $configurable; + $this->StockState = $StockState; + $this->storeManager = $storeManager; + $this->product = $product; + $this->category = $categoryCollectionFactory; + $this->manager = $manager; + $this->config = $config; + $this->ddFactory = $ddFactory; + $this->dirList = $dirList; + } + + /** + * Generate icml catelog + * + * @return void + */ + public function generate() + { + $this->shop = $this->manager->getStore()->getId(); + + $string = ' + + + '.$this->manager->getStore()->getName().' + + + + + '; + + $xml = simplexml_load_string( + $string, + '\Magento\Framework\Simplexml\Element', + LIBXML_NOENT | LIBXML_NOCDATA | LIBXML_COMPACT | LIBXML_PARSEHUGE + ); + + $this->dd = $this->ddFactory->create(); + $this->dd->preserveWhiteSpace = false; + $this->dd->formatOutput = true; + $this->dd->loadXML($xml->asXML()); + + $this->eCategories = $this->dd + ->getElementsByTagName('categories')->item(0); + $this->eOffers = $this->dd + ->getElementsByTagName('offers')->item(0); + + $this->addCategories(); + $this->addOffers(); + + $this->dd->saveXML(); + $shopCode = $this->manager->getStore()->getCode(); + $this->dd->save($this->dirList->getRoot() . '/retailcrm_' . $shopCode . '.xml'); + } + + /** + * Add product categories in icml catalog + * + * @return void + */ + private function addCategories() + { + $collection = $this->category->create(); + $collection->addAttributeToSelect('*'); + + foreach ($collection as $category) { + if ($category->getId() > 1) { + $e = $this->eCategories->appendChild( + $this->dd->createElement('category') + ); + $e->appendChild($this->dd->createTextNode($category->getName())); + $e->setAttribute('id', $category->getId()); + + if ($category->getParentId() > 1) { + $e->setAttribute('parentId', $category->getParentId()); + } + } + } + } + + /** + * Write products in icml catalog + * + * @return void + */ + private function addOffers() + { + $offers = $this->buildOffers(); + + foreach ($offers as $offer) { + $this->addOffer($offer); + } + } + + /** + * Write product in icml catalog + * + * @param array $offer + * + * @return void + */ + private function addOffer($offer) + { + $e = $this->eOffers->appendChild( + $this->dd->createElement('offer') + ); + + $e->setAttribute('id', $offer['id']); + $e->setAttribute('productId', $offer['productId']); + + if (!empty($offer['quantity'])) { + $e->setAttribute('quantity', (int) $offer['quantity']); + } else { + $e->setAttribute('quantity', 0); + } + + if (!empty($offer['categoryId'])) { + foreach ($offer['categoryId'] as $categoryId) { + $e->appendChild( + $this->dd->createElement('categoryId') + )->appendChild( + $this->dd->createTextNode($categoryId) + ); + } + } else { + $e->appendChild($this->dd->createElement('categoryId', 1)); + } + + $e->appendChild($this->dd->createElement('productActivity')) + ->appendChild( + $this->dd->createTextNode($offer['productActivity']) + ); + + $e->appendChild($this->dd->createElement('name')) + ->appendChild( + $this->dd->createTextNode($offer['name']) + ); + + $e->appendChild($this->dd->createElement('productName')) + ->appendChild( + $this->dd->createTextNode($offer['productName']) + ); + + $e->appendChild($this->dd->createElement('price')) + ->appendChild( + $this->dd->createTextNode($offer['initialPrice']) + ); + + if (!empty($offer['purchasePrice'])) { + $e->appendChild($this->dd->createElement('purchasePrice')) + ->appendChild( + $this->dd->createTextNode($offer['purchasePrice']) + ); + } + + if (!empty($offer['picture'])) { + $e->appendChild($this->dd->createElement('picture')) + ->appendChild( + $this->dd->createTextNode($offer['picture']) + ); + } + + if (!empty($offer['url'])) { + $e->appendChild($this->dd->createElement('url')) + ->appendChild( + $this->dd->createTextNode($offer['url']) + ); + } + + if (!empty($offer['vendor'])) { + $e->appendChild($this->dd->createElement('vendor')) + ->appendChild( + $this->dd->createTextNode($offer['vendor']) + ); + } + + if (!empty($offer['params'])) { + foreach ($offer['params'] as $param) { + $paramNode = $this->dd->createElement('param'); + $paramNode->setAttribute('name', $param['name']); + $paramNode->setAttribute('code', $param['code']); + $paramNode->appendChild( + $this->dd->createTextNode($param['value']) + ); + $e->appendChild($paramNode); + } + } + } + + /** + * Build offers array + * + * @return array $offers + */ + private function buildOffers() + { + $offers = []; + + $collection = $this->product->create(); + $collection->addFieldToFilter('visibility', 4);//catalog, search visible + $collection->addAttributeToSelect('*'); + $picUrl = $this->storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA); + $customAdditionalAttributes = $this->config->getValue('retailcrm/Misc/attributes_to_export_into_icml'); + + foreach ($collection as $product) { + if ($product->getTypeId() == 'simple') { + $offers[] = $this->buildOffer($product); + } + + if ($product->getTypeId() == 'configurable') { + $associated_products = $this->getAssociatedProducts($product); + + foreach ($associated_products as $associatedProduct) { + $offers[] = $this->buildOffer($product, $associatedProduct); + } + } + } + + return $offers; + } + + /** + * Build offer array + * + * @param object $product + * @param object $associatedProduct + * @return array $offer + */ + private function buildOffer($product, $associatedProduct = null) + { + $offer = []; + + $picUrl = $this->storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA); + + $offer['id'] = $associatedProduct === null ? $product->getId() : $associatedProduct->getId(); + $offer['productId'] = $product->getId(); + + if ($associatedProduct === null) { + $offer['productActivity'] = $product->isAvailable() ? 'Y' : 'N'; + } else { + $offer['productActivity'] = $associatedProduct->isAvailable() ? 'Y' : 'N'; + } + + $offer['name'] = $associatedProduct === null ? $product->getName() : $associatedProduct->getName(); + $offer['productName'] = $product->getName(); + $offer['initialPrice'] = $associatedProduct === null + ? $product->getFinalPrice() + : $associatedProduct->getFinalPrice(); + $offer['url'] = $product->getProductUrl(); + + if ($associatedProduct === null) { + $offer['picture'] = $picUrl . 'catalog/product' . $product->getImage(); + } else { + $offer['picture'] = $picUrl . 'catalog/product' . $associatedProduct->getImage(); + } + + $offer['quantity'] = $associatedProduct === null + ? $this->getStockQuantity($product) + : $this->getStockQuantity($associatedProduct); + $offer['categoryId'] = $associatedProduct === null + ? $product->getCategoryIds() + : $associatedProduct->getCategoryIds(); + $offer['vendor'] = $associatedProduct === null + ? $product->getAttributeText('manufacturer') + : $associatedProduct->getAttributeText('manufacturer'); + + $offer['params'] = $this->getOfferParams($product, $associatedProduct); + + return $offer; + } + + /** + * Get parameters offers + * + * @param object $product + * @param object $associatedProduct + * @return array $params + */ + private function getOfferParams($product, $associatedProduct = null) + { + $params = []; + + if ($associatedProduct !== null) { + if ($associatedProduct->getResource()->getAttribute('color')) { + $colorAttribute = $associatedProduct->getResource()->getAttribute('color'); + $color = $colorAttribute->getSource()->getOptionText($associatedProduct->getColor()); + } + + if (isset($color)) { + $params[] = [ + 'name' => 'Color', + 'code' => 'color', + 'value' => $color + ]; + } + + if ($associatedProduct->getResource()->getAttribute('size')) { + $sizeAttribute = $associatedProduct->getResource()->getAttribute('size'); + $size = $sizeAttribute->getSource()->getOptionText($associatedProduct->getSize()); + } + + if (isset($size)) { + $params[] = [ + 'name' => 'Size', + 'code' => 'size', + 'value' => $size + ]; + } + } + + $article = $associatedProduct === null ? $product->getSku() : $associatedProduct->getSku(); + + if (!empty($article)) { + $params[] = [ + 'name' => 'Article', + 'code' => 'article', + 'value' => $article + ]; + } + + $weight = $associatedProduct === null ? $product->getWeight() : $associatedProduct->getWeight(); + + if (!empty($weight)) { + $params[] = [ + 'name' => 'Weight', + 'code' => 'weight', + 'value' => $weight + ]; + } + + return $params; + } + + /** + * Get associated products + * + * @param object $product + * + * @return object + */ + private function getAssociatedProducts($product) + { + return $this->configurable + ->getUsedProductCollection($product) + ->addAttributeToSelect('*') + ->addFilterByRequiredOptions(); + } + + /** + * Get product stock quantity + * + * @param object $offer + * @return int $quantity + */ + private function getStockQuantity($offer) + { + $quantity = $this->StockState->getStockQty( + $offer->getId(), + $offer->getStore()->getWebsiteId() + ); + + return $quantity; + } +} diff --git a/Model/Logger/Logger.php b/src/Model/Logger/Logger.php similarity index 76% rename from Model/Logger/Logger.php rename to src/Model/Logger/Logger.php index a89c4e5..2ae50ba 100644 --- a/Model/Logger/Logger.php +++ b/src/Model/Logger/Logger.php @@ -6,18 +6,18 @@ class Logger { private $logDir; - public function __construct(\Magento\Framework\ObjectManagerInterface $objectManager) - { - $directory = $objectManager->get('\Magento\Framework\Filesystem\DirectoryList'); + public function __construct( + \Magento\Framework\Filesystem\DirectoryList $directory + ) { $this->logDir = $directory->getPath('log'); } /** * Write data in log file - * + * * @param array $data - * @param str $fileName - * + * @param string $fileName + * * @return void */ public function writeDump($data, $fileName) @@ -40,10 +40,10 @@ class Logger /** * Write data in log file - * - * @param str $data - * @param str $fileName - * + * + * @param string $data + * @param string $fileName + * * @return void */ public function writeRow($data, $fileName = 'retailcrm') @@ -64,24 +64,24 @@ class Logger /** * Clear file - * - * @param str $file - * + * + * @param string $file + * * @return void */ - protected function clear($file) + private function clear($file) { file_put_contents($file, ''); } /** * Check file size - * - * @param str $file - * + * + * @param string $file + * * @return boolean */ - protected function checkSize($file) + private function checkSize($file) { if (!file_exists($file)) { return true; diff --git a/src/Model/Observer/Customer.php b/src/Model/Observer/Customer.php new file mode 100644 index 0000000..3432dfa --- /dev/null +++ b/src/Model/Observer/Customer.php @@ -0,0 +1,66 @@ +api = $api; + $this->helper = $helper; + $this->registry = $registry; + $this->customer = []; + } + + public function execute(\Magento\Framework\Event\Observer $observer) + { + if ($this->registry->registry('RETAILCRM_HISTORY') === true + || !$this->api->isConfigured() + ) { + return false; + } + + $data = $observer->getEvent()->getCustomer(); + + $this->customer = [ + 'externalId' => $data->getId(), + 'email' => $data->getEmail(), + 'firstName' => $data->getFirstname(), + 'patronymic' => $data->getMiddlename(), + 'lastName' => $data->getLastname(), + 'createdAt' => date('Y-m-d H:i:s', strtotime($data->getCreatedAt())) + ]; + + $response = $this->api->customersEdit($this->customer); + + if ($response === false) { + return false; + } + + if (!$response->isSuccessful() && $response->errorMsg == $this->api->getErrorText('errorNotFound')) { + $this->api->setSite($this->helper->getSite($data->getStore())); + $this->api->customersCreate($this->customer); + } + + return $this; + } + + /** + * @return array + */ + public function getCustomer() + { + return $this->customer; + } +} diff --git a/Model/Observer/OrderCreate.php b/src/Model/Observer/OrderCreate.php similarity index 52% rename from Model/Observer/OrderCreate.php rename to src/Model/Observer/OrderCreate.php index fe8b597..39404ce 100644 --- a/Model/Observer/OrderCreate.php +++ b/src/Model/Observer/OrderCreate.php @@ -4,110 +4,92 @@ namespace Retailcrm\Retailcrm\Model\Observer; use Magento\Framework\Event\Observer; use Retailcrm\Retailcrm\Helper\Proxy as ApiClient; +use RetailCrm\Retailcrm\Helper\Data as Helper; class OrderCreate implements \Magento\Framework\Event\ObserverInterface { - protected $_api; - protected $_objectManager; - protected $_config; - protected $_helper; - protected $_logger; - protected $_registry; + protected $api; + protected $config; + protected $logger; + protected $helper; + + private $registry; + private $product; + private $order; /** * Constructor - * - * @param \Magento\Framework\ObjectManagerInterface $objectManager + * * @param \Magento\Framework\App\Config\ScopeConfigInterface $config - * @param \Retailcrm\Retailcrm\Model\Logger\Logger $logger * @param \Magento\Framework\Registry $registry + * @param \Retailcrm\Retailcrm\Model\Logger\Logger $logger + * @param \Magento\Catalog\Model\ProductRepository $product + * @param Helper $helper + * @param ApiClient $api */ public function __construct( - \Magento\Framework\ObjectManagerInterface $objectManager, \Magento\Framework\App\Config\ScopeConfigInterface $config, - \Magento\Framework\Registry $registry + \Magento\Framework\Registry $registry, + \Retailcrm\Retailcrm\Model\Logger\Logger $logger, + \Magento\Catalog\Model\ProductRepository $product, + Helper $helper, + ApiClient $api ) { - $helper = $objectManager->get('\Retailcrm\Retailcrm\Helper\Data'); - $this->_logger = $objectManager->get('\Retailcrm\Retailcrm\Model\Logger\Logger'); - $this->_helper = $helper; - $this->_objectManager = $objectManager; - $this->_config = $config; - $this->_registry = $registry; - - $url = $config->getValue('retailcrm/general/api_url'); - $key = $config->getValue('retailcrm/general/api_key'); - $apiVersion = $config->getValue('retailcrm/general/api_version'); - - if (!empty($url) && !empty($key)) { - $this->_api = new ApiClient($url, $key, $apiVersion); - } + $this->logger = $logger; + $this->config = $config; + $this->registry = $registry; + $this->product = $product; + $this->helper = $helper; + $this->api = $api; + $this->order = []; } /** * Execute send order in CRM - * + * * @param Observer $observer - * - * @return $this + * + * @return mixed */ public function execute(Observer $observer) { - if ($this->_registry->registry('RETAILCRM_HISTORY') === true) { - return; + if ($this->registry->registry('RETAILCRM_HISTORY') === true + || !$this->api->isConfigured() + ) { + return false; } $order = $observer->getEvent()->getOrder(); - + + $this->api->setSite($this->helper->getSite($order->getStore())); + if ($this->existsInCrm($order->getId()) === true) { - return; + return false; } - $items = []; $addressObj = $order->getBillingAddress(); - foreach ($order->getAllItems() as $item) { - if ($item->getProductType() == "simple") { - $price = $item->getPrice(); - - if ($price == 0) { - $omproduct = $this->_objectManager->get('Magento\Catalog\Model\ProductRepository') - ->getById($item->getProductId()); - $price = $omproduct->getPrice(); - } - - $product = [ - 'productId' => $item->getProductId(), - 'productName' => $item->getName(), - 'quantity' => $item->getQtyOrdered(), - 'initialPrice' => $price, - 'offer' => [ - 'externalId' => $item->getProductId() - ] - ]; - - unset($omproduct); - unset($price); - - $items[] = $product; - } - } - $shippingCode = $this->getShippingCode($order->getShippingMethod()); - $preparedOrder = [ - 'site' => $order->getStore()->getCode(), + $this->order = [ 'externalId' => $order->getId(), 'number' => $order->getRealOrderId(), 'createdAt' => $order->getCreatedAt(), - 'lastName' => $order->getCustomerLastname() ? $order->getCustomerLastname() : $addressObj->getLastname(), - 'firstName' => $order->getCustomerFirstname() ? $order->getCustomerFirstname() : $addressObj->getFirstname(), - 'patronymic' => $order->getCustomerMiddlename() ? $order->getCustomerMiddlename() : $addressObj->getMiddlename(), + 'lastName' => $order->getCustomerLastname() + ? $order->getCustomerLastname() + : $addressObj->getLastname(), + 'firstName' => $order->getCustomerFirstname() + ? $order->getCustomerFirstname() + : $addressObj->getFirstname(), + 'patronymic' => $order->getCustomerMiddlename() + ? $order->getCustomerMiddlename() + : $addressObj->getMiddlename(), 'email' => $order->getCustomerEmail(), 'phone' => $addressObj->getTelephone(), - 'status' => $this->_config->getValue('retailcrm/Status/' . $order->getStatus()), - 'items' => $items, + 'status' => $this->config->getValue('retailcrm/retailcrm_status/' . $order->getStatus()), + 'items' => $this->getOrderItems($order), 'delivery' => [ - 'code' => $this->_config->getValue('retailcrm/Shipping/' . $shippingCode), + 'code' => $this->config->getValue('retailcrm/retailcrm_shipping/' . $shippingCode), 'cost' => $order->getShippingAmount(), 'address' => [ 'index' => $addressObj->getData('postcode'), @@ -130,17 +112,21 @@ class OrderCreate implements \Magento\Framework\Event\ObserverInterface ]; if ($addressObj->getData('country_id')) { - $preparedOrder['countryIso'] = $addressObj->getData('country_id'); + $this->order['countryIso'] = $addressObj->getData('country_id'); } - if ($this->_api->getVersion() == 'v4') { - $preparedOrder['paymentType'] = $this->_config->getValue('retailcrm/Payment/'.$order->getPayment()->getMethodInstance()->getCode()); - $preparedOrder['discount'] = abs($order->getDiscountAmount()); - } elseif ($this->_api->getVersion() == 'v5') { - $preparedOrder['discountManualAmount'] = abs($order->getDiscountAmount()); + if ($this->api->getVersion() == 'v4') { + $this->order['paymentType'] = $this->config->getValue( + 'retailcrm/retailcrm_payment/' . $order->getPayment()->getMethodInstance()->getCode() + ); + $this->order['discount'] = abs($order->getDiscountAmount()); + } elseif ($this->api->getVersion() == 'v5') { + $this->order['discountManualAmount'] = abs($order->getDiscountAmount()); $payment = [ - 'type' => $this->_config->getValue('retailcrm/Payment/' . $order->getPayment()->getMethodInstance()->getCode()), + 'type' => $this->config->getValue( + 'retailcrm/retailcrm_payment/' . $order->getPayment()->getMethodInstance()->getCode() + ), 'externalId' => $order->getId(), 'order' => [ 'externalId' => $order->getId(), @@ -151,30 +137,52 @@ class OrderCreate implements \Magento\Framework\Event\ObserverInterface $payment['status'] = 'paid'; } - $preparedOrder['payments'][] = $payment; + $this->order['payments'][] = $payment; } - if (trim($preparedOrder['delivery']['code']) == '') { - unset($preparedOrder['delivery']['code']); + if (trim($this->order['delivery']['code']) == '') { + unset($this->order['delivery']['code']); } - if (isset($preparedOrder['paymentType']) && trim($preparedOrder['paymentType']) == '') { - unset($preparedOrder['paymentType']); + if (isset($this->order['paymentType']) && trim($this->order['paymentType']) == '') { + unset($this->order['paymentType']); } - if (trim($preparedOrder['status']) == '') { - unset($preparedOrder['status']); + if (trim($this->order['status']) == '') { + unset($this->order['status']); } + $this->setCustomer( + $order, + $addressObj + ); + + Helper::filterRecursive($this->order); + + $this->logger->writeDump($this->order, 'CreateOrder'); + + $this->api->ordersCreate($this->order); + + return $this; + } + + /** + * @param $order + * @param $addressObj + */ + private function setCustomer($order, $addressObj) + { if ($order->getCustomerIsGuest() == 1) { $customer = $this->getCustomerByEmail($order->getCustomerEmail()); if ($customer !== false) { - $preparedOrder['customer']['id'] = $customer['id']; + $this->order['customer']['id'] = $customer['id']; } - } elseif ($order->getCustomerIsGuest() == 0) { + } + + if ($order->getCustomerIsGuest() == 0) { if ($this->existsInCrm($order->getCustomerId(), 'customersGet')) { - $preparedOrder['customer']['externalId'] = $order->getCustomerId(); + $this->order['customer']['externalId'] = $order->getCustomerId(); } else { $preparedCustomer = [ 'externalId' => $order->getCustomerId(), @@ -189,29 +197,61 @@ class OrderCreate implements \Magento\Framework\Event\ObserverInterface ]; } - if ($this->_api->customersCreate($preparedCustomer)) { - $preparedOrder['customer']['externalId'] = $order->getCustomerId(); + if ($this->api->customersCreate($preparedCustomer)) { + $this->order['customer']['externalId'] = $order->getCustomerId(); } } } + } - $this->_helper->filterRecursive($preparedOrder); + /** + * Get order products + * + * @param object $order + * + * @return array $items + */ + private function getOrderItems($order) + { + $items = []; - $this->_logger->writeDump($preparedOrder,'CreateOrder'); + foreach ($order->getAllItems() as $item) { + if ($item->getProductType() == "simple") { + $price = $item->getPrice(); - $this->_api->ordersCreate($preparedOrder); + if ($price == 0) { + $magentoProduct = $this->product->getById($item->getProductId()); + $price = $magentoProduct->getPrice(); + } - return $this; - } + $product = [ + 'productId' => $item->getProductId(), + 'productName' => $item->getName(), + 'quantity' => $item->getQtyOrdered(), + 'initialPrice' => $price, + 'offer' => [ + 'externalId' => $item->getProductId() + ] + ]; + + unset($magentoProduct); + unset($price); + + $items[] = $product; + } + } + + return $items; + } /** * Get shipping code - * + * * @param string $string - * + * * @return string */ - protected function getShippingCode($string) + public function getShippingCode($string) { $split = array_values(explode('_', $string)); $length = count($split); @@ -222,20 +262,23 @@ class OrderCreate implements \Magento\Framework\Event\ObserverInterface /** * Check exists order or customer in CRM - * + * * @param int $id - * + * @param string $method + * @param string $by + * @param string $site + * * @return boolean */ - protected function existsInCrm($id, $method = 'ordersGet', $by = 'externalId') + private function existsInCrm($id, $method = 'ordersGet', $by = 'externalId', $site = null) { - $response = $this->_api->{$method}($id, $by); + $response = $this->api->{$method}($id, $by, $site); if ($response === false) { - return; + return false; } - if (!$response->isSuccessful() && $response->errorMsg == $this->_api->getErrorText('errorNotFound')) { + if (!$response->isSuccessful() && $response->errorMsg == $this->api->getErrorText('errorNotFound')) { return false; } @@ -244,14 +287,14 @@ class OrderCreate implements \Magento\Framework\Event\ObserverInterface /** * Get customer by email from CRM - * + * * @param string $email - * + * * @return mixed */ - protected function getCustomerByEmail($email) + private function getCustomerByEmail($email) { - $response = $this->_api->customersList(['email' => $email]); + $response = $this->api->customersList(['email' => $email]); if ($response === false) { return false; @@ -265,4 +308,12 @@ class OrderCreate implements \Magento\Framework\Event\ObserverInterface return false; } + + /** + * @return array + */ + public function getOrder() + { + return $this->order; + } } diff --git a/src/Model/Observer/OrderUpdate.php b/src/Model/Observer/OrderUpdate.php new file mode 100644 index 0000000..d324d09 --- /dev/null +++ b/src/Model/Observer/OrderUpdate.php @@ -0,0 +1,89 @@ +config = $config; + $this->registry = $registry; + $this->helper = $helper; + $this->api = $api; + $this->order = []; + } + + /** + * Execute update order in CRM + * + * @param Observer $observer + * + * @return mixed + */ + public function execute(Observer $observer) + { + if ($this->registry->registry('RETAILCRM_HISTORY') === true + || !$this->api->isConfigured() + ) { + return false; + } + + $order = $observer->getEvent()->getOrder(); + + if ($order) { + $this->order = [ + 'externalId' => $order->getId(), + 'status' => $this->config->getValue('retailcrm/retailcrm_status/' . $order->getStatus()) + ]; + + if ($order->getBaseTotalDue() == 0) { + if ($this->api->getVersion() == 'v4') { + $this->order['paymentStatus'] = 'paid'; + } elseif ($this->api->getVersion() == 'v5') { + $payment = [ + 'externalId' => $order->getPayment()->getId(), + 'status' => 'paid' + ]; + + $this->api->ordersPaymentsEdit($payment); + } + } + + Helper::filterRecursive($this->order); + $this->api->setSite($this->helper->getSite($order->getStore())); + $this->api->ordersEdit($this->order); + } + + return $this; + } + + /** + * @return mixed + */ + public function getOrder() + { + return $this->order; + } +} diff --git a/src/Model/Order/OrderNumber.php b/src/Model/Order/OrderNumber.php new file mode 100644 index 0000000..e8b1c67 --- /dev/null +++ b/src/Model/Order/OrderNumber.php @@ -0,0 +1,145 @@ +salesOrder = $salesOrder; + parent::__construct($config, $registry, $logger, $product, $helper, $api); + } + + public function exportOrderNumber() + { + $ordernumber = $this->config->getValue('retailcrm/Load/number_order'); + $ordersId = explode(",", $ordernumber); + $orders = []; + + foreach ($ordersId as $id) { + $magentoOrder = $this->salesOrder->load($id); + $orders[$magentoOrder->getStore()->getId()][] = $this->prepareOrder($magentoOrder); + } + + foreach ($orders as $storeId => $ordersStore) { + $chunked = array_chunk($ordersStore, 50); + unset($ordersStore); + + foreach ($chunked as $chunk) { + $this->api->setSite($this->helper->getSite($storeId)); + $this->api->ordersUpload($chunk); + time_nanosleep(0, 250000000); + } + + unset($chunked); + } + + return true; + } + + public function prepareOrder($magentoOrder) + { + $items = []; + $addressObj = $magentoOrder->getBillingAddress(); + + foreach ($magentoOrder->getAllItems() as $item) { + if ($item->getProductType() == "simple") { + $price = $item->getPrice(); + + if ($price == 0) { + $magentoProduct = $this->productRepository->getById($item->getProductId()); + $price = $magentoProduct->getPrice(); + } + + $product = [ + 'productId' => $item->getProductId(), + 'productName' => $item->getName(), + 'quantity' => $item->getQtyOrdered(), + 'initialPrice' => $price, + 'offer' => [ + 'externalId'=>$item->getProductId() + ] + ]; + + unset($magentoProduct); + unset($price); + + $items[] = $product; + } + } + + $ship = $this->getShippingCode($magentoOrder->getShippingMethod()); + + $preparedOrder = [ + 'externalId' => $magentoOrder->getRealOrderId(), + 'number' => $magentoOrder->getRealOrderId(), + 'createdAt' => date('Y-m-d H:i:s'), + 'lastName' => $magentoOrder->getCustomerLastname(), + 'firstName' => $magentoOrder->getCustomerFirstname(), + 'patronymic' => $magentoOrder->getCustomerMiddlename(), + 'email' => $magentoOrder->getCustomerEmail(), + 'phone' => $addressObj->getTelephone(), + 'paymentType' => $this->config->getValue( + 'retailcrm/Payment/' . $magentoOrder->getPayment()->getMethodInstance()->getCode() + ), + 'status' => $this->config->getValue('retailcrm/Status/'.$magentoOrder->getStatus()), + 'discount' => abs($magentoOrder->getDiscountAmount()), + 'items' => $items, + 'delivery' => [ + 'code' => $this->config->getValue('retailcrm/Shipping/'.$ship), + 'cost' => $magentoOrder->getShippingAmount(), + 'address' => [ + 'index' => $addressObj->getData('postcode'), + 'city' => $addressObj->getData('city'), + 'country' => $addressObj->getData('country_id'), + 'street' => $addressObj->getData('street'), + 'region' => $addressObj->getData('region'), + 'text' => trim( + ',', + implode( + ',', + [ + $addressObj->getData('postcode'), + $addressObj->getData('city'), + $addressObj->getData('street'), + ] + ) + ) + ] + ] + ]; + + if (trim($preparedOrder['delivery']['code']) == '') { + unset($preparedOrder['delivery']['code']); + } + + if (trim($preparedOrder['paymentType']) == '') { + unset($preparedOrder['paymentType']); + } + + if (trim($preparedOrder['status']) == '') { + unset($preparedOrder['status']); + } + + if ($magentoOrder->getCustomerIsGuest() == 0) { + $preparedOrder['customer']['externalId'] = $magentoOrder->getCustomerId(); + } + + $this->logger->writeDump($preparedOrder, 'OrderNumber'); + + return Helper::filterRecursive($preparedOrder); + } +} diff --git a/src/Model/Service/ConfigManager.php b/src/Model/Service/ConfigManager.php new file mode 100644 index 0000000..0f34391 --- /dev/null +++ b/src/Model/Service/ConfigManager.php @@ -0,0 +1,19 @@ +config = $config; + } + + public function getConfigValue($path) + { + return $this->config->getValue($path); + } +} diff --git a/Model/Setting/ApiVersions.php b/src/Model/Setting/ApiVersions.php similarity index 100% rename from Model/Setting/ApiVersions.php rename to src/Model/Setting/ApiVersions.php diff --git a/Model/Setting/Attribute.php b/src/Model/Setting/Attribute.php similarity index 57% rename from Model/Setting/Attribute.php rename to src/Model/Setting/Attribute.php index f00036f..99de0ee 100644 --- a/Model/Setting/Attribute.php +++ b/src/Model/Setting/Attribute.php @@ -4,28 +4,32 @@ namespace Retailcrm\Retailcrm\Model\Setting; class Attribute implements \Magento\Framework\Option\ArrayInterface { - protected $_entityType; - protected $_store; + private $entityType; + private $store; public function __construct( \Magento\Store\Model\Store $store, \Magento\Eav\Model\Entity\Type $entityType ) { - $this->_store = $store; - $this->_entityType = $entityType; + $this->store = $store; + $this->entityType = $entityType; } public function toOptionArray() { $types = ['text', 'multiselect', 'decimal']; - $attributes = $this->_entityType->loadByCode('catalog_product')->getAttributeCollection(); + $attributes = $this->entityType->loadByCode('catalog_product')->getAttributeCollection(); $attributes->addFieldToFilter('frontend_input', $types); $result = []; foreach ($attributes as $attr) { if ($attr->getFrontendLabel()) { - $result[] = array('value' => $attr->getAttributeId(), 'label' => $attr->getFrontendLabel(), 'title' => $attr->getAttributeCode()); + $result[] = [ + 'value' => $attr->getAttributeId(), + 'label' => $attr->getFrontendLabel(), + 'title' => $attr->getAttributeCode() + ]; } } diff --git a/Model/Setting/Shipping.php b/src/Model/Setting/Shipping.php similarity index 61% rename from Model/Setting/Shipping.php rename to src/Model/Setting/Shipping.php index 7fd266e..d6ca4c8 100644 --- a/Model/Setting/Shipping.php +++ b/src/Model/Setting/Shipping.php @@ -4,23 +4,26 @@ namespace Retailcrm\Retailcrm\Model\Setting; class Shipping implements \Magento\Framework\Option\ArrayInterface { - protected $_entityType; - protected $_store; + private $entityType; + private $store; + private $config; + private $shippingConfig; public function __construct( \Magento\Store\Model\Store $store, - \Magento\Eav\Model\Entity\Type $entityType + \Magento\Eav\Model\Entity\Type $entityType, + \Magento\Framework\App\Config\ScopeConfigInterface $config, + \Magento\Shipping\Model\Config $shippingConfig ) { - $this->_store = $store; - $this->_entityType = $entityType; + $this->store = $store; + $this->entityType = $entityType; + $this->config = $config; + $this->shippingConfig = $shippingConfig; } public function toOptionArray() { - $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); - $activeShipping = $objectManager->create('Magento\Shipping\Model\Config')->getActiveCarriers(); - - $config = $objectManager->get('Magento\Framework\App\Config\ScopeConfigInterface'); + $activeShipping = $this->shippingConfig->getActiveCarriers(); foreach ($activeShipping as $carrierCode => $carrierModel) { $options = []; @@ -36,7 +39,7 @@ class Shipping implements \Magento\Framework\Option\ArrayInterface ]; } - $carrierTitle = $config->getValue('carriers/' . $carrierCode . '/title'); + $carrierTitle = $this->config->getValue('carriers/' . $carrierCode . '/title'); } $methods[] = [ diff --git a/Model/Setting/Status.php b/src/Model/Setting/Status.php similarity index 93% rename from Model/Setting/Status.php rename to src/Model/Setting/Status.php index a7adbcb..6b439f6 100644 --- a/Model/Setting/Status.php +++ b/src/Model/Setting/Status.php @@ -9,7 +9,7 @@ class Status extends \Magento\Config\Model\Config\Backend\Serialized\ArraySerial // For value validations $exceptions = $this->getValue(); - // Validations + // Validations $this->setValue($exceptions); return parent::beforeSave(); diff --git a/src/README.md b/src/README.md new file mode 100644 index 0000000..8280653 --- /dev/null +++ b/src/README.md @@ -0,0 +1 @@ +Magento 2 module for interaction with retailCRM \ No newline at end of file diff --git a/src/Test/Helpers/FieldsetTest.php b/src/Test/Helpers/FieldsetTest.php new file mode 100644 index 0000000..e139d96 --- /dev/null +++ b/src/Test/Helpers/FieldsetTest.php @@ -0,0 +1,101 @@ +objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $factoryMock = $this->createMock(\Magento\Framework\Data\Form\Element\Factory::class); + $collectionFactoryMock = $this->createMock(\Magento\Framework\Data\Form\Element\CollectionFactory::class); + $escaperMock = $this->createMock(\Magento\Framework\Escaper::class); + $formElementMock = $this->createMock(\Magento\Framework\Data\Form\Element\Select::class); + $factoryMock->expects($this->any())->method('create')->willReturn($formElementMock); + + $formElementMock->expects($this->any())->method('setRenderer')->willReturn($formElementMock); + $elementCollection = $this->objectManager->getObject(\Magento\Framework\Data\Form\Element\Collection::class); + + // element mock + $this->elementMock = $this->getMockBuilder(\Magento\Framework\Data\Form\Element\AbstractElement::class) + ->setMethods([ + 'getId', + 'getHtmlId', + 'getName', + 'getElements', + 'getLegend', + 'getComment', + 'getIsNested', + 'getExpanded', + 'getForm', + 'addField' + ]) + ->setConstructorArgs([$factoryMock, $collectionFactoryMock, $escaperMock]) + ->getMockForAbstractClass(); + $this->elementMock->expects($this->any()) + ->method('getId') + ->willReturn($this->testElementId); + $this->elementMock->expects($this->any()) + ->method('getHtmlId') + ->willReturn($this->testElementId); + $this->elementMock->expects($this->any()) + ->method('addField') + ->willReturn($formElementMock); + $this->elementMock->expects($this->any()) + ->method('getElements') + ->willReturn($elementCollection); + + $this->authSessionMock = $this->getMockBuilder(\Magento\Backend\Model\Auth\Session::class) + ->setMethods(['getUser']) + ->disableOriginalConstructor() + ->getMock(); + + $this->userMock = $this->getMockBuilder(\Magento\User\Model\User::class) + ->setMethods(['getExtra']) + ->disableOriginalConstructor() + ->getMock(); + + $this->authSessionMock->expects($this->any()) + ->method('getUser') + ->willReturn($this->userMock); + + $this->requestMock = $this->getMockBuilder(\Magento\Framework\App\RequestInterface::class) + ->disableOriginalConstructor() + ->getMock(); + $this->requestMock->expects($this->any()) + ->method('getParam') + ->willReturn('Test Param'); + + $factoryCollection = $this->createMock(\Magento\Framework\Data\Form\Element\CollectionFactory::class); + $elementCollection = $this->createMock(\Magento\Framework\Data\Form\Element\Collection::class); + $factoryCollection->expects($this->any())->method('create')->willReturn($elementCollection); + $rendererMock = $this->createMock(\Magento\Framework\Data\Form\Element\Renderer\RendererInterface::class); + + $this->urlModelMock = $this->createMock(\Magento\Backend\Model\Url::class); + $this->layoutMock = $this->createMock(\Magento\Framework\View\Layout::class); + $this->groupMock = $this->createMock(\Magento\Config\Model\Config\Structure\Element\Group::class); + $this->groupMock->expects($this->any())->method('getFieldsetCss')->will($this->returnValue($this->testFieldSetCss)); + $this->context = $this->createMock(\Magento\Backend\Block\Context::class); + $this->context->expects($this->any())->method('getRequest')->willReturn($this->requestMock); + $this->context->expects($this->any())->method('getUrlBuilder')->willReturn($this->urlModelMock); + $this->layoutMock->expects($this->any())->method('getBlockSingleton')->willReturn($rendererMock); + $this->helperMock = $this->createMock(\Magento\Framework\View\Helper\Js::class); + $this->form = $this->createPartialMock(\Magento\Config\Block\System\Config\Form::class, ['getElements', 'getRequest']); + $this->form->expects($this->any())->method('getElements')->willReturn($elementCollection); + $this->form->expects($this->any())->method('getRequest')->willReturn($this->requestMock); + } +} diff --git a/src/Test/Unit/Block/Adminhtml/System/Config/Form/Fieldset/PaymentTest.php b/src/Test/Unit/Block/Adminhtml/System/Config/Form/Fieldset/PaymentTest.php new file mode 100644 index 0000000..8edf18f --- /dev/null +++ b/src/Test/Unit/Block/Adminhtml/System/Config/Form/Fieldset/PaymentTest.php @@ -0,0 +1,123 @@ +objectManager->getObject( + \RetailCrm\Response\ApiResponse::class, + [ + 'statusCode' => $isSuccessful ? 200 : 404, + 'responseBody' => json_encode($this->getTestResponse()) + ] + ); + + // api client mock + $client = $this->getMockBuilder(\Retailcrm\Retailcrm\Helper\Proxy::class) + ->disableOriginalConstructor() + ->setMethods( + [ + 'isConfigured', + 'paymentTypesList' + ] + ) + ->getMock(); + $client->expects($this->any()) + ->method('isConfigured') + ->willReturn($isConfigured); + $client->expects($this->any()) + ->method('paymentTypesList') + ->willReturn($response); + + // payment config mock + $paymentConfig = $this->getMockBuilder(\Magento\Payment\Model\Config::class) + ->disableOriginalConstructor() + ->getMock(); + $paymentConfig->expects($this->any()) + ->method('getActiveMethods') + ->willReturn($this->getTestActiveMethods()); + + $data = [ + 'authSession' => $this->authSessionMock, + 'jsHelper' => $this->helperMock, + 'data' => ['group' => $this->groupMock], + 'client' => $client, + 'paymentConfig' => $paymentConfig, + 'context' => $this->context + ]; + + $payment = $this->objectManager->getObject( + \Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Fieldset\Payment::class, + $data + ); + + $payment->setForm($this->form); + $payment->setLayout($this->layoutMock); + + $html = $payment->render($this->elementMock); + + $this->assertContains($this->testElementId, $html); + $this->assertContains($this->testFieldSetCss, $html); + + if (!$isConfigured) { + $expected = '
Please check your API Url & API Key
'; + $this->assertContains($expected, $html); + } + } + + protected function getTestActiveMethods() + { + $payment = $this->getMockBuilder(\Magento\Payment\Model\MethodInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); + + $payment->expects($this->any()) + ->method('getTitle') + ->willReturn('Test Payment'); + + return ['test_payment' => $payment]; + } + + private function getTestResponse() + { + return [ + 'success' => true, + 'paymentTypes' => [ + [ + 'code' => 'payment', + 'name' => 'Test payment type' + ] + ] + ]; + } + + public function dataProvider() + { + return [ + [ + 'is_successful' => true, + 'is_configured' => true + ], + [ + 'is_successful' => false, + 'is_configured' => false + ], + [ + 'is_successful' => true, + 'is_configured' => false + ], + [ + 'is_successful' => false, + 'is_configured' => true + ] + ]; + } +} diff --git a/src/Test/Unit/Block/Adminhtml/System/Config/Form/Fieldset/ShippingTest.php b/src/Test/Unit/Block/Adminhtml/System/Config/Form/Fieldset/ShippingTest.php new file mode 100644 index 0000000..a1511c8 --- /dev/null +++ b/src/Test/Unit/Block/Adminhtml/System/Config/Form/Fieldset/ShippingTest.php @@ -0,0 +1,124 @@ +objectManager->getObject( + \RetailCrm\Response\ApiResponse::class, + [ + 'statusCode' => $isSuccessful ? 200 : 404, + 'responseBody' => json_encode($this->getTestResponse()) + ] + ); + + // api client mock + $client = $this->getMockBuilder(\Retailcrm\Retailcrm\Helper\Proxy::class) + ->disableOriginalConstructor() + ->setMethods( + [ + 'isConfigured', + 'deliveryTypesList' + ] + ) + ->getMock(); + $client->expects($this->any()) + ->method('isConfigured') + ->willReturn($isConfigured); + $client->expects($this->any()) + ->method('deliveryTypesList') + ->willReturn($response); + + // shipping config mock + $shippingConfig = $this->getMockBuilder(\Magento\Shipping\Model\Config::class) + ->disableOriginalConstructor() + ->getMock(); + $shippingConfig->expects($this->any()) + ->method('getActiveCarriers') + ->willReturn($this->getTestActiveCarriers()); + + $data = [ + 'authSession' => $this->authSessionMock, + 'jsHelper' => $this->helperMock, + 'data' => ['group' => $this->groupMock], + 'client' => $client, + 'shippingConfig' => $shippingConfig, + 'context' => $this->context + ]; + + $shipping = $this->objectManager->getObject( + \Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Fieldset\Shipping::class, + $data + ); + + $shipping->setForm($this->form); + $shipping->setLayout($this->layoutMock); + + $html = $shipping->render($this->elementMock); + + $this->assertContains($this->testElementId, $html); + $this->assertContains($this->testFieldSetCss, $html); + + if (!$isConfigured) { + $expected = '
Please check your API Url & API Key
'; + $this->assertContains($expected, $html); + } + } + + protected function getTestActiveCarriers() + { + $shipping = $this->getMockBuilder(\Magento\Shipping\Model\Carrier\AbstractCarrierInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); + + $shipping->expects($this->any()) + ->method('getConfigData') + ->with('title') + ->willReturn('Test Shipping'); + + return ['test_shipping' => $shipping]; + } + + private function getTestResponse() + { + return [ + 'success' => true, + 'deliveryTypes' => [ + [ + 'code' => 'delivery', + 'name' => 'Test delivery type' + ] + ] + ]; + } + + public function dataProvider() + { + return [ + [ + 'is_successful' => true, + 'is_configured' => true + ], + [ + 'is_successful' => false, + 'is_configured' => false + ], + [ + 'is_successful' => true, + 'is_configured' => false + ], + [ + 'is_successful' => false, + 'is_configured' => true + ] + ]; + } +} diff --git a/src/Test/Unit/Block/Adminhtml/System/Config/Form/Fieldset/SiteTest.php b/src/Test/Unit/Block/Adminhtml/System/Config/Form/Fieldset/SiteTest.php new file mode 100644 index 0000000..82e5f4e --- /dev/null +++ b/src/Test/Unit/Block/Adminhtml/System/Config/Form/Fieldset/SiteTest.php @@ -0,0 +1,101 @@ +objectManager->getObject( + \RetailCrm\Response\ApiResponse::class, + [ + 'statusCode' => $isSuccessful ? 200 : 404, + 'responseBody' => json_encode($this->getTestResponse()) + ] + ); + + // api client mock + $client = $this->getMockBuilder(\Retailcrm\Retailcrm\Helper\Proxy::class) + ->disableOriginalConstructor() + ->setMethods( + [ + 'isConfigured', + 'sitesList' + ] + ) + ->getMock(); + $client->expects($this->any()) + ->method('isConfigured') + ->willReturn($isConfigured); + $client->expects($this->any()) + ->method('sitesList') + ->willReturn($response); + + $data = [ + 'authSession' => $this->authSessionMock, + 'jsHelper' => $this->helperMock, + 'data' => ['group' => $this->groupMock], + 'client' => $client, + 'context' => $this->context + ]; + + $site = $this->objectManager->getObject( + \Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Fieldset\Site::class, + $data + ); + + $site->setForm($this->form); + $site->setLayout($this->layoutMock); + + $html = $site->render($this->elementMock); + + $this->assertContains($this->testElementId, $html); + $this->assertContains($this->testFieldSetCss, $html); + + if (!$isConfigured) { + $expected = '
Please check your API Url & API Key
'; + $this->assertContains($expected, $html); + } + } + + private function getTestResponse() + { + return [ + 'success' => true, + 'sites' => [ + [ + 'code' => 'payment', + 'name' => 'Test site' + ] + ] + ]; + } + + public function dataProvider() + { + return [ + [ + 'is_successful' => true, + 'is_configured' => true + ], + [ + 'is_successful' => false, + 'is_configured' => false + ], + [ + 'is_successful' => true, + 'is_configured' => false + ], + [ + 'is_successful' => false, + 'is_configured' => true + ] + ]; + } +} diff --git a/src/Test/Unit/Block/Adminhtml/System/Config/Form/Fieldset/SitesTest.php b/src/Test/Unit/Block/Adminhtml/System/Config/Form/Fieldset/SitesTest.php new file mode 100644 index 0000000..7e81c88 --- /dev/null +++ b/src/Test/Unit/Block/Adminhtml/System/Config/Form/Fieldset/SitesTest.php @@ -0,0 +1,130 @@ +objectManager->getObject( + \RetailCrm\Response\ApiResponse::class, + [ + 'statusCode' => $isSuccessful ? 200 : 404, + 'responseBody' => json_encode($this->getTestResponse()) + ] + ); + + // api client mock + $client = $this->getMockBuilder(\Retailcrm\Retailcrm\Helper\Proxy::class) + ->disableOriginalConstructor() + ->setMethods( + [ + 'isConfigured', + 'sitesList' + ] + ) + ->getMock(); + $client->expects($this->any()) + ->method('isConfigured') + ->willReturn($isConfigured); + $client->expects($this->any()) + ->method('sitesList') + ->willReturn($response); + + $websiteMock = $this->createMock(\Magento\Store\Model\Website::class); + $websiteMock->expects($this->any())->method('getStores')->willReturn($this->getTestStores()); + + // payment config mock + $storeManager = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); + $storeManager->expects($this->any()) + ->method('getWebsite') + ->willReturn($websiteMock); + + $data = [ + 'authSession' => $this->authSessionMock, + 'jsHelper' => $this->helperMock, + 'data' => ['group' => $this->groupMock], + 'client' => $client, + 'storeManager' => $storeManager, + 'context' => $this->context + ]; + + $sites = $this->objectManager->getObject( + \Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Fieldset\Sites::class, + $data + ); + + $sites->setForm($this->form); + $sites->setLayout($this->layoutMock); + + $html = $sites->render($this->elementMock); + + $this->assertContains($this->testElementId, $html); + $this->assertContains($this->testFieldSetCss, $html); + + if (!$isConfigured) { + $expected = '
Please check your API Url & API Key
'; + $this->assertContains($expected, $html); + } + } + + protected function getTestStores() + { + $store = $this->getMockBuilder(\Magento\Store\Model\Store::class) + ->disableOriginalConstructor() + ->getMock(); + + $store->expects($this->any()) + ->method('getName') + ->willReturn('Test Store'); + + $store->expects($this->any()) + ->method('getCode') + ->willReturn('test_store_code'); + + return ['test_site' => $store]; + } + + private function getTestResponse() + { + return [ + 'success' => true, + 'sites' => [ + [ + 'code' => 'payment', + 'name' => 'Test site' + ] + ] + ]; + } + + public function dataProvider() + { + return [ + [ + 'is_successful' => true, + 'is_configured' => true + ], + [ + 'is_successful' => false, + 'is_configured' => false + ], + [ + 'is_successful' => true, + 'is_configured' => false + ], + [ + 'is_successful' => false, + 'is_configured' => true + ] + ]; + } +} diff --git a/src/Test/Unit/Block/Adminhtml/System/Config/Form/Fieldset/StatusTest.php b/src/Test/Unit/Block/Adminhtml/System/Config/Form/Fieldset/StatusTest.php new file mode 100644 index 0000000..16da0ff --- /dev/null +++ b/src/Test/Unit/Block/Adminhtml/System/Config/Form/Fieldset/StatusTest.php @@ -0,0 +1,120 @@ +objectManager->getObject( + \RetailCrm\Response\ApiResponse::class, + [ + 'statusCode' => $isSuccessful ? 200 : 404, + 'responseBody' => json_encode($this->getTestResponse()) + ] + ); + + // api client mock + $client = $this->getMockBuilder(\Retailcrm\Retailcrm\Helper\Proxy::class) + ->disableOriginalConstructor() + ->setMethods( + [ + 'isConfigured', + 'statusesList' + ] + ) + ->getMock(); + $client->expects($this->any()) + ->method('isConfigured') + ->willReturn($isConfigured); + $client->expects($this->any()) + ->method('statusesList') + ->willReturn($response); + + // status collection mock + $statusCollection = $this->getMockBuilder(\Magento\Sales\Model\ResourceModel\Order\Status\Collection::class) + ->disableOriginalConstructor() + ->getMock(); + $statusCollection->expects($this->any()) + ->method('toOptionArray') + ->willReturn($this->getTestStatuses()); + + $data = [ + 'authSession' => $this->authSessionMock, + 'jsHelper' => $this->helperMock, + 'data' => ['group' => $this->groupMock], + 'client' => $client, + 'statusCollection' => $statusCollection, + 'context' => $this->context + ]; + + $status = $this->objectManager->getObject( + \Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Fieldset\Status::class, + $data + ); + + $status->setForm($this->form); + $status->setLayout($this->layoutMock); + + $html = $status->render($this->elementMock); + + $this->assertContains($this->testElementId, $html); + $this->assertContains($this->testFieldSetCss, $html); + + if (!$isConfigured) { + $expected = '
Please check your API Url & API Key
'; + $this->assertContains($expected, $html); + } + } + + protected function getTestStatuses() + { + $status = [ + 'label' => 'Test Status', + 'value' => 'Test status' + ]; + + return ['test_status' => $status]; + } + + private function getTestResponse() + { + return [ + 'success' => true, + 'statuses' => [ + [ + 'code' => 'status', + 'name' => 'Test status' + ] + ] + ]; + } + + public function dataProvider() + { + return [ + [ + 'is_successful' => true, + 'is_configured' => true + ], + [ + 'is_successful' => false, + 'is_configured' => false + ], + [ + 'is_successful' => true, + 'is_configured' => false + ], + [ + 'is_successful' => false, + 'is_configured' => true + ] + ]; + } +} diff --git a/Test/Unit/Observer/CustomerTest.php b/src/Test/Unit/Model/Observer/CustomerTest.php similarity index 56% rename from Test/Unit/Observer/CustomerTest.php rename to src/Test/Unit/Model/Observer/CustomerTest.php index e8ae7da..e1bd331 100644 --- a/Test/Unit/Observer/CustomerTest.php +++ b/src/Test/Unit/Model/Observer/CustomerTest.php @@ -4,14 +4,14 @@ namespace Retailcrm\Retailcrm\Test\Unit\Observer; class CustomerTest extends \PHPUnit\Framework\TestCase { - protected $mockApi; - protected $mockResponse; - protected $config; - protected $registry; - protected $mockObserver; - protected $mockEvent; - protected $objectManager; - protected $mockCustomer; + private $mockApi; + private $mockResponse; + private $registry; + private $mockObserver; + private $mockEvent; + private $mockCustomer; + private $unit; + private $helper; public function setUp() { @@ -19,7 +19,9 @@ class CustomerTest extends \PHPUnit\Framework\TestCase ->disableOriginalConstructor() ->setMethods([ 'customersEdit', - 'customersCreate' + 'customersCreate', + 'isConfigured', + 'setSite' ]) ->getMock(); @@ -28,9 +30,6 @@ class CustomerTest extends \PHPUnit\Framework\TestCase ->setMethods(['isSuccessful']) ->getMock(); - $this->config = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) - ->getMockForAbstractClass(); - $this->registry = $this->getMockBuilder(\Magento\Framework\Registry::class) ->disableOriginalConstructor() ->getMock(); @@ -44,9 +43,6 @@ class CustomerTest extends \PHPUnit\Framework\TestCase ->setMethods(['getCustomer']) ->getMock(); - $this->objectManager = $this->getMockBuilder(\Magento\Framework\ObjectManagerInterface::class) - ->getMockForAbstractClass(); - $this->mockCustomer = $this->getMockBuilder(\Magento\Customer\Model\Customer::class) ->disableOriginalConstructor() ->setMethods([ @@ -54,28 +50,28 @@ class CustomerTest extends \PHPUnit\Framework\TestCase 'getEmail', 'getFirstname', 'getMiddlename', - 'getLastname' + 'getLastname', + 'getStore' ]) ->getMock(); - $this->unit = new \Retailcrm\Retailcrm\Model\Observer\Customer( - $this->objectManager, - $this->config, - $this->registry - ); + $this->helper = $this->createMock(\Retailcrm\Retailcrm\Helper\Data::class); - $reflection = new \ReflectionClass($this->unit); - $reflection_property = $reflection->getProperty('_api'); - $reflection_property->setAccessible(true); - $reflection_property->setValue($this->unit, $this->mockApi); + $this->unit = new \Retailcrm\Retailcrm\Model\Observer\Customer( + $this->registry, + $this->helper, + $this->mockApi + ); } /** * @param boolean $isSuccessful + * @param boolean $isConfigured * @dataProvider dataProviderCustomer */ public function testExecute( - $isSuccessful + $isSuccessful, + $isConfigured ) { $testData = $this->getAfterSaveCustomerTestData(); @@ -95,46 +91,69 @@ class CustomerTest extends \PHPUnit\Framework\TestCase ->method('customersCreate') ->willReturn($this->mockResponse); + $this->mockApi->expects($this->any()) + ->method('isConfigured') + ->willReturn($isConfigured); + // mock Customer - $this->mockCustomer->expects($this->once()) + $this->mockCustomer->expects($this->any()) ->method('getId') ->willReturn($testData['id']); - $this->mockCustomer->expects($this->once()) + $this->mockCustomer->expects($this->any()) ->method('getEmail') ->willReturn($testData['email']); - $this->mockCustomer->expects($this->once()) + $this->mockCustomer->expects($this->any()) ->method('getFirstname') ->willReturn($testData['firstname']); - $this->mockCustomer->expects($this->once()) + $this->mockCustomer->expects($this->any()) ->method('getMiddlename') ->willReturn($testData['middlename']); - $this->mockCustomer->expects($this->once()) + $this->mockCustomer->expects($this->any()) ->method('getLastname') ->willReturn($testData['lastname']); + $store = $this->createMock(\Magento\Store\Model\Store::class); + + $this->mockCustomer->expects($this->any()) + ->method('getStore') + ->willReturn($store); + // mock Event - $this->mockEvent->expects($this->once()) + $this->mockEvent->expects($this->any()) ->method('getCustomer') ->willReturn($this->mockCustomer); // mock Observer - $this->mockObserver->expects($this->once()) + $this->mockObserver->expects($this->any()) ->method('getEvent') ->willReturn($this->mockEvent); - $this->unit->execute($this->mockObserver); + $customerObserver = $this->unit->execute($this->mockObserver); + + if ($isConfigured) { + $this->assertNotEmpty($this->unit->getCustomer()); + $this->assertArrayHasKey('externalId', $this->unit->getCustomer()); + $this->assertArrayHasKey('email', $this->unit->getCustomer()); + $this->assertArrayHasKey('firstName', $this->unit->getCustomer()); + $this->assertArrayHasKey('lastName', $this->unit->getCustomer()); + $this->assertArrayHasKey('patronymic', $this->unit->getCustomer()); + $this->assertArrayHasKey('createdAt', $this->unit->getCustomer()); + $this->assertInstanceOf(\RetailCrm\Retailcrm\Model\Observer\Customer::class, $customerObserver); + } else { + $this->assertEmpty($this->unit->getCustomer()); + } } /** * Get test customer data - * + * * @return array */ - protected function getAfterSaveCustomerTestData() + private function getAfterSaveCustomerTestData() { return [ 'id' => 1, @@ -149,10 +168,20 @@ class CustomerTest extends \PHPUnit\Framework\TestCase { return [ [ - 'is_successful' => true + 'is_successful' => true, + 'is_configured' => true ], [ - 'is_successful' => false + 'is_successful' => false, + 'is_configured' => false + ], + [ + 'is_successful' => false, + 'is_configured' => true + ], + [ + 'is_successful' => true, + 'is_configured' => false ] ]; } diff --git a/Test/Unit/Observer/OrderCreateTest.php b/src/Test/Unit/Model/Observer/OrderCreateTest.php similarity index 56% rename from Test/Unit/Observer/OrderCreateTest.php rename to src/Test/Unit/Model/Observer/OrderCreateTest.php index 9be435f..143528e 100644 --- a/Test/Unit/Observer/OrderCreateTest.php +++ b/src/Test/Unit/Model/Observer/OrderCreateTest.php @@ -7,24 +7,24 @@ namespace Retailcrm\Retailcrm\Test\Unit\Observer; */ class OrderCreateTest extends \PHPUnit\Framework\TestCase { - protected $objectManager; - protected $_config; - protected $_unit; - protected $_mockEvent; - protected $_mockObserver; - protected $_registry; - protected $_mockApi; - protected $_mockOrder; - protected $_mockItem; - protected $_mockStore; - protected $_mockBillingAddress; - protected $_mockResponse; - protected $_mockPayment; - protected $_mockPaymentMethod; + private $config; + private $unit; + private $mockEvent; + private $mockObserver; + private $registry; + private $mockApi; + private $mockOrder; + private $mockItem; + private $mockStore; + private $mockBillingAddress; + private $mockResponse; + private $mockPayment; + private $mockPaymentMethod; + private $logger; - protected function setUp() + public function setUp() { - $this->_mockApi = $this->getMockBuilder(\Retailcrm\Retailcrm\Helper\Proxy::class) + $this->mockApi = $this->getMockBuilder(\Retailcrm\Retailcrm\Helper\Proxy::class) ->disableOriginalConstructor() ->setMethods([ 'ordersGet', @@ -32,43 +32,33 @@ class OrderCreateTest extends \PHPUnit\Framework\TestCase 'customersGet', 'customersCreate', 'customersList', - 'getVersion' + 'getVersion', + 'isConfigured', + 'setSite' ]) ->getMock(); - $this->_mockObserver = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) + $this->mockObserver = $this->getMockBuilder(\Magento\Framework\Event\Observer::class) ->disableOriginalConstructor() ->getMock(); - $this->_mockEvent = $this->getMockBuilder(\Magento\Framework\Event::class) + $this->mockEvent = $this->getMockBuilder(\Magento\Framework\Event::class) ->disableOriginalConstructor() ->setMethods(['getOrder']) ->getMock(); - - $this->objectManager = $this->getMockBuilder(\Magento\Framework\ObjectManagerInterface::class) - ->getMockForAbstractClass(); - - // mock Object Manager - $this->objectManager->expects($this->any()) - ->method('get') - ->with($this->logicalOr( - $this->equalTo('\Retailcrm\Retailcrm\Helper\Data'), - $this->equalTo('\Retailcrm\Retailcrm\Model\Logger\Logger') - )) - ->will($this->returnCallback([$this, 'getCallbackDataClasses'])); - $this->_config = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $this->config = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) ->getMockForAbstractClass(); - $this->_logger = $this->getMockBuilder(\Retailcrm\Retailcrm\Model\Logger\Logger::class) + $this->logger = $this->getMockBuilder(\Retailcrm\Retailcrm\Model\Logger\Logger::class) ->disableOriginalConstructor() ->getMock(); - $this->_registry = $this->getMockBuilder(\Magento\Framework\Registry::class) + $this->registry = $this->getMockBuilder(\Magento\Framework\Registry::class) ->disableOriginalConstructor() ->getMock(); - $this->_mockOrder = $this->getMockBuilder(\Magento\Sales\Order::class) + $this->mockOrder = $this->getMockBuilder(\Magento\Sales\Order::class) ->setMethods([ 'getId', 'getRealOrderId', @@ -91,16 +81,16 @@ class OrderCreateTest extends \PHPUnit\Framework\TestCase ]) ->getMock(); - $this->_mockPayment = $this->getMockBuilder(\Magento\Sales\Model\Order\Payment::class) + $this->mockPayment = $this->getMockBuilder(\Magento\Sales\Model\Order\Payment::class) ->setMethods(['getMethodInstance']) ->disableOriginalConstructor() ->getMock(); - $this->_mockPaymentMethod = $this->getMockBuilder(\Magento\Payment\Model\MethodInterface::class) + $this->mockPaymentMethod = $this->getMockBuilder(\Magento\Payment\Model\MethodInterface::class) ->disableOriginalConstructor() ->getMockForAbstractClass(); - $this->_mockItem = $this->getMockBuilder(\Magento\Sales\Model\Order\Item::class) + $this->mockItem = $this->getMockBuilder(\Magento\Sales\Model\Order\Item::class) ->disableOriginalConstructor() ->setMethods([ 'getPrice', @@ -111,31 +101,35 @@ class OrderCreateTest extends \PHPUnit\Framework\TestCase ]) ->getMock(); - $this->_mockStore = $this->getMockBuilder(\Magento\Store\Model\Store::class) + $this->mockStore = $this->getMockBuilder(\Magento\Store\Model\Store::class) ->disableOriginalConstructor() ->setMethods(['getCode']) ->getMock(); - $this->_mockBillingAddress = $this->getMockBuilder(\Magento\Customer\Model\Address\AddressModelInterface::class) + $this->mockBillingAddress = $this->getMockBuilder(\Magento\Customer\Model\Address\AddressModelInterface::class) ->disableOriginalConstructor() ->setMethods(['getTelephone', 'getData']) ->getMockForAbstractClass(); - $this->_mockResponse = $this->getMockBuilder(\RetailCrm\Response\ApiResponse::class) + $this->mockResponse = $this->getMockBuilder(\RetailCrm\Response\ApiResponse::class) ->disableOriginalConstructor() ->setMethods(['isSuccessful']) ->getMock(); - $this->_unit = new \Retailcrm\Retailcrm\Model\Observer\OrderCreate( - $this->objectManager, - $this->_config, - $this->_registry - ); + $product = $this->getMockBuilder(\Magento\Catalog\Model\ProductRepository::class) + ->disableOriginalConstructor() + ->getMock(); - $reflection = new \ReflectionClass($this->_unit); - $reflection_property = $reflection->getProperty('_api'); - $reflection_property->setAccessible(true); - $reflection_property->setValue($this->_unit, $this->_mockApi); + $helper = $this->createMock(\Retailcrm\Retailcrm\Helper\Data::class); + + $this->unit = new \Retailcrm\Retailcrm\Model\Observer\OrderCreate( + $this->config, + $this->registry, + $this->logger, + $product, + $helper, + $this->mockApi + ); } /** @@ -143,54 +137,60 @@ class OrderCreateTest extends \PHPUnit\Framework\TestCase * @param string $errorMsg * @param int $customerIsGuest * @param string $apiVersion + * @param boolean $isConfigured * @dataProvider dataProviderOrderCreate */ public function testExecute( $isSuccessful, $errorMsg, $customerIsGuest, - $apiVersion + $apiVersion, + $isConfigured ) { $testData = $this->getAfterSaveOrderTestData(); // mock Response - $this->_mockResponse->expects($this->any()) + $this->mockResponse->expects($this->any()) ->method('isSuccessful') ->willReturn($isSuccessful); - $this->_mockResponse->errorMsg = $errorMsg; + $this->mockResponse->errorMsg = $errorMsg; // mock API - $this->_mockApi->expects($this->any()) + $this->mockApi->expects($this->any()) ->method('ordersGet') - ->willReturn($this->_mockResponse); + ->willReturn($this->mockResponse); - $this->_mockApi->expects($this->any()) + $this->mockApi->expects($this->any()) ->method('ordersCreate') - ->willReturn($this->_mockResponse); + ->willReturn($this->mockResponse); - $this->_mockApi->expects($this->any()) + $this->mockApi->expects($this->any()) ->method('customersGet') - ->willReturn($this->_mockResponse); + ->willReturn($this->mockResponse); - $this->_mockApi->expects($this->any()) + $this->mockApi->expects($this->any()) ->method('customersCreate') - ->willReturn($this->_mockResponse); + ->willReturn($this->mockResponse); - $this->_mockApi->expects($this->any()) + $this->mockApi->expects($this->any()) ->method('customersList') - ->willReturn($this->_mockResponse); + ->willReturn($this->mockResponse); - $this->_mockApi->expects($this->any()) + $this->mockApi->expects($this->any()) ->method('getVersion') ->willReturn($apiVersion); + $this->mockApi->expects($this->any()) + ->method('isConfigured') + ->willReturn($isConfigured); + // billing address mock set data - $this->_mockBillingAddress->expects($this->any()) + $this->mockBillingAddress->expects($this->any()) ->method('getTelephone') ->willReturn($testData['order.billingAddress']['telephone']); - $this->_mockBillingAddress->expects($this->any()) + $this->mockBillingAddress->expects($this->any()) ->method('getData') ->with($this->logicalOr( $this->equalTo('city'), @@ -202,121 +202,146 @@ class OrderCreateTest extends \PHPUnit\Framework\TestCase ->will($this->returnCallback([$this, 'getCallbackDataAddress'])); // store mock set data - $this->_mockStore->expects($this->any()) + $this->mockStore->expects($this->any()) ->method('getCode') ->willReturn(1); // order item mock set data - $this->_mockItem->expects($this->any()) + $this->mockItem->expects($this->any()) ->method('getProductType') ->willReturn('simple'); - $this->_mockItem->expects($this->any()) + $this->mockItem->expects($this->any()) ->method('getPrice') ->willReturn(999.99); - $this->_mockItem->expects($this->any()) + $this->mockItem->expects($this->any()) ->method('getProductId') ->willReturn(10); - $this->_mockItem->expects($this->any()) + $this->mockItem->expects($this->any()) ->method('getName') ->willReturn('Product name'); - $this->_mockItem->expects($this->any()) + $this->mockItem->expects($this->any()) ->method('getQtyOrdered') ->willReturn(3); // order mock set data - $this->_mockOrder->expects($this->any()) + $this->mockOrder->expects($this->any()) ->method('getId') ->willReturn($testData['order.id']); - $this->_mockOrder->expects($this->any()) + $this->mockOrder->expects($this->any()) ->method('getBillingAddress') - ->willReturn($this->_mockBillingAddress); + ->willReturn($this->mockBillingAddress); - $this->_mockOrder->expects($this->any()) + $this->mockOrder->expects($this->any()) ->method('getShippingMethod') ->willReturn($testData['order.shippingMethod']); - $this->_mockOrder->expects($this->any()) + $this->mockOrder->expects($this->any()) ->method('getStore') - ->willReturn($this->_mockStore); + ->willReturn($this->mockStore); - $this->_mockOrder->expects($this->any()) + $this->mockOrder->expects($this->any()) ->method('getRealOrderId') ->willReturn($testData['order.realOrderId']); - $this->_mockOrder->expects($this->any()) + $this->mockOrder->expects($this->any()) ->method('getCreatedAt') ->willReturn(date('Y-m-d H:i:s')); - $this->_mockOrder->expects($this->any()) + $this->mockOrder->expects($this->any()) ->method('getCustomerLastname') ->willReturn($testData['order.customerLastname']); - $this->_mockOrder->expects($this->any()) + $this->mockOrder->expects($this->any()) ->method('getCustomerFirstname') ->willReturn($testData['order.customerFirstname']); - $this->_mockOrder->expects($this->any()) + $this->mockOrder->expects($this->any()) ->method('getCustomerMiddlename') ->willReturn($testData['order.customerMiddlename']); - $this->_mockOrder->expects($this->any()) + $this->mockOrder->expects($this->any()) ->method('getCustomerEmail') ->willReturn($testData['order.customerEmail']); - $this->_mockOrder->expects($this->any()) + $this->mockOrder->expects($this->any()) ->method('getAllItems') ->willReturn($testData['order.allItems']); - $this->_mockOrder->expects($this->any()) + $this->mockOrder->expects($this->any()) ->method('getStatus') ->willReturn($testData['order.status']); - $this->_mockOrder->expects($this->any()) + $this->mockOrder->expects($this->any()) ->method('getCustomerIsGuest') ->willReturn($customerIsGuest); - $this->_mockOrder->expects($this->any()) + $this->mockOrder->expects($this->any()) ->method('getCustomerId') ->willReturn(1); - $this->_mockOrder->expects($this->any()) + $this->mockOrder->expects($this->any()) ->method('getPayment') - ->willReturn($this->_mockPayment); + ->willReturn($this->mockPayment); // mock Payment Method - $this->_mockPaymentMethod->expects($this->any()) + $this->mockPaymentMethod->expects($this->any()) ->method('getCode') ->willReturn($testData['order.paymentMethod']); // mock Payment - $this->_mockPayment->expects($this->any()) + $this->mockPayment->expects($this->any()) ->method('getMethodInstance') - ->willReturn($this->_mockPaymentMethod); + ->willReturn($this->mockPaymentMethod); // mock Event - $this->_mockEvent->expects($this->once()) + $this->mockEvent->expects($this->any()) ->method('getOrder') - ->willReturn($this->_mockOrder); + ->willReturn($this->mockOrder); // mock Observer - $this->_mockObserver->expects($this->once()) + $this->mockObserver->expects($this->any()) ->method('getEvent') - ->willReturn($this->_mockEvent); + ->willReturn($this->mockEvent); - $this->_unit->execute($this->_mockObserver); + $orderCreateObserver = $this->unit->execute($this->mockObserver); + + if ($isConfigured && !$isSuccessful) { + $this->assertNotEmpty($this->unit->getOrder()); + $this->assertArrayHasKey('externalId', $this->unit->getOrder()); + $this->assertArrayHasKey('number', $this->unit->getOrder()); + $this->assertArrayHasKey('createdAt', $this->unit->getOrder()); + $this->assertArrayHasKey('lastName', $this->unit->getOrder()); + $this->assertArrayHasKey('firstName', $this->unit->getOrder()); + $this->assertArrayHasKey('patronymic', $this->unit->getOrder()); + $this->assertArrayHasKey('email', $this->unit->getOrder()); + $this->assertArrayHasKey('phone', $this->unit->getOrder()); +// $this->assertArrayHasKey('status', $this->unit->getOrder()); + $this->assertArrayHasKey('items', $this->unit->getOrder()); + $this->assertArrayHasKey('delivery', $this->unit->getOrder()); + + if ($apiVersion == 'v5') { + $this->assertArrayHasKey('payments', $this->unit->getOrder()); + } else { + $this->assertArrayHasKey('paymentType', $this->unit->getOrder()); + } + + $this->assertInstanceOf(\Retailcrm\Retailcrm\Model\Observer\OrderCreate::class, $orderCreateObserver); + } elseif (!$isConfigured || $isSuccessful) { + $this->assertEmpty($this->unit->getOrder()); + } } /** * Get test order data - * + * * @return array $testOrderData */ - protected function getAfterSaveOrderTestData() + private function getAfterSaveOrderTestData() { $testOrderData = [ 'order.id' => 1, @@ -332,7 +357,7 @@ class OrderCreateTest extends \PHPUnit\Framework\TestCase 'country_id' => 'RU' ] ], - 'order.allItems' => [$this->_mockItem], + 'order.allItems' => [$this->mockItem], 'order.shippingMethod' => 'flatrate_flatrate', 'order.paymentMethod' => 'checkmo', 'order.customerLastname' => 'Test', @@ -377,49 +402,57 @@ class OrderCreateTest extends \PHPUnit\Framework\TestCase 'is_successful' => true, 'error_msg' => 'Not found', 'customer_is_guest' => 1, - 'api_version' => 'v4' + 'api_version' => 'v4', + 'is_configured' => true ], [ 'is_successful' => true, 'error_msg' => 'Not found', 'customer_is_guest' => 0, - 'api_version' => 'v4' + 'api_version' => 'v4', + 'is_configured' => false ], [ 'is_successful' => false, 'error_msg' => 'Not found', 'customer_is_guest' => 1, - 'api_version' => 'v4' + 'api_version' => 'v4', + 'is_configured' => true ], [ 'is_successful' => false, 'error_msg' => 'Not found', 'customer_is_guest' => 0, - 'api_version' => 'v4' + 'api_version' => 'v4', + 'is_configured' => false ], [ 'is_successful' => true, 'error_msg' => 'Not found', 'customer_is_guest' => 1, - 'api_version' => 'v5' + 'api_version' => 'v5', + 'is_configured' => true ], [ 'is_successful' => true, 'error_msg' => 'Not found', 'customer_is_guest' => 0, - 'api_version' => 'v5' + 'api_version' => 'v5', + 'is_configured' => false ], [ 'is_successful' => false, 'error_msg' => 'Not found', 'customer_is_guest' => 1, - 'api_version' => 'v5' + 'api_version' => 'v5', + 'is_configured' => true ], [ 'is_successful' => false, 'error_msg' => 'Not found', 'customer_is_guest' => 0, - 'api_version' => 'v5' + 'api_version' => 'v5', + 'is_configured' => false ] ]; } diff --git a/Test/Unit/Observer/OrderUpdateTest.php b/src/Test/Unit/Model/Observer/OrderUpdateTest.php similarity index 62% rename from Test/Unit/Observer/OrderUpdateTest.php rename to src/Test/Unit/Model/Observer/OrderUpdateTest.php index 1c3709a..6ece21b 100644 --- a/Test/Unit/Observer/OrderUpdateTest.php +++ b/src/Test/Unit/Model/Observer/OrderUpdateTest.php @@ -4,24 +4,26 @@ namespace Retailcrm\Retailcrm\Test\Unit\Observer; class OrderUpdateTest extends \PHPUnit\Framework\TestCase { - protected $unit; - protected $objectManager; - protected $config; - protected $mockApi; - protected $mockObserver; - protected $mockEvent; - protected $mockOrder; - protected $mockPayment; - protected $registry; + private $unit; + private $objectManager; + private $config; + private $mockApi; + private $mockObserver; + private $mockEvent; + private $mockOrder; + private $mockPayment; + private $registry; - protected function setUp() + public function setUp() { $this->mockApi = $this->getMockBuilder(\Retailcrm\Retailcrm\Helper\Proxy::class) ->disableOriginalConstructor() ->setMethods([ 'ordersEdit', 'ordersPaymentsEdit', - 'getVersion' + 'getVersion', + 'isConfigured', + 'setSite' ]) ->getMock(); @@ -37,16 +39,14 @@ class OrderUpdateTest extends \PHPUnit\Framework\TestCase $this->objectManager = $this->getMockBuilder(\Magento\Framework\ObjectManagerInterface::class) ->getMockForAbstractClass(); - $helper = $this->getMockBuilder(\Retailcrm\Retailcrm\Helper\Data::class) + $this->mockOrder = $this->getMockBuilder(\Magento\Sales\Model\Order::class) ->disableOriginalConstructor() - ->getMock(); - - $this->mockOrder = $this->getMockBuilder(\Magento\Sales\Order::class) ->setMethods([ 'getId', 'getPayment', 'getBaseTotalDue', - 'getStatus' + 'getStatus', + 'getStore' ]) ->getMock(); @@ -55,12 +55,6 @@ class OrderUpdateTest extends \PHPUnit\Framework\TestCase ->disableOriginalConstructor() ->getMock(); - // mock Object Manager - $this->objectManager->expects($this->any()) - ->method('get') - ->with('\Retailcrm\Retailcrm\Helper\Data') - ->willReturn($helper); - $this->config = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) ->getMockForAbstractClass(); @@ -68,26 +62,26 @@ class OrderUpdateTest extends \PHPUnit\Framework\TestCase ->disableOriginalConstructor() ->getMock(); - $this->unit = new \Retailcrm\Retailcrm\Model\Observer\OrderUpdate( - $this->objectManager, - $this->config, - $this->registry - ); + $helper = $this->createMock(\Retailcrm\Retailcrm\Helper\Data::class); - $reflection = new \ReflectionClass($this->unit); - $reflection_property = $reflection->getProperty('_api'); - $reflection_property->setAccessible(true); - $reflection_property->setValue($this->unit, $this->mockApi); + $this->unit = new \Retailcrm\Retailcrm\Model\Observer\OrderUpdate( + $this->config, + $this->registry, + $helper, + $this->mockApi + ); } /** * @param int $getBaseTotalDue * @param string $apiVersion + * @param boolean $isConfigured * @dataProvider dataProviderOrderUpdate */ public function testExecute( $getBaseTotalDue, - $apiVersion + $apiVersion, + $isConfigured ) { $testData = $this->getAfterUpdateOrderTestData(); @@ -97,15 +91,15 @@ class OrderUpdateTest extends \PHPUnit\Framework\TestCase ->willReturn(1); // mock Order - $this->mockOrder->expects($this->once()) + $this->mockOrder->expects($this->any()) ->method('getId') ->willReturn($testData['order.id']); - $this->mockOrder->expects($this->once()) + $this->mockOrder->expects($this->any()) ->method('getStatus') ->willReturn($testData['order.status']); - $this->mockOrder->expects($this->once()) + $this->mockOrder->expects($this->any()) ->method('getBaseTotalDue') ->willReturn($getBaseTotalDue); @@ -113,30 +107,51 @@ class OrderUpdateTest extends \PHPUnit\Framework\TestCase ->method('getPayment') ->willReturn($this->mockPayment); + $store = $this->createMock(\Magento\Store\Model\Store::class); + + $this->mockOrder->expects($this->any()) + ->method('getStore') + ->willReturn($store); + // mock Api $this->mockApi->expects($this->any()) ->method('getVersion') ->willReturn($apiVersion); + $this->mockApi->expects($this->any()) + ->method('isConfigured') + ->willReturn($isConfigured); + // mock Event - $this->mockEvent->expects($this->once()) + $this->mockEvent->expects($this->any()) ->method('getOrder') ->willReturn($this->mockOrder); // mock Observer - $this->mockObserver->expects($this->once()) + $this->mockObserver->expects($this->any()) ->method('getEvent') ->willReturn($this->mockEvent); - $this->unit->execute($this->mockObserver); + $updateOrderObserver = $this->unit->execute($this->mockObserver); + + if ($isConfigured) { + $this->assertNotEmpty($this->unit->getOrder()); + $this->assertArrayHasKey('externalId', $this->unit->getOrder()); + $this->assertArrayHasKey('status', $this->unit->getOrder()); + $this->assertInstanceOf( + \Retailcrm\Retailcrm\Model\Observer\OrderUpdate::class, + $updateOrderObserver + ); + } else { + $this->assertEmpty($this->unit->getOrder()); + } } /** * Get test order data - * * @return array $testOrderData */ - protected function getAfterUpdateOrderTestData() + private function getAfterUpdateOrderTestData() { $testOrderData = [ 'order.id' => 1, @@ -152,19 +167,23 @@ class OrderUpdateTest extends \PHPUnit\Framework\TestCase return [ [ 'get_base_total_due' => 0, - 'api_version' => 'v4' + 'api_version' => 'v4', + 'is_configured' => false ], [ 'get_base_total_due' => 1, - 'api_version' => 'v4' + 'api_version' => 'v4', + 'is_configured' => true ], [ 'get_base_total_due' => 0, - 'api_version' => 'v5' + 'api_version' => 'v5', + 'is_configured' => true ], [ 'get_base_total_due' => 1, - 'api_version' => 'v5' + 'api_version' => 'v5', + 'is_configured' => false ] ]; } diff --git a/composer.json b/src/composer.json similarity index 88% rename from composer.json rename to src/composer.json index ea887e9..bc6ba84 100644 --- a/composer.json +++ b/src/composer.json @@ -2,7 +2,6 @@ "name": "retailcrm/retailcrm", "description": "Retailcrm", "require": { - "php": "~5.5.0|~5.6.0|~7.0.0", "retailcrm/api-client-php": "~5.0" }, "type": "magento2-module", @@ -13,7 +12,7 @@ ], "authors": [ { - "name": "Retailcrm", + "name": "RetailDriver LLC", "email": "gorokh@retailcrm.ru", "homepage": "https://www.retailcrm.ru", "role": "Developer" diff --git a/etc/adminhtml/menu.xml b/src/etc/adminhtml/menu.xml similarity index 100% rename from etc/adminhtml/menu.xml rename to src/etc/adminhtml/menu.xml diff --git a/etc/adminhtml/routes.xml b/src/etc/adminhtml/routes.xml similarity index 100% rename from etc/adminhtml/routes.xml rename to src/etc/adminhtml/routes.xml diff --git a/src/etc/adminhtml/system.xml b/src/etc/adminhtml/system.xml new file mode 100644 index 0000000..b1868a6 --- /dev/null +++ b/src/etc/adminhtml/system.xml @@ -0,0 +1,79 @@ + + + + + + +
+ separator-top + + retailcrm + Retailcrm_Retailcrm::retailcrm_configuration + + + + + + https://YourCrmName.retailcrm.ru + Retailcrm\Retailcrm\Model\Config\Backend\ApiUrl + + + + + To generate an API Key, log in to RetailCRM then select Admin > Integration > API Keys + + + + + Retailcrm\Retailcrm\Model\Setting\ApiVersions + Retailcrm\Retailcrm\Model\Config\Backend\ApiVersion + + + + + + + + Attributes to export into icml + Retailcrm\Retailcrm\Model\Setting\Attribute + + + + + + Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Fieldset\Shipping + + + + + Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Fieldset\Payment + + + + + Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Fieldset\Status + + + + + + + Enter your order number, separated by commas + + + Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Button + + + + + + Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Fieldset\Site + + + + + Retailcrm\Retailcrm\Block\Adminhtml\System\Config\Form\Fieldset\Sites + +
+
+
diff --git a/etc/config.xml b/src/etc/config.xml similarity index 97% rename from etc/config.xml rename to src/etc/config.xml index c35267a..3889d33 100644 --- a/etc/config.xml +++ b/src/etc/config.xml @@ -12,4 +12,4 @@ - \ No newline at end of file + diff --git a/etc/country.xml b/src/etc/country.xml similarity index 100% rename from etc/country.xml rename to src/etc/country.xml diff --git a/etc/crontab.xml b/src/etc/crontab.xml similarity index 100% rename from etc/crontab.xml rename to src/etc/crontab.xml diff --git a/src/etc/di.xml b/src/etc/di.xml new file mode 100644 index 0000000..43ec649 --- /dev/null +++ b/src/etc/di.xml @@ -0,0 +1,11 @@ + + + + + + Retailcrm\Retailcrm\Api\ConfigManagerInterface::URL_PATH + Retailcrm\Retailcrm\Api\ConfigManagerInterface::KEY_PATH + Retailcrm\Retailcrm\Api\ConfigManagerInterface::API_VERSION_PATH + + + diff --git a/etc/events.xml b/src/etc/events.xml similarity index 100% rename from etc/events.xml rename to src/etc/events.xml diff --git a/etc/frontend/events.xml b/src/etc/frontend/events.xml similarity index 100% rename from etc/frontend/events.xml rename to src/etc/frontend/events.xml diff --git a/etc/frontend/routes.xml b/src/etc/frontend/routes.xml similarity index 100% rename from etc/frontend/routes.xml rename to src/etc/frontend/routes.xml diff --git a/etc/module.xml b/src/etc/module.xml similarity index 100% rename from etc/module.xml rename to src/etc/module.xml diff --git a/src/registration.php b/src/registration.php new file mode 100644 index 0000000..d618979 --- /dev/null +++ b/src/registration.php @@ -0,0 +1,6 @@ +