From 2981afb05a09ad0f4188cea2f3cd10e03ecbeb95 Mon Sep 17 00:00:00 2001 From: Akolzin Dmitry Date: Fri, 7 Aug 2020 12:39:59 +0300 Subject: [PATCH] Corporate clients support & ability to change customer --- .docker/Dockerfile | 32 +- .docker/entrypoint.sh | 26 + .env-dist | 2 +- .travis.yml | 2 +- Makefile | 11 +- composer.json | 7 +- docker-compose.yml | 39 +- phpunit.xml.dist | 10 +- .../controller/extension/module/retailcrm.php | 255 +-- .../en-gb/extension/module/retailcrm.php | 1 + .../es-es/extension/module/retailcrm.php | 1 + .../ru-ru/extension/module/retailcrm.php | 1 + .../model/extension/retailcrm/customer.php | 120 +- .../model/extension/retailcrm/history.php | 464 +++-- .../model/extension/retailcrm/history/v3.php | 117 -- .../extension/retailcrm/history/v4_5.php | 837 -------- .../admin/model/extension/retailcrm/order.php | 316 +-- .../model/extension/retailcrm/references.php | 47 +- .../template/extension/module/retailcrm.tpl | 31 +- .../template/extension/module/retailcrm.twig | 237 +-- .../controller/extension/module/retailcrm.php | 74 +- .../model/extension/retailcrm/customer.php | 104 - .../library/retailcrm/RetailcrmApiClient3.php | 831 -------- .../library/retailcrm/RetailcrmApiClient4.php | 1799 ----------------- .../library/retailcrm/RetailcrmProxy.php | 58 - src/upload/system/library/retailcrm/base.php | 23 + .../system/library/retailcrm/bootstrap.php | 3 +- .../library/retailcrm/lib/ModelsProvider.php | 41 + .../system/library/retailcrm/lib/Utils.php | 34 + .../retailcrm/{ => lib/api}/CurlException.php | 0 .../{ => lib/api}/InvalidJsonException.php | 0 .../{ => lib/api}/OpencartApiClient.php | 0 .../{ => lib/api}/RetailcrmApiClient5.php | 632 +++++- .../{ => lib/api}/RetailcrmApiResponse.php | 0 .../{ => lib/api}/RetailcrmHistoryHelper.php | 0 .../{ => lib/api}/RetailcrmHttpClient.php | 0 .../retailcrm/lib/api/RetailcrmProxy.php | 56 + .../lib/factory/CustomerConverterFactory.php | 12 + .../lib/factory/OrderConverterFactory.php | 18 + .../retailcrm/lib/history/Customer.php | 113 ++ .../library/retailcrm/lib/history/Order.php | 350 ++++ .../lib/repository/CustomerRepository.php | 29 + .../lib/repository/DataRepository.php | 205 ++ .../lib/repository/OrderRepository.php | 29 + .../lib/repository/ProductsRepository.php | 23 + .../lib/service/CorporateCustomer.php | 217 ++ .../lib/service/CorporateCustomerBuilder.php | 109 + .../retailcrm/lib/service/CustomerManager.php | 102 + .../retailcrm/lib/service/OrderManager.php | 173 ++ .../service/RetailcrmCustomerConverter.php | 80 + .../lib/service/RetailcrmOrderConverter.php | 300 +++ .../retailcrm/lib/service/SettingsManager.php | 39 + .../system/library/retailcrm/retailcrm.php | 63 +- tests/2.3/TestCase.php | 53 +- tests/3.0/TestCase.php | 57 +- tests/RoboFile.php | 2 +- tests/admin/ControllerRetailcrmAdminTest.php | 23 +- .../admin/ModelRetailcrmCustomerAdminTest.php | 21 +- tests/admin/ModelRetailcrmOrderAdminTest.php | 127 +- tests/admin/ModelRetailcrmPricesAdminTest.php | 7 +- ...CollectorExtensionAnalyticsCatalogTest.php | 11 + .../ControllerRetailcrmApiCatalogTest.php | 14 - .../ModelRetailcrmCustomerCatalogTest.php | 64 - tests/opencart_sample_data.sql | 3 + tests/opencart_sample_data_3.sql | 3 + tests/system/RetailcrmTest.php | 18 + tests/system/lib/ModelsProviderAdminTest.php | 14 + tests/system/lib/ModelsProviderTest.php | 13 + tests/system/lib/UtilsTest.php | 21 + .../factory/CustomerConverterFactoryTest.php | 11 + .../lib/factory/OrderConverterFactoryTest.php | 11 + .../system/lib/history/CustomerAdminTest.php | 65 + tests/system/lib/history/OrderAdminTest.php | 147 ++ .../CustomerRespositoryAdminTest.php | 17 + .../repository/CustomerRespositoryTest.php | 17 + .../repository/DataRepositoryAdminTest.php | 63 + .../repository/OrderRepositoryAdminTest.php | 22 + .../repository/ProductsRespositoryTest.php | 31 + .../service/CorporateCustomerBuilderTest.php | 37 + .../lib/service/CorporateCustomerTest.php | 107 + .../lib/service/CustomerManagerTest.php | 77 + tests/system/lib/service/OrderManagerTest.php | 250 +++ .../RetailcrmCustomerConverterTest.php | 52 + .../service/RetailcrmOrderConverterTest.php | 134 ++ .../lib/service/SettingsManagerTest.php | 44 + 85 files changed, 4620 insertions(+), 4989 deletions(-) create mode 100644 .docker/entrypoint.sh delete mode 100644 src/upload/admin/model/extension/retailcrm/history/v3.php delete mode 100644 src/upload/admin/model/extension/retailcrm/history/v4_5.php delete mode 100644 src/upload/catalog/model/extension/retailcrm/customer.php delete mode 100644 src/upload/system/library/retailcrm/RetailcrmApiClient3.php delete mode 100644 src/upload/system/library/retailcrm/RetailcrmApiClient4.php delete mode 100644 src/upload/system/library/retailcrm/RetailcrmProxy.php create mode 100644 src/upload/system/library/retailcrm/base.php create mode 100644 src/upload/system/library/retailcrm/lib/ModelsProvider.php create mode 100644 src/upload/system/library/retailcrm/lib/Utils.php rename src/upload/system/library/retailcrm/{ => lib/api}/CurlException.php (100%) rename src/upload/system/library/retailcrm/{ => lib/api}/InvalidJsonException.php (100%) rename src/upload/system/library/retailcrm/{ => lib/api}/OpencartApiClient.php (100%) rename src/upload/system/library/retailcrm/{ => lib/api}/RetailcrmApiClient5.php (77%) rename src/upload/system/library/retailcrm/{ => lib/api}/RetailcrmApiResponse.php (100%) rename src/upload/system/library/retailcrm/{ => lib/api}/RetailcrmHistoryHelper.php (100%) rename src/upload/system/library/retailcrm/{ => lib/api}/RetailcrmHttpClient.php (100%) create mode 100644 src/upload/system/library/retailcrm/lib/api/RetailcrmProxy.php create mode 100644 src/upload/system/library/retailcrm/lib/factory/CustomerConverterFactory.php create mode 100644 src/upload/system/library/retailcrm/lib/factory/OrderConverterFactory.php create mode 100644 src/upload/system/library/retailcrm/lib/history/Customer.php create mode 100644 src/upload/system/library/retailcrm/lib/history/Order.php create mode 100644 src/upload/system/library/retailcrm/lib/repository/CustomerRepository.php create mode 100644 src/upload/system/library/retailcrm/lib/repository/DataRepository.php create mode 100644 src/upload/system/library/retailcrm/lib/repository/OrderRepository.php create mode 100644 src/upload/system/library/retailcrm/lib/repository/ProductsRepository.php create mode 100644 src/upload/system/library/retailcrm/lib/service/CorporateCustomer.php create mode 100644 src/upload/system/library/retailcrm/lib/service/CorporateCustomerBuilder.php create mode 100644 src/upload/system/library/retailcrm/lib/service/CustomerManager.php create mode 100644 src/upload/system/library/retailcrm/lib/service/OrderManager.php create mode 100644 src/upload/system/library/retailcrm/lib/service/RetailcrmCustomerConverter.php create mode 100644 src/upload/system/library/retailcrm/lib/service/RetailcrmOrderConverter.php create mode 100644 src/upload/system/library/retailcrm/lib/service/SettingsManager.php create mode 100644 tests/catalog/ControllerDaemonCollectorExtensionAnalyticsCatalogTest.php delete mode 100644 tests/catalog/ModelRetailcrmCustomerCatalogTest.php create mode 100644 tests/system/RetailcrmTest.php create mode 100644 tests/system/lib/ModelsProviderAdminTest.php create mode 100644 tests/system/lib/ModelsProviderTest.php create mode 100644 tests/system/lib/UtilsTest.php create mode 100644 tests/system/lib/factory/CustomerConverterFactoryTest.php create mode 100644 tests/system/lib/factory/OrderConverterFactoryTest.php create mode 100644 tests/system/lib/history/CustomerAdminTest.php create mode 100644 tests/system/lib/history/OrderAdminTest.php create mode 100644 tests/system/lib/repository/CustomerRespositoryAdminTest.php create mode 100644 tests/system/lib/repository/CustomerRespositoryTest.php create mode 100644 tests/system/lib/repository/DataRepositoryAdminTest.php create mode 100644 tests/system/lib/repository/OrderRepositoryAdminTest.php create mode 100644 tests/system/lib/repository/ProductsRespositoryTest.php create mode 100644 tests/system/lib/service/CorporateCustomerBuilderTest.php create mode 100644 tests/system/lib/service/CorporateCustomerTest.php create mode 100644 tests/system/lib/service/CustomerManagerTest.php create mode 100644 tests/system/lib/service/OrderManagerTest.php create mode 100644 tests/system/lib/service/RetailcrmCustomerConverterTest.php create mode 100644 tests/system/lib/service/RetailcrmOrderConverterTest.php create mode 100644 tests/system/lib/service/SettingsManagerTest.php diff --git a/.docker/Dockerfile b/.docker/Dockerfile index e0fb8a8..a638c72 100644 --- a/.docker/Dockerfile +++ b/.docker/Dockerfile @@ -1,8 +1,8 @@ -FROM php:7.1-cli +FROM php:7.1-apache RUN apt-get update -RUN apt-get install -y zlib1g-dev libpq-dev git libicu-dev libxml2-dev libpng-dev libjpeg-dev libmcrypt-dev libxslt-dev libfreetype6-dev \ +RUN apt-get install -y netcat zlib1g-dev libpq-dev git libicu-dev libxml2-dev libpng-dev libjpeg-dev libmcrypt-dev libxslt-dev libfreetype6-dev \ && docker-php-ext-configure intl \ && docker-php-ext-install intl \ && docker-php-ext-configure pgsql -with-pgsql=/usr/local/pgsql \ @@ -26,3 +26,31 @@ RUN curl --insecure https://getcomposer.org/download/1.9.3/composer.phar -o /usr RUN rm /etc/localtime RUN ln -s /usr/share/zoneinfo/Europe/Moscow /etc/localtime RUN "date" + +ARG TEST_SUITE +ARG OPENCART +ARG SERVER_PORT +ARG OC_DB_HOSTNAME +ARG OC_DB_USERNAME +ARG OC_DB_PASSWORD +ARG OC_DB_DATABASE +ARG OC_USERNAME +ARG OC_PASSWORD +ARG OC_EMAIL + +ENV TEST_SUITE=${TEST_SUITE} +ENV OPENCART=${OPENCART} +ENV PORT=${SERVER_PORT} +ENV OC_DB_HOSTNAME=${OC_DB_HOSTNAME} +ENV OC_DB_USERNAME=${OC_DB_USERNAME} +ENV OC_DB_PASSWORD=${OC_DB_PASSWORD} +ENV OC_DB_DATABASE=${OC_DB_DATABASE} +ENV OC_USERNAME=${OC_USERNAME} +ENV OC_PASSWORD=${OC_PASSWORD} +ENV OC_EMAIL=${OC_EMAIL} + +ADD .docker/entrypoint.sh /usr/local/bin/docker-php-entrypoint + +RUN sed -i "s/80/$PORT/g" /etc/apache2/sites-enabled/000-default.conf /etc/apache2/ports.conf +RUN sed -i 's/var\/www\/html/opencart-module\/www/g' /etc/apache2/sites-enabled/000-default.conf +RUN sed -i 's/var\/www/opencart-module/g' /etc/apache2/apache2.conf diff --git a/.docker/entrypoint.sh b/.docker/entrypoint.sh new file mode 100644 index 0000000..9383e96 --- /dev/null +++ b/.docker/entrypoint.sh @@ -0,0 +1,26 @@ +#!/bin/sh + +until nc -z -v -w30 mysql 3306 +do + echo "Waiting for database connection..." + sleep 5 +done + +make -C /opencart-module run + +mkdir /opencart-module/www/system/storage/session + +echo '\nini_set("session.save_path", DIR_SYSTEM . "storage/session");' >> /opencart-module/www/config.php +echo '\nini_set("session.save_path", DIR_SYSTEM . "storage/session");' >> /opencart-module/www/admin/config.php + +#chown -R www-data:www-data /opencart-module \ +# && find /opencart-module -type d -exec chmod 755 {} \; \ +# && find /opencart-module -type f -exec chmod 644 {} \; + +# first arg is `-f` or `--some-option` +if [ "${1#-}" != "$1" ]; then + set -- apache2-foreground "$@" +fi + +exec "$@" + diff --git a/.env-dist b/.env-dist index 05c05b6..21b845c 100644 --- a/.env-dist +++ b/.env-dist @@ -11,7 +11,7 @@ OC_PASSWORD=admin OC_EMAIL=you@example.com # Server Specification -SERVER_PORT=80 +SERVER_PORT=8080 SERVER_URL=http://localhost TEST_SUITE= diff --git a/.travis.yml b/.travis.yml index 177b463..f828c00 100644 --- a/.travis.yml +++ b/.travis.yml @@ -137,4 +137,4 @@ jobs: on: condition: "$LAST_TAG != $CURRENT_VERSION" if: branch = master AND type = push AND fork = false - after_deploy: make delete_archive \ No newline at end of file + after_deploy: make delete_archive diff --git a/Makefile b/Makefile index 6b36c43..4bf3481 100644 --- a/Makefile +++ b/Makefile @@ -2,6 +2,8 @@ FILE = $(TRAVIS_BUILD_DIR)/VERSION VERSION = `cat $(FILE)` ARCHIVE_NAME = '/tmp/retailcrm-'$(VERSION)'.ocmod.zip' +.PHONY: coverage + all: build_archive send_to_ftp delete_archive build_archive: @@ -30,11 +32,16 @@ coverage: robo_deploy: bin/robo --load-from tests/RoboFile.php project:deploy -run_test: +run: composer require --dev beyondit/opencart-test-suite ~$(TEST_SUITE) composer require --dev opencart/opencart $(OPENCART) composer setup bin/robo --load-from tests/RoboFile.php project:deploy - (php -S localhost:80 -t www &) 2> /dev/null > /dev/null + +run_test: run + (php -S localhost:$(SERVER_PORT) -t www &) 2> /dev/null > /dev/null sleep 2 composer test + +test: robo_deploy + composer test diff --git a/composer.json b/composer.json index a15a455..97132b6 100644 --- a/composer.json +++ b/composer.json @@ -19,12 +19,17 @@ "scripts" : { "test-admin": "bin/phpunit --coverage-php coverage/admin.cov --testsuite admin-tests --colors=always", "test-catalog": "bin/phpunit --coverage-php coverage/catalog.cov --testsuite catalog-tests --colors=always", + "test-system": "bin/phpunit --coverage-php coverage/system.cov --testsuite system-tests --colors=always", "test": [ "@test-admin", - "@test-catalog" + "@test-catalog", + "@test-system" ], "setup" : "bin/robo --load-from tests/RoboFile.php opencart:setup" }, + "require": { + "ext-json": "*" + }, "require-dev": { "consolidation/robo": "~1.0" } diff --git a/docker-compose.yml b/docker-compose.yml index 1fccab4..f177d29 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -2,35 +2,34 @@ version: '3' services: app: build: - context: ./.docker + context: . + dockerfile: ./.docker/Dockerfile + args: + - TEST_SUITE=${TEST_SUITE} + - OPENCART=${OPENCART} + - SERVER_PORT=${SERVER_PORT} + - OC_DB_HOSTNAME=${OC_DB_HOSTNAME} + - OC_DB_USERNAME=${OC_DB_USERNAME} + - OC_DB_PASSWORD=${OC_DB_PASSWORD} + - OC_DB_DATABASE=${OC_DB_DATABASE} + - OC_USERNAME=${OC_USERNAME} + - OC_PASSWORD=${OC_PASSWORD} + - OC_EMAIL=${OC_EMAIL} volumes: - - ./:/home/code + - ./:/opencart-module links: - "mysql" - user: ${UID:-1000}:${GID:-1000} + ports: + - "${SERVER_PORT}:${SERVER_PORT}" depends_on: - mysql env_file: - - ./.env - environment: - - OC_DB_HOSTNAME=${OC_DB_HOSTNAME} - - OC_DB_USERNAME=${OC_DB_USERNAME} - - OC_DB_PASSWORD=${OC_DB_PASSWORD} - - OC_DB_DATABASE=${OC_DB_DATABASE} - - OC_DB_DRIVER=${OC_DB_DRIVER} - - OC_USERNAME=${OC_USERNAME} - - OC_PASSWORD=${OC_PASSWORD} - - OC_EMAIL=${OC_EMAIL} - - SERVER_PORT=${SERVER_PORT} - - SERVER_URL=${SERVER_URL} - - TEST_SUITE=${TEST_SUITE} - - OPENCART=${OPENCART} - command: make run - working_dir: /home/code + - .env + working_dir: /opencart-module mysql: image: mysql:5.7 env_file: - - ./.env + - .env environment: - MYSQL_DATABASE=${OC_DB_DATABASE} - MYSQL_USER=${OC_DB_USERNAME} diff --git a/phpunit.xml.dist b/phpunit.xml.dist index 367879c..026767c 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -16,6 +16,9 @@ ./tests/admin/ + + ./tests/system/ + @@ -23,13 +26,16 @@ - + ./www/admin/controller ./www/admin/model/extension/retailcrm ./www/catalog/controller ./www/catalog/controller ./www/catalog/model/extension/retailcrm ./www/system/library/retailcrm + + ./www/system/library/retailcrm/lib/api + - \ No newline at end of file + diff --git a/src/upload/admin/controller/extension/module/retailcrm.php b/src/upload/admin/controller/extension/module/retailcrm.php index 2438992..949f800 100644 --- a/src/upload/admin/controller/extension/module/retailcrm.php +++ b/src/upload/admin/controller/extension/module/retailcrm.php @@ -59,11 +59,9 @@ class ControllerExtensionModuleRetailcrm extends Controller $this->integrationModule( $this->retailcrm->getApiClient( $settings['retailcrm_setting_url'], - $settings['retailcrm_setting_key'], - $settings['retailcrm_setting_version'] + $settings['retailcrm_setting_key'] ), $clientId, - $settings['retailcrm_setting_version'], false ); @@ -162,48 +160,43 @@ class ControllerExtensionModuleRetailcrm extends Controller $this->request->post ); - if ($this->request->post[$this->moduleTitle . '_apiversion'] != 'v3') { - if (!isset($history_setting['retailcrm_history_orders']) && !isset($history_setting['retailcrm_history_customers'])) { - $api = $this->retailcrm->getApiClient( - $this->request->post[$this->moduleTitle . '_url'], - $this->request->post[$this->moduleTitle . '_apikey'], - $this->request->post[$this->moduleTitle . '_apiversion'] - ); + if (!isset($history_setting['retailcrm_history_orders']) && !isset($history_setting['retailcrm_history_customers'])) { + $api = $this->retailcrm->getApiClient( + $this->request->post[$this->moduleTitle . '_url'], + $this->request->post[$this->moduleTitle . '_apikey'] + ); - $ordersHistory = $api->ordersHistory(); + $ordersHistory = $api->ordersHistory(); - if ($ordersHistory->isSuccessful() && !empty($ordersHistory['history'])) { - $ordersHistory = $api->ordersHistory(array(), $ordersHistory['pagination']['totalPageCount']); + if ($ordersHistory && $ordersHistory->isSuccessful() && !empty($ordersHistory['history'])) { + $ordersHistory = $api->ordersHistory(array(), $ordersHistory['pagination']['totalPageCount']); - if ($ordersHistory->isSuccessful()) { - $ordersHistoryArr = $ordersHistory['history']; - $lastChangeOrders = end($ordersHistoryArr); - $sinceIdOrders = $lastChangeOrders['id']; - $generatedAt = $ordersHistory['generatedAt']; - } + if ($ordersHistory && $ordersHistory->isSuccessful()) { + $ordersHistoryArr = $ordersHistory['history']; + $lastChangeOrders = end($ordersHistoryArr); + $sinceIdOrders = $lastChangeOrders['id']; } - - $customersHistory = $api->customersHistory(); - - if ($customersHistory->isSuccessful() && !empty($customersHistory['history'])) { - $customersHistory = $api->customersHistory(array(), $customersHistory['pagination']['totalPageCount']); - - if ($customersHistory->isSuccessful()) { - $customersHistoryArr = $customersHistory['history']; - $lastChangeCustomers = end($customersHistoryArr); - $sinceIdCustomers = $lastChangeCustomers['id']; - } - } - - $this->model_setting_setting->editSetting( - 'retailcrm_history', - array( - 'retailcrm_history_orders' => isset($sinceIdOrders) ? $sinceIdOrders : 1, - 'retailcrm_history_customers' => isset($sinceIdCustomers) ? $sinceIdCustomers : 1, - 'retailcrm_history_datetime' => isset($generatedAt) ? $generatedAt : date('Y-m-d H:i:s') - ) - ); } + + $customersHistory = $api->customersHistory(); + + if ($customersHistory && $customersHistory->isSuccessful() && !empty($customersHistory['history'])) { + $customersHistory = $api->customersHistory(array(), $customersHistory['pagination']['totalPageCount']); + + if ($customersHistory && $customersHistory->isSuccessful()) { + $customersHistoryArr = $customersHistory['history']; + $lastChangeCustomers = end($customersHistoryArr); + $sinceIdCustomers = $lastChangeCustomers['id']; + } + } + + $this->model_setting_setting->editSetting( + 'retailcrm_history', + array( + 'retailcrm_history_orders' => isset($sinceIdOrders) ? $sinceIdOrders : 1, + 'retailcrm_history_customers' => isset($sinceIdCustomers) ? $sinceIdCustomers : 1 + ) + ); } $retailcrm_setting = $this->model_setting_setting->getSetting('retailcrm_setting'); @@ -212,14 +205,12 @@ class ControllerExtensionModuleRetailcrm extends Controller $clientId = uniqid(); $api = $this->retailcrm->getApiClient( $this->request->post[$this->moduleTitle . '_url'], - $this->request->post[$this->moduleTitle . '_apikey'], - $this->request->post[$this->moduleTitle . '_apiversion'] + $this->request->post[$this->moduleTitle . '_apikey'] ); $result = $this->integrationModule( $api, - $clientId, - $this->request->post[$this->moduleTitle . '_apiversion'] + $clientId ); if ($result === true) { @@ -229,8 +220,7 @@ class ControllerExtensionModuleRetailcrm extends Controller 'retailcrm_setting_active_in_crm' => true, 'retailcrm_setting_client_id' => $clientId, 'retailcrm_setting_url' => $this->request->post[$this->moduleTitle . '_url'], - 'retailcrm_setting_key' => $this->request->post[$this->moduleTitle . '_apikey'], - 'retailcrm_setting_version' => $this->request->post[$this->moduleTitle . '_apiversion'] + 'retailcrm_setting_key' => $this->request->post[$this->moduleTitle . '_apikey'] ) ); } @@ -309,7 +299,8 @@ class ControllerExtensionModuleRetailcrm extends Controller 'status_changes', 'text_status_changes', 'text_lenght', - 'text_lenght_label' + 'text_lenght_label', + 'corporate_enabled_label' ); $_data = &$data; @@ -348,12 +339,9 @@ class ControllerExtensionModuleRetailcrm extends Controller } $_data['lenghts'] = $this->model_localisation_length_class->getLengthClasses(); - - if ($apiVersion != 'v3') { - $_data['priceTypes'] = $this->model_extension_retailcrm_references - ->getPriceTypes(); - $_data['customerGroups'] = $this->model_customer_customer_group->getCustomerGroups(); - } + $_data['priceTypes'] = $this->model_extension_retailcrm_references + ->getPriceTypes(); + $_data['customerGroups'] = $this->model_customer_customer_group->getCustomerGroups(); } $config_data = array( @@ -444,8 +432,6 @@ class ControllerExtensionModuleRetailcrm extends Controller ); $_data['collectorFields'] = $collectorFields; - $_data['api_versions'] = array('v3', 'v4', 'v5'); - $_data['default_apiversion'] = 'v4'; $retailcrmLog = file_exists(DIR_SYSTEM . 'storage/logs/retailcrm.log') ? DIR_SYSTEM . 'storage/logs/retailcrm.log' : false; $ocApiLog = file_exists(DIR_SYSTEM . 'storage/logs/opencartapi.log') ? DIR_SYSTEM . 'storage/logs/opencartapi.log' : false; @@ -479,24 +465,13 @@ class ControllerExtensionModuleRetailcrm extends Controller public function history() { $this->load->model('setting/setting'); - $settings = $this->model_setting_setting->getSetting($this->moduleTitle); - if ($settings[$this->moduleTitle . '_apiversion'] == 'v3') { - if (file_exists(DIR_APPLICATION . 'model/extension/retailcrm/custom/history/v3.php')) { - $this->load->model('extension/retailcrm/custom/history/v3'); - $this->model_extension_retailcrm_custom_history_v3->request($this->retailcrm->getApiClient()); - } else { - $this->load->model('extension/retailcrm/history/v3'); - $this->model_extension_retailcrm_history_v3->request($this->retailcrm->getApiClient()); - } + if (file_exists(DIR_APPLICATION . 'model/extension/retailcrm/custom/history/v4_5.php')) { + $this->load->model('extension/retailcrm/custom/history/v4_5'); + $this->model_extension_retailcrm_custom_history_v4_5->request($this->retailcrm->getApiClient()); } else { - if (file_exists(DIR_APPLICATION . 'model/extension/retailcrm/custom/history/v4-5.php')) { - $this->load->model('extension/retailcrm/custom/history/v4-5'); - $this->model_extension_retailcrm_custom_history_v4_5->request($this->retailcrm->getApiClient()); - } else { - $this->load->model('extension/retailcrm/history/v4_5'); - $this->model_extension_retailcrm_history_v4_5->request($this->retailcrm->getApiClient()); - } + $this->load->model('extension/retailcrm/history'); + $this->model_extension_retailcrm_history->request($this->retailcrm->getApiClient()); } } @@ -532,27 +507,13 @@ class ControllerExtensionModuleRetailcrm extends Controller $customerId = $customer[0]; $customer = $customer[1]; - $addresses = $customer['address']; unset($customer); $customer = $this->model_customer_customer->getCustomer($customerId); + $address = $this->model_customer_customer->getAddress($customer['address_id']); - foreach ($addresses as $address) { - $country = $this->model_localisation_country->getCountry($address['country_id']); - $zone = $this->model_localisation_zone->getZone($address['zone_id']); - - $customer['address'] = array( - 'address_1' => $address['address_1'], - 'address_2' => $address['address_2'], - 'city' => $address['city'], - 'postcode' => $address['postcode'], - 'iso_code_2' => $country['iso_code_2'], - 'zone' => $zone['name'] - ); - } - - $this->load->model('extension/retailcrm/customer'); - $this->model_extension_retailcrm_customer->changeInCrm($customer, $this->retailcrm->getApiClient()); + $customer_manager = $this->retailcrm->getCustomerManager(); + $customer_manager->editCustomer($customer, $address); } /** @@ -560,52 +521,49 @@ class ControllerExtensionModuleRetailcrm extends Controller * * @return void */ - public function exportOrder() - { + public function exportOrder() { $order_id = isset($this->request->get['order_id']) ? $this->request->get['order_id'] : ''; - $this->load->model('sale/order'); - $data = $this->model_sale_order->getOrder($order_id); - $data['products'] = $this->model_sale_order->getOrderProducts($order_id); - $data['totals'] = $this->model_sale_order->getOrderTotals($order_id); + $products = $this->model_sale_order->getOrderProducts($order_id); + $totals = $this->model_sale_order->getOrderTotals($order_id); - foreach ($data['products'] as $key => $product) { - $data['products'][$key]['option'] = $this->model_sale_order->getOrderOptions($product['order_id'], $product['order_product_id']); + foreach ($products as $key => $product) { + $products[$key]['option'] = $this->model_sale_order->getOrderOptions($product['order_id'], $product['order_product_id']); } if (!isset($data['fromApi'])) { - $this->load->model('setting/setting'); $status = $this->model_setting_setting->getSetting($this->moduleTitle); $data['order_status'] = $status[$this->moduleTitle . '_status'][$data['order_status_id']]; - $this->load->model('extension/retailcrm/order'); - $this->model_extension_retailcrm_order->uploadOrder($data, $this->retailcrm->getApiClient()); - $response = ModelExtensionRetailcrmOrder::getLastResponse(); - } + $order_manager = $this->retailcrm->getOrderManager(); + $response = $order_manager->createOrder($data, $products, $totals); - if (!$response->isSuccessful()) { - if (isset($response['errors'])) { - $error = implode("\n", $response['errors']); - } else { - $error = $response->getErrorMsg(); + if ($response) { + if (!$response->isSuccessful()) { + if (isset($response['errors'])) { + $error = implode("\n", $response['errors']); + } else { + $error = $response->getErrorMsg(); + } + + $this->response->setOutput( + json_encode( + array( + 'status_code' => $response->getStatusCode(), + 'error_msg' => $error + ) + ) + ); + } else { + $this->response->setOutput( + json_encode( + array( + 'status_code' => $response->getStatusCode() + ) + ) + ); + } } - - $this->response->setOutput( - json_encode( - array( - 'status_code' => $response->getStatusCode(), - 'error_msg' => $error - ) - ) - ); - } else { - $this->response->setOutput( - json_encode( - array( - 'status_code' => $response->getStatusCode() - ) - ) - ); } } @@ -616,10 +574,8 @@ class ControllerExtensionModuleRetailcrm extends Controller */ public function export() { - $this->load->model('customer/customer'); $this->load->model('extension/retailcrm/customer'); $this->load->model('extension/retailcrm/order'); - $this->load->model('sale/order'); $customers = $this->model_customer_customer->getCustomers(); $this->model_extension_retailcrm_customer->uploadToCrm($customers, $this->retailcrm->getApiClient()); @@ -670,12 +626,6 @@ class ControllerExtensionModuleRetailcrm extends Controller */ private function validate() { - $versionsMap = array( - 'v3' => '3.0', - 'v4' => '4.0', - 'v5' => '5.0' - ); - if (!empty($this->request->post[$this->moduleTitle . '_url']) && !empty($this->request->post[$this->moduleTitle . '_apikey'])) { $apiClient = $this->retailcrm->getApiClient( $this->request->post[$this->moduleTitle . '_url'], @@ -685,12 +635,8 @@ class ControllerExtensionModuleRetailcrm extends Controller $response = $apiClient->apiVersions(); - if ($response && $response->isSuccessful()) { - if (!in_array($versionsMap[$this->request->post[$this->moduleTitle . '_apiversion']], $response['versions'])) { - $this->_error['warning'] = $this->language->get('text_error_api'); - } - } else { - $this->_error['warning'] = $this->language->get('text_error_save'); + if (!$response || !$response->isSuccessful()) { + $this->_error['warning'] = $this->language->get('text_error_api'); } if (!$this->user->hasPermission('modify', 'extension/module/retailcrm')) { @@ -911,12 +857,11 @@ class ControllerExtensionModuleRetailcrm extends Controller * * @param \RetailcrmProxy $apiClient * @param string $clientId - * @param string $api_version * @param boolean $active * * @return boolean */ - private function integrationModule($apiClient, $clientId, $api_version, $active = true) + private function integrationModule($apiClient, $clientId, $active = true) { $scheme = isset($this->request->server['HTTPS']) ? 'https://' : 'http://'; $logo = 'https://s3.eu-central-1.amazonaws.com/retailcrm-billing/images/5af48736c6a0c-opencart-seeklogo.com.svg'; @@ -924,29 +869,17 @@ class ControllerExtensionModuleRetailcrm extends Controller $name = 'Opencart'; $accountUrl = $scheme . $this->request->server['HTTP_HOST'] . '/admin'; - if ($api_version == 'v4') { - $configuration = array( - 'name' => $name, - 'code' => $integrationCode . '-' . $clientId, - 'logo' => $logo, - 'configurationUrl' => $accountUrl, - 'active' => $active - ); + $configuration = array( + 'clientId' => $clientId, + 'code' => $integrationCode . '-' . $clientId, + 'integrationCode' => $integrationCode, + 'active' => $active, + 'name' => $name, + 'logo' => $logo, + 'accountUrl' => $accountUrl + ); - $response = $apiClient->marketplaceSettingsEdit($configuration); - } else { - $configuration = array( - 'clientId' => $clientId, - 'code' => $integrationCode . '-' . $clientId, - 'integrationCode' => $integrationCode, - 'active' => $active, - 'name' => $name, - 'logo' => $logo, - 'accountUrl' => $accountUrl - ); - - $response = $apiClient->integrationModulesEdit($configuration); - } + $response = $apiClient->integrationModulesEdit($configuration); if (!$response) { return false; diff --git a/src/upload/admin/language/en-gb/extension/module/retailcrm.php b/src/upload/admin/language/en-gb/extension/module/retailcrm.php index 75ea46a..f3884a4 100644 --- a/src/upload/admin/language/en-gb/extension/module/retailcrm.php +++ b/src/upload/admin/language/en-gb/extension/module/retailcrm.php @@ -22,6 +22,7 @@ $_['custom_fields_tab_text'] = 'Custom fields'; $_['retailcrm_apiversion'] = 'API Version'; $_['retailcrm_url'] = 'URL of retailCRM'; $_['retailcrm_apikey'] = 'API key of retailCRM'; +$_['corporate_enabled_label'] = 'Corporate customers support'; $_['collector_site_key'] = 'Site key'; $_['special_price_settings'] = 'Setting of uploading promotion price'; $_['special_price'] = 'Price type to which the promotion price will be uploaded'; diff --git a/src/upload/admin/language/es-es/extension/module/retailcrm.php b/src/upload/admin/language/es-es/extension/module/retailcrm.php index b8d2060..2e7db08 100644 --- a/src/upload/admin/language/es-es/extension/module/retailcrm.php +++ b/src/upload/admin/language/es-es/extension/module/retailcrm.php @@ -22,6 +22,7 @@ $_['custom_fields_tab_text'] = 'Campos personalizados'; $_['retailcrm_apiversion'] = 'Versión de la API'; $_['retailcrm_url'] = 'Dirección del retailCRM'; $_['retailcrm_apikey'] = 'Clave de la API del retailCRM'; +$_['corporate_enabled_label'] = 'Corporate customers support'; $_['collector_site_key'] = 'Clave de la página web'; $_['special_price_settings'] = 'Ajuste de la descarga del precio promocional'; $_['special_price'] = 'Tipo de precio en el que se cargará el precio de promoción'; diff --git a/src/upload/admin/language/ru-ru/extension/module/retailcrm.php b/src/upload/admin/language/ru-ru/extension/module/retailcrm.php index a9817b3..47da0d1 100644 --- a/src/upload/admin/language/ru-ru/extension/module/retailcrm.php +++ b/src/upload/admin/language/ru-ru/extension/module/retailcrm.php @@ -22,6 +22,7 @@ $_['custom_fields_tab_text'] = 'Пользовательские поля'; $_['retailcrm_apiversion'] = 'Версия API'; $_['retailcrm_url'] = 'Адрес RetailCRM'; $_['retailcrm_apikey'] = 'Api ключ RetailCRM'; +$_['corporate_enabled_label'] = 'Поддержка корпоративных клиентов'; $_['collector_site_key'] = 'Ключ сайта'; $_['special_price_settings'] = 'Настройка выгрузки акционной цены'; $_['special_price'] = 'Тип цены, в который будет выгружаться цена по акции'; diff --git a/src/upload/admin/model/extension/retailcrm/customer.php b/src/upload/admin/model/extension/retailcrm/customer.php index 1702e9a..f71c2de 100644 --- a/src/upload/admin/model/extension/retailcrm/customer.php +++ b/src/upload/admin/model/extension/retailcrm/customer.php @@ -1,137 +1,29 @@ load->model('setting/setting'); - $this->load->library('retailcrm/retailcrm'); - - $this->moduleTitle = $this->retailcrm->getModuleTitle(); - $this->settings = $this->model_setting_setting->getSetting($this->moduleTitle); - } - /** * Upload customers - * + * * @param array $customers - * @param \RetailcrmProxy $retailcrmApiClient * * @return mixed */ - public function uploadToCrm($customers, $retailcrmApiClient) + public function uploadToCrm($customers) { - if ($retailcrmApiClient === false || empty($customers)) { - return false; - } - $customersToCrm = array(); + /** @var CustomerManager $customer_manager */ + $customer_manager = $this->retailcrm->getCustomerManager(); foreach($customers as $customer) { - $customersToCrm[] = $this->process($customer); + $customersToCrm[] = $customer_manager->prepareCustomer($customer, array()); } $chunkedCustomers = array_chunk($customersToCrm, 50); foreach($chunkedCustomers as $customersPart) { - $retailcrmApiClient->customersUpload($customersPart); + $customer_manager->uploadCustomers($customersPart); } return $chunkedCustomers; } - - /** - * Edit customer - * - * @param array $customer - * @param \RetailcrmProxy $retailcrmApiClient - * - * @return mixed - */ - public function changeInCrm($customer, $retailcrmApiClient) - { - if ($retailcrmApiClient === false || empty($customer)) { - return false; - } - - $customerToCrm = $this->process($customer); - - $retailcrmApiClient->customersEdit($customerToCrm); - - return $customerToCrm; - } - - /** - * Create customer - * - * @param array $customer - * @param \RetailcrmProxy $retailcrmApiClient - * - * @return mixed - */ - public function sendToCrm($customer, $retailcrmApiClient) - { - if ($retailcrmApiClient === false || empty($customer)) { - return false; - } - - $customerToCrm = $this->process($customer); - - $retailcrmApiClient->customersCreate($customerToCrm); - - return $customerToCrm; - } - - /** - * Process customer - * - * @param array $customer - * - * @return array $customerToCrm - */ - private function process($customer) - { - $customerToCrm = array( - 'externalId' => $customer['customer_id'], - 'firstName' => $customer['firstname'], - 'lastName' => $customer['lastname'], - 'email' => $customer['email'], - 'phones' => array( - array( - 'number' => $customer['telephone'] - ) - ), - 'createdAt' => $customer['date_added'] - ); - - if (isset($customer['address'])) { - $customerToCrm['address'] = array( - 'index' => $customer['address']['postcode'], - 'countryIso' => $customer['address']['iso_code_2'], - 'region' => $customer['address']['zone'], - 'city' => $customer['address']['city'], - 'text' => $customer['address']['address_1'] . ' ' . $customer['address']['address_2'] - ); - } - - if (isset($this->settings[$this->moduleTitle . '_custom_field']) && $customer['custom_field']) { - $customFields = json_decode($customer['custom_field']); - - foreach ($customFields as $key => $value) { - if (isset($this->settings[$this->moduleTitle . '_custom_field']['c_' . $key])) { - $customFieldsToCrm[$this->settings[$this->moduleTitle . '_custom_field']['c_' . $key]] = $value; - } - } - - if (isset($customFieldsToCrm)) { - $customerToCrm['customFields'] = $customFieldsToCrm; - } - } - - return $customerToCrm; - } } diff --git a/src/upload/admin/model/extension/retailcrm/history.php b/src/upload/admin/model/extension/retailcrm/history.php index b12a49d..a6bb026 100644 --- a/src/upload/admin/model/extension/retailcrm/history.php +++ b/src/upload/admin/model/extension/retailcrm/history.php @@ -1,194 +1,348 @@ db->query("INSERT INTO `" . DB_PREFIX . "order` SET store_id = '" . (int)$order['store_id'] . "', store_name = '" . $order['store_name'] . "', customer_id = '" . (int)$order['customer_id'] . "', customer_group_id = '" . (int)$order['customer_group_id'] . "', firstname = '" . $this->db->escape($order['firstname']) . "', lastname = '" . $this->db->escape($order['lastname']) . "', email = '" . $this->db->escape($order['email']) . "', telephone = '" . $this->db->escape($order['telephone']) . "', custom_field = '" . $this->db->escape(isset($order['custom_field']) ? json_encode($order['custom_field']) : '') . "', payment_firstname = '" . $this->db->escape($order['payment_firstname']) . "', payment_lastname = '" . $this->db->escape($order['payment_lastname']) . "', payment_address_1 = '" . $this->db->escape($order['payment_address_1']) . "', payment_city = '" . $this->db->escape($order['payment_city']) . "', payment_postcode = '" . $this->db->escape($order['payment_postcode']) . "', payment_country = '" . $this->db->escape($order['payment_country']) . "', payment_country_id = '" . (int)$order['payment_country_id'] . "', payment_zone = '" . $this->db->escape($order['payment_zone']) . "', payment_zone_id = '" . (int)$order['payment_zone_id'] . "', payment_method = '" . $this->db->escape($order['payment_method']) . "', payment_code = '" . $this->db->escape($order['payment_code']) . "', shipping_firstname = '" . $this->db->escape($order['shipping_firstname']) . "', shipping_lastname = '" . $this->db->escape($order['shipping_lastname']) . "', shipping_address_1 = '" . $this->db->escape($order['shipping_address_1']) . "', shipping_address_2 = '" . $this->db->escape($order['shipping_address_2']) . "', shipping_city = '" . $this->db->escape($order['shipping_city']) . "', shipping_postcode = '" . $this->db->escape($order['shipping_postcode']) . "', shipping_country = '" . $this->db->escape($order['shipping_country']) . "', shipping_country_id = '" . (int)$order['shipping_country_id'] . "', shipping_zone = '" . $this->db->escape($order['shipping_zone']) . "', shipping_zone_id = '" . (int)$order['shipping_zone_id'] . "', shipping_method = '" . $this->db->escape($order['shipping_method']) . "', shipping_code = '" . $this->db->escape($order['shipping_code']) . "', comment = '" . $this->db->escape($order['comment']) . "', total = '" . (float)$order['total'] . "', affiliate_id = '" . (int)$order['affiliate_id'] . "', language_id = '" . (int)$order['language_id'] . "', currency_id = '" . (int)$order['currency_id'] . "', currency_code = '" . $this->db->escape($order['currency_code']) . "', currency_value = '" . (float)$order['currency_value'] . "', order_status_id = '" . (int)$order['order_status_id'] . "', date_added = NOW(), date_modified = NOW()"); +class ModelExtensionRetailcrmHistory extends Model { + protected $createResult; + protected $settings; + protected $moduleTitle; + protected $opencartApiClient; - $order_id = $this->db->getLastId(); + private $orders_history; + private $customers_history; + private $data_repository; - // Products - if (isset($order['order_product']) && $order['order_product']) { - $this->addOrderProducts($order_id, $order['order_product']); - } - - // Totals - if (isset($order['order_total'])) { - $this->addOrderTotals($order_id, $order['order_total']); - } - - return $order_id; + public function __construct($registry) { + parent::__construct($registry); + $this->load->library('retailcrm/retailcrm'); + $this->moduleTitle = $this->retailcrm->getModuleTitle(); + $this->opencartApiClient = $this->retailcrm->getOcApiClient($registry); } /** - * Edit order in OC + * Getting changes from RetailCRM + * @param \RetailcrmProxy $retailcrmApiClient * - * @param int $order_id - * @param array $order - * - * @return void + * @return boolean */ - public function editOrder($order_id, $order) - { - $this->db->query("UPDATE `" . DB_PREFIX . "order` SET customer_id = '" . (int)$order['customer_id'] . "', customer_group_id = '" . (int)$order['customer_group_id'] . "', firstname = '" . $this->db->escape($order['firstname']) . "', lastname = '" . $this->db->escape($order['lastname']) . "', email = '" . $this->db->escape($order['email']) . "', telephone = '" . $this->db->escape($order['telephone']) . "', custom_field = '" . $this->db->escape(json_encode($order['custom_field'])) . "', payment_firstname = '" . $this->db->escape($order['payment_firstname']) . "', payment_lastname = '" . $this->db->escape($order['payment_lastname']) . "', payment_address_1 = '" . $this->db->escape($order['payment_address_1']) . "', payment_address_2 = '" . $this->db->escape($order['payment_address_2']) . "', payment_city = '" . $this->db->escape($order['payment_city']) . "', payment_postcode = '" . $this->db->escape($order['payment_postcode']) . "', payment_country = '" . $this->db->escape($order['payment_country']) . "', payment_country_id = '" . (int)$order['payment_country_id'] . "', payment_zone = '" . $this->db->escape($order['payment_zone']) . "', payment_zone_id = '" . (int)$order['payment_zone_id'] . "', payment_method = '" . $this->db->escape($order['payment_method']) . "', payment_code = '" . $this->db->escape($order['payment_code']) . "', shipping_firstname = '" . $this->db->escape($order['shipping_firstname']) . "', shipping_lastname = '" . $this->db->escape($order['shipping_lastname']) . "', shipping_address_1 = '" . $this->db->escape($order['shipping_address_1']) . "', shipping_address_2 = '" . $this->db->escape($order['shipping_address_2']) . "', shipping_city = '" . $this->db->escape($order['shipping_city']) . "', shipping_postcode = '" . $this->db->escape($order['shipping_postcode']) . "', shipping_country = '" . $this->db->escape($order['shipping_country']) . "', shipping_country_id = '" . (int)$order['shipping_country_id'] . "', shipping_zone = '" . $this->db->escape($order['shipping_zone']) . "', shipping_zone_id = '" . (int)$order['shipping_zone_id'] . "', shipping_method = '" . $this->db->escape($order['shipping_method']) . "', shipping_code = '" . $this->db->escape($order['shipping_code']) . "', comment = '" . $this->db->escape($order['comment']) . "', total = '" . (float)$order['total'] . "', order_status_id = '" . (int)$order['order_status_id'] . "', date_modified = NOW() WHERE order_id = '" . (int)$order_id . "'"); + public function request($retailcrmApiClient) { + $this->load->library('retailcrm/retailcrm'); + $this->load->model('setting/setting'); + $this->load->model('setting/store'); + $this->load->model('user/api'); + $this->load->model('sale/order'); + $this->load->model('customer/customer'); + $this->load->model('extension/retailcrm/references'); + $this->load->model('catalog/product'); + $this->load->model('catalog/option'); + $this->load->model('localisation/zone'); - $this->db->query("DELETE FROM " . DB_PREFIX . "order_product WHERE order_id = '" . (int)$order_id . "'"); + $this->load->language('extension/module/retailcrm'); - // Products - if (isset($order['order_product']) && $order['order_product']) { - $this->addOrderProducts($order_id, $order['order_product']); + $this->data_repository = new \retailcrm\repository\DataRepository($this->registry); + $this->orders_history = new retailcrm\history\Order( + $this->data_repository, + new \retailcrm\service\SettingsManager($this->registry), + new \retailcrm\repository\ProductsRepository($this->registry), + new \retailcrm\repository\OrderRepository($this->registry) + ); + + $this->customers_history = new retailcrm\history\Customer( + $this->data_repository, + new \retailcrm\repository\CustomerRepository($this->registry), + new \retailcrm\service\SettingsManager($this->registry) + ); + + $this->orders_history->setOcDelivery( + $this->model_extension_retailcrm_references->getOpercartDeliveryTypes() + ); + + $this->orders_history->setOcPayment( + $this->model_extension_retailcrm_references->getOpercartPaymentTypes() + ); + + $settings = $this->model_setting_setting->getSetting($this->moduleTitle); + $history = $this->model_setting_setting->getSetting('retailcrm_history'); + $settings['domain'] = parse_url(HTTP_SERVER, PHP_URL_HOST); + + $url = isset($settings[$this->moduleTitle . '_url']) ? $settings[$this->moduleTitle . '_url'] : null; + $key = isset($settings[$this->moduleTitle . '_apikey']) ? $settings[$this->moduleTitle . '_apikey'] : null; + + if (empty($url) || empty($key)) { + $this->log->addNotice('You need to configure retailcrm module first.'); + + return false; } - // Totals - $this->db->query("DELETE FROM " . DB_PREFIX . "order_total WHERE order_id = '" . (int)$order_id . "'"); + $sinceIdOrders = $history['retailcrm_history_orders'] ? $history['retailcrm_history_orders'] : null; + $sinceIdCustomers = $history['retailcrm_history_customers'] ? $history['retailcrm_history_customers'] : null; - if (isset($order['order_total'])) { - $this->addOrderTotals($order_id, $order['order_total']); + $packsOrders = $retailcrmApiClient->ordersHistory(array( + 'sinceId' => $sinceIdOrders ? $sinceIdOrders : 0 + ), 1, 100); + $packsCustomers = $retailcrmApiClient->customersHistory(array( + 'sinceId' => $sinceIdCustomers ? $sinceIdCustomers : 0 + ), 1, 100); + + if (!$packsOrders->isSuccessful() && count($packsOrders->history) <= 0 + && !$packsCustomers->isSuccessful() && count($packsCustomers->history) <= 0 + ) { + return false; } - } - /** - * Add order products - * - * @param int $order_id - * @param array $products - * - * @return void - */ - public function addOrderProducts($order_id, $products) - { - foreach ($products as $product) { - $this->db->query("INSERT INTO " . DB_PREFIX . "order_product SET order_id = '" . (int)$order_id . "', product_id = '" . (int)$product['product_id'] . "', name = '" . $this->db->escape($product['name']) . "', model = '" . $this->db->escape($product['model']) . "', quantity = '" . (int)$product['quantity'] . "', price = '" . (float)$product['price'] . "', total = '" . (float)$product['total'] . "', reward = '" . (float)$product['reward'] . "'"); + $orders = RetailcrmHistoryHelper::assemblyOrder($packsOrders->history); + $customers = RetailcrmHistoryHelper::assemblyCustomer($packsCustomers->history); - $order_product_id = $this->db->getLastId(); + $ordersHistory = $packsOrders->history; + $customersHistory = $packsCustomers->history; - foreach ($product['option'] as $option) { - $this->db->query("INSERT INTO " . DB_PREFIX . "order_option SET order_id = '" . (int)$order_id . "', order_product_id = '" . (int)$order_product_id . "', product_option_id = '" . (int)$option['product_option_id'] . "', product_option_value_id = '" . (int)$option['product_option_value_id'] . "', name = '" . $this->db->escape($option['name']) . "', `value` = '" . $this->db->escape($option['value']) . "', `type` = '" . $this->db->escape($option['type']) . "'"); + $lastChangeOrders = $ordersHistory ? end($ordersHistory) : null; + $lastChangeCustomers = $customersHistory ? end($customersHistory) : null; + + if ($lastChangeOrders !== null) { + $sinceIdOrders = $lastChangeOrders['id']; + } + + if ($lastChangeCustomers !== null) { + $sinceIdCustomers = $lastChangeCustomers['id']; + } + + $this->settings = $settings; + + $this->status = array_flip($settings[$this->moduleTitle . '_status']); + + $updatedOrders = array(); + $newOrders = array(); + + foreach ($orders as $order) { + if (isset($order['deleted'])) { + continue; + } + + if (isset($order['externalId'])) { + $updatedOrders[] = $order['id']; + } else { + $newOrders[] = $order['id']; } } + + unset($orders); + + $updateCustomers = array(); + + foreach ($customers as $customer) { + if (isset($customer['deleted'])) { + continue; + } + + if (isset($customer['externalId'])) { + $updateCustomers[] = $customer['id']; + } + } + + unset($customers); + + if (!empty($updateCustomers)) { + $customers = $retailcrmApiClient->customersList(array('ids' => $updateCustomers)); + if ($customers) { + $this->updateCustomers($customers['customers']); + } + } + + if (!empty($newOrders)) { + $orders = $retailcrmApiClient->ordersList(array('ids' => $newOrders)); + if ($orders) { + $this->createResult = $this->createOrders($orders['orders'], $retailcrmApiClient); + } + } + + if (!empty($updatedOrders)) { + $orders = $retailcrmApiClient->ordersList(array('ids' => $updatedOrders)); + if ($orders) { + $this->updateOrders($orders['orders'], $retailcrmApiClient); + } + } + + $this->model_setting_setting->editSetting( + 'retailcrm_history', + array( + 'retailcrm_history_orders' => $sinceIdOrders, + 'retailcrm_history_customers' => $sinceIdCustomers + ) + ); + + if (!empty($this->createResult['customers'])) { + $retailcrmApiClient->customersFixExternalIds($this->createResult['customers']); + } + + if (!empty($this->createResult['orders'])) { + $retailcrmApiClient->ordersFixExternalIds($this->createResult['orders']); + } + + return true; } /** - * Add order totals + * Create orders from history * - * @param int $order_id - * @param array $totals + * @param array $orders + * @param \RetailcrmProxy $retailcrmApiClient + * + * @return array + */ + protected function createOrders($orders, $retailcrmApiClient) { + $customersIdsFix = array(); + $ordersIdsFix = array(); + + foreach ($orders as $order) { + $data = array(); + $corporateAddress = array(); + + if (!empty($order['customer']['type']) && $order['customer']['type'] === 'customer_corporate') { + $customer = $order['contact']; + if (empty($customer['address'])) { + $corporateAddress = $this->getCorporateCustomerAddress($retailcrmApiClient, $order); + + if (!empty($corporateAddress)) { + $customer['address'] = $corporateAddress; + } + } + } else { + $customer = $order['customer']; + } + + $customer_id = (!empty($customer['externalId'])) + ? $customer['externalId'] + : 0; + + if ($customer_id === 0) { + $customer_data = array(); + + $this->customers_history->handleCustomer($customer_data, $customer); + $address = $this->customers_history->handleAddress($customer, $order); + $this->customers_history->handleCustomFields($customer_data, $customer); + $customer_data['address'] = array($address); + $customer_id = $this->model_customer_customer->addCustomer($customer_data); + + $customersIdsFix[] = array('id' => $customer['id'], 'externalId' => (int)$customer_id); + } + + $this->orders_history->handleBaseOrderData($data, $order); + $this->orders_history->handleShipping($data, $order); + $this->orders_history->handlePayment($data, $order, $corporateAddress); + $this->orders_history->handleProducts($data, $order); + $this->orders_history->handleTotals($data, $order); + $this->orders_history->handleCustomFields($data, $order); + $data['customer_id'] = $customer_id; + + $data['order_status_id'] = 1; + + $order_id = $this->data_repository->addOrder($data); + + $ordersIdsFix[] = array('id' => $order['id'], 'externalId' => (int) $order_id); + } + + return array('customers' => $customersIdsFix, 'orders' => $ordersIdsFix); + } + + /** + * Update orders from history + * + * @param array $orders + * @param \RetailcrmProxy $retailcrmApiClient * * @return void */ - public function addOrderTotals($order_id, $totals) - { - foreach ($totals as $total) { - $this->db->query("INSERT INTO " . DB_PREFIX . "order_total SET order_id = '" . (int)$order_id . "', code = '" . $this->db->escape($total['code']) . "', title = '" . $this->db->escape($total['title']) . "', `value` = '" . (float)$total['value'] . "', sort_order = '" . (int)$total['sort_order'] . "'"); + protected function updateOrders($orders, $retailcrmApiClient) { + foreach ($orders as $order) { + $corporateAddress = array(); + $data = $this->model_sale_order->getOrder($order['externalId']); + + if (!empty($order['customer']['type']) && $order['customer']['type'] === 'customer_corporate') { + $customer = $order['contact']; + if (empty($customer['address'])) { + $corporateAddress = $this->getCorporateCustomerAddress($retailcrmApiClient, $order); + + if (!empty($corporateAddress)) { + $customer['address'] = $corporateAddress; + } + } + } else { + $customer = $order['customer']; + } + + $customer_id = (!empty($customer['externalId'])) + ? $customer['externalId'] + : 0; + + if ($customer_id === 0) { + $customer_data = array(); + + $this->customers_history->handleCustomer($customer_data, $customer); + $address = $this->customers_history->handleAddress($customer, $order); + $this->customers_history->handleCustomFields($customer_data, $customer); + $customer_data['address'] = array($address); + $customer_id = $this->model_customer_customer->addCustomer($customer_data); + + $this->createResult['customers'][] = array('id' => $customer['id'], 'externalId' => (int)$customer_id); + } + + $this->orders_history->handleBaseOrderData($data, $order); + $this->orders_history->handleShipping($data, $order); + $this->orders_history->handlePayment($data, $order, $corporateAddress); + $this->orders_history->handleProducts($data, $order); + $this->orders_history->handleTotals($data, $order); + $this->orders_history->handleCustomFields($data, $order); + + $data['customer_id'] = $customer_id; + if (array_key_exists($order['status'], $this->status)) { + $data['order_status_id'] = $this->status[$order['status']]; + } + + if (isset($this->settings[$this->moduleTitle . '_status_changes']) + && $this->settings[$this->moduleTitle . '_status_changes'] + ) { + $this->opencartApiClient->addHistory($order['externalId'], $data['order_status_id']); + } + + $this->data_repository->editOrder($order['externalId'], $data); + } + } + + protected function updateCustomers($customers) { + foreach ($customers as $customer) { + $customer_id = $customer['externalId']; + $customer_data = $this->model_customer_customer->getCustomer($customer_id); + + $this->customers_history->handleCustomer($customer_data, $customer); + $this->customers_history->handleCustomFields($customer_data, $customer); + + $updateAddress = $this->customers_history->handleAddress($customer, array(), $customer_data['address_id']); + $addresses = $this->model_customer_customer->getAddresses($customer_id); + $addresses[$customer_data['address_id']] = $updateAddress; + $customer_data['address'] = $addresses; + + $this->model_customer_customer->editCustomer($customer_id, $customer_data); } } /** - * Get total titles - * - * @return string $title - */ - protected function totalTitles() - { - if (version_compare(VERSION, '3.0', '<')) { - $title = ''; - } else { - $title = 'total_'; - } - - return $title; - } - - /** - * Get country by iso code 2 - * - * @param string $isoCode + * @param \RetailcrmProxy $retailcrmApiClient + * @param array $order * * @return array */ - public function getCountryByIsoCode($isoCode) - { - $query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "country` WHERE iso_code_2 = '" . $isoCode . "'"); + private function getCorporateCustomerAddress($retailcrmApiClient, $order) { + $addresses = $retailcrmApiClient->customersCorporateAddresses( + $order['customer']['id'], + array('ids' => array($order['customer']['mainAddress'])), + null, + null, + 'id' + ); - return $query->row; - } - - /** - * Get zone by name - * - * @param string $name - * - * @return array - */ - public function getZoneByName($name) - { - $query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "zone` WHERE name = '" . $name . "'"); - - return $query->row; - } - - /** - * Get currency - * - * @param string $code - * @param string $field (default = '') - * - * @return mixed array | string - */ - public function getCurrencyByCode($code, $field = '') - { - $query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "currency` WHERE code = '" . $code . "'"); - - if (!$field) { - return $query->row; + if ($addresses->isSuccessful() && !empty($addresses['addresses'])) { + return $addresses['addresses'][0]; } - return $query->row[$field]; - } - - /** - * Get language - * - * @param string $code - * @param string $field (default = '') - * - * @return mixed array | string - */ - public function getLanguageByCode($code, $field = '') - { - $query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "language` WHERE code = '" . $code . "'"); - - if (!$field) { - return $query->row; - } - - return $query->row[$field]; - } - - /** - * Get product option value - * - * @param int $option_value_id - * @param string $field - * - * @return mixed array | string - */ - public function getOptionValue($option_value_id, $field = '') - { - $query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "option_value_description` WHERE option_value_id = '" . $option_value_id . "'"); - - if (!$field) { - return $query->row; - } - - return $query->row[$field]; + return array(); } } diff --git a/src/upload/admin/model/extension/retailcrm/history/v3.php b/src/upload/admin/model/extension/retailcrm/history/v3.php deleted file mode 100644 index 25fadb0..0000000 --- a/src/upload/admin/model/extension/retailcrm/history/v3.php +++ /dev/null @@ -1,117 +0,0 @@ -retailcrm->getModuleTitle(); - $this->load->model('setting/setting'); - $this->load->model('setting/store'); - $this->load->model('user/api'); - $this->load->model('sale/order'); - $this->load->model('customer/customer'); - $this->load->model('extension/retailcrm/references'); - $this->load->model('catalog/product'); - $this->load->model('catalog/option'); - $this->load->model('localisation/zone'); - - $this->load->language('extension/module/retailcrm'); - - $settings = $this->model_setting_setting->getSetting($moduleTitle); - $history = $this->model_setting_setting->getSetting('retailcrm_history'); - $settings['domain'] = parse_url(HTTP_SERVER, PHP_URL_HOST); - - $url = isset($settings[$moduleTitle . '_url']) ? $settings[$moduleTitle . '_url'] : null; - $key = isset($settings[$moduleTitle . '_apikey']) ? $settings[$moduleTitle . '_apikey'] : null; - - if (empty($url) || empty($key)) { - $this->log->addNotice('You need to configure retailcrm module first.'); - return false; - } - - $lastRun = !empty($history['retailcrm_history_datetime']) - ? new DateTime($history['retailcrm_history_datetime']) - : new DateTime(date('Y-m-d H:i:s', strtotime('-1 days', strtotime(date('Y-m-d H:i:s'))))); - - $packsOrders = $retailcrmApiClient->ordersHistory($lastRun); - - if(!$packsOrders->isSuccessful() && count($packsOrders['orders']) <= 0) { - return false; - } - - $generatedAt = $packsOrders['generatedAt']; - - $this->totalTitle = $this->totalTitles(); - $this->subtotalSettings = $this->model_setting_setting->getSetting($this->totalTitle . 'sub_total'); - $this->totalSettings = $this->model_setting_setting->getSetting($this->totalTitle . 'total'); - $this->shippingSettings = $this->model_setting_setting->getSetting($this->totalTitle . 'shipping'); - $this->delivery = array_flip($settings[$moduleTitle . '_delivery']); - $this->payment = array_flip($settings[$moduleTitle . '_payment']); - $this->status = array_flip($settings[$moduleTitle . '_status']); - $this->payment_default = $settings[$moduleTitle . '_default_payment']; - $this->delivery_default = $settings[$moduleTitle . '_default_shipping']; - $this->ocPayment = $this->model_extension_retailcrm_references - ->getOpercartPaymentTypes(); - - $this->ocDelivery = $this->model_extension_retailcrm_references - ->getOpercartDeliveryTypes(); - - $this->zones = $this->model_localisation_zone->getZones(); - - $updatedOrders = array(); - $newOrders = array(); - $orders = $packsOrders['orders']; - - foreach ($orders as $order) { - - if (isset($order['deleted'])) { - continue; - } - - if (isset($order['externalId'])) { - $updatedOrders[] = $order['id']; - } else { - $newOrders[] = $order['id']; - } - } - - unset($orders); - - if (!empty($newOrders)) { - $orders = $retailcrmApiClient->ordersList($filter = array('ids' => $newOrders)); - if ($orders) { - $this->createResult = $this->createOrders($orders['orders']); - } - } - - if (!empty($updatedOrders)) { - $orders = $retailcrmApiClient->ordersList($filter = array('ids' => $updatedOrders)); - if ($orders) { - $this->updateOrders($orders['orders']); - } - } - - $this->model_setting_setting->editSetting('retailcrm_history', array('retailcrm_history_datetime' => $generatedAt)); - - if (!empty($this->createResult['customers'])) { - $retailcrmApiClient->customersFixExternalIds($this->createResult['customers']); - } - - if (!empty($this->createResult['orders'])) { - $retailcrmApiClient->ordersFixExternalIds($this->createResult['orders']); - } - - return true; - } -} diff --git a/src/upload/admin/model/extension/retailcrm/history/v4_5.php b/src/upload/admin/model/extension/retailcrm/history/v4_5.php deleted file mode 100644 index a6580dd..0000000 --- a/src/upload/admin/model/extension/retailcrm/history/v4_5.php +++ /dev/null @@ -1,837 +0,0 @@ -load->library('retailcrm/retailcrm'); - $this->moduleTitle = $this->retailcrm->getModuleTitle(); - $this->opencartApiClient = $this->retailcrm->getOcApiClient($registry); - } - - /** - * Getting changes from RetailCRM - * @param \RetailcrmProxy $retailcrmApiClient - * - * @return boolean - */ - public function request($retailcrmApiClient) - { - $this->load->library('retailcrm/retailcrm'); - $this->load->model('setting/setting'); - $this->load->model('setting/store'); - $this->load->model('user/api'); - $this->load->model('sale/order'); - $this->load->model('customer/customer'); - $this->load->model('extension/retailcrm/references'); - $this->load->model('catalog/product'); - $this->load->model('catalog/option'); - $this->load->model('localisation/zone'); - - $this->load->language('extension/module/retailcrm'); - - $settings = $this->model_setting_setting->getSetting($this->moduleTitle); - $history = $this->model_setting_setting->getSetting('retailcrm_history'); - $settings['domain'] = parse_url(HTTP_SERVER, PHP_URL_HOST); - - $url = isset($settings[$this->moduleTitle . '_url']) ? $settings[$this->moduleTitle . '_url'] : null; - $key = isset($settings[$this->moduleTitle . '_apikey']) ? $settings[$this->moduleTitle . '_apikey'] : null; - - if (empty($url) || empty($key)) { - $this->log->addNotice('You need to configure retailcrm module first.'); - return false; - } - - $sinceIdOrders = $history['retailcrm_history_orders'] ? $history['retailcrm_history_orders'] : null; - $sinceIdCustomers = $history['retailcrm_history_customers'] ? $history['retailcrm_history_customers'] : null; - - $packsOrders = $retailcrmApiClient->ordersHistory(array( - 'sinceId' => $sinceIdOrders ? $sinceIdOrders : 0 - ), 1, 100); - $packsCustomers = $retailcrmApiClient->customersHistory(array( - 'sinceId' => $sinceIdCustomers ? $sinceIdCustomers : 0 - ), 1, 100); - - if(!$packsOrders->isSuccessful() && count($packsOrders->history) <= 0 && !$packsCustomers->isSuccessful() && count($packsCustomers->history) <= 0) { - return false; - } - - $generatedAt = $packsOrders['generatedAt']; - $orders = RetailcrmHistoryHelper::assemblyOrder($packsOrders->history); - $customers = RetailcrmHistoryHelper::assemblyCustomer($packsCustomers->history); - - $ordersHistory = $packsOrders->history; - $customersHistory = $packsCustomers->history; - - $lastChangeOrders = $ordersHistory ? end($ordersHistory) : null; - $lastChangeCustomers = $customersHistory ? end($customersHistory) : null; - - if ($lastChangeOrders !== null) { - $sinceIdOrders = $lastChangeOrders['id']; - } - - if ($lastChangeCustomers !== null) { - $sinceIdCustomers = $lastChangeCustomers['id']; - } - - $this->settings = $settings; - $this->totalTitle = $this->totalTitles(); - $this->subtotalSettings = $this->model_setting_setting->getSetting($this->totalTitle . 'sub_total'); - $this->totalSettings = $this->model_setting_setting->getSetting($this->totalTitle . 'total'); - $this->shippingSettings = $this->model_setting_setting->getSetting($this->totalTitle . 'shipping'); - - $this->delivery = array_flip($settings[$this->moduleTitle . '_delivery']); - $this->payment = array_flip($settings[$this->moduleTitle . '_payment']); - $this->status = array_flip($settings[$this->moduleTitle . '_status']); - $this->delivery_default = $settings[$this->moduleTitle . '_default_shipping']; - $this->payment_default = $settings[$this->moduleTitle . '_default_payment']; - $this->ocPayment = $this->model_extension_retailcrm_references - ->getOpercartPaymentTypes(); - - $this->ocDelivery = $this->model_extension_retailcrm_references - ->getOpercartDeliveryTypes(); - - $this->zones = $this->model_localisation_zone->getZones(); - - if (isset($settings[$this->moduleTitle . '_custom_field'])) { - $this->customFieldSetting = array_flip($settings[$this->moduleTitle . '_custom_field']); - } - - $updatedOrders = array(); - $newOrders = array(); - - foreach ($orders as $order) { - - if (isset($order['deleted'])) { - continue; - } - - if (isset($order['externalId'])) { - $updatedOrders[] = $order['id']; - } else { - $newOrders[] = $order['id']; - } - } - - unset($orders); - - $updateCustomers = array(); - - foreach ($customers as $customer) { - - if (isset($customer['deleted'])) { - continue; - } - - if (isset($customer['externalId'])) { - $updateCustomers[] = $customer['id']; - } - } - - unset($customers); - - if (!empty($updateCustomers)) { - $customers = $retailcrmApiClient->customersList($filter = array('ids' => $updateCustomers)); - if ($customers) { - $this->updateCustomers($customers['customers']); - } - } - - if (!empty($newOrders)) { - $orders = $retailcrmApiClient->ordersList($filter = array('ids' => $newOrders)); - if ($orders) { - $this->createResult = $this->createOrders($orders['orders']); - } - } - - if (!empty($updatedOrders)) { - $orders = $retailcrmApiClient->ordersList($filter = array('ids' => $updatedOrders)); - if ($orders) { - $this->updateOrders($orders['orders']); - } - } - - $this->model_setting_setting->editSetting( - 'retailcrm_history', - array( - 'retailcrm_history_orders' => $sinceIdOrders, - 'retailcrm_history_customers' => $sinceIdCustomers, - 'retailcrm_history_datetime' => $generatedAt - ) - ); - - if (!empty($this->createResult['customers'])) { - $retailcrmApiClient->customersFixExternalIds($this->createResult['customers']); - } - - if (!empty($this->createResult['orders'])) { - $retailcrmApiClient->ordersFixExternalIds($this->createResult['orders']); - } - - return true; - } - - /** - * Update orders from history - * - * @param array $orders - * - * @return void - */ - protected function updateOrders($orders) - { - foreach ($orders as $order) { - $ocOrder = $this->model_sale_order->getOrder($order['externalId']); - - if (isset($order['payments']) && $order['payments']) { - foreach ($order['payments'] as $orderPayment) { - if (isset($orderPayment['externalId'])) { - $payment = $orderPayment; - } - } - - if (!isset($payment) && count($order['payments']) == 1) { - $payment = end($order['payments']); - } - } elseif (isset($order['paymentType'])) { - $payment['type'] = $order['paymentType']; - } - - $data = array(); - - $mail = isset($order['email']) ? $order['email'] : $order['customer']['email']; - $phone = isset($order['phone']) ? $order['phone'] : ''; - - if (!$phone) { - $data['telephone'] = $order['customer']['phones'] ? $order['customer']['phones'][0]['number'] : '80000000000'; - } else { - $data['telephone'] = $phone; - } - - if (isset($order['customer']['externalId']) && $order['customer']['externalId']) { - $customer = $this->model_customer_customer->getCustomer($order['customer']['externalId']); - } - - $data['customer'] = $order['firstName']; - $data['customer_id'] = (isset($customer)) ? $customer['customer_id'] : 0; - $data['customer_group_id'] = (isset($customer)) ? $customer['customer_group_id'] : 1; - $data['firstname'] = $order['firstName']; - $data['lastname'] = isset($order['lastName']) ? $order['lastName'] : $order['firstName']; - $data['email'] = $mail ? $mail : uniqid() . '@retailrcm.ru'; - $data['comment'] = !empty($order['customerComment']) ? $order['customerComment'] : ''; - $data['payment_address'] = '0'; - $data['payment_firstname'] = $order['firstName']; - $data['payment_lastname'] = isset($order['lastName']) ? $order['lastName'] : $order['firstName']; - $data['payment_address_1'] = isset($order['customer']['address']) ? $order['customer']['address']['text'] : ''; - $data['payment_address_2'] = ''; - $data['payment_city'] = !empty($order['customer']['address']['city']) ? $order['customer']['address']['city'] : $order['delivery']['address']['city']; - $data['payment_postcode'] = !empty( $order['customer']['address']['index'] ) ? $order['customer']['address']['index'] : $order['delivery']['address']['index']; - - $shippingZone = ''; - - if (is_int($order['delivery']['address']['region'])) { - $shippingZone = $order['delivery']['address']['region']; - } else { - $shippingZone = $this->getZoneByName($order['delivery']['address']['region']); - - if ($shippingZone) { - $shipping_zone_id = $shippingZone['zone_id']; - } else { - $shipping_zone_id = 0; - } - } - - if (isset($order['customer']['address']['region'])) { - $paymentZone = $this->getZoneByName($order['customer']['address']['region']); - - if ($paymentZone) { - $payment_zone_id = $paymentZone['zone_id']; - } else { - $payment_zone_id = 0; - } - } - - if (isset($order['countryIso']) && !empty($order['countryIso'])) { - $shippingCountry = $this->getCountryByIsoCode($order['countryIso']); - } - - if (isset($order['customer']['address']['countryIso']) && !empty($order['customer']['address']['countryIso'])) { - $paymentCountry = $this->getCountryByIsoCode($order['customer']['address']['countryIso']); - } else { - $paymentCountry = $this->getCountryByIsoCode($order['countryIso']); - } - - $delivery = isset($order['delivery']['code']) ? $order['delivery']['code'] : null; - $data['payment_country_id'] = $paymentCountry ? $paymentCountry['country_id'] : $ocOrder['payment_country_id']; - $data['payment_country'] = isset($paymentCountry) ? $paymentCountry['name'] : $ocOrder['payment_country']; - $data['payment_zone_id'] = $payment_zone_id ? $payment_zone_id : $ocOrder['payment_zone_id']; - $data['payment_zone'] = isset($order['customer']['address']['region']) ? $order['customer']['address']['region'] : $ocOrder['payment_zone']; - $data['shipping_country_id'] = isset($shippingCountry) ? $shippingCountry['country_id'] : $ocOrder['shipping_country_id']; - $data['shipping_country'] = isset($shippingCountry) ? $shippingCountry['name'] : $ocOrder['shipping_country']; - $data['shipping_zone_id'] = $shipping_zone_id ? $shipping_zone_id : $ocOrder['shipping_zone_id']; - $data['shipping_zone'] = $shippingZone ? $shippingZone['name'] : $ocOrder['shipping_zone']; - $data['shipping_address'] = '0'; - $data['shipping_firstname'] = $order['firstName']; - $data['shipping_lastname'] = isset($order['lastName']) ? $order['lastName'] : $order['firstName']; - $data['shipping_address_1'] = $order['delivery']['address']['text']; - $data['shipping_address_2'] = ''; - $data['shipping_company'] = ''; - $data['shipping_company_id'] = ''; - $data['shipping_city'] = $order['delivery']['address']['city']; - $data['shipping_postcode'] = $order['delivery']['address']['index']; - - if ($delivery !== null) { - if (isset($this->settings[$this->moduleTitle . '_delivery'][$ocOrder['shipping_code']]) - && isset($this->delivery[$delivery]) - ) { - $data['shipping'] = $this->delivery[$delivery]; - - $shipping = explode('.', $data['shipping']); - $shippingModule = $shipping[0]; - - if (isset($this->ocDelivery[$shippingModule][$data['shipping']]['title'])) { - $data['shipping_method'] = $this->ocDelivery[$shippingModule][$data['shipping']]['title']; - } else { - $data['shipping_method'] = $this->ocDelivery[$shippingModule]['title']; - } - - $data['shipping_code'] = $data['shipping']; - } elseif (!isset($this->settings[$this->moduleTitle . '_delivery'][$ocOrder['shipping_code']]) - ) { - $data['shipping_method'] = $ocOrder['shipping_method']; - $data['shipping_code'] = $ocOrder['shipping_code']; - } - } else { - if (!isset($this->settings[$ocOrder['shipping_code']]) - || !isset($this->delivery[$delivery]) - ) { - $data['shipping_method'] = $ocOrder['shipping_method']; - $data['shipping_code'] = $ocOrder['shipping_code']; - } - } - - if (isset($payment)) { - $data['payment'] = $this->payment[$payment['type']]; - $data['payment_method'] = isset($this->ocPayment[$data['payment']]) ? $this->ocPayment[$data['payment']] : $ocOrder['payment_method']; - $data['payment_code'] = isset($this->payment[$payment['type']]) ? $this->payment[$payment['type']] : $ocOrder['payment_code']; - } else { - $data['payment_method'] = $ocOrder['payment_method']; - $data['payment_code'] = $ocOrder['payment_code']; - } - - // this data will not retrive from crm for now - $data['tax'] = ''; - $data['tax_id'] = ''; - $data['product'] = ''; - $data['product_id'] = ''; - $data['reward'] = ''; - $data['affiliate'] = ''; - $data['affiliate_id'] = ''; - $data['payment_tax_id'] = ''; - $data['order_product_id'] = ''; - $data['payment_company'] = ''; - $data['payment_company_id'] = ''; - $data['company'] = ''; - $data['company_id'] = ''; - - $data['order_product'] = array(); - - $discount = false; - - foreach ($order['items'] as $item) { - $productId = $item['offer']['externalId']; - $options = array(); - - if (isset($item['discountTotal']) && $item['discountTotal'] > 0) { - $discount = true; - } - - if (mb_strpos($item['offer']['externalId'], '#') > 1) { - $offer = explode('#', $item['offer']['externalId']); - $productId = $offer[0]; - $optionsFromCRM = explode('_', $offer[1]); - - foreach ($optionsFromCRM as $optionFromCRM) { - $optionData = explode('-', $optionFromCRM); - $productOptionId = $optionData[0]; - $optionValueId = $optionData[1]; - - $productOptions = $this->model_catalog_product->getProductOptions($productId); - - foreach($productOptions as $productOption) { - if($productOptionId == $productOption['product_option_id']) { - foreach($productOption['product_option_value'] as $productOptionValue) { - if($productOptionValue['option_value_id'] == $optionValueId) { - $options[] = array( - 'product_option_id' => $productOptionId, - 'product_option_value_id' => $productOptionValue['product_option_value_id'], - 'value' => $this->getOptionValue($productOptionValue['option_value_id'], 'name'), - 'type' => $productOption['type'], - 'name' => $productOption['name'], - ); - } - } - } - } - } - } - - $product = $this->model_catalog_product->getProduct($productId); - $rewards = $this->model_catalog_product->getProductRewards($productId); - - $data['order_product'][] = array( - 'name' => $product['name'], - 'model' => $product['model'], - 'price' => $item['initialPrice'], - 'total' => (float)($item['initialPrice'] * $item['quantity']), - 'product_id' => $productId, - 'quantity' => $item['quantity'], - 'option' => $options, - 'reward' => $rewards[$data['customer_group_id']]['points'] * $item['quantity'] - ); - } - - if (isset($this->customFieldSetting) && $order['customFields']) { - foreach ($order['customFields'] as $code => $value) { - if (array_key_exists($code, $this->customFieldSetting)) { - $fieldCode = str_replace('o_', '', $this->customFieldSetting[$code]); - $customFields[$fieldCode] = $value; - } - } - - $data['custom_field'] = isset($customFields) ? $customFields : ''; - } else { - $data['custom_field'] = $ocOrder['custom_field']; - } - - $deliveryCost = !empty($order['delivery']['cost']) ? $order['delivery']['cost'] : 0; - - $data['total'] = $order['totalSumm']; - $data['order_total'] = array( - array( - 'order_total_id' => '', - 'code' => 'sub_total', - 'title' => $this->language->get('product_summ'), - 'value' => $order['summ'], - 'text' => $order['summ'], - 'sort_order' => $this->subtotalSettings['sub_total_sort_order'] - ), - array( - 'order_total_id' => '', - 'code' => 'shipping', - 'title' => $data['shipping_method'], - 'value' => $deliveryCost, - 'text' => $deliveryCost, - 'sort_order' => $this->shippingSettings[$this->totalTitle . 'shipping_sort_order'] - ), - array( - 'order_total_id' => '', - 'code' => 'total', - 'title' => $this->language->get('column_total'), - 'value' => isset($order['totalSumm']) ? $order['totalSumm'] : $order['summ'] + $deliveryCost, - 'text' => isset($order['totalSumm']) ? $order['totalSumm'] : $order['summ'] + $deliveryCost, - 'sort_order' => $this->totalSettings[$this->totalTitle . 'total_sort_order'] - ) - ); - - if ((isset($order['discount']) - && $order['discount'] > 0) - || $discount - ) { - $orderTotals = $this->model_sale_order->getOrderTotals($order['externalId']); - foreach ($orderTotals as $orderTotal) { - if ($orderTotal['code'] == 'coupon' - || $orderTotal['code'] == 'reward' - ) { - $data['order_total'][] = $orderTotal; - } - } - } - - $data['fromApi'] = true; - - if (array_key_exists($order['status'], $this->status)) { - $data['order_status_id'] = $this->status[$order['status']]; - } else { - $tmpOrder = $this->model_sale_order->getOrder($order['externalId']); - $data['order_status_id'] = $tmpOrder['order_status_id']; - } - - if (isset($this->settings[$this->moduleTitle . '_status_changes']) - && $this->settings[$this->moduleTitle . '_status_changes'] - ) { - $this->opencartApiClient->addHistory($order['externalId'], $data['order_status_id']); - } - - $this->editOrder($order['externalId'], $data); - } - } - - /** - * Create orders from history - * - * @param array $orders - * - * @return array - */ - protected function createOrders($orders) - { - $customersIdsFix = array(); - $ordersIdsFix = array(); - - foreach ($orders as $order) { - $store = $this->config->get('config_store_id'); - - if (isset($order['payments']) && $order['payments']) { - $payment = end($order['payments']); - } elseif (isset($order['paymentType'])) { - $payment['type'] = $order['paymentType']; - } - - $customer_id = (!empty($order['customer']['externalId'])) - ? $order['customer']['externalId'] - : 0; - - $data = array(); - - if ($customer_id == 0) { - if (isset($order['customer']['address']['countryIso'])) { - $customerCountry = $this->getCountryByIsoCode($order['customer']['address']['countryIso']); - } else { - $customerCountry = $this->getCountryByIsoCode($order['delivery']['address']['countryIso']); - } - - if (isset($order['customer']['address']['region'])) { - $customerZone = $this->getZoneByName($order['customer']['address']['region']); - } else { - $customerZone = $this->getZoneByName($order['delivery']['address']['region']); - } - - $cData = array( - 'store_id' => 0, - 'customer_group_id' => '1', - 'firstname' => isset($order['patronymic']) ? $order['firstName'] . ' ' . $order['patronymic'] : $order['firstName'], - 'lastname' => (!empty($order['customer']['lastName'])) ? $order['customer']['lastName'] : ' ', - 'email' => $order['customer']['email'], - 'telephone' => $order['customer']['phones'] ? $order['customer']['phones'][0]['number'] : ' ', - 'fax' => '', - 'newsletter' => 0, - 'password' => 'tmppass', - 'status' => 1, - 'approved' => 1, - 'safe' => 0, - 'affiliate' => '', - 'address' => array( - array( - 'firstname' => isset($order['patronymic']) ? $order['firstName'] . ' ' . $order['patronymic'] : $order['firstName'], - 'lastname' => (!empty($order['customer']['lastName'])) ? $order['customer']['lastName'] : ' ', - 'address_1' => $order['customer']['address']['text'], - 'address_2' => ' ', - 'city' => !empty($order['customer']['address']['city']) ? $order['customer']['address']['city'] : $order['delivery']['address']['city'], - 'postcode' => isset($order['customer']['address']['index']) ? $order['customer']['address']['index'] : $order['delivery']['address']['index'], - 'tax_id' => '1', - 'company' => '', - 'company_id' => '', - 'zone_id' => $customerZone ? $customerZone['zone_id'] : 0, - 'country_id' => $customerCountry ? $customerCountry['country_id'] : 0, - 'default' => '1' - ) - ), - ); - - $customer_id = $this->model_customer_customer->addCustomer($cData); - - $customersIdsFix[] = array('id' => $order['customer']['id'], 'externalId' => (int)$customer_id); - } - - $mail = isset($order['email']) ? $order['email'] : $order['customer']['email']; - $phone = isset($order['phone']) ? $order['phone'] : ''; - - if (!$phone) { - $data['telephone'] = $order['customer']['phones'] ? $order['customer']['phones'][0]['number'] : '80000000000'; - } else { - $data['telephone'] = $phone; - } - - $data['currency_code'] = $this->config->get('config_currency'); - $data['currency_value'] = $this->getCurrencyByCode($data['currency_code'], 'value'); - $data['currency_id'] = $this->getCurrencyByCode($data['currency_code'], 'currency_id'); - $data['language_id'] = $this->getLanguageByCode($this->config->get('config_language'), 'language_id'); - $data['store_id'] = $store == null ? 0 : $store; - $data['store_name'] = $this->config->get('config_name'); - $data['customer'] = $order['firstName']; - $data['customer_id'] = $customer_id; - $data['customer_group_id'] = 1; - $data['firstname'] = $order['firstName']; - $data['lastname'] = (isset($order['lastName'])) ? $order['lastName'] : $order['firstName']; - $data['email'] = $mail ? $mail : uniqid() . '@retailrcm.ru'; - $data['comment'] = !empty($order['customerComment']) ? $order['customerComment'] : ''; - $data['fax'] = ''; - $data['payment_address'] = '0'; - $data['payment_firstname'] = $order['firstName']; - $data['payment_lastname'] = (isset($order['lastName'])) ? $order['lastName'] : $order['firstName']; - $data['payment_address_1'] = $order['customer']['address']['text']; - $data['payment_address_2'] = ''; - $data['payment_company'] = ''; - $data['payment_company_id'] = ''; - $data['payment_city'] = !empty($order['customer']['address']['city']) ? $order['customer']['address']['city'] : $order['delivery']['address']['city']; - $data['payment_postcode'] = !empty($order['customer']['address']['index']) ? $order['customer']['address']['index'] : $order['delivery']['address']['index']; - - $shippingZone = ''; - - if (!empty($order['delivery']['address']['region']) && is_int($order['delivery']['address']['region'])) { - $shippingZone = $order['delivery']['address']['region']; - } else { - $shippingZone = $this->getZoneByName($order['delivery']['address']['region']); - - if ($shippingZone) { - $shipping_zone_id = $shippingZone['zone_id']; - } else { - $shipping_zone_id = 0; - } - } - - if (isset($order['customer']['address']['region'])) { - $paymentZone = $this->getZoneByName($order['customer']['address']['region']); - - if ($paymentZone) { - $payment_zone_id = $paymentZone['zone_id']; - } else { - $payment_zone_id = 0; - } - } - - if (isset($order['countryIso'])) { - $shippingCountry = $this->getCountryByIsoCode($order['countryIso']); - } - - if (isset($order['customer']['address']['countryIso'])) { - $paymentCountry = $this->getCountryByIsoCode($order['customer']['address']['countryIso']); - } - - $delivery = isset($order['delivery']['code']) ? $order['delivery']['code'] : null; - $data['payment_country_id'] = $paymentCountry ? $paymentCountry['country_id'] : 0; - $data['payment_country'] = isset($paymentCountry) ? $paymentCountry['name'] : ''; - $data['payment_zone_id'] = $payment_zone_id; - $data['payment_zone'] = isset($order['customer']['address']['region']) ? $order['customer']['address']['region'] : ''; - $data['shipping_country_id'] = isset($shippingCountry) ? $shippingCountry['country_id'] : 0; - $data['shipping_country'] = isset($shippingCountry) ? $shippingCountry['name'] : ''; - $data['shipping_zone_id'] = $shipping_zone_id; - $data['shipping_zone'] = $shippingZone ? $shippingZone['name'] : $data['payment_zone']; - $data['shipping_address'] = '0'; - $data['shipping_firstname'] = $order['firstName']; - $data['shipping_lastname'] = (isset($order['lastName'])) ? $order['lastName'] : $order['firstName']; - $data['shipping_address_1'] = $order['delivery']['address']['text']; - $data['shipping_address_2'] = ''; - $data['shipping_company'] = ''; - $data['shipping_company_id'] = ''; - $data['shipping_city'] = $order['delivery']['address']['city']; - $data['shipping_postcode'] = $order['delivery']['address']['index']; - $data['shipping'] = $delivery != null ? $this->delivery[$delivery] : $this->delivery_default; - $data['shipping_code'] = $delivery != null ? $this->delivery[$delivery] : $this->delivery_default; - - $shipping = explode('.', $data['shipping']); - $shippingModule = $shipping[0]; - - if (isset($this->ocDelivery[$shippingModule][$data['shipping']]['title'])) { - $data['shipping_method'] = $this->ocDelivery[$shippingModule][$data['shipping']]['title']; - } else { - $data['shipping_method'] = $this->ocDelivery[$shippingModule]['title']; - } - - if (isset($payment)) { - $data['payment'] = $this->payment[$payment['type']]; - $data['payment_method'] = $this->ocPayment[$data['payment']]; - $data['payment_code'] = $this->payment[$payment['type']]; - } else { - $data['payment'] = $this->payment_default; - $data['payment_method'] = $this->ocPayment[$data['payment']]; - $data['payment_code'] = $this->payment_default; - } - - // this data will not retrive from crm for now - $data['tax'] = ''; - $data['tax_id'] = ''; - $data['product'] = ''; - $data['product_id'] = ''; - $data['reward'] = ''; - $data['affiliate'] = ''; - $data['affiliate_id'] = 0; - $data['payment_tax_id'] = ''; - $data['order_product_id'] = ''; - $data['payment_company'] = ''; - $data['payment_company_id'] = ''; - $data['company'] = ''; - $data['company_id'] = ''; - - $data['order_product'] = array(); - - foreach ($order['items'] as $item) { - $productId = $item['offer']['externalId']; - $options = array(); - - if(mb_strpos($item['offer']['externalId'], '#') > 1) { - $offer = explode('#', $item['offer']['externalId']); - $productId = $offer[0]; - $optionsFromCRM = explode('_', $offer[1]); - - foreach ($optionsFromCRM as $optionFromCRM) { - $optionData = explode('-', $optionFromCRM); - $productOptionId = $optionData[0]; - $optionValueId = $optionData[1]; - - $productOptions = $this->model_catalog_product->getProductOptions($productId); - - foreach($productOptions as $productOption) { - if($productOptionId == $productOption['product_option_id']) { - foreach($productOption['product_option_value'] as $productOptionValue) { - if($productOptionValue['option_value_id'] == $optionValueId) { - $options[] = array( - 'product_option_id' => $productOptionId, - 'product_option_value_id' => $productOptionValue['product_option_value_id'], - 'value' => $this->getOptionValue($productOptionValue['option_value_id'], 'name'), - 'type' => $productOption['type'], - 'name' => $productOption['name'], - ); - } - } - } - } - } - } - - $product = $this->model_catalog_product->getProduct($productId); - $rewards = $this->model_catalog_product->getProductRewards($productId); - - $data['order_product'][] = array( - 'name' => $product['name'], - 'model' => $product['model'], - 'price' => $item['initialPrice'], - 'total' => (float)($item['initialPrice'] * $item['quantity']), - 'product_id' => $productId, - 'quantity' => $item['quantity'], - 'option' => $options, - 'reward' => $rewards[$data['customer_group_id']]['points'] * $item['quantity'] - ); - } - - if (isset($this->customFieldSetting) && $order['customFields']) { - foreach ($order['customFields'] as $code => $value) { - if (array_key_exists($code, $this->customFieldSetting)) { - $fieldCode = str_replace('o_', '', $this->customFieldSetting[$code]); - $customFields[$fieldCode] = $value; - } - } - - $data['custom_field'] = isset($customFields) ? $customFields : ''; - } - - $deliveryCost = !empty($order['delivery']['cost']) ? $order['delivery']['cost'] : 0; - - $data['total'] = $order['totalSumm']; - $data['order_total'] = array( - array( - 'order_total_id' => '', - 'code' => 'sub_total', - 'title' => $this->language->get('product_summ'), - 'value' => $order['summ'], - 'text' => $order['summ'], - 'sort_order' => $this->subtotalSettings['sub_total_sort_order'] - ), - array( - 'order_total_id' => '', - 'code' => 'shipping', - 'title' => $data['shipping_method'], - 'value' => $deliveryCost, - 'text' => $deliveryCost, - 'sort_order' => $this->shippingSettings[$this->totalTitle . 'shipping_sort_order'] - ), - array( - 'order_total_id' => '', - 'code' => 'total', - 'title' => $this->language->get('column_total'), - 'value' => !empty($order['totalSumm']) ? $order['totalSumm'] : $order['summ'] + $deliveryCost, - 'text' => isset($order['totalSumm']) ? $order['totalSumm'] : $order['summ'] + $deliveryCost, - 'sort_order' => $this->totalSettings[$this->totalTitle . 'total_sort_order'] - ) - ); - - $data['fromApi'] = true; - $data['order_status_id'] = 1; - - $order_id = $this->addOrder($data); - - $ordersIdsFix[] = array('id' => $order['id'], 'externalId' => (int) $order_id); - } - - return array('customers' => $customersIdsFix, 'orders' => $ordersIdsFix); - } - - protected function updateCustomers($customers) - { - foreach ($customers as $customer) { - $customer_id = $customer['externalId']; - $customerData = $this->model_customer_customer->getCustomer($customer_id); - - if (!$customerData) { - continue; - } - - $customerData['password'] = false; - - $customerData['firstname'] = $customer['firstName']; - $customerData['lastname'] = isset($customer['lastName']) ? $customer['lastName'] : ''; - $customerData['email'] = $customer['email']; - $customerData['telephone'] = $customer['phones'] ? $customer['phones'][0]['number'] : ''; - - $customerAddress = $this->model_customer_customer->getAddress($customerData['address_id']); - - if (isset($customer['address']['countryIso'])) { - $customerCountry = $this->getCountryByIsoCode($customer['address']['countryIso']); - } - - if (isset($customer['address']['region'])) { - $customerZone = $this->getZoneByName($customer['address']['region']); - } - - $customerAddress['firstname'] = isset($customer['patronymic']) ? $customer['firstName'] . ' ' . $customer['patronymic'] : $customer['firstName']; - $customerAddress['lastname'] = isset($customer['lastName']) ? $customer['lastName'] : ''; - $customerAddress['address_1'] = $customer['address']['text']; - $customerAddress['city'] = $customer['address']['city']; - $customerAddress['postcode'] = isset($customer['address']['index']) ? $customer['address']['index'] : ''; - - if (isset($customerCountry)) { - $customerAddress['country_id'] = $customerCountry['country_id']; - } - - if (isset($customerZone) && isset($customerZone['zone_id'])) { - $customerAddress['zone_id'] = $customerZone['zone_id']; - } - - $customerData['address'] = array($customerAddress); - - if (isset($this->customFieldSetting) && $customer['customFields']) { - foreach ($customer['customFields'] as $code => $value) { - if (array_key_exists($code, $this->customFieldSetting)) { - $fieldCode = str_replace('c_', '', $this->customFieldSetting[$code]); - $customFields[$fieldCode] = $value; - } - } - - $customerData['custom_field'] = isset($customFields) ? $customFields : ''; - } - - $this->model_customer_customer->editCustomer($customer_id, $customerData); - } - } -} diff --git a/src/upload/admin/model/extension/retailcrm/order.php b/src/upload/admin/model/extension/retailcrm/order.php index 1046d6d..51b6318 100644 --- a/src/upload/admin/model/extension/retailcrm/order.php +++ b/src/upload/admin/model/extension/retailcrm/order.php @@ -1,335 +1,29 @@ load->model('setting/setting'); - $this->load->library('retailcrm/retailcrm'); - - $this->moduleTitle = $this->retailcrm->getModuleTitle(); - $this->settings = $this->model_setting_setting->getSetting($this->moduleTitle); - } - /** * Upload orders to CRM * * @param array $orders - * @param \RetailcrmProxy $retailcrmApiClient * * @return mixed */ - public function uploadToCrm($orders, $retailcrmApiClient) + public function uploadToCrm($orders) { - if ($retailcrmApiClient === false) { - return false; - } - $ordersToCrm = array(); + /** @var OrderManager $order_manager */ + $order_manager = $this->retailcrm->getOrderManager(); foreach ($orders as $order) { - $ordersToCrm[] = $this->process($order); + $ordersToCrm[] = $order_manager->prepareOrder($order, $order['products'], $order['totals']); } $chunkedOrders = array_chunk($ordersToCrm, 50); foreach($chunkedOrders as $ordersPart) { - $retailcrmApiClient->ordersUpload($ordersPart); + $order_manager->uploadOrders($ordersPart); } return $chunkedOrders; } - - /** - * Send one order by id - * - * @param array $order_data - * @param \RetailcrmProxy $retailcrmApiClient - * - * @return mixed - */ - public function uploadOrder($order_data, $retailcrmApiClient) - { - if ($retailcrmApiClient === false) { - return false; - } - - if (isset($this->request->post['fromApi'])) { - return false; - } - - $order = $this->process($order_data); - - if (isset($order['customer']['externalId'])) { - $this->load->model('extension/retailcrm/customer'); - $this->load->model('customer/customer'); - $customer = $this->model_customer_customer->getCustomer($order['customer']['externalId']); - $this->model_extension_retailcrm_customer->sendToCrm($customer, $retailcrmApiClient); - } else { - $customers = $retailcrmApiClient->customersList( - array( - 'name' => $order_data['telephone'], - 'email' => $order_data['email'] - ), - 1, - 100 - ); - - if ($customers) { - foreach ($customers['customers'] as $customer) { - $order['customer']['id'] = $customer['id']; - } - } - - unset($customers); - } - - if (!isset($order['customer']['externalId']) && !isset($order['customer']['id'])) { - $new_customer = array( - 'firstName' => $order_data['firstname'], - 'lastName' => $order_data['lastname'], - 'email' => $order_data['email'], - 'createdAt' => $order_data['date_added'], - 'address' => array( - 'countryIso' => $order_data['payment_iso_code_2'], - 'index' => $order_data['payment_postcode'], - 'city' => $order_data['payment_city'], - 'region' => $order_data['payment_zone'], - 'text' => $order_data['payment_address_1'] . ' ' . $order_data['payment_address_2'] - ) - ); - - if (!empty($order_data['telephone'])) { - $new_customer['phones'] = array( - array( - 'number' => $order_data['telephone'] - ) - ); - } - - $res = $retailcrmApiClient->customersCreate($new_customer); - - if ($res->isSuccessful() && isset($res['id'])) { - $order['customer']['id'] = $res['id']; - } - } - - self::$lastRepsonse = $retailcrmApiClient->ordersCreate($order); - - return $order; - } - - /** - * Process order - * - * @param array $order_data - * - * @return array $order - */ - private function process($order_data) { - $order = array(); - - $this->load->model('catalog/product'); - - if (!empty($order_data['payment_code']) && isset($this->settings[$this->moduleTitle . '_payment'][$order_data['payment_code']])) { - $payment_code = $this->settings[$this->moduleTitle . '_payment'][$order_data['payment_code']]; - } else { - $payment_code = ''; - } - - if (!empty($order_data['shipping_code'])) { - $shippingCode = explode('.', $order_data['shipping_code']); - $shippingModule = $shippingCode[0]; - - if (isset($this->settings[$this->moduleTitle . '_delivery'][$order_data['shipping_code']])) { - $delivery_code = $this->settings[$this->moduleTitle . '_delivery'][$order_data['shipping_code']]; - } elseif (isset($this->settings[$this->moduleTitle . '_delivery'][$shippingModule])) { - $delivery_code = $this->settings[$this->moduleTitle . '_delivery'][$shippingModule]; - } - } - - if (!isset($delivery_code) && isset($shippingModule)) { - if (isset($this->settings[$this->moduleTitle . '_delivery']) - && $this->settings[$this->moduleTitle . '_delivery'] - ) { - $deliveries = array_keys($this->settings[$this->moduleTitle . '_delivery']); - $shipping_code = ''; - - array_walk($deliveries, function($item, $key) use ($shippingModule, &$shipping_code) { - if (strripos($item, $shippingModule) !== false) { - $shipping_code = $item; - } - }); - - $delivery_code = $this->settings[$this->moduleTitle . '_delivery'][$shipping_code]; - } - } - - if (!empty($order_data['payment_iso_code_2'])) { - $order['countryIso'] = $order_data['payment_iso_code_2']; - } - - if (isset($this->settings[$this->moduleTitle . '_order_number']) - && $this->settings[$this->moduleTitle . '_order_number'] == 1 - ) { - $order['number'] = $order_data['order_id']; - } - - $order['externalId'] = $order_data['order_id']; - $order['firstName'] = $order_data['shipping_firstname']; - $order['lastName'] = $order_data['shipping_lastname']; - $order['phone'] = $order_data['telephone']; - $order['customerComment'] = $order_data['comment']; - - if (!empty($order_data['email'])) { - $order['email'] = $order_data['email']; - } - - if ($order_data['customer_id']) { - $order['customer']['externalId'] = $order_data['customer_id']; - } - - $deliveryCost = 0; - $orderTotals = isset($order_data['totals']) ? $order_data['totals'] : $order_data['order_total'] ; - - foreach ($orderTotals as $totals) { - if ($totals['code'] == 'shipping') { - $deliveryCost = $totals['value']; - } - } - - $order['createdAt'] = $order_data['date_added']; - - if ($this->settings[$this->moduleTitle . '_apiversion'] != 'v5') { - $order['paymentType'] = $payment_code; - } - - $country = (isset($order_data['shipping_country'])) ? $order_data['shipping_country'] : '' ; - - $order['delivery'] = array( - 'code' => isset($delivery_code) ? $delivery_code : '', - 'cost' => $deliveryCost, - 'address' => array( - 'countryIso' => $order_data['shipping_iso_code_2'], - 'index' => $order_data['shipping_postcode'], - 'city' => $order_data['shipping_city'], - 'region' => $order_data['shipping_zone'], - 'text' => implode(', ', array( - $order_data['shipping_postcode'], - $country, - $order_data['shipping_city'], - $order_data['shipping_address_1'], - $order_data['shipping_address_2'] - )) - ) - ); - - $orderProducts = isset($order_data['products']) ? $order_data['products'] : $order_data['order_product']; - $offerOptions = array('select', 'radio'); - - foreach ($orderProducts as $product) { - $offerId = ''; - - if (!empty($product['option'])) { - $options = array(); - - $productOptions = $this->model_catalog_product->getProductOptions($product['product_id']); - - foreach ($product['option'] as $option) { - if ($option['type'] == 'checkbox') { - $properties[] = array( - 'code' => $option['product_option_value_id'], - 'name' => $option['name'], - 'value' => $option['value'] - ); - } - - if (!in_array($option['type'], $offerOptions)) continue; - foreach($productOptions as $productOption) { - if($productOption['product_option_id'] = $option['product_option_id']) { - foreach($productOption['product_option_value'] as $productOptionValue) { - if($productOptionValue['product_option_value_id'] == $option['product_option_value_id']) { - $options[$option['product_option_id']] = $productOptionValue['option_value_id']; - } - } - } - } - } - - ksort($options); - - $offerId = array(); - foreach($options as $optionKey => $optionValue) { - $offerId[] = $optionKey.'-'.$optionValue; - } - $offerId = implode('_', $offerId); - } - - if ($this->settings[$this->moduleTitle . '_apiversion'] != 'v3') { - $item = array( - 'offer' => array( - 'externalId' => !empty($offerId) ? $product['product_id'].'#'.$offerId : $product['product_id'] - ), - 'productName' => $product['name'], - 'initialPrice' => $product['price'], - 'quantity' => $product['quantity'], - ); - } else { - $item = array( - 'productName' => $product['name'], - 'initialPrice' => $product['price'], - 'quantity' => $product['quantity'], - 'productId' => !empty($offerId) ? $product['product_id'].'#'.$offerId : $product['product_id'] - ); - } - - if (isset($properties)) $item['properties'] = $properties; - $order['items'][] = $item; - } - - if (isset($order_data['order_status_id']) && $order_data['order_status_id'] > 0) { - $order['status'] = $this->settings[$this->moduleTitle . '_status'][$order_data['order_status_id']]; - } - - if ($this->settings[$this->moduleTitle . '_apiversion'] == 'v5') { - if ($payment_code) { - $payment = array( - 'externalId' => $order_data['order_id'], - 'type' => $payment_code - ); - - $order['payments'][] = $payment; - } - } - - if (isset($this->settings[$this->moduleTitle . '_custom_field']) && $order_data['custom_field']) { - $customFields = json_decode($order_data['custom_field']); - - foreach ($customFields as $key => $value) { - if (isset($this->settings[$this->moduleTitle . '_custom_field']['o_' . $key])) { - $customFieldsToCrm[$this->settings[$this->moduleTitle . '_custom_field']['o_' . $key]] = $value; - } - } - - if (isset($customFieldsToCrm)) { - $order['customFields'] = $customFieldsToCrm; - } - } - - return $order; - } - - /** - * @return mixed - */ - public static function getLastResponse() - { - return self::$lastRepsonse; - } } diff --git a/src/upload/admin/model/extension/retailcrm/references.php b/src/upload/admin/model/extension/retailcrm/references.php index 722c499..aea9f0e 100644 --- a/src/upload/admin/model/extension/retailcrm/references.php +++ b/src/upload/admin/model/extension/retailcrm/references.php @@ -21,7 +21,7 @@ class ModelExtensionRetailcrmReferences extends Model /** * Get opencart delivery methods - * + * * @return array */ public function getOpercartDeliveryTypes() @@ -33,7 +33,7 @@ class ModelExtensionRetailcrmReferences extends Model /** * Get all delivery types - * + * * @return array */ public function getDeliveryTypes() @@ -48,7 +48,7 @@ class ModelExtensionRetailcrmReferences extends Model /** * Get all statuses - * + * * @return array */ public function getOrderStatuses() @@ -61,7 +61,7 @@ class ModelExtensionRetailcrmReferences extends Model /** * Get all payment types - * + * * @return array */ public function getPaymentTypes() @@ -74,7 +74,7 @@ class ModelExtensionRetailcrmReferences extends Model /** * Get all custom fields - * + * * @return array */ public function getCustomFields() @@ -87,7 +87,7 @@ class ModelExtensionRetailcrmReferences extends Model /** * Get opencart order statuses - * + * * @return array */ public function getOpercartOrderStatuses() @@ -100,7 +100,7 @@ class ModelExtensionRetailcrmReferences extends Model /** * Get opencart payment types - * + * * @return array */ public function getOpercartPaymentTypes() @@ -113,7 +113,7 @@ class ModelExtensionRetailcrmReferences extends Model $extension = basename($file, '.php'); $this->load->language('extension/payment/' . $extension); - + if (version_compare(VERSION, '3.0', '<')) { $configStatus = $extension . '_status'; } else { @@ -133,61 +133,73 @@ class ModelExtensionRetailcrmReferences extends Model /** * Get opencart custom fields - * + * * @return array */ public function getOpencartCustomFields() { $this->load->model('customer/custom_field'); - + return $this->model_customer_custom_field->getCustomFields(); } /** * Get RetailCRM delivery types - * + * * @return array */ public function getApiDeliveryTypes() { $response = $this->retailcrmApiClient->deliveryTypesList(); + if (!$response) { + return array(); + } return (!$response->isSuccessful()) ? array() : $response->deliveryTypes; } /** * Get RetailCRM order statuses - * + * * @return array */ public function getApiOrderStatuses() { $response = $this->retailcrmApiClient->statusesList(); + if (!$response) { + return array(); + } return (!$response->isSuccessful()) ? array() : $response->statuses; } /** * Get RetailCRM payment types - * + * * @return array */ public function getApiPaymentTypes() { $response = $this->retailcrmApiClient->paymentTypesList(); + if (!$response) { + return array(); + } return (!$response->isSuccessful()) ? array() : $response->paymentTypes; } /** * Get RetailCRM custom fields - * + * * @return array */ public function getApiCustomFields() { $customers = $this->retailcrmApiClient->customFieldsList(array('entity' => 'customer')); $orders = $this->retailcrmApiClient->customFieldsList(array('entity' => 'order')); + if (!$customers || !$orders) { + return array(); + } $customFieldsCustomers = (!$customers->isSuccessful()) ? array() : $customers->customFields; $customFieldsOrders = (!$orders->isSuccessful()) ? array() : $orders->customFields; @@ -195,18 +207,21 @@ class ModelExtensionRetailcrmReferences extends Model if (!$customFieldsCustomers && !$customFieldsOrders) { return array(); } - + return array('customers' => $customFieldsCustomers, 'orders' => $customFieldsOrders); } /** * Get RetailCRM price types - * + * * @return array */ public function getPriceTypes() { $response = $this->retailcrmApiClient->priceTypesList(); + if (!$response) { + return array(); + } return (!$response->isSuccessful()) ? array() : $response->priceTypes; } diff --git a/src/upload/admin/view/template/extension/module/retailcrm.tpl b/src/upload/admin/view/template/extension/module/retailcrm.tpl index 743b958..2e6f3da 100644 --- a/src/upload/admin/view/template/extension/module/retailcrm.tpl +++ b/src/upload/admin/view/template/extension/module/retailcrm.tpl @@ -40,9 +40,7 @@
  • -
  • -
  • @@ -51,16 +49,6 @@
    -
    - -
    - -
    -
    @@ -73,6 +61,21 @@
    +
    + +
    + + +
    +
    @@ -166,7 +169,6 @@
    -
    @@ -190,7 +192,6 @@
    -
    @@ -455,7 +456,6 @@
    -
    @@ -543,7 +543,6 @@
    -
    retailCRM API error log diff --git a/src/upload/admin/view/template/extension/module/retailcrm.twig b/src/upload/admin/view/template/extension/module/retailcrm.twig index 90679af..de5c92d 100644 --- a/src/upload/admin/view/template/extension/module/retailcrm.twig +++ b/src/upload/admin/view/template/extension/module/retailcrm.twig @@ -39,9 +39,7 @@ {% if saved_settings.module_retailcrm_apikey is defined and saved_settings.module_retailcrm_apikey and saved_settings.module_retailcrm_url is defined and saved_settings.module_retailcrm_url %}
  • {{ references_tab_text }}
  • {{ collector_tab_text }}
  • - {% if saved_settings.module_retailcrm_apiversion == 'v5' %} -
  • {{ custom_fields_tab_text }}
  • - {% endif %} +
  • {{ custom_fields_tab_text }}
  • {{ logs_tab_text }}
  • {% endif %} @@ -50,16 +48,6 @@
    {{ retailcrm_base_settings }} -
    - -
    - -
    -
    @@ -72,6 +60,25 @@
    +
    + +
    + + +
    +
    {{ retailcrm_countries_settings }} @@ -167,31 +174,29 @@
    - {% if saved_settings.module_retailcrm_apiversion is defined and saved_settings.module_retailcrm_apiversion != 'v3' %} -
    - {{ special_price_settings }} -
    - {% for customerGroup in customerGroups %} - {% set cud = customerGroup.customer_group_id %} -
    - -
    - -
    +
    + {{ special_price_settings }} +
    + {% for customerGroup in customerGroups %} + {% set cud = customerGroup.customer_group_id %} +
    + +
    +
    - {% endfor %} -
    -
    - {% endif %} +
    + {% endfor %} +
    +
    {{ order_number }}
    @@ -460,95 +465,93 @@ {% endfor %}
    - {% if saved_settings.module_retailcrm_apiversion is defined and saved_settings.module_retailcrm_apiversion == 'v5' and customFields is defined %} -
    -
    - {{ retailcrm_dict_custom_fields }} - {% if customFields.retailcrm is not empty and customFields.opencart is not empty %} -
    - -
    - - -
    +
    +
    + {{ retailcrm_dict_custom_fields }} + {% if customFields.retailcrm is not empty and customFields.opencart is not empty %} +
    + +
    + +
    -
    - -
    -
    - {% for customField in customFields.opencart %} -
    -
    - {% set fid = 'c_' ~ customField.custom_field_id %} -
    - -
    - +
    +
    + +
    +
    + {% for customField in customFields.opencart %} +
    +
    + {% set fid = 'c_' ~ customField.custom_field_id %} +
    +
    +
    - {% endfor %} -
    +
    + {% endfor %}
    -
    - -
    -
    - {% for customField in customFields.opencart %} -
    -
    - {% set fid = 'o_' ~ customField.custom_field_id %} -
    - -
    - +
    +
    + +
    +
    + {% for customField in customFields.opencart %} +
    +
    + {% set fid = 'o_' ~ customField.custom_field_id %} +
    +
    +
    - {% endfor %} -
    +
    + {% endfor %}
    - {% elseif customFields.retailcrm is empty and customFields.opencart is empty %} -
    - - {{ text_error_custom_field }} -
    - {% elseif customFields.retailcrm is empty %} -
    - - {{ text_error_cf_retailcrm }} -
    - {% elseif customFields.opencart is empty %} -
    - - {{ text_error_cf_opencart }} -
    - {% endif %} -
    -
    - {% endif %} +
    + {% elseif customFields.retailcrm is empty and customFields.opencart is empty %} +
    + + {{ text_error_custom_field }} +
    + {% elseif customFields.retailcrm is empty %} +
    + + {{ text_error_cf_retailcrm }} +
    + {% elseif customFields.opencart is empty %} +
    + + {{ text_error_cf_opencart }} +
    + {% endif %} +
    +
    Retailcrm API error log diff --git a/src/upload/catalog/controller/extension/module/retailcrm.php b/src/upload/catalog/controller/extension/module/retailcrm.php index 42874b9..6be57af 100644 --- a/src/upload/catalog/controller/extension/module/retailcrm.php +++ b/src/upload/catalog/controller/extension/module/retailcrm.php @@ -35,38 +35,35 @@ class ControllerExtensionModuleRetailcrm extends Controller { return; } - $this->load->model('checkout/order'); - $this->load->model('account/order'); $this->load->library('retailcrm/retailcrm'); - $data = $this->model_checkout_order->getOrder($order_id);; - $data['products'] = $this->model_account_order->getOrderProducts($order_id); - $data['totals'] = $this->model_account_order->getOrderTotals($order_id); + $order_data = $this->model_checkout_order->getOrder($order_id); + $products = $this->model_account_order->getOrderProducts($order_id); + $totals = $this->model_account_order->getOrderTotals($order_id); $moduleTitle = $this->retailcrm->getModuleTitle(); - foreach ($data['products'] as $key => $product) { + foreach ($products as $key => $product) { $productOptions = $this->model_account_order->getOrderOptions($order_id, $product['order_product_id']); if (!empty($productOptions)) { - $data['products'][$key]['option'] = $productOptions; + $products[$key]['option'] = $productOptions; } } $this->load->model('setting/setting'); $status = $this->model_setting_setting->getSetting($moduleTitle); - if (isset($data['order_status_id']) && $data['order_status_id'] > 0) { - $data['order_status'] = $status[$moduleTitle . '_status'][$data['order_status_id']]; + if (isset($order_data['order_status_id']) && $order_data['order_status_id'] > 0) { + $order_data['order_status'] = $status[$moduleTitle . '_status'][$order_data['order_status_id']]; } if (file_exists(DIR_APPLICATION . 'model/extension/retailcrm/custom/order.php')) { $this->load->model('extension/retailcrm/custom/order'); - $order = $this->model_extension_retailcrm_custom_order->processOrder($data); - $this->model_extension_retailcrm_custom_order->sendToCrm($order, $this->retailcrmApiClient, $data); + $order = $this->model_extension_retailcrm_custom_order->processOrder($order_data); + $this->model_extension_retailcrm_custom_order->sendToCrm($order, $this->retailcrmApiClient, $order_data); } else { - $this->load->model('extension/retailcrm/order'); - $order = $this->model_extension_retailcrm_order->processOrder($data); - $this->model_extension_retailcrm_order->sendToCrm($order, $this->retailcrmApiClient, $data); + $order_manager = $this->retailcrm->getOrderManager(); + $order_manager->createOrder($order_data, $products, $totals); } } @@ -85,8 +82,6 @@ class ControllerExtensionModuleRetailcrm extends Controller { $order_id = $parameter2[0]; - $this->load->model('checkout/order'); - $this->load->model('account/order'); $this->load->library('retailcrm/retailcrm'); $moduleTitle = $this->retailcrm->getModuleTitle(); @@ -96,19 +91,18 @@ class ControllerExtensionModuleRetailcrm extends Controller { return; } - $data['products'] = $this->model_account_order->getOrderProducts($order_id); - $data['totals'] = $this->model_account_order->getOrderTotals($order_id); + $products = $this->model_account_order->getOrderProducts($order_id); + $totals = $this->model_account_order->getOrderTotals($order_id); - foreach ($data['products'] as $key => $product) { + foreach ($products as $key => $product) { $productOptions = $this->model_account_order->getOrderOptions($order_id, $product['order_product_id']); if (!empty($productOptions)) { - $data['products'][$key]['option'] = $productOptions; + $products[$key]['option'] = $productOptions; } } if (!isset($data['fromApi'])) { - $this->load->model('setting/setting'); $status = $this->model_setting_setting->getSetting($moduleTitle); if ($data['order_status_id'] > 0) { @@ -120,9 +114,8 @@ class ControllerExtensionModuleRetailcrm extends Controller { $order = $this->model_extension_retailcrm_custom_order->processOrder($data, false); $this->model_extension_retailcrm_custom_order->sendToCrm($order, $this->retailcrmApiClient, $data, false); } else { - $this->load->model('extension/retailcrm/order'); - $order = $this->model_extension_retailcrm_order->processOrder($data, false); - $this->model_extension_retailcrm_order->sendToCrm($order, $this->retailcrmApiClient, $data, false); + $order_manager = $this->retailcrm->getOrderManager(); + $order_manager->editOrder($data, $products, $totals); } } } @@ -135,33 +128,16 @@ class ControllerExtensionModuleRetailcrm extends Controller { * @return void */ public function customer_create($parameter1, $parameter2 = null, $parameter3 = null) { - $this->load->model('account/customer'); - $this->load->model('localisation/country'); - $this->load->model('localisation/zone'); - $customerId = $parameter3; $customer = $this->model_account_customer->getCustomer($customerId); - if ($this->request->post) { - $country = $this->model_localisation_country->getCountry($this->request->post['country_id']); - $zone = $this->model_localisation_zone->getZone($this->request->post['zone_id']); - - $customer['address'] = array( - 'address_1' => $this->request->post['address_1'], - 'address_2' => $this->request->post['address_2'], - 'city' => $this->request->post['city'], - 'postcode' => $this->request->post['postcode'], - 'iso_code_2' => $country['iso_code_2'], - 'zone' => $zone['name'] - ); - } - if (file_exists(DIR_APPLICATION . 'model/extension/retailcrm/custom/customer.php')) { $this->load->model('extension/retailcrm/custom/customer'); $this->model_extension_retailcrm_custom_customer->sendToCrm($customer, $this->retailcrmApiClient); } else { - $this->load->model('extension/retailcrm/customer'); - $this->model_extension_retailcrm_customer->sendToCrm($customer, $this->retailcrmApiClient); + $address = array(); + $customer_manager = $this->retailcrm->getCustomerManager(); + $customer_manager->createCustomer($customer, $address); } } @@ -175,18 +151,16 @@ class ControllerExtensionModuleRetailcrm extends Controller { public function customer_edit($parameter1, $parameter2, $parameter3) { $customerId = $this->customer->getId(); - $this->load->model('account/customer'); $customer = $this->model_account_customer->getCustomer($customerId); - - $this->load->model('account/address'); - $customer['address'] = $this->model_account_address->getAddress($customer['address_id']); + $address = $this->model_account_address->getAddress($customer['address_id']); if (file_exists(DIR_APPLICATION . 'model/extension/retailcrm/custom/customer.php')) { $this->load->model('extension/retailcrm/custom/customer'); + $customer['address'] = $address; $this->model_extension_retailcrm_custom_customer->changeInCrm($customer, $this->retailcrmApiClient); } else { - $this->load->model('extension/retailcrm/customer'); - $this->model_extension_retailcrm_customer->changeInCrm($customer, $this->retailcrmApiClient); + $customer_manager = $this->retailcrm->getCustomerManager(); + $customer_manager->editCustomer($customer, $address); } } } diff --git a/src/upload/catalog/model/extension/retailcrm/customer.php b/src/upload/catalog/model/extension/retailcrm/customer.php deleted file mode 100644 index fd586e0..0000000 --- a/src/upload/catalog/model/extension/retailcrm/customer.php +++ /dev/null @@ -1,104 +0,0 @@ -load->model('setting/setting'); - $this->load->library('retailcrm/retailcrm'); - - $this->moduleTitle = $this->retailcrm->getModuleTitle(); - $this->settings = $this->model_setting_setting->getSetting($this->moduleTitle); - } - - /** - * Create customer - * - * @param array $customer - * - * @return mixed - */ - public function sendToCrm($customer, $retailcrmApiClient) - { - if (empty($customer) || $retailcrmApiClient === false) { - return false; - } - - $customerToCrm = $this->process($customer); - - $retailcrmApiClient->customersCreate($customerToCrm); - - return $customerToCrm; - } - - /** - * Edit customer - * - * @param array $customer - * - * @return mixed - */ - public function changeInCrm($customer, $retailcrmApiClient) - { - if (empty($customer) || $retailcrmApiClient === false) { - return false; - } - - $customerToCrm = $this->process($customer); - - $retailcrmApiClient->customersEdit($customerToCrm); - - return $customerToCrm; - } - - /** - * Process customer - * - * @param array $customer - * - * @return array $customerToCrm - */ - private function process($customer) { - $customerToCrm = array( - 'externalId' => $customer['customer_id'], - 'firstName' => $customer['firstname'], - 'lastName' => $customer['lastname'], - 'email' => $customer['email'], - 'phones' => array( - array( - 'number' => $customer['telephone'] - ) - ), - 'createdAt' => $customer['date_added'] - ); - - if (isset($customer['address'])) { - $customerToCrm['address'] = array( - 'index' => $customer['address']['postcode'], - 'countryIso' => $customer['address']['iso_code_2'], - 'region' => $customer['address']['zone'], - 'city' => $customer['address']['city'], - 'text' => $customer['address']['address_1'] . ' ' . $customer['address']['address_2'] - ); - } - - if (isset($this->settings[$this->moduleTitle . '_custom_field']) && $customer['custom_field']) { - $customFields = json_decode($customer['custom_field']); - - foreach ($customFields as $key => $value) { - if (isset($this->settings[$this->moduleTitle . '_custom_field']['c_' . $key])) { - $customFieldsToCrm[$this->settings[$this->moduleTitle . '_custom_field']['c_' . $key]] = $value; - } - } - - if (isset($customFieldsToCrm)) { - $customerToCrm['customFields'] = $customFieldsToCrm; - } - } - - return $customerToCrm; - } -} diff --git a/src/upload/system/library/retailcrm/RetailcrmApiClient3.php b/src/upload/system/library/retailcrm/RetailcrmApiClient3.php deleted file mode 100644 index d61d3e3..0000000 --- a/src/upload/system/library/retailcrm/RetailcrmApiClient3.php +++ /dev/null @@ -1,831 +0,0 @@ - - * @license https://opensource.org/licenses/MIT MIT License - * @link http://www.retailcrm.ru/docs/Developers/ApiVersion3 - */ -class RetailcrmApiClient3 -{ - protected $client; - - /** - * Site code - */ - protected $siteCode; - - /** - * Client creating - * - * @param string $url - * @param string $apiKey - * @param string $site - * @return mixed - */ - public function __construct($url, $apiKey, $version = null, $site = null) - { - if ('/' != substr($url, strlen($url) - 1, 1)) { - $url .= '/'; - } - - $url = $version == null ? $url . 'api' : $url . 'api/' . $version; - - $this->client = new RetailcrmHttpClient($url, array('apiKey' => $apiKey)); - $this->siteCode = $site; - } - - /** - * Returns api versions list - * - * @throws \RetailCrm\Exception\InvalidJsonException - * @throws \RetailCrm\Exception\CurlException - * @throws \InvalidArgumentException - * - * @return ApiResponse - */ - public function apiVersions() - { - return $this->client->makeRequest('/api-versions', RetailcrmHttpClient::METHOD_GET); - } - - /** - * Create a order - * - * @param array $order - * @param string $site (default: null) - * @return ApiResponse - */ - public function ordersCreate(array $order, $site = null) - { - if (!sizeof($order)) { - throw new InvalidArgumentException('Parameter `order` must contains a data'); - } - - return $this->client->makeRequest("/orders/create", RetailcrmHttpClient::METHOD_POST, $this->fillSite($site, array( - 'order' => json_encode($order) - ))); - } - - /** - * Edit a order - * - * @param array $order - * @param string $by - * @param string $site (default: null) - * @return ApiResponse - */ - public function ordersEdit(array $order, $by = 'externalId', $site = null) - { - if (!sizeof($order)) { - throw new InvalidArgumentException('Parameter `order` must contains a data'); - } - - $this->checkIdParameter($by); - - if (!isset($order[$by])) { - throw new InvalidArgumentException(sprintf('Order array must contain the "%s" parameter.', $by)); - } - - return $this->client->makeRequest( - "/orders/" . $order[$by] . "/edit", - RetailcrmHttpClient::METHOD_POST, - $this->fillSite($site, array( - 'order' => json_encode($order), - 'by' => $by, - )) - ); - } - - /** - * Upload array of the orders - * - * @param array $orders - * @param string $site (default: null) - * @return ApiResponse - */ - public function ordersUpload(array $orders, $site = null) - { - if (!sizeof($orders)) { - throw new InvalidArgumentException('Parameter `orders` must contains array of the orders'); - } - - return $this->client->makeRequest("/orders/upload", RetailcrmHttpClient::METHOD_POST, $this->fillSite($site, array( - 'orders' => json_encode($orders), - ))); - } - - /** - * Get order by id or externalId - * - * @param string $id - * @param string $by (default: 'externalId') - * @param string $site (default: null) - * @return ApiResponse - */ - public function ordersGet($id, $by = 'externalId', $site = null) - { - $this->checkIdParameter($by); - - return $this->client->makeRequest("/orders/$id", RetailcrmHttpClient::METHOD_GET, $this->fillSite($site, array( - 'by' => $by - ))); - } - - /** - * Returns a orders history - * - * @param DateTime $startDate (default: null) - * @param DateTime $endDate (default: null) - * @param int $limit (default: 100) - * @param int $offset (default: 0) - * @param bool $skipMyChanges (default: true) - * @return ApiResponse - */ - public function ordersHistory( - DateTime $startDate = null, - DateTime $endDate = null, - $limit = 100, - $offset = 0, - $skipMyChanges = true - ) { - $parameters = array(); - - if ($startDate) { - $parameters['startDate'] = $startDate->format('Y-m-d H:i:s'); - } - if ($endDate) { - $parameters['endDate'] = $endDate->format('Y-m-d H:i:s'); - } - if ($limit) { - $parameters['limit'] = (int) $limit; - } - if ($offset) { - $parameters['offset'] = (int) $offset; - } - if ($skipMyChanges) { - $parameters['skipMyChanges'] = (bool) $skipMyChanges; - } - - return $this->client->makeRequest('/orders/history', RetailcrmHttpClient::METHOD_GET, $parameters); - } - - /** - * Returns filtered orders list - * - * @param array $filter (default: array()) - * @param int $page (default: null) - * @param int $limit (default: null) - * @return ApiResponse - */ - public function ordersList(array $filter = array(), $page = null, $limit = null) - { - $parameters = array(); - - if (sizeof($filter)) { - $parameters['filter'] = $filter; - } - if (null !== $page) { - $parameters['page'] = (int) $page; - } - if (null !== $limit) { - $parameters['limit'] = (int) $limit; - } - - return $this->client->makeRequest('/orders', RetailcrmHttpClient::METHOD_GET, $parameters); - } - - /** - * Returns statuses of the orders - * - * @param array $ids (default: array()) - * @param array $externalIds (default: array()) - * @return ApiResponse - */ - public function ordersStatuses(array $ids = array(), array $externalIds = array()) - { - $parameters = array(); - - if (sizeof($ids)) { - $parameters['ids'] = $ids; - } - if (sizeof($externalIds)) { - $parameters['externalIds'] = $externalIds; - } - - return $this->client->makeRequest('/orders/statuses', RetailcrmHttpClient::METHOD_GET, $parameters); - } - - /** - * Save order IDs' (id and externalId) association in the CRM - * - * @param array $ids - * @return ApiResponse - */ - public function ordersFixExternalIds(array $ids) - { - if (!sizeof($ids)) { - throw new InvalidArgumentException('Method parameter must contains at least one IDs pair'); - } - - return $this->client->makeRequest("/orders/fix-external-ids", RetailcrmHttpClient::METHOD_POST, array( - 'orders' => json_encode($ids), - )); - } - - /** - * Get orders assembly history - * - * @param array $filter (default: array()) - * @param int $page (default: null) - * @param int $limit (default: null) - * @return ApiResponse - */ - public function ordersPacksHistory(array $filter = array(), $page = null, $limit = null) - { - $parameters = array(); - - if (sizeof($filter)) { - $parameters['filter'] = $filter; - } - if (null !== $page) { - $parameters['page'] = (int) $page; - } - if (null !== $limit) { - $parameters['limit'] = (int) $limit; - } - - return $this->client->makeRequest('/orders/packs/history', RetailcrmHttpClient::METHOD_GET, $parameters); - } - - /** - * Create a customer - * - * @param array $customer - * @param string $site (default: null) - * @return ApiResponse - */ - public function customersCreate(array $customer, $site = null) - { - if (!sizeof($customer)) { - throw new InvalidArgumentException('Parameter `customer` must contains a data'); - } - - return $this->client->makeRequest("/customers/create", RetailcrmHttpClient::METHOD_POST, $this->fillSite($site, array( - 'customer' => json_encode($customer) - ))); - } - - /** - * Edit a customer - * - * @param array $customer - * @param string $by (default: 'externalId') - * @param string $site (default: null) - * @return ApiResponse - */ - public function customersEdit(array $customer, $by = 'externalId', $site = null) - { - if (!sizeof($customer)) { - throw new InvalidArgumentException('Parameter `customer` must contains a data'); - } - - $this->checkIdParameter($by); - - if (!isset($customer[$by])) { - throw new InvalidArgumentException(sprintf('Customer array must contain the "%s" parameter.', $by)); - } - - return $this->client->makeRequest( - "/customers/" . $customer[$by] . "/edit", - RetailcrmHttpClient::METHOD_POST, - $this->fillSite( - $site, - array( - 'customer' => json_encode($customer), - 'by' => $by - ) - ) - ); - } - - /** - * Upload array of the customers - * - * @param array $customers - * @param string $site (default: null) - * @return ApiResponse - */ - public function customersUpload(array $customers, $site = null) - { - if (!sizeof($customers)) { - throw new InvalidArgumentException('Parameter `customers` must contains array of the customers'); - } - - return $this->client->makeRequest("/customers/upload", RetailcrmHttpClient::METHOD_POST, $this->fillSite($site, array( - 'customers' => json_encode($customers), - ))); - } - - /** - * Get customer by id or externalId - * - * @param string $id - * @param string $by (default: 'externalId') - * @param string $site (default: null) - * @return ApiResponse - */ - public function customersGet($id, $by = 'externalId', $site = null) - { - $this->checkIdParameter($by); - - return $this->client->makeRequest("/customers/$id", RetailcrmHttpClient::METHOD_GET, $this->fillSite($site, array( - 'by' => $by - ))); - } - - /** - * Returns filtered customers list - * - * @param array $filter (default: array()) - * @param int $page (default: null) - * @param int $limit (default: null) - * @return ApiResponse - */ - public function customersList(array $filter = array(), $page = null, $limit = null) - { - $parameters = array(); - - if (sizeof($filter)) { - $parameters['filter'] = $filter; - } - if (null !== $page) { - $parameters['page'] = (int) $page; - } - if (null !== $limit) { - $parameters['limit'] = (int) $limit; - } - - return $this->client->makeRequest('/customers', RetailcrmHttpClient::METHOD_GET, $parameters); - } - - /** - * Save customer IDs' (id and externalId) association in the CRM - * - * @param array $ids - * @return ApiResponse - */ - public function customersFixExternalIds(array $ids) - { - if (!sizeof($ids)) { - throw new InvalidArgumentException('Method parameter must contains at least one IDs pair'); - } - - return $this->client->makeRequest("/customers/fix-external-ids", RetailcrmHttpClient::METHOD_POST, array( - 'customers' => json_encode($ids), - )); - } - - /** - * Get purchace prices & stock balance - * - * @param array $filter (default: array()) - * @param int $page (default: null) - * @param int $limit (default: null) - * @param string $site (default: null) - * @return ApiResponse - */ - public function storeInventories(array $filter = array(), $page = null, $limit = null, $site = null) - { - $parameters = array(); - - if (sizeof($filter)) { - $parameters['filter'] = $filter; - } - if (null !== $page) { - $parameters['page'] = (int) $page; - } - if (null !== $limit) { - $parameters['limit'] = (int) $limit; - } - - return $this->client->makeRequest('/store/inventories', RetailcrmHttpClient::METHOD_GET, $this->fillSite($site, $parameters)); - } - - /** - * Upload store inventories - * - * @param array $offers - * @param string $site (default: null) - * @return ApiResponse - */ - public function storeInventoriesUpload(array $offers, $site = null) - { - if (!sizeof($offers)) { - throw new InvalidArgumentException('Parameter `offers` must contains array of the customers'); - } - - return $this->client->makeRequest( - "/store/inventories/upload", - RetailcrmHttpClient::METHOD_POST, - $this->fillSite($site, array('offers' => json_encode($offers))) - ); - } - - /** - * Returns deliveryServices list - * - * @return ApiResponse - */ - public function deliveryServicesList() - { - return $this->client->makeRequest('/reference/delivery-services', RetailcrmHttpClient::METHOD_GET); - } - - /** - * Returns deliveryTypes list - * - * @return ApiResponse - */ - public function deliveryTypesList() - { - return $this->client->makeRequest('/reference/delivery-types', RetailcrmHttpClient::METHOD_GET); - } - - /** - * Returns orderMethods list - * - * @return ApiResponse - */ - public function orderMethodsList() - { - return $this->client->makeRequest('/reference/order-methods', RetailcrmHttpClient::METHOD_GET); - } - - /** - * Returns orderTypes list - * - * @return ApiResponse - */ - public function orderTypesList() - { - return $this->client->makeRequest('/reference/order-types', RetailcrmHttpClient::METHOD_GET); - } - - /** - * Returns paymentStatuses list - * - * @return ApiResponse - */ - public function paymentStatusesList() - { - return $this->client->makeRequest('/reference/payment-statuses', RetailcrmHttpClient::METHOD_GET); - } - - /** - * Returns paymentTypes list - * - * @return ApiResponse - */ - public function paymentTypesList() - { - return $this->client->makeRequest('/reference/payment-types', RetailcrmHttpClient::METHOD_GET); - } - - /** - * Returns productStatuses list - * - * @return ApiResponse - */ - public function productStatusesList() - { - return $this->client->makeRequest('/reference/product-statuses', RetailcrmHttpClient::METHOD_GET); - } - - /** - * Returns statusGroups list - * - * @return ApiResponse - */ - public function statusGroupsList() - { - return $this->client->makeRequest('/reference/status-groups', RetailcrmHttpClient::METHOD_GET); - } - - /** - * Returns statuses list - * - * @return ApiResponse - */ - public function statusesList() - { - return $this->client->makeRequest('/reference/statuses', RetailcrmHttpClient::METHOD_GET); - } - - /** - * Returns sites list - * - * @return ApiResponse - */ - public function sitesList() - { - return $this->client->makeRequest('/reference/sites', RetailcrmHttpClient::METHOD_GET); - } - - /** - * Returns stores list - * - * @return ApiResponse - */ - public function storesList() - { - return $this->client->makeRequest('/reference/stores', RetailcrmHttpClient::METHOD_GET); - } - - /** - * Edit deliveryService - * - * @param array $data delivery service data - * @return ApiResponse - */ - public function deliveryServicesEdit(array $data) - { - if (!isset($data['code'])) { - throw new InvalidArgumentException('Data must contain "code" parameter.'); - } - - return $this->client->makeRequest( - '/reference/delivery-services/' . $data['code'] . '/edit', - RetailcrmHttpClient::METHOD_POST, - array( - 'deliveryService' => json_encode($data) - ) - ); - } - - /** - * Edit deliveryType - * - * @param array $data delivery type data - * @return ApiResponse - */ - public function deliveryTypesEdit(array $data) - { - if (!isset($data['code'])) { - throw new InvalidArgumentException('Data must contain "code" parameter.'); - } - - return $this->client->makeRequest( - '/reference/delivery-types/' . $data['code'] . '/edit', - RetailcrmHttpClient::METHOD_POST, - array( - 'deliveryType' => json_encode($data) - ) - ); - } - - /** - * Edit orderMethod - * - * @param array $data order method data - * @return ApiResponse - */ - public function orderMethodsEdit(array $data) - { - if (!isset($data['code'])) { - throw new InvalidArgumentException('Data must contain "code" parameter.'); - } - - return $this->client->makeRequest( - '/reference/order-methods/' . $data['code'] . '/edit', - RetailcrmHttpClient::METHOD_POST, - array( - 'orderMethod' => json_encode($data) - ) - ); - } - - /** - * Edit orderType - * - * @param array $data order type data - * @return ApiResponse - */ - public function orderTypesEdit(array $data) - { - if (!isset($data['code'])) { - throw new InvalidArgumentException('Data must contain "code" parameter.'); - } - - return $this->client->makeRequest( - '/reference/order-types/' . $data['code'] . '/edit', - RetailcrmHttpClient::METHOD_POST, - array( - 'orderType' => json_encode($data) - ) - ); - } - - /** - * Edit paymentStatus - * - * @param array $data payment status data - * @return ApiResponse - */ - public function paymentStatusesEdit(array $data) - { - if (!isset($data['code'])) { - throw new InvalidArgumentException('Data must contain "code" parameter.'); - } - - return $this->client->makeRequest( - '/reference/payment-statuses/' . $data['code'] . '/edit', - RetailcrmHttpClient::METHOD_POST, - array( - 'paymentStatus' => json_encode($data) - ) - ); - } - - /** - * Edit paymentType - * - * @param array $data payment type data - * @return ApiResponse - */ - public function paymentTypesEdit(array $data) - { - if (!isset($data['code'])) { - throw new InvalidArgumentException('Data must contain "code" parameter.'); - } - - return $this->client->makeRequest( - '/reference/payment-types/' . $data['code'] . '/edit', - RetailcrmHttpClient::METHOD_POST, - array( - 'paymentType' => json_encode($data) - ) - ); - } - - /** - * Edit productStatus - * - * @param array $data product status data - * @return ApiResponse - */ - public function productStatusesEdit(array $data) - { - if (!isset($data['code'])) { - throw new InvalidArgumentException('Data must contain "code" parameter.'); - } - - return $this->client->makeRequest( - '/reference/product-statuses/' . $data['code'] . '/edit', - RetailcrmHttpClient::METHOD_POST, - array( - 'productStatus' => json_encode($data) - ) - ); - } - - /** - * Edit order status - * - * @param array $data status data - * @return ApiResponse - */ - public function statusesEdit(array $data) - { - if (!isset($data['code'])) { - throw new InvalidArgumentException('Data must contain "code" parameter.'); - } - - return $this->client->makeRequest( - '/reference/statuses/' . $data['code'] . '/edit', - RetailcrmHttpClient::METHOD_POST, - array( - 'status' => json_encode($data) - ) - ); - } - - /** - * Edit site - * - * @param array $data site data - * @return ApiResponse - */ - public function sitesEdit(array $data) - { - if (!isset($data['code'])) { - throw new InvalidArgumentException('Data must contain "code" parameter.'); - } - - return $this->client->makeRequest( - '/reference/sites/' . $data['code'] . '/edit', - RetailcrmHttpClient::METHOD_POST, - array( - 'site' => json_encode($data) - ) - ); - } - - /** - * Edit store - * - * @param array $data site data - * @return ApiResponse - */ - public function storesEdit(array $data) - { - if (!isset($data['code'])) { - throw new InvalidArgumentException('Data must contain "code" parameter.'); - } - - if (!isset($data['name'])) { - throw new InvalidArgumentException('Data must contain "name" parameter.'); - } - - return $this->client->makeRequest( - '/reference/stores/' . $data['code'] . '/edit', - RetailcrmHttpClient::METHOD_POST, - array( - 'store' => json_encode($data) - ) - ); - } - - /** - * Update CRM basic statistic - * - * @return ApiResponse - */ - public function statisticUpdate() - { - return $this->client->makeRequest('/statistic/update', RetailcrmHttpClient::METHOD_GET); - } - - /** - * Return current site - * - * @return string - */ - public function getSite() - { - return $this->siteCode; - } - - /** - * Set site - * - * @param string $site - * @return void - */ - public function setSite($site) - { - $this->siteCode = $site; - } - - /** - * Check ID parameter - * - * @param string $by - * @return bool - */ - protected function checkIdParameter($by) - { - $allowedForBy = array('externalId', 'id'); - if (!in_array($by, $allowedForBy)) { - throw new InvalidArgumentException(sprintf( - 'Value "%s" for parameter "by" is not valid. Allowed values are %s.', - $by, - implode(', ', $allowedForBy) - )); - } - - return true; - } - - /** - * Fill params by site value - * - * @param string $site - * @param array $params - * @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/src/upload/system/library/retailcrm/RetailcrmApiClient4.php b/src/upload/system/library/retailcrm/RetailcrmApiClient4.php deleted file mode 100644 index 98a3f98..0000000 --- a/src/upload/system/library/retailcrm/RetailcrmApiClient4.php +++ /dev/null @@ -1,1799 +0,0 @@ - - * @license https://opensource.org/licenses/MIT MIT License - * @link http://www.retailcrm.ru/docs/Developers/ApiVersion4 - */ -class RetailcrmApiClient4 -{ - 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 - * - * @return mixed - */ - public function __construct($url, $apiKey, $version = null, $site = null) - { - if ('/' !== $url[strlen($url) - 1]) { - $url .= '/'; - } - - $url = $version == null ? $url . 'api' : $url . 'api/' . $version; - - $this->client = new RetailcrmHttpClient($url, array('apiKey' => $apiKey)); - $this->siteCode = $site; - } - - /** - * Returns api versions list - * - * @throws \RetailCrm\Exception\InvalidJsonException - * @throws \RetailCrm\Exception\CurlException - * @throws \InvalidArgumentException - * - * @return ApiResponse - */ - public function apiVersions() - { - return $this->client->makeRequest('/api-versions', RetailcrmHttpClient::METHOD_GET); - } - - /** - * 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', - RetailcrmHttpClient::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", RetailcrmHttpClient::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', - RetailcrmHttpClient::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', - RetailcrmHttpClient::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', - RetailcrmHttpClient::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', - RetailcrmHttpClient::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', - RetailcrmHttpClient::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", - RetailcrmHttpClient::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]), - RetailcrmHttpClient::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', - RetailcrmHttpClient::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', - RetailcrmHttpClient::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', - RetailcrmHttpClient::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', - RetailcrmHttpClient::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', - RetailcrmHttpClient::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", - RetailcrmHttpClient::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]), - RetailcrmHttpClient::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', - RetailcrmHttpClient::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', - RetailcrmHttpClient::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', - RetailcrmHttpClient::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', - RetailcrmHttpClient::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", - RetailcrmHttpClient::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), - RetailcrmHttpClient::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']), - RetailcrmHttpClient::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', - RetailcrmHttpClient::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", - RetailcrmHttpClient::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']), - RetailcrmHttpClient::METHOD_POST, - $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', - RetailcrmHttpClient::METHOD_POST, - $this->fillSite($site, array('offers' => json_encode($offers))) - ); - } - - /** - * 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', - RetailcrmHttpClient::METHOD_GET, - $parameters - ); - } - - /** - * Upload prices - * - * @param array $prices (default: array()) - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function storePricesUpload(array $prices = array()) - { - return $this->client->makeRequest( - '/store/prices/upload', - RetailcrmHttpClient::METHOD_POST, - array('prices' => json_encode($prices)) - ); - } - - /** - * 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", - RetailcrmHttpClient::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']), - RetailcrmHttpClient::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), - RetailcrmHttpClient::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', - RetailcrmHttpClient::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', - RetailcrmHttpClient::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']), - RetailcrmHttpClient::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', - RetailcrmHttpClient::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']), - RetailcrmHttpClient::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', - RetailcrmHttpClient::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']), - RetailcrmHttpClient::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', - RetailcrmHttpClient::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']), - RetailcrmHttpClient::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', - RetailcrmHttpClient::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']), - RetailcrmHttpClient::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', - RetailcrmHttpClient::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']), - RetailcrmHttpClient::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', - RetailcrmHttpClient::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']), - RetailcrmHttpClient::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', - RetailcrmHttpClient::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']), - RetailcrmHttpClient::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', - RetailcrmHttpClient::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', - RetailcrmHttpClient::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']), - RetailcrmHttpClient::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', - RetailcrmHttpClient::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']), - RetailcrmHttpClient::METHOD_POST, - array('store' => json_encode($data)) - ); - } - - /** - * Returns price types list - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function priceTypesList() - { - return $this->client->makeRequest( - '/reference/price-types', - RetailcrmHttpClient::METHOD_GET - ); - } - - /** - * 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", - RetailcrmHttpClient::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", - RetailcrmHttpClient::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', - RetailcrmHttpClient::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', - RetailcrmHttpClient::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', - RetailcrmHttpClient::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', - RetailcrmHttpClient::METHOD_GET - ); - } - - /** - * Edit marketplace configuration - * - * @param array $configuration - * - * @throws \RetailCrm\Exception\InvalidJsonException - * @throws \RetailCrm\Exception\CurlException - * @throws \InvalidArgumentException - * - * @return ApiResponse - */ - public function marketplaceSettingsEdit(array $configuration) - { - if (!count($configuration) || empty($configuration['code'])) { - throw new \InvalidArgumentException( - 'Parameter `configuration` must contains a data & configuration `code` must be set' - ); - } - - $code = $configuration['code']; - - return $this->client->makeRequest( - "/marketplace/external/setting/$code/edit", - RetailcrmHttpClient::METHOD_POST, - array('configuration' => json_encode($configuration)) - ); - } - - /** - * 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/src/upload/system/library/retailcrm/RetailcrmProxy.php b/src/upload/system/library/retailcrm/RetailcrmProxy.php deleted file mode 100644 index bbf687f..0000000 --- a/src/upload/system/library/retailcrm/RetailcrmProxy.php +++ /dev/null @@ -1,58 +0,0 @@ -api = new RetailcrmApiClient5($url, $key, $version); - break; - case 'v4': - $this->api = new RetailcrmApiClient4($url, $key, $version); - break; - case 'v3': - $this->api = new RetailcrmApiClient3($url, $key, $version); - break; - case null: - $this->api = new RetailcrmApiClient3($url, $key, $version); - break; - } - - $this->log = $log; - } - - public function __call($method, $arguments) - { - $date = date('[Y-m-d H:i:s]'); - - try { - $response = call_user_func_array(array($this->api, $method), $arguments); - - if (!$response->isSuccessful()) { - error_log($date . " [$method] " . $response->getErrorMsg() . "\n", 3, $this->log); - if (isset($response['errors'])) { - $error = implode("\n", $response['errors']); - error_log($date .' '. $error . "\n", 3, $this->log); - } - } - - return $response; - } catch (CurlException $e) { - error_log($date . " [$method] " . $e->getMessage() . "\n", 3, $this->log); - return false; - } catch (InvalidJsonException $e) { - error_log($date . " [$method] " . $e->getMessage() . "\n", 3, $this->log); - return false; - } - } - -} diff --git a/src/upload/system/library/retailcrm/base.php b/src/upload/system/library/retailcrm/base.php new file mode 100644 index 0000000..420dbe6 --- /dev/null +++ b/src/upload/system/library/retailcrm/base.php @@ -0,0 +1,23 @@ +registry = $registry; + } + + public function __get($name) { + return $this->registry->get($name); + } +} diff --git a/src/upload/system/library/retailcrm/bootstrap.php b/src/upload/system/library/retailcrm/bootstrap.php index 7c0cc34..d81d257 100644 --- a/src/upload/system/library/retailcrm/bootstrap.php +++ b/src/upload/system/library/retailcrm/bootstrap.php @@ -62,13 +62,14 @@ class RetailcrmAutoloader $directory = new RecursiveDirectoryIterator(self::$pathTop); $fileIterator = new RecursiveIteratorIterator($directory); $filename = $className . self::$fileExt; + $chunks = explode("\\", $filename); + $filename = end($chunks); foreach ($fileIterator as $file) { if (strtolower($file->getFilename()) === strtolower($filename) && $file->isReadable()) { include_once $file->getPathname(); } } - } /** diff --git a/src/upload/system/library/retailcrm/lib/ModelsProvider.php b/src/upload/system/library/retailcrm/lib/ModelsProvider.php new file mode 100644 index 0000000..59249e2 --- /dev/null +++ b/src/upload/system/library/retailcrm/lib/ModelsProvider.php @@ -0,0 +1,41 @@ +getDependencies(); + + foreach ($dependencies[$this->getContext()] as $dependency) { + $this->load->model($dependency); + } + } + + private function getContext() { + $match = preg_match('/\/catalog\/$/i', DIR_APPLICATION); + + return $match === 1 ? 'catalog' : 'admin'; + } + + private function getDependencies() { + return array( + 'catalog' => array( + 'setting/setting', + 'checkout/order', + 'account/order', + 'account/customer', + 'account/address', + 'localisation/country', + 'localisation/zone', + 'account/address', + 'catalog/product', + ), + 'admin' => array( + 'setting/setting', + 'sale/order', + 'customer/customer', + 'catalog/product' + ) + ); + } +} diff --git a/src/upload/system/library/retailcrm/lib/Utils.php b/src/upload/system/library/retailcrm/lib/Utils.php new file mode 100644 index 0000000..6077dca --- /dev/null +++ b/src/upload/system/library/retailcrm/lib/Utils.php @@ -0,0 +1,34 @@ + $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; + } + + public static function addressEquals($address1, $address2) { + foreach ($address1 as $field => $value) { + if (isset($address2[$field]) && $value !== $address2[$field]) { + return false; + } + } + + return true; + } +} diff --git a/src/upload/system/library/retailcrm/CurlException.php b/src/upload/system/library/retailcrm/lib/api/CurlException.php similarity index 100% rename from src/upload/system/library/retailcrm/CurlException.php rename to src/upload/system/library/retailcrm/lib/api/CurlException.php diff --git a/src/upload/system/library/retailcrm/InvalidJsonException.php b/src/upload/system/library/retailcrm/lib/api/InvalidJsonException.php similarity index 100% rename from src/upload/system/library/retailcrm/InvalidJsonException.php rename to src/upload/system/library/retailcrm/lib/api/InvalidJsonException.php diff --git a/src/upload/system/library/retailcrm/OpencartApiClient.php b/src/upload/system/library/retailcrm/lib/api/OpencartApiClient.php similarity index 100% rename from src/upload/system/library/retailcrm/OpencartApiClient.php rename to src/upload/system/library/retailcrm/lib/api/OpencartApiClient.php diff --git a/src/upload/system/library/retailcrm/RetailcrmApiClient5.php b/src/upload/system/library/retailcrm/lib/api/RetailcrmApiClient5.php similarity index 77% rename from src/upload/system/library/retailcrm/RetailcrmApiClient5.php rename to src/upload/system/library/retailcrm/lib/api/RetailcrmApiClient5.php index d657a58..5c2d14d 100644 --- a/src/upload/system/library/retailcrm/RetailcrmApiClient5.php +++ b/src/upload/system/library/retailcrm/lib/api/RetailcrmApiClient5.php @@ -12,7 +12,10 @@ */ class RetailcrmApiClient5 { + const VERSION = 'v5'; + protected $client; + protected $clientWithoutVersion; /** * Site code @@ -22,23 +25,22 @@ class RetailcrmApiClient5 /** * Client creating * - * @param string $url api url + * @param string $url api url * @param string $apiKey api key - * @param string $site site code + * @param string $site site code * * @throws \InvalidArgumentException * * @return mixed */ - public function __construct($url, $apiKey, $version = null, $site = null) + public function __construct($url, $apiKey, $site = null) { if ('/' !== $url[strlen($url) - 1]) { $url .= '/'; } - $url = $version == null ? $url . 'api' : $url . 'api/' . $version; - - $this->client = new RetailcrmHttpClient($url, array('apiKey' => $apiKey)); + $this->client = new RetailcrmHttpClient($url . 'api/' . static::VERSION, array('apiKey' => $apiKey)); + $this->clientWithoutVersion = new RetailcrmHttpClient($url . 'api', array('apiKey' => $apiKey)); $this->siteCode = $site; } @@ -53,7 +55,7 @@ class RetailcrmApiClient5 */ public function apiVersions() { - return $this->client->makeRequest('/api-versions', RetailcrmHttpClient::METHOD_GET); + return $this->clientWithoutVersion->makeRequest('/api-versions', RetailcrmHttpClient::METHOD_GET); } /** @@ -2369,6 +2371,622 @@ class RetailcrmApiClient5 ); } + /** + * Returns filtered corporate customers list + * + * @param array $filter (default: array()) + * @param int $page (default: null) + * @param int $limit (default: null) + * + * @throws \InvalidArgumentException + * @throws \CurlException + * @throws \InvalidJsonException + * + * @return \ApiResponse + */ + public function customersCorporateList(array $filter = [], $page = null, $limit = null) + { + $parameters = []; + + 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-corporate', + RetailcrmHttpClient::METHOD_GET, + $parameters + ); + } + + /** + * Create a corporate customer + * + * @param array $customerCorporate corporate customer data + * @param string $site (default: null) + * + * @throws \InvalidArgumentException + * @throws \CurlException + * @throws \InvalidJsonException + * + * @return \ApiResponse + */ + public function customersCorporateCreate(array $customerCorporate, $site = null) + { + if (! count($customerCorporate)) { + throw new \InvalidArgumentException( + 'Parameter `customerCorporate` must contains a data' + ); + } + + /* @noinspection PhpUndefinedMethodInspection */ + return $this->client->makeRequest( + '/customers-corporate/create', + RetailcrmHttpClient::METHOD_POST, + $this->fillSite($site, ['customerCorporate' => json_encode($customerCorporate)]) + ); + } + + /** + * Save corporate customer IDs' (id and externalId) association in the CRM + * + * @param array $ids ids mapping + * + * @throws \InvalidArgumentException + * @throws \CurlException + * @throws \InvalidJsonException + * + * @return \ApiResponse + */ + public function customersCorporateFixExternalIds(array $ids) + { + if (! count($ids)) { + throw new \InvalidArgumentException( + 'Method parameter must contains at least one IDs pair' + ); + } + + /* @noinspection PhpUndefinedMethodInspection */ + return $this->client->makeRequest( + '/customers-corporate/fix-external-ids', + RetailcrmHttpClient::METHOD_POST, + ['customersCorporate' => json_encode($ids)] + ); + } + + /** + * Get corporate customers history + * @param array $filter + * @param null $page + * @param null $limit + * + * @return \ApiResponse + */ + public function customersCorporateHistory(array $filter = [], $page = null, $limit = null) + { + $parameters = []; + + 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-corporate/history', + RetailcrmHttpClient::METHOD_GET, + $parameters + ); + } + + /** + * Returns filtered corporate customers notes list + * + * @param array $filter (default: array()) + * @param int $page (default: null) + * @param int $limit (default: null) + * + * @throws \InvalidArgumentException + * @throws \CurlException + * @throws \InvalidJsonException + * + * @return \ApiResponse + */ + public function customersCorporateNotesList(array $filter = [], $page = null, $limit = null) + { + $parameters = []; + + 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-corporate/notes', + RetailcrmHttpClient::METHOD_GET, + $parameters + ); + } + + /** + * Create corporate customer note + * + * @param array $note (default: array()) + * @param string $site (default: null) + * + * @throws \InvalidArgumentException + * @throws \CurlException + * @throws \InvalidJsonException + * + * @return \ApiResponse + */ + public function customersCorporateNotesCreate($note, $site = null) + { + if (empty($note['customer']['id']) && empty($note['customer']['externalId'])) { + throw new \InvalidArgumentException( + 'Customer identifier must be set' + ); + } + + return $this->client->makeRequest( + '/customers-corporate/notes/create', + RetailcrmHttpClient::METHOD_POST, + $this->fillSite($site, ['note' => json_encode($note)]) + ); + } + + /** + * Delete corporate customer note + * + * @param integer $id + * + * @throws \InvalidArgumentException + * @throws \CurlException + * @throws \InvalidJsonException + * + * @return \ApiResponse + */ + public function customersCorporateNotesDelete($id) + { + if (empty($id)) { + throw new \InvalidArgumentException( + 'Note id must be set' + ); + } + + return $this->client->makeRequest( + "/customers-corporate/notes/$id/delete", + RetailcrmHttpClient::METHOD_POST + ); + } + + /** + * Upload array of the corporate customers + * + * @param array $customersCorporate array of corporate customers + * @param string $site (default: null) + * + * @return \ApiResponse + * @throws \CurlException + * @throws \InvalidJsonException + * + * @throws \InvalidArgumentException + */ + public function customersCorporateUpload(array $customersCorporate, $site = null) + { + if (!count($customersCorporate)) { + throw new \InvalidArgumentException( + 'Parameter `customersCorporate` must contains array of the corporate customers' + ); + } + + return $this->client->makeRequest( + '/customers-corporate/upload', + RetailcrmHttpClient::METHOD_POST, + $this->fillSite($site, ['customersCorporate' => json_encode($customersCorporate)]) + ); + } + + /** + * Get corporate customer by id or externalId + * + * @param string $id corporate customer identifier + * @param string $by (default: 'externalId') + * @param string $site (default: null) + * + * @throws \InvalidArgumentException + * @throws \CurlException + * @throws \InvalidJsonException + * + * @return \ApiResponse + */ + public function customersCorporateGet($id, $by = 'externalId', $site = null) + { + $this->checkIdParameter($by); + + return $this->client->makeRequest( + "/customers-corporate/$id", + RetailcrmHttpClient::METHOD_GET, + $this->fillSite($site, ['by' => $by]) + ); + } + + /** + * Get corporate customer addresses by id or externalId + * + * @param string $id corporate customer identifier + * @param array $filter (default: array()) + * @param int $page (default: null) + * @param int $limit (default: null) + * @param string $by (default: 'externalId') + * @param string $site (default: null) + * + * @throws \InvalidArgumentException + * @throws \CurlException + * @throws \InvalidJsonException + * + * @return \ApiResponse + */ + public function customersCorporateAddresses( + $id, + array $filter = [], + $page = null, + $limit = null, + $by = 'externalId', + $site = null + ) { + $this->checkIdParameter($by); + + $parameters = ['by' => $by]; + + 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-corporate/$id/addresses", + RetailcrmHttpClient::METHOD_GET, + $this->fillSite($site, $parameters) + ); + } + + /** + * Create corporate customer address + * + * @param string $id corporate customer identifier + * @param array $address (default: array()) + * @param string $by (default: 'externalId') + * @param string $site (default: null) + * + * @throws \InvalidArgumentException + * @throws \CurlException + * @throws \InvalidJsonException + * + * @return \ApiResponse + */ + public function customersCorporateAddressesCreate($id, array $address = [], $by = 'externalId', $site = null) + { + return $this->client->makeRequest( + "/customers-corporate/$id/addresses/create", + RetailcrmHttpClient::METHOD_POST, + $this->fillSite($site, ['address' => json_encode($address), 'by' => $by]) + ); + } + + /** + * Edit corporate customer address + * + * @param string $customerId corporate customer identifier + * @param string $addressId corporate customer identifier + * @param array $address (default: array()) + * @param string $customerBy (default: 'externalId') + * @param string $addressBy (default: 'externalId') + * @param string $site (default: null) + * + * @throws \InvalidArgumentException + * @throws \CurlException + * @throws \InvalidJsonException + * + * @return \ApiResponse + */ + public function customersCorporateAddressesEdit( + $customerId, + $addressId, + array $address = [], + $customerBy = 'externalId', + $addressBy = 'externalId', + $site = null + ) { + $addressFiltered = array_filter($address); + + if ((count(array_keys($addressFiltered)) <= 1) + && (!isset($addressFiltered['text']) + || (isset($addressFiltered['text']) && empty($addressFiltered['text'])) + ) + ) { + throw new \InvalidArgumentException( + 'Parameter `address` must contain address text or all other address field' + ); + } + + return $this->client->makeRequest( + "/customers-corporate/$customerId/addresses/$addressId/edit", + RetailcrmHttpClient::METHOD_POST, + $this->fillSite($site, [ + 'address' => json_encode($address), + 'by' => $customerBy, + 'entityBy' => $addressBy + ]) + ); + } + + /** + * Get corporate customer companies by id or externalId + * + * @param string $id corporate customer identifier + * @param array $filter (default: array()) + * @param int $page (default: null) + * @param int $limit (default: null) + * @param string $by (default: 'externalId') + * @param string $site (default: null) + * + * @throws \InvalidArgumentException + * @throws \CurlException + * @throws \InvalidJsonException + * + * @return \ApiResponse + */ + public function customersCorporateCompanies( + $id, + array $filter = [], + $page = null, + $limit = null, + $by = 'externalId', + $site = null + ) { + $this->checkIdParameter($by); + + $parameters = ['by' => $by]; + + 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-corporate/$id/companies", + RetailcrmHttpClient::METHOD_GET, + $this->fillSite($site, $parameters) + ); + } + + /** + * Create corporate customer company + * + * @param string $id corporate customer identifier + * @param array $company (default: array()) + * @param string $by (default: 'externalId') + * @param string $site (default: null) + * + * @throws \InvalidArgumentException + * @throws \CurlException + * @throws \InvalidJsonException + * + * @return \ApiResponse + */ + public function customersCorporateCompaniesCreate($id, array $company = [], $by = 'externalId', $site = null) + { + return $this->client->makeRequest( + "/customers-corporate/$id/companies/create", + RetailcrmHttpClient::METHOD_POST, + $this->fillSite($site, ['company' => json_encode($company), 'by' => $by]) + ); + } + + /** + * Edit corporate customer company + * + * @param string $customerId corporate customer identifier + * @param string $companyId corporate customer identifier + * @param array $company (default: array()) + * @param string $customerBy (default: 'externalId') + * @param string $companyBy (default: 'externalId') + * @param string $site (default: null) + * + * @return \ApiResponse + * @throws \InvalidArgumentException + * @throws \CurlException + * @throws \InvalidJsonException + * + */ + public function customersCorporateCompaniesEdit( + $customerId, + $companyId, + array $company = [], + $customerBy = 'externalId', + $companyBy = 'externalId', + $site = null + ) { + + return $this->client->makeRequest( + "/customers-corporate/$customerId/companies/$companyId/edit", + RetailcrmHttpClient::METHOD_POST, + $this->fillSite($site, [ + 'company' => json_encode($company), + 'by' => $customerBy, + 'entityBy' => $companyBy + ]) + ); + } + + /** + * Get corporate customer contacts by id or externalId + * + * @param string $id corporate customer identifier + * @param array $filter (default: array()) + * @param int $page (default: null) + * @param int $limit (default: null) + * @param string $by (default: 'externalId') + * @param string $site (default: null) + * + * @throws \InvalidArgumentException + * @throws \CurlException + * @throws \InvalidJsonException + * + * @return \ApiResponse + */ + public function customersCorporateContacts( + $id, + array $filter = [], + $page = null, + $limit = null, + $by = 'externalId', + $site = null + ) { + $this->checkIdParameter($by); + + $parameters = ['by' => $by]; + + 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-corporate/$id/contacts", + RetailcrmHttpClient::METHOD_GET, + $this->fillSite($site, $parameters) + ); + } + + /** + * Create corporate customer contact + * + * @param string $id corporate customer identifier + * @param array $contact (default: array()) + * @param string $by (default: 'externalId') + * @param string $site (default: null) + * + * @return \ApiResponse + * @throws \CurlException + * @throws \InvalidJsonException + * + * @throws \InvalidArgumentException + */ + public function customersCorporateContactsCreate($id, array $contact = [], $by = 'externalId', $site = null) + { + return $this->client->makeRequest( + "/customers-corporate/$id/contacts/create", + RetailcrmHttpClient::METHOD_POST, + $this->fillSite($site, ['contact' => json_encode($contact), 'by' => $by]) + ); + } + + /** + * Edit corporate customer contact + * + * @param string $customerId corporate customer identifier + * @param string $contactId corporate customer identifier + * @param array $contact (default: array()) + * @param string $customerBy (default: 'externalId') + * @param string $contactBy (default: 'externalId') + * @param string $site (default: null) + * + * @return \ApiResponse + * @throws \InvalidArgumentException + * @throws \CurlException + * @throws \InvalidJsonException + * + */ + public function customersCorporateContactsEdit( + $customerId, + $contactId, + array $contact = [], + $customerBy = 'externalId', + $contactBy = 'externalId', + $site = null + ) { + return $this->client->makeRequest( + "/customers-corporate/$customerId/contacts/$contactId/edit", + RetailcrmHttpClient::METHOD_POST, + $this->fillSite($site, [ + 'contact' => json_encode($contact), + 'by' => $customerBy, + 'entityBy' => $contactBy + ]) + ); + } + + /** + * Edit a corporate customer + * + * @param array $customerCorporate corporate customer data + * @param string $by (default: 'externalId') + * @param string $site (default: null) + * + * @throws \InvalidArgumentException + * @throws \CurlException + * @throws \InvalidJsonException + * + * @return \ApiResponse + */ + public function customersCorporateEdit(array $customerCorporate, $by = 'externalId', $site = null) + { + if (!count($customerCorporate)) { + throw new \InvalidArgumentException( + 'Parameter `customerCorporate` must contains a data' + ); + } + + $this->checkIdParameter($by); + + if (!array_key_exists($by, $customerCorporate)) { + throw new \InvalidArgumentException( + sprintf('Corporate customer array must contain the "%s" parameter.', $by) + ); + } + + return $this->client->makeRequest( + sprintf('/customers-corporate/%s/edit', $customerCorporate[$by]), + RetailcrmHttpClient::METHOD_POST, + $this->fillSite( + $site, + ['customerCorporate' => json_encode($customerCorporate), 'by' => $by] + ) + ); + } + /** * Return current site * diff --git a/src/upload/system/library/retailcrm/RetailcrmApiResponse.php b/src/upload/system/library/retailcrm/lib/api/RetailcrmApiResponse.php similarity index 100% rename from src/upload/system/library/retailcrm/RetailcrmApiResponse.php rename to src/upload/system/library/retailcrm/lib/api/RetailcrmApiResponse.php diff --git a/src/upload/system/library/retailcrm/RetailcrmHistoryHelper.php b/src/upload/system/library/retailcrm/lib/api/RetailcrmHistoryHelper.php similarity index 100% rename from src/upload/system/library/retailcrm/RetailcrmHistoryHelper.php rename to src/upload/system/library/retailcrm/lib/api/RetailcrmHistoryHelper.php diff --git a/src/upload/system/library/retailcrm/RetailcrmHttpClient.php b/src/upload/system/library/retailcrm/lib/api/RetailcrmHttpClient.php similarity index 100% rename from src/upload/system/library/retailcrm/RetailcrmHttpClient.php rename to src/upload/system/library/retailcrm/lib/api/RetailcrmHttpClient.php diff --git a/src/upload/system/library/retailcrm/lib/api/RetailcrmProxy.php b/src/upload/system/library/retailcrm/lib/api/RetailcrmProxy.php new file mode 100644 index 0000000..6694b7e --- /dev/null +++ b/src/upload/system/library/retailcrm/lib/api/RetailcrmProxy.php @@ -0,0 +1,56 @@ +api = new RetailcrmApiClient5($url, $key); + + $this->log = new \Log('retailcrm.log'); + } + + public function __call($method, $arguments) { + try { + $response = call_user_func_array(array($this->api, $method), $arguments); + + if (!$response->isSuccessful()) { + $this->log->write(sprintf("[%s] %s", $method, $response->getErrorMsg())); + if (isset($response['errors'])) { + $error = implode("\n", $response['errors']); + $this->log->write($error . "\n"); + } + } + + return $response; + } catch (CurlException $e) { + $this->log->write(sprintf("[%s] %s", $method, $e->getMessage())); + return false; + } catch (InvalidJsonException $e) { + $this->log->write(sprintf("[%s] %s", $method, $e->getMessage())); + return false; + } + } +} diff --git a/src/upload/system/library/retailcrm/lib/factory/CustomerConverterFactory.php b/src/upload/system/library/retailcrm/lib/factory/CustomerConverterFactory.php new file mode 100644 index 0000000..b54c8e0 --- /dev/null +++ b/src/upload/system/library/retailcrm/lib/factory/CustomerConverterFactory.php @@ -0,0 +1,12 @@ +data_repository = $data_repository; + $this->customer_repository = $customer_repository; + $this->settings_manager = $settings_manager; + } + + public function handleCustomer(&$customer_data, $customer) { + // is new customer + if (!$customer_data) { + $customer_data['store_id'] = 0; + $customer_data['customer_group_id'] = '1'; + $customer_data['fax'] = ''; + $customer_data['newsletter'] = 0; + $customer_data['password'] = 'tmppass'; + $customer_data['status'] = 1; + $customer_data['approved'] = 1; + $customer_data['safe'] = 0; + $customer_data['affiliate'] = ''; + } else { + $customer_data['password'] = false; + } + + $customer_data['firstname'] = $customer['firstName']; + $customer_data['lastname'] = isset($customer['lastName']) ? $customer['lastName'] : ''; + $customer_data['email'] = $customer['email']; + $customer_data['telephone'] = $customer['phones'] ? $customer['phones'][0]['number'] : ''; + + $customer_data['affiliate'] = false; + } + + public function handleAddress($customer, $order, $address_id = 0) { + if (empty($customer['address']) && !empty($order)) { + $customer['address'] = $order['delivery']['address']; + } + + if ($address_id) { + $customer_address = $this->customer_repository->getAddress($address_id); + } else { + $customer_address = array(); + } + + if (isset($customer['address']['countryIso'])) { + $customer_country = $this->data_repository->getCountryByIsoCode($customer['address']['countryIso']); + } + + if (isset($customer['address']['region'])) { + $customer_zone = $this->data_repository->getZoneByName($customer['address']['region']); + } + + $customer_address['firstname'] = isset($customer['patronymic']) + ? $customer['firstName'] . ' ' . $customer['patronymic'] + : $customer['firstName']; + $customer_address['lastname'] = isset($customer['lastName']) ? $customer['lastName'] : ''; + $customer_address['address_2'] = !empty($customer_address['address_2']) ? $customer_address['address_2'] : ''; + $customer_address['company'] = !empty($customer_address['company']) ? $customer_address['company'] : ''; + + if (!empty($customer['address'])) { + $customer_address['address_1'] = !empty($customer['address']['text']) ? $customer['address']['text'] : ''; + $customer_address['city'] = !empty($customer['address']['city']) ? $customer['address']['city'] : ''; + $customer_address['postcode'] = isset($customer['address']['index']) ? $customer['address']['index'] : ''; + } + + $customer_address['zone_id'] = 0; + $customer_address['country_id'] = 0; + + if (isset($customer_country)) { + $customer_address['country_id'] = $customer_country['country_id']; + } + + if (isset($customer_zone) && isset($customer_zone['zone_id'])) { + $customer_address['zone_id'] = $customer_zone['zone_id']; + } + + $customer_address['default'] = true; + + return $customer_address; + } + + public function handleCustomFields(&$customer_data, $customer) { + $settings = $this->settings_manager->getSetting('custom_field'); + if (!empty($settings)) { + $custom_field_setting = array_flip($settings); + } + + if (isset($custom_field_setting) && $customer['customFields']) { + foreach ($customer['customFields'] as $code => $value) { + if (array_key_exists($code, $custom_field_setting)) { + $field_code = str_replace('c_', '', $custom_field_setting[$code]); + $custom_fields[$field_code] = $value; + } + } + + $customer_data['custom_field'] = isset($custom_fields) ? $custom_fields : ''; + } + } +} diff --git a/src/upload/system/library/retailcrm/lib/history/Order.php b/src/upload/system/library/retailcrm/lib/history/Order.php new file mode 100644 index 0000000..b7d3f4b --- /dev/null +++ b/src/upload/system/library/retailcrm/lib/history/Order.php @@ -0,0 +1,350 @@ +data_repository = $data_repository; + $this->settings_manager = $settings_manager; + $this->product_repository = $product_repository; + $this->order_repository = $order_repository; + + $this->payment = array_flip($settings_manager->getPaymentSettings()); + $this->delivery = array_flip($settings_manager->getDeliverySettings()); + } + + public function setOcPayment($oc_payment) { + $this->oc_payment = $oc_payment; + } + + public function setOcDelivery($oc_delivery) { + $this->oc_delivery = $oc_delivery; + } + + /** + * @param array $data opencart order + * @param array $order retailCRM order + */ + public function handleBaseOrderData(&$data, $order) { + $mail = !empty($order['email']) ? $order['email'] : $order['customer']['email']; + $phone = !empty($order['phone']) ? $order['phone'] : ''; + + if (!$phone) { + $data['telephone'] = $order['customer']['phones'] ? $order['customer']['phones'][0]['number'] : '80000000000'; + } else { + $data['telephone'] = $phone; + } + + $data['currency_code'] = $this->data_repository->getConfig('config_currency'); + $data['currency_value'] = $this->data_repository->getCurrencyByCode($data['currency_code'], 'value'); + $data['currency_id'] = $this->data_repository->getCurrencyByCode($data['currency_code'], 'currency_id'); + $data['language_id'] = $this->data_repository->getLanguageByCode( + $this->data_repository->getConfig('config_language'), + 'language_id' + ); + $data['store_id'] = !is_null($this->data_repository->getConfig('config_store_id')) + ? $this->data_repository->getConfig('config_store_id') : 0; + $data['store_name'] = $this->data_repository->getConfig('config_name'); +// $data['customer_id'] = $customer_id; + $data['customer_group_id'] = 1; + $data['firstname'] = $order['firstName']; + $data['lastname'] = (!empty($order['lastName'])) ? $order['lastName'] : $order['firstName']; + $data['email'] = !empty($mail) ? $mail : uniqid() . '@retailrcm.ru'; + $data['comment'] = !empty($order['customerComment']) ? $order['customerComment'] : ''; + + // this data will not retrive from crm for now + $data['fax'] = ''; + $data['tax'] = ''; + $data['tax_id'] = ''; + $data['product'] = ''; + $data['product_id'] = ''; + $data['reward'] = ''; + $data['affiliate'] = ''; + $data['affiliate_id'] = 0; + $data['payment_tax_id'] = ''; + $data['order_product_id'] = ''; + $data['payment_company'] = ''; + } + + /** + * @param array $data opencart order + * @param array $order retailCRM order + * @param array $corporateAddress + */ + public function handlePayment(&$data, $order, $corporateAddress = array()) { + if (!empty($order['customer']['type']) && $order['customer']['type'] === 'customer_corporate') { + $customer = $order['contact']; + + if (empty($customer['address'])) { + $customer['address'] = $corporateAddress; + } + if (empty($customer['address'])) { + $customer['address'] = $order['delivery']['address']; + } + } else { + $customer = $order['customer']; + } + + $default_payment_country = !empty($data['payment_country']) ? $data['payment_country'] : ''; + $default_payment_country_id = !empty($data['payment_country_id']) ? $data['payment_country_id'] : 0; + $default_payment_zone = !empty($data['payment_zone']) ? $data['payment_zone'] : ''; + $default_payment_zone_id = !empty($data['payment_zone_id']) ? $data['payment_zone_id'] : 0; + if (isset($customer['address']['countryIso'])) { + $payment_country = $this->data_repository->getCountryByIsoCode($customer['address']['countryIso']); + } + + if (isset($customer['address']['region'])) { + $payment_zone = $this->data_repository->getZoneByName($customer['address']['region']); + + if ($payment_zone) { + $payment_zone_id = $payment_zone['zone_id']; + } + } + + $data['payment_firstname'] = $customer['firstName']; + $data['payment_lastname'] = (isset($customer['lastName'])) ? $customer['lastName'] : $customer['firstName']; + $data['payment_address_2'] = ''; + + if (!empty($order['company'])) { + $data['payment_company'] = $order['company']['name']; + } + + if (!empty($customer['address'])) { + $data['payment_address_1'] = $customer['address']['text']; + $data['payment_city'] = !empty($customer['address']['city']) + ? $customer['address']['city'] + : $order['delivery']['address']['city']; + $data['payment_postcode'] = !empty($customer['address']['index']) + ? $customer['address']['index'] + : $order['delivery']['address']['index']; + } + + $data['payment_country_id'] = !empty($payment_country['country_id']) ? $payment_country['country_id'] : $default_payment_country_id; + $data['payment_country'] = !empty($payment_country['name']) ? $payment_country['name'] : $default_payment_country; + $data['payment_zone'] = isset($customer['address']['region']) ? $customer['address']['region'] : $default_payment_zone; + $data['payment_zone_id'] = isset($payment_zone_id) ? $payment_zone_id : $default_payment_zone_id; + + if (isset($order['payments']) && $order['payments']) { + $payment = end($order['payments']); + $data['payment_method'] = $this->oc_payment[$this->payment[$payment['type']]]; + $data['payment_code'] = $this->payment[$payment['type']]; + } elseif (empty($data['payment_code']) && empty($data['payment_method'])) { + $data['payment_method'] = $this->oc_payment[$this->settings_manager->getSetting('default_payment')]; + $data['payment_code'] = $this->settings_manager->getSetting('default_payment'); + } + } + + /** + * @param array $data opencart order + * @param array $order retailCRM order + */ + public function handleShipping(&$data, $order) { + $default_shipping_country = !empty($data['shipping_country']) ? $data['shipping_country'] : ''; + $default_shipping_country_id = !empty($data['shipping_country_id']) ? $data['shipping_country_id'] : 0; + $default_shipping_zone = !empty($data['shipping_zone']) ? $data['shipping_zone'] : ''; + $default_shipping_zone_id = !empty($data['shipping_zone_id']) ? $data['shipping_zone_id'] : 0; + if (!empty($order['delivery']['address']['region'])) { + $shipping_zone = $this->data_repository->getZoneByName($order['delivery']['address']['region']); + } + + if (isset($order['countryIso'])) { + $shipping_country = $this->data_repository->getCountryByIsoCode($order['countryIso']); + } + + $delivery = isset($order['delivery']['code']) ? $order['delivery']['code'] : null; + + $data['shipping_country_id'] = isset($shipping_country['country_id']) ? $shipping_country['country_id'] : $default_shipping_country_id; + $data['shipping_country'] = isset($shipping_country['name']) ? $shipping_country['name'] : $default_shipping_country; + $data['shipping_zone_id'] = isset($shipping_zone['zone_id']) ? $shipping_zone['zone_id'] : $default_shipping_zone_id; + $data['shipping_zone'] = isset($shipping_zone['name']) ? $shipping_zone['name'] : $default_shipping_zone; + $data['shipping_firstname'] = $order['firstName']; + $data['shipping_lastname'] = (isset($order['lastName'])) ? $order['lastName'] : $order['firstName']; + $data['shipping_address_1'] = $order['delivery']['address']['text']; + $data['shipping_address_2'] = ''; + $data['shipping_company'] = ''; + $data['shipping_city'] = $order['delivery']['address']['city']; + $data['shipping_postcode'] = $order['delivery']['address']['index']; + + if (!isset($data['shipping_code'])) { + $data['shipping_code'] = $delivery != null + ? $this->delivery[$delivery] + : $this->settings_manager->getSetting('default_shipping'); + + $shipping = explode('.', $data['shipping_code']); + $shipping_module = $shipping[0]; + + if (isset($this->oc_delivery[$shipping_module][$data['shipping_code']]['title'])) { + $data['shipping_method'] = $this->oc_delivery[$shipping_module][$data['shipping_code']]['title']; + } else { + $data['shipping_method'] = $this->oc_delivery[$shipping_module]['title']; + } + } else { + if ($delivery !== null) { + if (isset($this->settings_manager->getDeliverySettings()[$data['shipping_code']]) + && isset($this->delivery[$delivery]) + ) { + $data['shipping_code'] = $this->delivery[$delivery]; + + $shipping = explode('.', $data['shipping_code']); + $shippingModule = $shipping[0]; + + if (isset($this->ocDelivery[$shippingModule][$data['shipping_code']]['title'])) { + $data['shipping_method'] = $this->oc_delivery[$shippingModule][$data['shipping_code']]['title']; + } else { + $data['shipping_method'] = $this->oc_delivery[$shippingModule]['title']; + } + } + } + } + } + + /** + * @param array $data opencart order + * @param array $order retailCRM order + */ + public function handleProducts(&$data, $order) { + $data['order_product'] = array(); + + foreach ($order['items'] as $item) { + $product_id = $item['offer']['externalId']; + $options = array(); + + if (mb_strpos($item['offer']['externalId'], '#') > 1) { + $offer = explode('#', $item['offer']['externalId']); + $product_id = $offer[0]; + $options_from_crm = explode('_', $offer[1]); + + foreach ($options_from_crm as $option_from_crm) { + $option_data = explode('-', $option_from_crm); + $product_option_id = $option_data[0]; + $option_value_id = $option_data[1]; + + $product_options = $this->product_repository->getProductOptions($product_id); + + foreach ($product_options as $product_option) { + if ($product_option_id == $product_option['product_option_id']) { + foreach ($product_option['product_option_value'] as $product_option_value) { + if ($product_option_value['option_value_id'] == $option_value_id) { + $options[] = array( + 'product_option_id' => $product_option_id, + 'product_option_value_id' => $product_option_value['product_option_value_id'], + 'value' => $this->data_repository->getOptionValue($product_option_value['option_value_id'], 'name'), + 'type' => $product_option['type'], + 'name' => $product_option['name'], + ); + } + } + } + } + } + } + + $product = $this->product_repository->getProduct($product_id); + $rewards = $this->product_repository->getProductRewards($product_id); + + $data['order_product'][] = array( + 'name' => $product['name'], + 'model' => $product['model'], + 'price' => $item['initialPrice'], + 'total' => (float)($item['initialPrice'] * $item['quantity']), + 'product_id' => $product_id, + 'quantity' => $item['quantity'], + 'option' => $options, + 'reward' => $rewards[$data['customer_group_id']]['points'] * $item['quantity'] + ); + } + } + + /** + * @param array $data opencart order + * @param array $order retailCRM order + */ + public function handleTotals(&$data, $order) { + $delivery_cost = !empty($order['delivery']['cost']) ? $order['delivery']['cost'] : 0; + + $subtotal_settings = $this->settings_manager->getSettingByKey($this->data_repository->totalTitles() . 'sub_total'); + $total_settings = $this->settings_manager->getSettingByKey($this->data_repository->totalTitles() . 'total'); + $shipping_settings = $this->settings_manager->getSettingByKey($this->data_repository->totalTitles() . 'shipping'); + + $data['total'] = $order['totalSumm']; + $data['order_total'] = array( + array( + 'order_total_id' => '', + 'code' => 'sub_total', + 'title' => $this->data_repository->getLanguage('product_summ'), + 'value' => $order['summ'], + 'text' => $order['summ'], + 'sort_order' => $subtotal_settings['sub_total_sort_order'] + ), + array( + 'order_total_id' => '', + 'code' => 'shipping', + 'title' => $data['shipping_method'], + 'value' => $delivery_cost, + 'text' => $delivery_cost, + 'sort_order' => $shipping_settings[$this->data_repository->totalTitles() . 'shipping_sort_order'] + ), + array( + 'order_total_id' => '', + 'code' => 'total', + 'title' => $this->data_repository->getLanguage('column_total'), + 'value' => !empty($order['totalSumm']) ? $order['totalSumm'] : $order['summ'] + $delivery_cost, + 'text' => isset($order['totalSumm']) ? $order['totalSumm'] : $order['summ'] + $delivery_cost, + 'sort_order' => $total_settings[$this->data_repository->totalTitles() . 'total_sort_order'] + ) + ); + + if (!empty($order['externalId'])) { + $orderTotals = $this->order_repository->getOrderTotals($order['externalId']); + foreach ($orderTotals as $orderTotal) { + if ($orderTotal['code'] == 'coupon' + || $orderTotal['code'] == 'reward' + ) { + $data['order_total'][] = $orderTotal; + } + } + } + } + + /** + * @param array $data opencart order + * @param array $order retailCRM order + */ + public function handleCustomFields(&$data, $order) { + $settings = $this->settings_manager->getSetting('custom_field'); + if (!empty($settings)) { + $custom_field_setting = array_flip($settings); + } + + if (isset($custom_field_setting) && $order['customFields']) { + foreach ($order['customFields'] as $code => $value) { + if (array_key_exists($code, $custom_field_setting)) { + $field_code = str_replace('o_', '', $custom_field_setting[$code]); + $custom_fields[$field_code] = $value; + } + } + + $data['custom_field'] = isset($custom_fields) ? $custom_fields : ''; + } + } +} diff --git a/src/upload/system/library/retailcrm/lib/repository/CustomerRepository.php b/src/upload/system/library/retailcrm/lib/repository/CustomerRepository.php new file mode 100644 index 0000000..6f76b5c --- /dev/null +++ b/src/upload/system/library/retailcrm/lib/repository/CustomerRepository.php @@ -0,0 +1,29 @@ +model_account_customer) { + return $this->model_account_customer->getCustomer($customer_id); + } + + if (null !== $this->model_customer_customer) { + return $this->model_customer_customer->getCustomer($customer_id); + } + + return array(); + } + + public function getAddress($address_id) { + if (null !== $this->model_customer_customer) { + $address_model = $this->model_customer_customer; + } elseif (null !== $this->model_account_address) { + $address_model = $this->model_account_address; + } else { + return array(); + } + + return $address_model->getAddress($address_id); + } +} diff --git a/src/upload/system/library/retailcrm/lib/repository/DataRepository.php b/src/upload/system/library/retailcrm/lib/repository/DataRepository.php new file mode 100644 index 0000000..74abcb7 --- /dev/null +++ b/src/upload/system/library/retailcrm/lib/repository/DataRepository.php @@ -0,0 +1,205 @@ +db->query("INSERT INTO `" . DB_PREFIX . "order` SET store_id = '" . (int)$order['store_id'] . "', store_name = '" . $order['store_name'] . "', customer_id = '" . (int)$order['customer_id'] . "', customer_group_id = '" . (int)$order['customer_group_id'] . "', firstname = '" . $this->db->escape($order['firstname']) . "', lastname = '" . $this->db->escape($order['lastname']) . "', email = '" . $this->db->escape($order['email']) . "', telephone = '" . $this->db->escape($order['telephone']) . "', custom_field = '" . $this->db->escape(isset($order['custom_field']) ? json_encode($order['custom_field']) : '') . "', payment_firstname = '" . $this->db->escape($order['payment_firstname']) . "', payment_lastname = '" . $this->db->escape($order['payment_lastname']) . "', payment_address_1 = '" . $this->db->escape($order['payment_address_1']) . "', payment_city = '" . $this->db->escape($order['payment_city']) . "', payment_postcode = '" . $this->db->escape($order['payment_postcode']) . "', payment_country = '" . $this->db->escape($order['payment_country']) . "', payment_country_id = '" . (int)$order['payment_country_id'] . "', payment_zone = '" . $this->db->escape($order['payment_zone']) . "', payment_zone_id = '" . (int)$order['payment_zone_id'] . "', payment_method = '" . $this->db->escape($order['payment_method']) . "', payment_code = '" . $this->db->escape($order['payment_code']) . "', payment_company = '" . $this->db->escape($order['payment_company']) . "', shipping_firstname = '" . $this->db->escape($order['shipping_firstname']) . "', shipping_lastname = '" . $this->db->escape($order['shipping_lastname']) . "', shipping_address_1 = '" . $this->db->escape($order['shipping_address_1']) . "', shipping_address_2 = '" . $this->db->escape($order['shipping_address_2']) . "', shipping_city = '" . $this->db->escape($order['shipping_city']) . "', shipping_postcode = '" . $this->db->escape($order['shipping_postcode']) . "', shipping_country = '" . $this->db->escape($order['shipping_country']) . "', shipping_country_id = '" . (int)$order['shipping_country_id'] . "', shipping_zone = '" . $this->db->escape($order['shipping_zone']) . "', shipping_zone_id = '" . (int)$order['shipping_zone_id'] . "', shipping_method = '" . $this->db->escape($order['shipping_method']) . "', shipping_code = '" . $this->db->escape($order['shipping_code']) . "', comment = '" . $this->db->escape($order['comment']) . "', total = '" . (float)$order['total'] . "', affiliate_id = '" . (int)$order['affiliate_id'] . "', language_id = '" . (int)$order['language_id'] . "', currency_id = '" . (int)$order['currency_id'] . "', currency_code = '" . $this->db->escape($order['currency_code']) . "', currency_value = '" . (float)$order['currency_value'] . "', order_status_id = '" . (int)$order['order_status_id'] . "', date_added = NOW(), date_modified = NOW()"); + + $order_id = $this->db->getLastId(); + + // Products + if (isset($order['order_product']) && $order['order_product']) { + $this->addOrderProducts($order_id, $order['order_product']); + } + + // Totals + if (isset($order['order_total'])) { + $this->addOrderTotals($order_id, $order['order_total']); + } + + return $order_id; + } + + /** + * Edit order in OC + * + * @param int $order_id + * @param array $order + * + * @return void + */ + public function editOrder($order_id, $order) { + $this->db->query("UPDATE `" . DB_PREFIX . "order` SET customer_id = '" . (int)$order['customer_id'] . "', customer_group_id = '" . (int)$order['customer_group_id'] . "', firstname = '" . $this->db->escape($order['firstname']) . "', lastname = '" . $this->db->escape($order['lastname']) . "', email = '" . $this->db->escape($order['email']) . "', telephone = '" . $this->db->escape($order['telephone']) . "', custom_field = '" . $this->db->escape(json_encode($order['custom_field'])) . "', payment_firstname = '" . $this->db->escape($order['payment_firstname']) . "', payment_lastname = '" . $this->db->escape($order['payment_lastname']) . "', payment_address_1 = '" . $this->db->escape($order['payment_address_1']) . "', payment_address_2 = '" . $this->db->escape($order['payment_address_2']) . "', payment_city = '" . $this->db->escape($order['payment_city']) . "', payment_postcode = '" . $this->db->escape($order['payment_postcode']) . "', payment_country = '" . $this->db->escape($order['payment_country']) . "', payment_country_id = '" . (int)$order['payment_country_id'] . "', payment_zone = '" . $this->db->escape($order['payment_zone']) . "', payment_zone_id = '" . (int)$order['payment_zone_id'] . "', payment_method = '" . $this->db->escape($order['payment_method']) . "', payment_code = '" . $this->db->escape($order['payment_code']) . "', payment_company = '" . $this->db->escape($order['payment_company']) . "', shipping_firstname = '" . $this->db->escape($order['shipping_firstname']) . "', shipping_lastname = '" . $this->db->escape($order['shipping_lastname']) . "', shipping_address_1 = '" . $this->db->escape($order['shipping_address_1']) . "', shipping_address_2 = '" . $this->db->escape($order['shipping_address_2']) . "', shipping_city = '" . $this->db->escape($order['shipping_city']) . "', shipping_postcode = '" . $this->db->escape($order['shipping_postcode']) . "', shipping_country = '" . $this->db->escape($order['shipping_country']) . "', shipping_country_id = '" . (int)$order['shipping_country_id'] . "', shipping_zone = '" . $this->db->escape($order['shipping_zone']) . "', shipping_zone_id = '" . (int)$order['shipping_zone_id'] . "', shipping_method = '" . $this->db->escape($order['shipping_method']) . "', shipping_code = '" . $this->db->escape($order['shipping_code']) . "', comment = '" . $this->db->escape($order['comment']) . "', total = '" . (float)$order['total'] . "', order_status_id = '" . (int)$order['order_status_id'] . "', date_modified = NOW() WHERE order_id = '" . (int)$order_id . "'"); + + $this->db->query("DELETE FROM " . DB_PREFIX . "order_product WHERE order_id = '" . (int)$order_id . "'"); + + // Products + if (isset($order['order_product']) && $order['order_product']) { + $this->addOrderProducts($order_id, $order['order_product']); + } + + // Totals + $this->db->query("DELETE FROM " . DB_PREFIX . "order_total WHERE order_id = '" . (int)$order_id . "'"); + + if (isset($order['order_total'])) { + $this->addOrderTotals($order_id, $order['order_total']); + } + } + + /** + * Add order products + * + * @param int $order_id + * @param array $products + * + * @return void + */ + public function addOrderProducts($order_id, $products) { + foreach ($products as $product) { + $this->db->query("INSERT INTO " . DB_PREFIX . "order_product SET order_id = '" . (int)$order_id . "', product_id = '" . (int)$product['product_id'] . "', name = '" . $this->db->escape($product['name']) . "', model = '" . $this->db->escape($product['model']) . "', quantity = '" . (int)$product['quantity'] . "', price = '" . (float)$product['price'] . "', total = '" . (float)$product['total'] . "', reward = '" . (float)$product['reward'] . "'"); + + $order_product_id = $this->db->getLastId(); + + foreach ($product['option'] as $option) { + $this->db->query("INSERT INTO " . DB_PREFIX . "order_option SET order_id = '" . (int)$order_id . "', order_product_id = '" . (int)$order_product_id . "', product_option_id = '" . (int)$option['product_option_id'] . "', product_option_value_id = '" . (int)$option['product_option_value_id'] . "', name = '" . $this->db->escape($option['name']) . "', `value` = '" . $this->db->escape($option['value']) . "', `type` = '" . $this->db->escape($option['type']) . "'"); + } + } + } + + /** + * Add order totals + * + * @param int $order_id + * @param array $totals + * + * @return void + */ + public function addOrderTotals($order_id, $totals) { + foreach ($totals as $total) { + $this->db->query("INSERT INTO " . DB_PREFIX . "order_total SET order_id = '" . (int)$order_id . "', code = '" . $this->db->escape($total['code']) . "', title = '" . $this->db->escape($total['title']) . "', `value` = '" . (float)$total['value'] . "', sort_order = '" . (int)$total['sort_order'] . "'"); + } + } + + /** + * Get total titles + * + * @return string $title + */ + public function totalTitles() { + if (version_compare(VERSION, '3.0', '<')) { + $title = ''; + } else { + $title = 'total_'; + } + + return $title; + } + + /** + * Get country by iso code 2 + * + * @param string $isoCode + * + * @return array + */ + public function getCountryByIsoCode($isoCode) { + $query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "country` WHERE iso_code_2 = '" . $isoCode . "'"); + + return $query->row; + } + + /** + * Get zone by name + * + * @param string $name + * + * @return array + */ + public function getZoneByName($name) { + $query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "zone` WHERE name = '" . $name . "'"); + + return $query->row; + } + + /** + * Get currency + * + * @param string $code + * @param string $field (default = '') + * + * @return mixed array | string + */ + public function getCurrencyByCode($code, $field = '') { + $query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "currency` WHERE code = '" . $code . "'"); + + if (!$field) { + return $query->row; + } + + return $query->row[$field]; + } + + /** + * Get language + * + * @param string $code + * @param string $field (default = '') + * + * @return mixed array | string + */ + public function getLanguageByCode($code, $field = '') { + $query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "language` WHERE code = '" . $code . "'"); + + if (!$field) { + return $query->row; + } + + return $query->row[$field]; + } + + /** + * Get product option value + * + * @param int $option_value_id + * @param string $field + * + * @return mixed array | string + */ + public function getOptionValue($option_value_id, $field = '') { + $query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "option_value_description` WHERE option_value_id = '" . $option_value_id . "'"); + + if (!$field) { + return $query->row; + } + + return $query->row[$field]; + } + + public function getConfig($key) { + return $this->config->get($key); + } + + public function getLanguage($key) { + return $this->language->get($key); + } + + public function getDeliveryTypes() { + $this->load->model('extension/retailcrm/references'); + + return $this->model_extension_retailcrm_references->getOpercartDeliveryTypes(); + } + + public function getPaymentTypes() { + $this->load->model('extension/retailcrm/references'); + + return $this->model_extension_retailcrm_references->getOpercartPaymentTypes(); + } +} diff --git a/src/upload/system/library/retailcrm/lib/repository/OrderRepository.php b/src/upload/system/library/retailcrm/lib/repository/OrderRepository.php new file mode 100644 index 0000000..bea07b8 --- /dev/null +++ b/src/upload/system/library/retailcrm/lib/repository/OrderRepository.php @@ -0,0 +1,29 @@ +model_sale_order) { + return $this->model_sale_order->getOrder($order_id); + } + + if (null !== $this->model_checkout_order) { + return $this->model_checkout_order->getOrder($order_id); + } + + return array(); + } + + public function getOrderTotals($order_id) { + if (null !== $this->model_sale_order) { + return $this->model_sale_order->getOrderTotals($order_id); + } + + if (null !== $this->model_account_order) { + return $this->model_account_order->getOrderTotals($order_id); + } + + return array(); + } +} diff --git a/src/upload/system/library/retailcrm/lib/repository/ProductsRepository.php b/src/upload/system/library/retailcrm/lib/repository/ProductsRepository.php new file mode 100644 index 0000000..7cba956 --- /dev/null +++ b/src/upload/system/library/retailcrm/lib/repository/ProductsRepository.php @@ -0,0 +1,23 @@ +db->query("SELECT * FROM " . DB_PREFIX . "product_special WHERE product_id = '" . (int)$product_id . "' ORDER BY priority, price"); + + return $query->rows; + } + + public function getProductOptions($product_id) { + return $this->model_catalog_product->getProductOptions($product_id); + } + + public function getProduct($product_id) { + return $this->model_catalog_product->getProduct($product_id); + } + + public function getProductRewards($product_id) { + return $this->model_catalog_product->getProductRewards($product_id); + } +} diff --git a/src/upload/system/library/retailcrm/lib/service/CorporateCustomer.php b/src/upload/system/library/retailcrm/lib/service/CorporateCustomer.php new file mode 100644 index 0000000..fba574f --- /dev/null +++ b/src/upload/system/library/retailcrm/lib/service/CorporateCustomer.php @@ -0,0 +1,217 @@ +api = $api; + $this->customer_repository = $customer_repository; + } + + /** + * @param $order_data + * @param $customer + * @return int|null + */ + public function createCorporateCustomer($order_data, $customer) { + if (!empty($customer['externalId'])) { + return $this->createFromExistingCustomer($order_data, $customer); + } + + if (!empty($customer['id'])) { + return $this->createFromNotExistingCustomer($order_data, $customer); + } + + return null; + } + + public function buildFromExistingCustomer($customer_data, $order_data) { + $builder = CorporateCustomerBuilder::create() + ->setCompany($order_data['payment_company']) + ->setCustomerExternalId($customer_data['customer_id']); + + return $builder->build(); + } + + public function buildCorporateCustomerFromOrder($order_data, $crm_customer_id) { + $builder = CorporateCustomerBuilder::create() + ->setCompany($order_data['payment_company']) + ->setCustomerId($crm_customer_id); + + return $builder->build(); + } + + /** + * Search by provided filter, returns first found customer + * + * @param array $filter + * @param bool $returnGroup Return all customers for group filter instead of first + * + * @return bool|array + */ + public function searchCorporateCustomer($filter, $returnGroup = false) + { + $search = $this->api->customersCorporateList($filter); + + if ($search && $search->isSuccessful()) { + $customer = false; + + if (!empty($search['customersCorporate'])) { + if ($returnGroup) { + return $search['customersCorporate']; + } else { + $dataCorporateCustomers = $search['customersCorporate']; + $customer = reset($dataCorporateCustomers); + } + } + + return $customer; + } + + return false; + } + + /** + * @param $order_data + * @param $customer + * @return int|null + */ + private function createFromExistingCustomer($order_data, $customer) { + $response = $this->api->customersGet($customer['externalId']); + if (!$response || !$response->isSuccessful() || empty($response['customer'])) { + return null; + } + + $customer_data = $this->customer_repository->getCustomer($customer['externalId']); + + $corp_client = $this->searchCorporateCustomer(array( + 'contactIds' => array($response['customer']['id']), + 'companyName' => $order_data['payment_company'] + )); + + if (empty($corp_client)) { + $corp_client = $this->searchCorporateCustomer(array( + 'companyName' => $order_data['payment_company'] + )); + } + + if ($corp_client) { + $this->updateOrCreateAddress($order_data, $corp_client); + + return $corp_client['id']; + } + + $response = $this->api->customersCorporateCreate($this->buildFromExistingCustomer($customer_data, $order_data)); + if ($response && $response->isSuccessful()) { + $this->createAddressAndCompany($order_data, $response['id']); + + return $response['id']; + } + + return null; + } + + /** + * @param $order_data + * @param $customer + * @return int|null + */ + private function createFromNotExistingCustomer($order_data, $customer) { + $corp_client = $this->searchCorporateCustomer(array( + 'contactIds' => array($customer['id']), + 'companyName' => $order_data['payment_company'] + )); + + if (empty($corp_client)) { + $corp_client = $this->searchCorporateCustomer(array( + 'companyName' => $order_data['payment_company'] + )); + } + + if ($corp_client) { + $this->updateOrCreateAddress($order_data, $corp_client); + + return $corp_client['id']; + } + + $response = $this->api->customersCorporateCreate( + $this->buildCorporateCustomerFromOrder($order_data, $customer['id']) + ); + + if ($response && $response->isSuccessful()) { + $this->createAddressAndCompany($order_data, $response['id']); + + return $response['id']; + } + + return null; + } + + private function createAddressAndCompany($order_data, $corp_client_id) { + $corp_address = CorporateCustomerBuilder::create(false)->buildAddress($order_data); + $address_response = $this->api->customersCorporateAddressesCreate($corp_client_id, $corp_address, 'id'); + + if ($address_response && $address_response->isSuccessful()) { + $company = CorporateCustomerBuilder::create(false) + ->setCompany($order_data['payment_company']) + ->buildCompany($order_data); + + $company['address'] = array( + 'id' => $address_response['id'] + ); + + $this->api->customersCorporateCompaniesCreate($corp_client_id, $company, 'id'); + } + } + + /** + * @param $order_data + * @param $corp_client + * + * @return void + */ + private function updateOrCreateAddress($order_data, $corp_client) { + $addresses_response = $this->api->customersCorporateAddresses($corp_client['id'], array(), null, null, 'id'); + $corp_address = CorporateCustomerBuilder::create(false)->buildAddress($order_data); + if ($addresses_response && $addresses_response->isSuccessful() && !empty($addresses_response['addresses'])) { + foreach ($addresses_response['addresses'] as $address) { + if (Utils::addressEquals($corp_address, $address)) { + $exist_address = $address; + + break; + } + } + } + + if (!isset($exist_address)) { + $this->api->customersCorporateAddressesCreate( + $corp_client['id'], + $corp_address, + 'id' + ); + } + + if (!empty($corp_client['mainCompany'])) { + $company = CorporateCustomerBuilder::create(false) + ->setCompany($order_data['payment_company']) + ->buildCompany($order_data); + + $this->api->customersCorporateCompaniesEdit( + $corp_client['id'], + $corp_client['mainCompany']['id'], + $company, + 'id', + 'id' + ); + } + } +} diff --git a/src/upload/system/library/retailcrm/lib/service/CorporateCustomerBuilder.php b/src/upload/system/library/retailcrm/lib/service/CorporateCustomerBuilder.php new file mode 100644 index 0000000..abbe299 --- /dev/null +++ b/src/upload/system/library/retailcrm/lib/service/CorporateCustomerBuilder.php @@ -0,0 +1,109 @@ +initData(); + } + + return $self; + } + + public function initData() { + $this->data = array( + 'customerContacts' => array( + array( + 'isMain' => true, + 'customer' => array() + ) + ), + 'companies' => array() + ); + + return $this; + } + + public function build() { + $this->data['nickName'] = $this->company; + + return $this->data; + } + + public function setCompany($company) { + $this->company = $company; + + return $this; + } + + public function setCustomerId($customer_id) { + $this->setCustomer($customer_id); + + return $this; + } + + public function setCustomerExternalId($customer_external_id) { + $this->setCustomer($customer_external_id, 'externalId'); + + return $this; + } + + public function buildAddress($data) { + return array( + 'index' => $data['shipping_postcode'], + 'countryIso' => $data['shipping_iso_code_2'], + 'region' => $data['shipping_zone'], + 'city' => $data['shipping_city'], + 'name' => $data['payment_company'], + 'text' => $data['shipping_address_1'] . ' ' . $data['shipping_address_2'] + ); + } + + public function addAddress($data) { + $this->data['addresses'][] = $this->buildAddress($data); + + return $this; + } + + public function buildLegalAddress($data) { + return sprintf( + "%s %s %s %s %s", + $data['payment_postcode'], + $data['payment_zone'], + $data['payment_city'], + $data['payment_address_1'], + $data['payment_address_2'] + ); + } + + public function buildCompany($data) { + return array( + 'isMain' => true, + 'name' => $this->company, + 'contragent' => array( + 'legalAddress' => $this->buildLegalAddress($data), + 'contragentType' => 'legal-entity', + ) + ); + } + + public function addCompany($data) { + $this->data['companies'][] = $this->buildCompany($data); + + return $this; + } + + private function setCustomer($id, $field = 'id') { + foreach ($this->data['customerContacts'] as $key => $customerContact) { + if ($customerContact['isMain']) { + $this->data['customerContacts'][$key]['customer'][$field] = $id; + } + } + } +} diff --git a/src/upload/system/library/retailcrm/lib/service/CustomerManager.php b/src/upload/system/library/retailcrm/lib/service/CustomerManager.php new file mode 100644 index 0000000..df01c97 --- /dev/null +++ b/src/upload/system/library/retailcrm/lib/service/CustomerManager.php @@ -0,0 +1,102 @@ +api = $proxy; + $this->customer_converter = $customer_converter; + } + + public function createCustomer($customer_data, $address) { + $customer = $this->prepareCustomer($customer_data, $address); + + $this->api->customersCreate($customer); + } + + public function editCustomer($customer_data, $address) { + $customer = $this->prepareCustomer($customer_data, $address); + + $this->api->customersEdit($customer); + } + + public function uploadCustomers($customers) { + $this->api->customersUpload($customers); + } + + public function prepareCustomer($customer_data, $address) { + return $this->customer_converter + ->initCustomerData($customer_data, $address) + ->setCustomerData() + ->setAddress() + ->setCustomFields() + ->getCustomer(); + } + + public function getCustomerForOrder($order_data) { + $customer = $this->searchCustomer($order_data['telephone'], $order_data['email']); + if ($customer) { + return $customer; + } + + $new_customer = array( + 'firstName' => $order_data['firstname'], + 'lastName' => $order_data['lastname'], + 'email' => $order_data['email'], + 'createdAt' => $order_data['date_added'], + 'address' => array( + 'countryIso' => $order_data['payment_iso_code_2'], + 'index' => $order_data['payment_postcode'], + 'city' => $order_data['payment_city'], + 'region' => $order_data['payment_zone'], + 'text' => $order_data['payment_address_1'] . ' ' . $order_data['payment_address_2'] + ) + ); + + if (!empty($order_data['telephone'])) { + $new_customer['phones'] = array( + array( + 'number' => $order_data['telephone'] + ) + ); + } + + $res = $this->api->customersCreate($new_customer); + + $customer = array(); + if ($res && $res->isSuccessful() && isset($res['id'])) { + $customer['id'] = $res['id']; + } + + return $customer; + } + + private function searchCustomer($phone, $email) { + $customer = array(); + + $response = $this->api->customersList( + array( + 'name' => $phone, + 'email' => $email + ), + 1, + 100 + ); + + if ($response && $response->isSuccessful() && isset($response['customers'])) { + $customers = $response['customers']; + + if ($customers) { + $customer = end($customers); + } + } + + return $customer; + } +} diff --git a/src/upload/system/library/retailcrm/lib/service/OrderManager.php b/src/upload/system/library/retailcrm/lib/service/OrderManager.php new file mode 100644 index 0000000..2f2a7ec --- /dev/null +++ b/src/upload/system/library/retailcrm/lib/service/OrderManager.php @@ -0,0 +1,173 @@ +api = $proxy; + $this->customer_manager = $customer_manager; + $this->order_converter = $order_converter; + $this->corporate_customer_service = $corporate_customer_service; + $this->settings_manager = $settings_manager; + } + + /** + * @param array $order_data + * @param array $order_products + * @param array $order_totals + */ + public function createOrder($order_data, $order_products, $order_totals) { + $order = $this->prepareOrder($order_data, $order_products, $order_totals); + + if (!isset($order['customer'])) { + $customer = $this->customer_manager->getCustomerForOrder($order_data); + if (!empty($customer)) { + $order['customer'] = $customer; + } + } + + $order['contragent']['contragentType'] = 'individual'; + $this->handleCorporate($order, $order_data); + + return $this->api->ordersCreate($order); + } + + /** + * @param array $order_data + * @param array $order_products + * @param array $order_totals + */ + public function editOrder($order_data, $order_products, $order_totals) { + $order = $this->prepareOrder($order_data, $order_products, $order_totals); + + if (!isset($order['customer'])) { + $customer = $this->customer_manager->getCustomerForOrder($order_data); + if (!empty($customer)) { + $order['customer'] = array( + 'id' => $customer['id'] + ); + } + } + + $order['contragent']['contragentType'] = 'individual'; + $this->handleCorporate($order, $order_data); + + $payments = $order['payments']; + unset($order['payments']); + + $order_payment = $payments[0]; + $order = \retailcrm\Utils::filterRecursive($order); + $response = $this->api->ordersEdit($order); + + if ($response && $response->isSuccessful()) { + $this->updatePayment($order_payment, $order['externalId']); + } + } + + /** + * @param array $orders + */ + public function uploadOrders($orders) { + $this->api->ordersUpload($orders); + } + + /** + * @param array $order_data array of order fields + * @param array $order_products array of order products + * @param array $order_totals array of order totals + * @return array + */ + public function prepareOrder($order_data, $order_products, $order_totals) { + return $this->order_converter->initOrderData($order_data, $order_products, $order_totals) + ->setOrderData() + ->setDelivery() + ->setItems() + ->setPayment(false) + ->setDiscount() + ->setCustomFields() + ->getOrder(); + } + + private function handleCorporate(&$order, $order_data) { + if ($this->isCorporateOrder($order_data) + && !empty($order['customer']) + && $this->settings_manager->getSetting('corporate_enabled') == 1 + ) { + $order_data['payment_company'] = htmlspecialchars_decode($order_data['payment_company']); + $corp_customer_id = $this->corporate_customer_service->createCorporateCustomer($order_data, $order['customer']); + + if ($corp_customer_id) { + $order = $this->order_converter->setCorporateCustomer($order, $corp_customer_id); + $companiesResponse = $this->api->customersCorporateCompanies($corp_customer_id, array(), 1, 100, 'id'); + if ($companiesResponse && $companiesResponse->isSuccessful() && !empty($companiesResponse['companies'])) { + foreach ($companiesResponse['companies'] as $company) { + if ($company['name'] === $order_data['payment_company']) { + $order['company'] = array( + 'id' => $company['id'] + ); + } + } + } + } + } + } + + /** + * @param array $order_data array of order fields + * @return bool + */ + private function isCorporateOrder($order_data) { + return !empty($order_data['payment_company']); + } + + /** + * @param array $order_payment + * @param int $orderId + */ + private function updatePayment($order_payment, $orderId) { + $response_order = $this->api->ordersGet($orderId); + + if ($response_order && $response_order->isSuccessful()) { + $order_info = $response_order['order']; + } + + foreach ($order_info['payments'] as $payment_data) { + if (isset($payment_data['externalId']) && $payment_data['externalId'] == $orderId) { + $payment = $payment_data; + } + } + + if (isset($payment) && $payment['type'] != $order_payment['type']) { + $response = $this->api->ordersPaymentDelete($payment['id']); + + if ($response && $response->isSuccessful()) { + $this->api->ordersPaymentCreate($order_payment); + } + } elseif (isset($payment) && $payment['type'] == $order_payment['type']) { + $this->api->ordersPaymentEdit($order_payment); + } + } +} diff --git a/src/upload/system/library/retailcrm/lib/service/RetailcrmCustomerConverter.php b/src/upload/system/library/retailcrm/lib/service/RetailcrmCustomerConverter.php new file mode 100644 index 0000000..d1cd1f6 --- /dev/null +++ b/src/upload/system/library/retailcrm/lib/service/RetailcrmCustomerConverter.php @@ -0,0 +1,80 @@ +settingsManager = $settingsManager; + } + + public function getCustomer() { + return $this->data; + } + + public function initCustomerData($customer_data, $address) { + $this->data = array(); + $this->customer_data = $customer_data; + $this->address = $address; + + return $this; + } + + public function setCustomerData() { + $this->data['externalId'] = $this->customer_data['customer_id']; + $this->data['firstName'] = $this->customer_data['firstname']; + $this->data['lastName'] = $this->customer_data['lastname']; + $this->data['email'] = $this->customer_data['email']; + $this->data['createdAt'] = $this->customer_data['date_added']; + + if (!empty($this->customer_data['telephone'])) { + $this->data['phones'] = array( + array( + 'number' => $this->customer_data['telephone'] + ) + ); + } + + return $this; + } + + public function setAddress() { + if (!empty($this->address)) { + $this->data['address'] = array( + 'index' => $this->address['postcode'], + 'countryIso' => $this->address['iso_code_2'], + 'region' => $this->address['zone'], + 'city' => $this->address['city'], + 'text' => $this->address['address_1'] . ' ' . $this->address['address_2'] + ); + } + + return $this; + } + + public function setCustomFields() { + $settings = $this->settingsManager->getSetting('custom_field'); + if (!empty($settings) && $this->customer_data['custom_field']) { + $customFields = json_decode($this->customer_data['custom_field']); + + foreach ($customFields as $key => $value) { + if (isset($settings['c_' . $key])) { + $customFieldsToCrm[$settings['c_' . $key]] = $value; + } + } + + if (isset($customFieldsToCrm)) { + $this->data['customFields'] = $customFieldsToCrm; + } + } + + return $this; + } +} diff --git a/src/upload/system/library/retailcrm/lib/service/RetailcrmOrderConverter.php b/src/upload/system/library/retailcrm/lib/service/RetailcrmOrderConverter.php new file mode 100644 index 0000000..91bbbb8 --- /dev/null +++ b/src/upload/system/library/retailcrm/lib/service/RetailcrmOrderConverter.php @@ -0,0 +1,300 @@ +settingsManager = $settingsManager; + $this->customerRepository = $customerRepository; + $this->productsRepository = $productsRepository; + } + + public function initOrderData($order_data, $order_products, $order_totals) { + $this->data = array(); + $this->order_data = $order_data; + $this->order_products = $order_products; + $this->order_totals = $order_totals; + + return $this; + } + + public function getOrder() { + return $this->data; + } + + public function setOrderData() { + if (!empty($this->order_data['shipping_iso_code_2'])) { + $this->data['countryIso'] = $this->order_data['shipping_iso_code_2']; + } + + if ($this->settingsManager->getSetting('order_number') + && $this->settingsManager->getSetting('order_number') == 1 + ) { + $this->data['number'] = $this->order_data['order_id']; + } + + $this->data['externalId'] = $this->order_data['order_id']; + $this->data['firstName'] = $this->order_data['shipping_firstname']; + $this->data['lastName'] = $this->order_data['shipping_lastname']; + $this->data['phone'] = $this->order_data['telephone']; + $this->data['customerComment'] = $this->order_data['comment']; + + if (!empty($this->order_data['customer_id'])) { + $this->data['customer']['externalId'] = $this->order_data['customer_id']; + } + + if (!empty($this->order_data['email'])) { + $this->data['email'] = $this->order_data['email']; + } + + $this->data['createdAt'] = $this->order_data['date_added']; + + if (!empty($this->order_data['order_status_id'])) { + $this->data['status'] = $this->settingsManager->getStatusSettings()[$this->order_data['order_status_id']]; + } elseif (isset($this->order_data['order_status_id']) && $this->order_data['order_status_id'] == 0) { + $this->data['status'] = $this->settingsManager->getSetting('missing_status'); + } + + return $this; + } + + public function setDiscount() { + $discount = 0; + + if (!empty($this->getTotal('coupon'))) { + $discount += abs($this->getTotal('coupon')); + } + + if (!empty($this->getTotal('reward'))) { + $discount += abs($this->getTotal('reward')); + } + + if ($discount > 0) { + $order['discountManualAmount'] = $discount; + } + + return $this; + } + + public function setPayment($create = true) { + $settings = $this->settingsManager->getPaymentSettings(); + if (!empty($this->order_data['payment_code']) && isset($settings[$this->order_data['payment_code']])) { + $payment_type = $settings[$this->order_data['payment_code']]; + } + + $payment = array( + 'externalId' => sprintf("opencart_%d", $this->order_data['order_id']), + 'amount' => $this->getTotal('total') + ); + + if (!empty($payment_type)) { + $payment['type'] = $payment_type; + } + + if (!$create) { + $payment['order'] = array( + 'externalId' => $this->order_data['order_id'] + ); + } + + $this->data['payments'][] = $payment; + + return $this; + } + + public function setDelivery() { + $settings = $this->settingsManager->getDeliverySettings(); + + $this->data['delivery']['address'] = array( + 'index' => $this->order_data['shipping_postcode'], + 'city' => $this->order_data['shipping_city'], + 'countryIso' => $this->order_data['shipping_iso_code_2'], + 'region' => $this->order_data['shipping_zone'], + 'text' => implode(', ', array( + $this->order_data['shipping_postcode'], + $this->order_data['shipping_country'] ? $this->order_data['shipping_country'] : '', + $this->order_data['shipping_city'], + $this->order_data['shipping_address_1'], + $this->order_data['shipping_address_2'] + )) + ); + + if (!empty($this->order_data['shipping_code'])) { + $shippingCode = explode('.', $this->order_data['shipping_code']); + $shippingModule = $shippingCode[0]; + + if (isset($settings[$this->order_data['shipping_code']])) { + $delivery_code = $settings[$this->order_data['shipping_code']]; + } elseif (isset($settings[$shippingModule])) { + $delivery_code = $settings[$shippingModule]; + } + } + + if (!isset($delivery_code) && isset($shippingModule)) { + if (!empty($settings)) { + $deliveries = array_keys($settings); + $shipping_code = ''; + + array_walk($deliveries, function ($item, $key) use ($shippingModule, &$shipping_code) { + if (strripos($item, $shippingModule) !== false) { + $shipping_code = $item; + } + }); + + $delivery_code = $settings[$shipping_code]; + } + } + + if (!empty($delivery_code)) { + $this->data['delivery']['code'] = $delivery_code; + } + + if (!empty($this->getTotal('shipping'))) { + $this->data['delivery']['cost'] = $this->getTotal('shipping'); + } + + return $this; + } + + public function setItems() { + $offerOptions = array('select', 'radio'); + + foreach ($this->order_products as $product) { + $offerId = ''; + + if (!empty($product['option'])) { + $options = array(); + + foreach ($product['option'] as $option) { + if ($option['type'] == 'checkbox') { + $properties[] = array( + 'code' => $option['product_option_value_id'], + 'name' => $option['name'], + 'value' => $option['value'] + ); + } + + if (!in_array($option['type'], $offerOptions)) continue; + + $productOptions = $this->productsRepository->getProductOptions($product['product_id']); + + foreach ($productOptions as $productOption) { + if ($productOption['product_option_id'] = $option['product_option_id']) { + foreach ($productOption['product_option_value'] as $productOptionValue) { + if ($productOptionValue['product_option_value_id'] == $option['product_option_value_id']) { + $options[$option['product_option_id']] = $productOptionValue['option_value_id']; + } + } + } + } + } + + ksort($options); + + $offerId = array(); + foreach ($options as $optionKey => $optionValue) { + $offerId[] = $optionKey . '-' . $optionValue; + } + $offerId = implode('_', $offerId); + } + + $item = array( + 'offer' => array( + 'externalId' => !empty($offerId) ? $product['product_id'] . '#' . $offerId : $product['product_id'] + ), + 'productName' => $product['name'], + 'initialPrice' => $product['price'], + 'quantity' => $product['quantity'] + ); + + $specials = $this->productsRepository->getProductSpecials($product['product_id']); + + if (!empty($specials)) { + $customer = $this->customerRepository->getCustomer($this->order_data['customer_id']); + + foreach ($specials as $special) { + if (empty($customer['customer_group_id'])) { + continue; + } + + $specialSetting = $this->settingsManager->getSetting('special_' . $customer['customer_group_id']); + if ($special['customer_group_id'] == $customer['customer_group_id'] && !empty($specialSetting)) { + $item['priceType']['code'] = $specialSetting; + } + } + } + + if (isset($properties)) $item['properties'] = $properties; + + $this->data['items'][] = $item; + } + + return $this; + } + + public function setCorporateCustomer($order, $corp_customer_id) { + $order['contragent']['contragentType'] = 'legal-entity'; + $order['contact'] = $order['customer']; + unset($order['customer']); + $order['customer'] = array( + 'id' => $corp_customer_id + ); + + return $order; + } + + public function setCustomFields() { + $settings = $this->settingsManager->getSetting('custom_field'); + if (!empty($settings) && $this->order_data['custom_field']) { + $customFields = $this->order_data['custom_field']; + + foreach ($customFields as $key => $value) { + if (isset($settings['o_' . $key])) { + $customFieldsToCrm[$settings['o_' . $key]] = $value; + } + } + + if (isset($customFieldsToCrm)) { + $this->data['customFields'] = $customFieldsToCrm; + } + } + + return $this; + } + + private function getTotal($total) { + $totals = $this->getTotals(); + + if (!empty($totals[$total])) { + return $totals[$total]; + } + + return 0; + } + + private function getTotals() { + $totals = array(); + + foreach ($this->order_totals as $total) { + $totals[$total['code']] = $total['value']; + } + + return $totals; + } +} diff --git a/src/upload/system/library/retailcrm/lib/service/SettingsManager.php b/src/upload/system/library/retailcrm/lib/service/SettingsManager.php new file mode 100644 index 0000000..962d975 --- /dev/null +++ b/src/upload/system/library/retailcrm/lib/service/SettingsManager.php @@ -0,0 +1,39 @@ +settings) { + $this->settings = $this->model_setting_setting->getSetting($this->retailcrm->getModuleTitle()); + } + + return $this->settings; + } + + public function getSettingByKey($key) { + return $this->model_setting_setting->getSetting($key); + } + + public function getSetting($key) { + if (!empty($this->getSettings()[$this->retailcrm->getModuleTitle() . '_' . $key])) { + return $this->getSettings()[$this->retailcrm->getModuleTitle() . '_' . $key]; + } + + return null; + } + + public function getPaymentSettings() { + return $this->getSettings()[$this->retailcrm->getModuleTitle() . '_payment']; + } + + public function getDeliverySettings() { + return $this->getSettings()[$this->retailcrm->getModuleTitle() . '_delivery']; + } + + public function getStatusSettings() { + return $this->getSettings()[$this->retailcrm->getModuleTitle() . '_status']; + } +} diff --git a/src/upload/system/library/retailcrm/retailcrm.php b/src/upload/system/library/retailcrm/retailcrm.php index 8a76040..a4f828d 100644 --- a/src/upload/system/library/retailcrm/retailcrm.php +++ b/src/upload/system/library/retailcrm/retailcrm.php @@ -2,23 +2,51 @@ namespace retailcrm; +use retailcrm\repository\CustomerRepository; +use retailcrm\service\CorporateCustomer; +use retailcrm\service\CustomerManager; +use retailcrm\service\OrderManager; +use retailcrm\factory\OrderConverterFactory; +use retailcrm\factory\CustomerConverterFactory; +use retailcrm\service\SettingsManager; + require_once 'bootstrap.php'; class Retailcrm { - protected $apiClient; protected $registry; /** @var bool */ public static $history_run = false; - public function __construct($registry) { + public function __construct(\Registry $registry) { $this->registry = $registry; + + $modelsProvider = new ModelsProvider($this->registry); + $modelsProvider->includeDependencies(); } public function __get($name) { return $this->registry->get($name); } + public function getCustomerManager() { + return new CustomerManager($this->getApiClient(), CustomerConverterFactory::create($this->registry)); + } + + public function getOrderManager() { + return new OrderManager( + $this->getApiClient(), + $this->getCustomerManager(), + OrderConverterFactory::create($this->registry), + $this->getCorporateCustomerService(), + new SettingsManager($this->registry) + ); + } + + public function getCorporateCustomerService() { + return new CorporateCustomer($this->getApiClient(), new CustomerRepository($this->registry)); + } + /** * Get api client object * @@ -29,24 +57,27 @@ class Retailcrm { * @return mixed object | boolean */ public function getApiClient($apiUrl = null, $apiKey = null, $apiVersion = null) { - $this->load->model('setting/setting'); + if (!$this->registry->has(\RetailcrmProxy::class)) { + $setting = $this->model_setting_setting->getSetting($this->getModuleTitle()); - $setting = $this->model_setting_setting->getSetting($this->getModuleTitle()); + if ($apiUrl === null && $apiKey === null) { + $apiUrl = isset($setting[$this->getModuleTitle() . '_url']) + ? $setting[$this->getModuleTitle() . '_url'] : ''; + $apiKey = isset($setting[$this->getModuleTitle() . '_apikey']) + ? $setting[$this->getModuleTitle() . '_apikey'] : ''; + } - if ($apiUrl === null && $apiKey === null) { - $apiUrl = isset($setting[$this->getModuleTitle() . '_url']) - ? $setting[$this->getModuleTitle() . '_url'] : ''; - $apiKey = isset($setting[$this->getModuleTitle() . '_apikey']) - ? $setting[$this->getModuleTitle() . '_apikey'] : ''; - $apiVersion = isset($setting[$this->getModuleTitle() . '_apiversion']) - ? $setting[$this->getModuleTitle() . '_apiversion'] : ''; + if (!$apiUrl || !$apiKey) { + return false; + } + + $this->registry->set( + \RetailcrmProxy::class, + new \RetailcrmProxy($apiUrl, $apiKey) + ); } - if ($apiUrl && $apiKey) { - return new \RetailcrmProxy($apiUrl, $apiKey, DIR_LOGS . 'retailcrm.log', $apiVersion); - } - - return false; + return $this->registry->get(\RetailcrmProxy::class); } /** diff --git a/tests/2.3/TestCase.php b/tests/2.3/TestCase.php index 06cc76f..2a378aa 100644 --- a/tests/2.3/TestCase.php +++ b/tests/2.3/TestCase.php @@ -1,5 +1,54 @@ load->library('retailcrm/retailcrm'); + + $this->setSetting( + $this->retailcrm->getModuleTitle(), + array( + $this->retailcrm->getModuleTitle() . '_apiversion' => 'v5', + $this->retailcrm->getModuleTitle() . '_order_number' => 1, + $this->retailcrm->getModuleTitle() . '_status' => array( + 1 => 'new' + ), + $this->retailcrm->getModuleTitle() . '_delivery' => array( + 'flat.flat' => 'flat' + ), + $this->retailcrm->getModuleTitle() . '_payment' => array( + 'cod' => 'cod' + ), + $this->retailcrm->getModuleTitle() . '_special_1' => 'special1', + $this->retailcrm->getModuleTitle() . '_special_2' => 'special2', + $this->retailcrm->getModuleTitle() . '_special_3' => 'special3', + $this->retailcrm->getModuleTitle() . '_collector' => array( + 'site_key' => 'RC-XXXXXXXXXX-X', + 'custom_form' => 1, + 'custom' => array( + 'name' => 'Name', + 'email' => 'Email', + 'phone' => 'Phone', + ), + 'form_capture' => 1, + 'period' => 1 + ) + ) + ); + } + + protected function setSetting($code, $data, $store_id = 0) { + $this->db->query("DELETE FROM `" . DB_PREFIX . "setting` WHERE store_id = '" . (int)$store_id . "' AND `code` = '" . $this->db->escape($code) . "'"); + + foreach ($data as $key => $value) { + if (substr($key, 0, strlen($code)) == $code) { + if (!is_array($value)) { + $this->db->query("INSERT INTO " . DB_PREFIX . "setting SET store_id = '" . (int)$store_id . "', `code` = '" . $this->db->escape($code) . "', `key` = '" . $this->db->escape($key) . "', `value` = '" . $this->db->escape($value) . "'"); + } else { + $this->db->query("INSERT INTO " . DB_PREFIX . "setting SET store_id = '" . (int)$store_id . "', `code` = '" . $this->db->escape($code) . "', `key` = '" . $this->db->escape($key) . "', `value` = '" . $this->db->escape(json_encode($value, true)) . "', serialized = '1'"); + } + } + } + } } diff --git a/tests/3.0/TestCase.php b/tests/3.0/TestCase.php index c7053b7..1609eb8 100644 --- a/tests/3.0/TestCase.php +++ b/tests/3.0/TestCase.php @@ -1,5 +1,58 @@ load->library('retailcrm/retailcrm'); + + $this->setSetting( + $this->retailcrm->getModuleTitle(), + array( + $this->retailcrm->getModuleTitle() . '_apiversion' => 'v5', + $this->retailcrm->getModuleTitle() . '_order_number' => 1, + $this->retailcrm->getModuleTitle() . '_status' => array( + 1 => 'new' + ), + $this->retailcrm->getModuleTitle() . '_delivery' => array( + 'flat.flat' => 'flat' + ), + $this->retailcrm->getModuleTitle() . '_payment' => array( + 'cod' => 'cod' + ), + $this->retailcrm->getModuleTitle() . '_special_1' => 'special1', + $this->retailcrm->getModuleTitle() . '_special_2' => 'special2', + $this->retailcrm->getModuleTitle() . '_special_3' => 'special3', + $this->retailcrm->getModuleTitle() . '_collector' => array( + 'site_key' => 'RC-XXXXXXXXXX-X', + 'custom_form' => 1, + 'custom' => array( + 'name' => 'Name', + 'email' => 'Email', + 'phone' => 'Phone', + ), + 'form_capture' => 1, + 'period' => 1 + ) + ) + ); + } + + protected function setSetting($code, $data, $store_id = 0) { + $this->db->query("DELETE FROM `" . DB_PREFIX . "setting` WHERE store_id = '" . (int)$store_id . "' AND `code` = '" . $this->db->escape($code) . "'"); + + foreach ($data as $key => $value) { + if (substr($key, 0, strlen($code)) == $code) { + if (!is_array($value)) { + $this->db->query("INSERT INTO " . DB_PREFIX . "setting SET store_id = '" . (int)$store_id . "', `code` = '" . $this->db->escape($code) . "', `key` = '" . $this->db->escape($key) . "', `value` = '" . $this->db->escape($value) . "'"); + } else { + $this->db->query("INSERT INTO " . DB_PREFIX . "setting SET store_id = '" . (int)$store_id . "', `code` = '" . $this->db->escape($code) . "', `key` = '" . $this->db->escape($key) . "', `value` = '" . $this->db->escape(json_encode($value, true)) . "', serialized = '1'"); + } + } + } + } + + public function tearDown() + { + } } diff --git a/tests/RoboFile.php b/tests/RoboFile.php index 63e723c..9b8d301 100644 --- a/tests/RoboFile.php +++ b/tests/RoboFile.php @@ -209,4 +209,4 @@ EOF; } } } -} \ No newline at end of file +} diff --git a/tests/admin/ControllerRetailcrmAdminTest.php b/tests/admin/ControllerRetailcrmAdminTest.php index 365b9fc..cfdec6b 100644 --- a/tests/admin/ControllerRetailcrmAdminTest.php +++ b/tests/admin/ControllerRetailcrmAdminTest.php @@ -23,43 +23,22 @@ class ControllerRetailcrmAdminTest extends TestCase ->getMock(); } - public function testIndex() + public function testController() { $this->login('admin', 'admin'); $response = $this->dispatchAction('extension/module/retailcrm'); $this->assertRegExp('/Connection settings/', $response->getOutput()); - } - - public function testIcml() - { - $this->login('admin', 'admin'); $response = $this->dispatchAction('extension/module/retailcrm/icml'); $this->assertRegExp('/Connection settings/', $response->getOutput()); $this->assertFileExists(DIR_SYSTEM . '../' . 'retailcrm.xml'); - } - - public function testInstallCollector() - { - $this->login('admin', 'admin'); $response = $this->dispatchAction('extension/module/retailcrm/install_collector'); - $this->assertRegExp('/Connection settings/', $response->getOutput()); - } - - public function testUnnstallCollector() - { - $this->login('admin', 'admin'); $response = $this->dispatchAction('extension/module/retailcrm/uninstall_collector'); - $this->assertRegExp('/Connection settings/', $response->getOutput()); } - - public function tearDown() - { - } } diff --git a/tests/admin/ModelRetailcrmCustomerAdminTest.php b/tests/admin/ModelRetailcrmCustomerAdminTest.php index c294b13..d9fb1d1 100644 --- a/tests/admin/ModelRetailcrmCustomerAdminTest.php +++ b/tests/admin/ModelRetailcrmCustomerAdminTest.php @@ -22,6 +22,8 @@ class ModelRetailcrmCustomerAdminTest extends TestCase 'customersEdit' )) ->getMock(); + + self::$registry->set(\RetailcrmProxy::class, $this->apiClientMock); } public function testUploadToCrm() @@ -39,23 +41,4 @@ class ModelRetailcrmCustomerAdminTest extends TestCase $this->assertArrayHasKey('lastName', $customer); $this->assertArrayHasKey('email', $customer); } - - public function testChangeInCrm() - { - $customerModel = $this->loadModel('customer/customer'); - $customer = $customerModel->getCustomer(self::CUSTOMER_ID); - - $customerSend = $this->customerModel->changeInCrm($customer, $this->apiClientMock); - - $this->assertArrayHasKey('externalId', $customerSend); - $this->assertEquals(self::CUSTOMER_ID, $customerSend['externalId']); - $this->assertArrayHasKey('firstName', $customerSend); - $this->assertEquals('Test', $customerSend['firstName']); - $this->assertArrayHasKey('lastName', $customerSend); - $this->assertEquals('Test', $customerSend['lastName']); - $this->assertArrayHasKey('email', $customerSend); - $this->assertEquals('test@mail.ru', $customerSend['email']); - $this->assertArrayHasKey('phones', $customerSend); - $this->assertEquals('+7 (000) 000-00-00', $customerSend['phones'][0]['number']); - } } diff --git a/tests/admin/ModelRetailcrmOrderAdminTest.php b/tests/admin/ModelRetailcrmOrderAdminTest.php index 497eadc..d956197 100644 --- a/tests/admin/ModelRetailcrmOrderAdminTest.php +++ b/tests/admin/ModelRetailcrmOrderAdminTest.php @@ -7,7 +7,6 @@ class ModelRetailcrmOrderAdminTest extends TestCase private $orderModel; private $apiClientMock; private $settingModel; - private $retailcrm; const CUSTOMER_ID = 1; const ORDER_WITH_CUST_ID = 1; @@ -17,8 +16,6 @@ class ModelRetailcrmOrderAdminTest extends TestCase { parent::setUp(); - $this->orderModel = $this->loadModel('extension/retailcrm/order'); - $this->apiClientMock = $this->getMockBuilder(\RetailcrmProxy::class) ->disableOriginalConstructor() ->setMethods(array( @@ -30,25 +27,10 @@ class ModelRetailcrmOrderAdminTest extends TestCase )) ->getMock(); - $this->settingModel = $this->loadModel('setting/setting'); - $this->retailcrm = new \retailcrm\Retailcrm(self::$registry); + self::$registry->set(\RetailcrmProxy::class, $this->apiClientMock); + $this->orderModel = $this->loadModel('extension/retailcrm/order'); - $this->settingModel->editSetting( - $this->retailcrm->getModuleTitle(), - array( - $this->retailcrm->getModuleTitle() . '_apiversion' => 'v5', - $this->retailcrm->getModuleTitle() . '_order_number' => 1, - $this->retailcrm->getModuleTitle() . '_status' => array( - 1 => 'new' - ), - $this->retailcrm->getModuleTitle() . '_delivery' => array( - 'flat.flat' => 'flat' - ), - $this->retailcrm->getModuleTitle() . '_payment' => array( - 'cod' => 'cod' - ) - ) - ); + $this->settingModel = $this->loadModel('setting/setting'); } public function testUploadToCrm() @@ -60,7 +42,7 @@ class ModelRetailcrmOrderAdminTest extends TestCase foreach ($orders as $order) { $fullOrder = $saleOrderModel->getOrder($order['order_id']); - $fullOrder['order_total'] = $saleOrderModel->getOrderTotals($order['order_id']); + $fullOrder['totals'] = $saleOrderModel->getOrderTotals($order['order_id']); $fullOrder['products'] = $saleOrderModel->getOrderProducts($order['order_id']); foreach($fullOrder['products'] as $key => $product) { @@ -70,7 +52,7 @@ class ModelRetailcrmOrderAdminTest extends TestCase $fullOrders[] = $fullOrder; } - $chunkedOrders = $this->orderModel->uploadToCrm($fullOrders, $this->apiClientMock); + $chunkedOrders = $this->orderModel->uploadToCrm($fullOrders); $order = $chunkedOrders[0][0]; @@ -90,103 +72,4 @@ class ModelRetailcrmOrderAdminTest extends TestCase $this->assertArrayHasKey('payments', $order); $this->assertNotEmpty($order['payments']); } - - public function testUploadWithCustomerTest() - { - $saleOrderModel = $this->loadModel('sale/order'); - $order = $saleOrderModel->getOrder(self::ORDER_WITH_CUST_ID); - - $order['totals'] = $saleOrderModel->getOrderTotals($order['order_id']); - $order['products'] = $saleOrderModel->getOrderProducts($order['order_id']); - - foreach($order['products'] as $key => $product) { - $order['products'][$key]['option'] = $saleOrderModel->getOrderOptions($product['order_id'], $product['order_product_id']); - } - - $response = new \RetailcrmApiResponse( - 201, - json_encode( - array( - 'success' => true, - 'id' => 1 - ) - ) - ); - - $this->apiClientMock->expects($this->any())->method('ordersCreate')->willReturn($response); - $orderSend = $this->orderModel->uploadOrder($order, $this->apiClientMock); - - $this->assertArrayHasKey('status', $orderSend); - $this->assertEquals('new', $orderSend['status']); - $this->assertArrayHasKey('externalId', $orderSend); - $this->assertArrayHasKey('number', $orderSend); - $this->assertArrayHasKey('firstName', $orderSend); - $this->assertEquals('Test', $orderSend['firstName']); - $this->assertArrayHasKey('lastName', $orderSend); - $this->assertEquals('Test', $orderSend['lastName']); - $this->assertArrayHasKey('email', $orderSend); - $this->assertEquals('test@mail.ru', $orderSend['email']); - $this->assertArrayHasKey('phone', $orderSend); - $this->assertEquals('+7 (000) 000-00-00', $orderSend['phone']); - $this->assertArrayHasKey('createdAt', $orderSend); - $this->assertArrayHasKey('delivery', $orderSend); - $this->assertInternalType('array', $orderSend['delivery']); - $this->assertEquals('flat', $orderSend['delivery']['code']); - $this->assertEquals('Test', $orderSend['delivery']['address']['city']); - $this->assertEquals('Rostov-na-Donu', $orderSend['delivery']['address']['region']); - $this->assertEquals('111111', $orderSend['delivery']['address']['index']); - $this->assertArrayHasKey('items', $orderSend); - $this->assertArrayHasKey('customerComment', $orderSend); - $this->assertArrayHasKey('customer', $orderSend); - $this->assertArrayHasKey('externalId', $orderSend['customer']); - $this->assertEquals(self::CUSTOMER_ID, $orderSend['customer']['externalId']); - $this->assertArrayHasKey('payments', $orderSend); - $this->assertEquals('cod', $orderSend['payments'][0]['type']); - $this->assertNotEmpty($orderSend['payments']); - } - - public function testUploadWithoutCustomerTest() - { - $saleOrderModel = $this->loadModel('sale/order'); - $order = $saleOrderModel->getOrder(self::ORDER_ID); - - $order['totals'] = $saleOrderModel->getOrderTotals($order['order_id']); - $order['products'] = $saleOrderModel->getOrderProducts($order['order_id']); - - foreach($order['products'] as $key => $product) { - $order['products'][$key]['option'] = $saleOrderModel->getOrderOptions($product['order_id'], $product['order_product_id']); - } - - $response = new \RetailcrmApiResponse( - 201, - json_encode( - array( - 'success' => true, - 'id' => 1 - ) - ) - ); - - $this->apiClientMock->expects($this->any())->method('ordersCreate')->willReturn($response); - $this->apiClientMock->expects($this->any())->method('customersCreate')->willReturn($response); - $orderSend = $this->orderModel->uploadOrder($order, $this->apiClientMock); - - $this->assertArrayHasKey('status', $orderSend); - $this->assertArrayHasKey('externalId', $orderSend); - $this->assertArrayHasKey('number', $orderSend); - $this->assertArrayHasKey('firstName', $orderSend); - $this->assertArrayHasKey('lastName', $orderSend); - $this->assertArrayHasKey('email', $orderSend); - $this->assertArrayHasKey('phone', $orderSend); - $this->assertArrayHasKey('createdAt', $orderSend); - $this->assertArrayHasKey('delivery', $orderSend); - $this->assertArrayHasKey('items', $orderSend); - $this->assertContains('#', $orderSend['items'][0]['offer']['externalId']); - $this->assertArrayHasKey('payments', $orderSend); - $this->assertArrayHasKey('customerComment', $orderSend); - $this->assertArrayHasKey('customer', $orderSend); - $this->assertArrayNotHasKey('externalId', $orderSend['customer']); - $this->assertArrayHasKey('id', $orderSend['customer']); - $this->assertNotEmpty($orderSend['payments']); - } } diff --git a/tests/admin/ModelRetailcrmPricesAdminTest.php b/tests/admin/ModelRetailcrmPricesAdminTest.php index 88d99e8..ba97f83 100644 --- a/tests/admin/ModelRetailcrmPricesAdminTest.php +++ b/tests/admin/ModelRetailcrmPricesAdminTest.php @@ -40,9 +40,8 @@ class ModelRetailcrmPricesAdminTest extends TestCase public function testUploadPrices() { - $response = new \RetailcrmApiResponse( - 201, + 200, json_encode( $this->sites() ) @@ -73,7 +72,7 @@ class ModelRetailcrmPricesAdminTest extends TestCase return array( "success"=> true, "sites"=> array( - "BitrixMod"=> array( + "opencart"=> array( "name"=> "site", "url"=> "http://site.ru", "code"=> "site", @@ -94,4 +93,4 @@ class ModelRetailcrmPricesAdminTest extends TestCase ), ); } -} \ No newline at end of file +} diff --git a/tests/catalog/ControllerDaemonCollectorExtensionAnalyticsCatalogTest.php b/tests/catalog/ControllerDaemonCollectorExtensionAnalyticsCatalogTest.php new file mode 100644 index 0000000..6206b9f --- /dev/null +++ b/tests/catalog/ControllerDaemonCollectorExtensionAnalyticsCatalogTest.php @@ -0,0 +1,11 @@ +load->controller('extension/analytics/daemon_collector'); + + $this->assertContains('RC-XXXXXXXXXX-X', $data); + } +} diff --git a/tests/catalog/ControllerRetailcrmApiCatalogTest.php b/tests/catalog/ControllerRetailcrmApiCatalogTest.php index ad2d520..cae3fb5 100644 --- a/tests/catalog/ControllerRetailcrmApiCatalogTest.php +++ b/tests/catalog/ControllerRetailcrmApiCatalogTest.php @@ -61,18 +61,4 @@ class ControllerRetailcrmApiCatalogTest extends TestCase $this->assertEquals('Not found data', $data->error); } - - protected function setSetting($code, $data, $store_id = 0) { - $this->db->query("DELETE FROM `" . DB_PREFIX . "setting` WHERE store_id = '" . (int)$store_id . "' AND `code` = '" . $this->db->escape($code) . "'"); - - foreach ($data as $key => $value) { - if (substr($key, 0, strlen($code)) == $code) { - if (!is_array($value)) { - $this->db->query("INSERT INTO " . DB_PREFIX . "setting SET store_id = '" . (int)$store_id . "', `code` = '" . $this->db->escape($code) . "', `key` = '" . $this->db->escape($key) . "', `value` = '" . $this->db->escape($value) . "'"); - } else { - $this->db->query("INSERT INTO " . DB_PREFIX . "setting SET store_id = '" . (int)$store_id . "', `code` = '" . $this->db->escape($code) . "', `key` = '" . $this->db->escape($key) . "', `value` = '" . $this->db->escape(json_encode($value, true)) . "', serialized = '1'"); - } - } - } - } } diff --git a/tests/catalog/ModelRetailcrmCustomerCatalogTest.php b/tests/catalog/ModelRetailcrmCustomerCatalogTest.php deleted file mode 100644 index 7fbf523..0000000 --- a/tests/catalog/ModelRetailcrmCustomerCatalogTest.php +++ /dev/null @@ -1,64 +0,0 @@ -customerModel = $this->loadModel('extension/retailcrm/customer'); - - $this->apiClientMock = $this->getMockBuilder(\RetailcrmProxy::class) - ->disableOriginalConstructor() - ->setMethods(array( - 'customersCreate', - 'customersEdit' - )) - ->getMock(); - } - - public function testSendToCrm() - { - $customerModel = $this->loadModel('account/customer'); - $customer = $customerModel->getCustomer(self::CUSTOMER_ID); - - $customerSend = $this->customerModel->sendToCrm($customer, $this->apiClientMock); - - $this->assertArrayHasKey('externalId', $customerSend); - $this->assertEquals(self::CUSTOMER_ID, $customerSend['externalId']); - $this->assertArrayHasKey('firstName', $customerSend); - $this->assertEquals('Test', $customerSend['firstName']); - $this->assertArrayHasKey('lastName', $customerSend); - $this->assertEquals('Test', $customerSend['lastName']); - $this->assertArrayHasKey('email', $customerSend); - $this->assertEquals('test@mail.ru', $customerSend['email']); - $this->assertArrayHasKey('phones', $customerSend); - $this->assertEquals('+7 (000) 000-00-00', $customerSend['phones'][0]['number']); - } - - public function testChangeInCrm() - { - $customerModel = $this->loadModel('account/customer'); - $customer = $customerModel->getCustomer(self::CUSTOMER_ID); - - $customerSend = $this->customerModel->changeInCrm($customer, $this->apiClientMock); - - $this->assertArrayHasKey('externalId', $customerSend); - $this->assertEquals(self::CUSTOMER_ID, $customerSend['externalId']); - $this->assertArrayHasKey('firstName', $customerSend); - $this->assertEquals('Test', $customerSend['firstName']); - $this->assertArrayHasKey('lastName', $customerSend); - $this->assertEquals('Test', $customerSend['lastName']); - $this->assertArrayHasKey('email', $customerSend); - $this->assertEquals('test@mail.ru', $customerSend['email']); - $this->assertArrayHasKey('phones', $customerSend); - $this->assertEquals('+7 (000) 000-00-00', $customerSend['phones'][0]['number']); - } -} \ No newline at end of file diff --git a/tests/opencart_sample_data.sql b/tests/opencart_sample_data.sql index 1954565..6285340 100644 --- a/tests/opencart_sample_data.sql +++ b/tests/opencart_sample_data.sql @@ -1,6 +1,9 @@ TRUNCATE TABLE `oc_customer`; INSERT INTO `oc_customer` (`customer_id`, `customer_group_id`, `store_id`, `language_id`, `firstname`, `lastname`, `email`, `telephone`, `fax`, `password`, `salt`, `cart`, `wishlist`, `newsletter`, `address_id`, `custom_field`, `ip`, `status`, `approved`, `safe`, `token`, `code`, `date_added`) VALUES ('1', '1', '0', '1', 'Test', 'Test', 'test@mail.ru', '+7 (000) 000-00-00', '', 'ed3798da75d6cdd695e99e87a60d587a10aa95ff', '51TalnrgH', '', '', '0', '1', '', '172.21.0.1', '1', '1', '0', '', '', '2018-06-07 13:50:08'); +TRUNCATE TABLE `oc_address`; +INSERT INTO `oc_address` (`address_id`, `customer_id`, `firstname`, `lastname`, `company`, `address_1`, `address_2`, `city`, `postcode`, `country_id`, `zone_id`, `custom_field`) values (1, 1, 'Test', 'Test', '', 'Address 1', '', 'City', '111111', '176', '99', ''); + TRUNCATE TABLE `oc_customer_activity`; TRUNCATE TABLE `oc_customer_group`; INSERT INTO `oc_customer_group` (`customer_group_id`, `approval`, `sort_order`) VALUES ('1', '0', '1'); diff --git a/tests/opencart_sample_data_3.sql b/tests/opencart_sample_data_3.sql index 598d7b4..8d44c63 100644 --- a/tests/opencart_sample_data_3.sql +++ b/tests/opencart_sample_data_3.sql @@ -1,6 +1,9 @@ TRUNCATE TABLE `oc_customer`; INSERT INTO `oc_customer` (`customer_id`, `customer_group_id`, `store_id`, `language_id`, `firstname`, `lastname`, `email`, `telephone`, `fax`, `password`, `salt`, `cart`, `wishlist`, `newsletter`, `address_id`, `custom_field`, `ip`, `status`, `safe`, `token`, `code`, `date_added`) VALUES ('1', '1', '0', '1', 'Test', 'Test', 'test@mail.ru', '+7 (000) 000-00-00', '', 'ed3798da75d6cdd695e99e87a60d587a10aa95ff', '51TalnrgH', '', '', '0', '1', '', '172.21.0.1', '1', '0', '', '', '2018-06-07 13:50:08'); +TRUNCATE TABLE `oc_address`; +INSERT INTO `oc_address` (`address_id`, `customer_id`, `firstname`, `lastname`, `company`, `address_1`, `address_2`, `city`, `postcode`, `country_id`, `zone_id`, `custom_field`) values (1, 1, 'Test', 'Test', '', 'Address 1', '', 'City', '111111', '176', '99', ''); + TRUNCATE TABLE `oc_customer_activity`; TRUNCATE TABLE `oc_customer_group`; INSERT INTO `oc_customer_group` (`customer_group_id`, `approval`, `sort_order`) VALUES ('1', '0', '1'); diff --git a/tests/system/RetailcrmTest.php b/tests/system/RetailcrmTest.php new file mode 100644 index 0000000..76ff790 --- /dev/null +++ b/tests/system/RetailcrmTest.php @@ -0,0 +1,18 @@ +getMockBuilder(\RetailcrmProxy::class) + ->disableOriginalConstructor() + ->getMock(); + + static::$registry->set(\RetailcrmProxy::class, $proxy); + $manager = $retailcrm->getOrderManager(); + + $this->assertInstanceOf(\retailcrm\service\OrderManager::class, $manager); + } +} diff --git a/tests/system/lib/ModelsProviderAdminTest.php b/tests/system/lib/ModelsProviderAdminTest.php new file mode 100644 index 0000000..95f6c39 --- /dev/null +++ b/tests/system/lib/ModelsProviderAdminTest.php @@ -0,0 +1,14 @@ +includeDependencies(); +// +// $this->assertNotEmpty($this->model_sale_order); + } +} diff --git a/tests/system/lib/ModelsProviderTest.php b/tests/system/lib/ModelsProviderTest.php new file mode 100644 index 0000000..72a8262 --- /dev/null +++ b/tests/system/lib/ModelsProviderTest.php @@ -0,0 +1,13 @@ +includeDependencies(); + + $this->assertNotEmpty($this->model_checkout_order); + } +} diff --git a/tests/system/lib/UtilsTest.php b/tests/system/lib/UtilsTest.php new file mode 100644 index 0000000..da2b509 --- /dev/null +++ b/tests/system/lib/UtilsTest.php @@ -0,0 +1,21 @@ + 0, 1 => 1, 'array' => array(), 'array0' => array('0'), 'emptyString' => '' + ); + + $array = \retailcrm\Utils::filterRecursive($testArray); + + $this->assertNotEmpty($array); + $this->assertArrayHasKey('0', $array); + $this->assertArrayHasKey(1, $array); + $this->assertArrayHasKey('array0', $array); + $this->assertEquals('0', $array['array0'][0]); + $this->assertArrayNotHasKey('array', $array); + $this->assertArrayNotHasKey('emptyString', $array); + } +} diff --git a/tests/system/lib/factory/CustomerConverterFactoryTest.php b/tests/system/lib/factory/CustomerConverterFactoryTest.php new file mode 100644 index 0000000..6ba6632 --- /dev/null +++ b/tests/system/lib/factory/CustomerConverterFactoryTest.php @@ -0,0 +1,11 @@ +assertInstanceOf(\retailcrm\service\RetailcrmCustomerConverter::class, $converter); + } +} diff --git a/tests/system/lib/factory/OrderConverterFactoryTest.php b/tests/system/lib/factory/OrderConverterFactoryTest.php new file mode 100644 index 0000000..2524592 --- /dev/null +++ b/tests/system/lib/factory/OrderConverterFactoryTest.php @@ -0,0 +1,11 @@ +assertInstanceOf(\retailcrm\service\RetailcrmOrderConverter::class, $converter); + } +} diff --git a/tests/system/lib/history/CustomerAdminTest.php b/tests/system/lib/history/CustomerAdminTest.php new file mode 100644 index 0000000..9987d17 --- /dev/null +++ b/tests/system/lib/history/CustomerAdminTest.php @@ -0,0 +1,65 @@ +customer = array( + 'firstName' => 'Test', + 'lastName' => 'Test', + 'email' => 'test@mail.com', + 'phones' => array( + array('number' => '800000000') + ), + 'address' => array( + 'countryIso' => 'RU', + 'index' => '111111', + 'city' => 'City', + 'region' => 'Region', + 'text' => 'Text' + ) + ); + } + + public function testHandleExistingCustomer() { + $data_repository = new \retailcrm\repository\DataRepository(static::$registry); + $customer_repository = new \retailcrm\repository\CustomerRepository(static::$registry); + $settings_manager = new \retailcrm\service\SettingsManager(static::$registry); + + $customer_history = new \retailcrm\history\Customer($data_repository, $customer_repository, $settings_manager); + $customer_data = $customer_repository->getCustomer(OrderManagerTest::CUSTOMER_ID); + + $customer_history->handleCustomer($customer_data, $this->customer); + + $this->assertEquals(false, $customer_data['password']); + } + + public function testHandleNotExistingCustomer() { + $data_repository = new \retailcrm\repository\DataRepository(static::$registry); + $customer_repository = new \retailcrm\repository\CustomerRepository(static::$registry); + $settings_manager = new \retailcrm\service\SettingsManager(static::$registry); + + $customer_history = new \retailcrm\history\Customer($data_repository, $customer_repository, $settings_manager); + $customer_data = array(); + + $customer_history->handleCustomer($customer_data, $this->customer); + + $this->assertNotEquals(false, $customer_data['password']); + } + + public function testHandleAddress() { + $data_repository = new \retailcrm\repository\DataRepository(static::$registry); + $customer_repository = new \retailcrm\repository\CustomerRepository(static::$registry); + $settings_manager = new \retailcrm\service\SettingsManager(static::$registry); + + $customer_history = new \retailcrm\history\Customer($data_repository, $customer_repository, $settings_manager); + + $address = $customer_history->handleAddress($this->customer, array()); + + $this->assertEquals(true, $address['default']); + } +} diff --git a/tests/system/lib/history/OrderAdminTest.php b/tests/system/lib/history/OrderAdminTest.php new file mode 100644 index 0000000..89e57a0 --- /dev/null +++ b/tests/system/lib/history/OrderAdminTest.php @@ -0,0 +1,147 @@ +order = $this->getOrder(); + + $data_repository = new \retailcrm\repository\DataRepository(static::$registry); + $settings_manager = new \retailcrm\service\SettingsManager(static::$registry); + $products_repository = new \retailcrm\repository\ProductsRepository(static::$registry); + $order_repository = new \retailcrm\repository\OrderRepository(static::$registry); + + $this->order_history = new \retailcrm\history\Order( + $data_repository, + $settings_manager, + $products_repository, + $order_repository + ); + + $this->order_history->setOcDelivery(array( + "flat" => array( + "title" => "Flat Rate", + "flat.flat" => array( + "code" => "flat.flat", + "title" => "Flat Shipping Rate", + "cost" => "5.00", + "tax_class_id" => "9", + "text" => "$8.00" + ) + ) + )); + + $this->order_history->setOcPayment(array( + "cod" => "Cash on delivery" + )); + } + + public function testHandleBaseOrderData() { + $data = array(); + + $this->order_history->handleBaseOrderData($data, $this->order); + + $this->assertNotEmpty($data['telephone']); + $this->assertNotEmpty($data['email']); + $this->assertNotEmpty($data['email']); + $this->assertNotEmpty($data['firstname']); + $this->assertNotEmpty($data['lastname']); + $this->assertNotEmpty($data['store_name']); + } + + public function testHandlePayment() { + $data = array(); + + $this->order_history->handlePayment($data, $this->order); + + $this->assertNotEmpty($data['payment_firstname']); + $this->assertNotEmpty($data['payment_lastname']); + $this->assertNotEmpty($data['payment_city']); + $this->assertNotEmpty($data['payment_postcode']); + $this->assertNotEmpty($data['payment_country']); + $this->assertNotEmpty($data['payment_method']); + $this->assertNotEmpty($data['payment_code']); + $this->assertEquals('cod', $data['payment_code']); + } + + public function testHandleShipping() { + $data = array(); + + $this->order_history->handleShipping($data, $this->order); + + $this->assertNotEmpty($data['shipping_firstname']); + $this->assertNotEmpty($data['shipping_lastname']); + $this->assertNotEmpty($data['shipping_city']); + $this->assertNotEmpty($data['shipping_postcode']); + $this->assertNotEmpty($data['shipping_method']); + $this->assertNotEmpty($data['shipping_code']); + $this->assertEquals('flat.flat', $data['shipping_code']); + } + + public function testHandleTotals() { + $data = array('shipping_method' => 'Flat rate'); + + $this->order_history->handleTotals($data, $this->order); + + $this->assertNotEmpty($data['order_total']); + $this->assertNotEmpty($data['total']); + } + + private function getOrder() { + return array( + 'externalId' => '1', + 'email' => 'test@test.com', + 'phone' => '8000000000', + 'firstName' => 'Test', + 'lastName' => 'Test', + 'customerComment' => 'Test comment', + 'countryIso' => 'RU', + 'totalSumm' => 200, + 'summ' => 100, + 'customer' => array( + 'firstName' => 'Test customer', + 'lastName' => 'Test customer', + 'address' => array( + 'countryIso' => 'RU', + 'index' => '111111', + 'region' => 'Test region', + 'city' => 'Test city', + 'text' => '' + ) + ), + 'delivery' => array( + 'code' => 'flat', + 'cost' => 100, + 'address' => array( + 'index' => '111111', + 'region' => 'Test region', + 'city' => 'Test city', + 'text' => '' + ) + ), + 'payments' => array( + array( + 'externalId' => 'opencart_1', + 'type' => 'cod' + ) + ), + 'items' => array( + array( + 'initialPrice' => 100, + 'discountTotal' => 0, + 'quantity' => 1, + 'offer' => array( + 'displayName' => 'Test', + 'externalId' => '42#217-39_218-43', + 'name' => 'Test' + ) + ) + ) + ); + } +} diff --git a/tests/system/lib/repository/CustomerRespositoryAdminTest.php b/tests/system/lib/repository/CustomerRespositoryAdminTest.php new file mode 100644 index 0000000..1fe9e5a --- /dev/null +++ b/tests/system/lib/repository/CustomerRespositoryAdminTest.php @@ -0,0 +1,17 @@ +getCustomer(static::CUSTOMER_ID); + + $this->assertNotEmpty($customer); + $this->assertEquals(static::CUSTOMER_ID, $customer['customer_id']); + } +} diff --git a/tests/system/lib/repository/CustomerRespositoryTest.php b/tests/system/lib/repository/CustomerRespositoryTest.php new file mode 100644 index 0000000..4120637 --- /dev/null +++ b/tests/system/lib/repository/CustomerRespositoryTest.php @@ -0,0 +1,17 @@ +getCustomer(static::CUSTOMER_ID); + + $this->assertNotEmpty($customer); + $this->assertEquals(static::CUSTOMER_ID, $customer['customer_id']); + } +} diff --git a/tests/system/lib/repository/DataRepositoryAdminTest.php b/tests/system/lib/repository/DataRepositoryAdminTest.php new file mode 100644 index 0000000..071e760 --- /dev/null +++ b/tests/system/lib/repository/DataRepositoryAdminTest.php @@ -0,0 +1,63 @@ +getCountryByIsoCode('RU'); + + $this->assertNotEmpty($country); + $this->assertNotEmpty($country['name']); + } + + public function testGetZoneByName() { + $repository = new \retailcrm\repository\DataRepository(static::$registry); + + $zone = $repository->getZoneByName('Rostov-na-Donu'); + + $this->assertNotEmpty($zone); + $this->assertNotEmpty($zone['zone_id']); + } + + public function testGetCurrencyByCode() { + $repository = new \retailcrm\repository\DataRepository(static::$registry); + + $currency = $repository->getCurrencyByCode('USD'); + + $this->assertNotEmpty($currency); + + $currency = $repository->getCurrencyByCode('USD', 'title'); + + $this->assertNotEmpty($currency); + } + + public function testGetLanguageByCode() { + $repository = new \retailcrm\repository\DataRepository(static::$registry); + + $language = $repository->getLanguageByCode('en-gb'); + + $this->assertNotEmpty($language); + + $language = $repository->getLanguageByCode('en-gb', 'name'); + + $this->assertNotEmpty($language); + } + + public function testGetConfig() { + $repository = new \retailcrm\repository\DataRepository(static::$registry); + + $value = $repository->getConfig('config_currency'); + + $this->assertNotEmpty($value); + } + + public function testGetLanguage() { + $repository = new \retailcrm\repository\DataRepository(static::$registry); + + $value = $repository->getLanguage('product_summ'); + + $this->assertNotEmpty($value); + } +} diff --git a/tests/system/lib/repository/OrderRepositoryAdminTest.php b/tests/system/lib/repository/OrderRepositoryAdminTest.php new file mode 100644 index 0000000..98a0c77 --- /dev/null +++ b/tests/system/lib/repository/OrderRepositoryAdminTest.php @@ -0,0 +1,22 @@ +getOrder(OrderManagerTest::ORDER_WITH_CUST_ID); + + $this->assertNotEmpty($order); + $this->assertEquals(OrderManagerTest::ORDER_WITH_CUST_ID, $order['order_id']); + } + + public function testGetOrderTotals() { + $repository = new \retailcrm\repository\OrderRepository(static::$registry); + + $totals = $repository->getOrderTotals(OrderManagerTest::ORDER_WITH_CUST_ID); + + $this->assertNotEmpty($totals); + } +} diff --git a/tests/system/lib/repository/ProductsRespositoryTest.php b/tests/system/lib/repository/ProductsRespositoryTest.php new file mode 100644 index 0000000..f853a96 --- /dev/null +++ b/tests/system/lib/repository/ProductsRespositoryTest.php @@ -0,0 +1,31 @@ +getProductSpecials(42); + + $this->assertNotEmpty($specials); + } + + public function testGetProductOptions() { + $repository = new \retailcrm\repository\ProductsRepository(static::$registry); + + $options = $repository->getProductOptions(42); + + $this->assertNotEmpty($options); + } + + public function testGetProduct() { + $repository = new \retailcrm\repository\ProductsRepository(static::$registry); + + $options = $repository->getProduct(42); + + $this->assertNotEmpty($options); + } +} diff --git a/tests/system/lib/service/CorporateCustomerBuilderTest.php b/tests/system/lib/service/CorporateCustomerBuilderTest.php new file mode 100644 index 0000000..3328bca --- /dev/null +++ b/tests/system/lib/service/CorporateCustomerBuilderTest.php @@ -0,0 +1,37 @@ + '111111', + 'payment_iso_code_2' => 'RU', + 'payment_zone' => 'Zone', + 'payment_city' => 'City', + 'payment_company' => 'Company', + 'payment_address_1' => 'Address', + 'payment_address_2' => '', + 'shipping_postcode' => '111111', + 'shipping_iso_code_2' => 'RU', + 'shipping_zone' => 'Zone', + 'shipping_city' => 'City', + 'shipping_company' => 'Company', + 'shipping_address_1' => 'Address', + 'shipping_address_2' => '' + ); + + $corp = \retailcrm\service\CorporateCustomerBuilder::create() + ->setCustomerExternalId(1) + ->setCompany('Company') + ->addCompany($data) + ->addAddress($data) + ->build(); + + $this->assertNotEmpty($corp); + $this->assertNotEmpty($corp['addresses']); + $this->assertNotEmpty($corp['companies']); + $this->assertNotEmpty($corp['customerContacts'][0]['customer']); + $this->assertEquals(1, $corp['customerContacts'][0]['customer']['externalId']); + } +} diff --git a/tests/system/lib/service/CorporateCustomerTest.php b/tests/system/lib/service/CorporateCustomerTest.php new file mode 100644 index 0000000..7cd6646 --- /dev/null +++ b/tests/system/lib/service/CorporateCustomerTest.php @@ -0,0 +1,107 @@ +loadModel('checkout/order'); + $order_data = $model->getOrder(static::ORDER_ID); + $order_data['payment_company'] = 'Test company'; + + $proxy = $this->getMockBuilder(\RetailcrmProxy::class) + ->disableOriginalConstructor() + ->setMethods([]) + ->getMock(); + + $customer_repository = new \retailcrm\repository\CustomerRepository(static::$registry); + + $corporate_customer = new \retailcrm\service\CorporateCustomer($proxy, $customer_repository); + $corp = $corporate_customer->buildCorporateCustomerFromOrder($order_data, 1); + + $this->assertNotEmpty($corp); + $this->assertEquals(1, $corp['customerContacts'][0]['customer']['id']); + } + + public function testCreateCorporateCustomerFromExistingCustomer() { + $customer = array( + 'externalId' => 1 + ); + + $model = $this->loadModel('checkout/order'); + $order_data = $model->getOrder(OrderManagerTest::ORDER_WITH_CUST_ID); + + $proxy = $this->getMockBuilder(\RetailcrmProxy::class) + ->disableOriginalConstructor() + ->setMethods([ + 'customersGet', + 'customersCorporateList', + 'customersCorporateCreate', + 'customersCorporateAddressesCreate', + 'customersCorporateCompaniesCreate' + ]) + ->getMock(); + + $proxy->expects($this->once())->method('customersGet')->willReturn( + new \RetailcrmApiResponse(200, '{"success": true, "customer": {"id": 1}}') + ); + + $proxy->expects($this->any())->method('customersCorporateList')->willReturn( + new \RetailcrmApiResponse(200, '{"success": true, "customersCorporate": []}') + ); + + $proxy->expects($this->once())->method('customersCorporateCreate')->willReturn( + new \RetailcrmApiResponse(201, '{"success": true, "id": 1}') + ); + + $proxy->expects($this->once())->method('customersCorporateAddressesCreate')->willReturn( + new \RetailcrmApiResponse(201, '{"success": true, "id": 1}') + ); + + $customer_repository = new \retailcrm\repository\CustomerRepository(static::$registry); + $corporate_customer = new \retailcrm\service\CorporateCustomer($proxy, $customer_repository); + + $corp = $corporate_customer->createCorporateCustomer($order_data, $customer); + + $this->assertEquals(1, $corp); + } + + public function testCreateCorporateCustomerFromNotExistingCustomer() { + $customer = array( + 'id' => 1 + ); + + $model = $this->loadModel('checkout/order'); + $order_data = $model->getOrder(OrderManagerTest::ORDER_WITH_CUST_ID); + + $proxy = $this->getMockBuilder(\RetailcrmProxy::class) + ->disableOriginalConstructor() + ->setMethods([ + 'customersCorporateList', + 'customersCorporateCreate', + 'customersCorporateAddressesCreate', + 'customersCorporateCompaniesCreate' + ]) + ->getMock(); + + $proxy->expects($this->atLeast(2))->method('customersCorporateList')->willReturn( + new \RetailcrmApiResponse(200, '{"success": true, "customersCorporate": []}') + ); + + $proxy->expects($this->once())->method('customersCorporateCreate')->willReturn( + new \RetailcrmApiResponse(201, '{"success": true, "id": 1}') + ); + + $proxy->expects($this->once())->method('customersCorporateAddressesCreate')->willReturn( + new \RetailcrmApiResponse(201, '{"success": true, "id": 1}') + ); + + $customer_repository = new \retailcrm\repository\CustomerRepository(static::$registry); + $corporate_customer = new \retailcrm\service\CorporateCustomer($proxy, $customer_repository); + + $corp = $corporate_customer->createCorporateCustomer($order_data, $customer); + + $this->assertEquals(1, $corp); + } +} diff --git a/tests/system/lib/service/CustomerManagerTest.php b/tests/system/lib/service/CustomerManagerTest.php new file mode 100644 index 0000000..c999d0c --- /dev/null +++ b/tests/system/lib/service/CustomerManagerTest.php @@ -0,0 +1,77 @@ +loadModel('account/customer'); + $customer = $customerModel->getCustomer(self::CUSTOMER_ID); + + $proxy = $this->getMockBuilder(\RetailcrmProxy::class) + ->disableOriginalConstructor() + ->setMethods(array('customersCreate')) + ->getMock(); + + $proxy->expects($this->once())->method('customersCreate'); + + $customer_manager = new \retailcrm\service\CustomerManager( + $proxy, + \retailcrm\factory\CustomerConverterFactory::create(static::$registry) + ); + + $customer_manager->createCustomer($customer, array()); + } + + public function testEditCustomer() { + $customerModel = $this->loadModel('account/customer'); + $customer = $customerModel->getCustomer(self::CUSTOMER_ID); + + $proxy = $this->getMockBuilder(\RetailcrmProxy::class) + ->disableOriginalConstructor() + ->setMethods(['customersEdit']) + ->getMock(); + + $proxy->expects($this->once())->method('customersEdit'); + + $customer_manager = new \retailcrm\service\CustomerManager( + $proxy, + \retailcrm\factory\CustomerConverterFactory::create(static::$registry) + ); + + $customer_manager->editCustomer($customer, array()); + } + + public function testPrepareCustomer() { + $customer_model = $this->loadModel('account/customer'); + $customer = $customer_model->getCustomer(self::CUSTOMER_ID); + $address = array( + 'postcode' => '111111', + 'iso_code_2' => 'EN', + 'zone' => 'Zone', + 'city' => 'City', + 'address_1' => 'Address', + 'address_2' => '' + ); + + $proxy = $this->getMockBuilder(\RetailcrmProxy::class) + ->disableOriginalConstructor() + ->getMock(); + + $customer_manager = new \retailcrm\service\CustomerManager( + $proxy, + \retailcrm\factory\CustomerConverterFactory::create(static::$registry) + ); + + $customer = $customer_manager->prepareCustomer($customer, $address); + + $this->assertArrayHasKey('externalId', $customer); + $this->assertArrayHasKey('firstName', $customer); + $this->assertArrayHasKey('lastName', $customer); + $this->assertArrayHasKey('email', $customer); + $this->assertArrayHasKey('externalId', $customer); + $this->assertArrayHasKey('createdAt', $customer); + $this->assertArrayHasKey('address', $customer); + } +} diff --git a/tests/system/lib/service/OrderManagerTest.php b/tests/system/lib/service/OrderManagerTest.php new file mode 100644 index 0000000..9063755 --- /dev/null +++ b/tests/system/lib/service/OrderManagerTest.php @@ -0,0 +1,250 @@ +getMockBuilder(\RetailcrmProxy::class) + ->disableOriginalConstructor() + ->setMethods(['ordersCreate']) + ->getMock(); + + $proxy->expects($this->once())->method('ordersCreate'); + + $customer_manager = new \retailcrm\service\CustomerManager( + $proxy, + \retailcrm\factory\CustomerConverterFactory::create(static::$registry) + ); + + $converter = \retailcrm\factory\OrderConverterFactory::create(static::$registry); + $corporate_customer = new \retailcrm\service\CorporateCustomer( + $proxy, new \retailcrm\repository\CustomerRepository(static::$registry) + ); + $settings_manager = new \retailcrm\service\SettingsManager(static::$registry); + + $order_manager = new \retailcrm\service\OrderManager($proxy, $customer_manager, $converter, $corporate_customer, $settings_manager); + + $orderCheckoutModel = $this->loadModel('checkout/order'); + $orderAccountModel = $this->loadModel('account/order'); + $order_id = self::ORDER_WITH_CUST_ID; + $order = $orderCheckoutModel->getOrder($order_id); + $products = $orderAccountModel->getOrderProducts($order_id); + $totals = $orderAccountModel->getOrderTotals($order_id); + + foreach ($products as $key => $product) { + $productOptions = $orderAccountModel->getOrderOptions($order_id, $product['order_product_id']); + + if (!empty($productOptions)) { + $products[$key]['option'] = $productOptions; + } + } + + $order_manager->createOrder($order, $products, $totals); + } + + public function testCreateOrderWithoutExistingCustomer() { + $proxy = $this->getMockBuilder(\RetailcrmProxy::class) + ->disableOriginalConstructor() + ->setMethods(['ordersCreate', 'customersList']) + ->getMock(); + + $proxy->expects($this->once())->method('ordersCreate'); + $proxy->expects($this->once()) + ->method('customersList') + ->willReturn(new \RetailcrmApiResponse( + 200, + json_encode( + array( + 'success' => true, + 'pagination' => [ + 'limit'=> 20, + 'totalCount' => 0, + 'currentPage' => 1, + 'totalPageCount' => 0 + ], + 'customers' => [ + [ + 'id' => 1, + 'externalId' => 1 + ] + ] + ) + ) + )); + + $customer_manager = new \retailcrm\service\CustomerManager( + $proxy, + \retailcrm\factory\CustomerConverterFactory::create(static::$registry) + ); + + $converter = \retailcrm\factory\OrderConverterFactory::create(static::$registry); + $corporate_customer = new \retailcrm\service\CorporateCustomer( + $proxy, new \retailcrm\repository\CustomerRepository(static::$registry) + ); + $settings_manager = new \retailcrm\service\SettingsManager(static::$registry); + $order_manager = new \retailcrm\service\OrderManager($proxy, $customer_manager, $converter, $corporate_customer, $settings_manager); + + $orderCheckoutModel = $this->loadModel('checkout/order'); + $orderAccountModel = $this->loadModel('account/order'); + $order_id = self::ORDER_ID; + $order = $orderCheckoutModel->getOrder($order_id); + $products = $orderAccountModel->getOrderProducts($order_id); + $totals = $orderAccountModel->getOrderTotals($order_id); + + foreach ($products as $key => $product) { + $productOptions = $orderAccountModel->getOrderOptions($order_id, $product['order_product_id']); + + if (!empty($productOptions)) { + $products[$key]['option'] = $productOptions; + } + } + + $order_manager->createOrder($order, $products, $totals); + } + + public function testCreateOrderWithoutNotExistingCustomer() { + $proxy = $this->getMockBuilder(\RetailcrmProxy::class) + ->disableOriginalConstructor() + ->setMethods(['ordersCreate', 'customersList', 'customersCreate']) + ->getMock(); + + $proxy->expects($this->once())->method('ordersCreate'); + $proxy->expects($this->once()) + ->method('customersList') + ->willReturn(new \RetailcrmApiResponse( + 200, + json_encode( + array( + 'success' => true, + 'pagination' => [ + 'limit'=> 20, + 'totalCount' => 0, + 'currentPage' => 1, + 'totalPageCount' => 0 + ], + 'customers' => [] + ) + ) + )); + + $proxy->expects($this->once()) + ->method('customersCreate') + ->willReturn(new \RetailcrmApiResponse( + 201, + json_encode( + array( + 'success' => true, + 'id' => 1 + ) + ) + )); + + $customer_manager = new \retailcrm\service\CustomerManager( + $proxy, + \retailcrm\factory\CustomerConverterFactory::create(static::$registry) + ); + + $converter = \retailcrm\factory\OrderConverterFactory::create(static::$registry); + $corporate_customer = new \retailcrm\service\CorporateCustomer( + $proxy, new \retailcrm\repository\CustomerRepository(static::$registry) + ); + $settings_manager = new \retailcrm\service\SettingsManager(static::$registry); + $order_manager = new \retailcrm\service\OrderManager($proxy, $customer_manager, $converter, $corporate_customer, $settings_manager); + + $orderCheckoutModel = $this->loadModel('checkout/order'); + $orderAccountModel = $this->loadModel('account/order'); + $order_id = self::ORDER_ID; + $order = $orderCheckoutModel->getOrder($order_id); + $products = $orderAccountModel->getOrderProducts($order_id); + $totals = $orderAccountModel->getOrderTotals($order_id); + + foreach ($products as $key => $product) { + $productOptions = $orderAccountModel->getOrderOptions($order_id, $product['order_product_id']); + + if (!empty($productOptions)) { + $products[$key]['option'] = $productOptions; + } + } + + $order_manager->createOrder($order, $products, $totals); + } + + public function testEditOrderWithCustomer() { + $proxy = $this->getMockBuilder(\RetailcrmProxy::class) + ->disableOriginalConstructor() + ->setMethods(['ordersEdit', 'ordersGet', 'ordersPaymentEdit']) + ->getMock(); + + $orderEditResponse = new \RetailcrmApiResponse( + 200, + json_encode( + array( + 'success' => true, + 'id' => 1 + ) + ) + ); + + $ordersGetResponse = new \RetailcrmApiResponse( + 200, + json_encode( + array( + 'success' => true, + 'order' => $this->getOrder(self::ORDER_WITH_CUST_ID) + ) + ) + ); + + $proxy->expects($this->once())->method('ordersEdit')->willReturn($orderEditResponse); + $proxy->expects($this->once())->method('ordersGet')->willReturn($ordersGetResponse); + $proxy->expects($this->once())->method('ordersPaymentEdit'); + + $customer_manager = new \retailcrm\service\CustomerManager( + $proxy, + \retailcrm\factory\CustomerConverterFactory::create(static::$registry) + ); + + $converter = \retailcrm\factory\OrderConverterFactory::create(static::$registry); + $settings_manager = new \retailcrm\service\SettingsManager(static::$registry); + $corporate_customer = new \retailcrm\service\CorporateCustomer( + $proxy, new \retailcrm\repository\CustomerRepository(static::$registry) + ); + $order_manager = new \retailcrm\service\OrderManager($proxy, $customer_manager, $converter, $corporate_customer, $settings_manager); + + $orderCheckoutModel = $this->loadModel('checkout/order'); + $orderAccountModel = $this->loadModel('account/order'); + $order_id = self::ORDER_WITH_CUST_ID; + $order = $orderCheckoutModel->getOrder($order_id); + $products = $orderAccountModel->getOrderProducts($order_id); + $totals = $orderAccountModel->getOrderTotals($order_id); + + foreach ($products as $key => $product) { + $productOptions = $orderAccountModel->getOrderOptions($order_id, $product['order_product_id']); + + if (!empty($productOptions)) { + $products[$key]['option'] = $productOptions; + } + } + + $order_manager->editOrder($order, $products, $totals); + } + + private function getOrder($id) + { + return array( + 'payments' => array( + array( + 'id' => 1, + 'status' => 'not-paid', + 'type' => 'cod', + 'externalId' => $id, + 'amount' => '100' + ) + ) + ); + } +} diff --git a/tests/system/lib/service/RetailcrmCustomerConverterTest.php b/tests/system/lib/service/RetailcrmCustomerConverterTest.php new file mode 100644 index 0000000..52ed059 --- /dev/null +++ b/tests/system/lib/service/RetailcrmCustomerConverterTest.php @@ -0,0 +1,52 @@ +loadModel('account/customer'); + $customer_data = $model->getCustomer(1); + + $customer = $converter + ->initCustomerData($customer_data, array()) + ->setCustomerData() + ->getCustomer(); + + $this->assertEquals($customer_data['customer_id'], $customer['externalId']); + $this->assertEquals($customer_data['firstname'], $customer['firstName']); + $this->assertEquals($customer_data['lastname'], $customer['lastName']); + $this->assertEquals($customer_data['email'], $customer['email']); + $this->assertEquals($customer_data['date_added'], $customer['createdAt']); + } + + public function testSetAddress() { + $converter = \retailcrm\factory\CustomerConverterFactory::create(static::$registry); + $model = $this->loadModel('account/customer'); + $customer_data = $model->getCustomer(static::CUSTOMER_ID); + $address = array( + 'postcode' => '111111', + 'iso_code_2' => 'EN', + 'zone' => 'Zone', + 'city' => 'City', + 'address_1' => 'Address', + 'address_2' => '' + ); + + $customer = $converter + ->initCustomerData($customer_data, $address) + ->setAddress() + ->getCustomer(); + + $this->assertEquals($address['postcode'], $customer['address']['index']); + $this->assertEquals($address['iso_code_2'], $customer['address']['countryIso']); + $this->assertEquals($address['zone'], $customer['address']['region']); + $this->assertEquals($address['city'], $customer['address']['city']); + $this->assertEquals( + $address['address_1'] . ' '. $address['address_2'], + $customer['address']['text'] + ); + } +} diff --git a/tests/system/lib/service/RetailcrmOrderConverterTest.php b/tests/system/lib/service/RetailcrmOrderConverterTest.php new file mode 100644 index 0000000..c728a88 --- /dev/null +++ b/tests/system/lib/service/RetailcrmOrderConverterTest.php @@ -0,0 +1,134 @@ +loadModel('checkout/order'); + $order_account_model = $this->loadModel('account/order'); + + $order_data = $order_checkout_model->getOrder(static::ORDER_WITH_CUST_ID); + $products = $order_account_model->getOrderProducts(static::ORDER_WITH_CUST_ID); + $totals = $order_account_model->getOrderTotals(static::ORDER_WITH_CUST_ID); + + foreach ($products as $key => $product) { + $productOptions = $order_account_model->getOrderOptions(static::ORDER_WITH_CUST_ID, $product['order_product_id']); + + if (!empty($productOptions)) { + $products[$key]['option'] = $productOptions; + } + } + + $converter = \retailcrm\factory\OrderConverterFactory::create(static::$registry); + + $order = $converter->initOrderData( + $order_data, + $products, + $totals + )->setOrderData()->getOrder(); + + $this->assertEquals('new', $order['status']); + $this->assertEquals(static::ORDER_WITH_CUST_ID, $order['externalId']); + $this->assertEquals(static::ORDER_WITH_CUST_ID, $order['number']); + $this->assertEquals('Test', $order['firstName']); + $this->assertEquals('Test', $order['lastName']); + $this->assertEquals('test@mail.ru', $order['email']); + $this->assertEquals('+7 (000) 000-00-00', $order['phone']); + $this->assertEquals($order_data['date_added'], $order['createdAt']); + $this->assertEquals($order_data['comment'], $order['customerComment']); + $this->assertEquals(self::CUSTOMER_ID, $order['customer']['externalId']); + } + + public function testSetPayment() { + $order_checkout_model = $this->loadModel('checkout/order'); + $order_account_model = $this->loadModel('account/order'); + + $order_data = $order_checkout_model->getOrder(static::ORDER_WITH_CUST_ID); + $products = $order_account_model->getOrderProducts(static::ORDER_WITH_CUST_ID); + $totals = $order_account_model->getOrderTotals(static::ORDER_WITH_CUST_ID); + + foreach ($products as $key => $product) { + $productOptions = $order_account_model->getOrderOptions(static::ORDER_WITH_CUST_ID, $product['order_product_id']); + + if (!empty($productOptions)) { + $products[$key]['option'] = $productOptions; + } + } + + $converter = \retailcrm\factory\OrderConverterFactory::create(static::$registry); + + $order = $converter->initOrderData( + $order_data, + $products, + $totals + )->setPayment()->getOrder(); + + $this->assertArrayHasKey('payments', $order); + $this->assertNotEmpty($order['payments']); + $this->assertEquals('cod', $order['payments'][0]['type']); + } + + public function testSetDelivery() { + $order_checkout_model = $this->loadModel('checkout/order'); + $order_account_model = $this->loadModel('account/order'); + + $order_data = $order_checkout_model->getOrder(static::ORDER_WITH_CUST_ID); + $products = $order_account_model->getOrderProducts(static::ORDER_WITH_CUST_ID); + $totals = $order_account_model->getOrderTotals(static::ORDER_WITH_CUST_ID); + + foreach ($products as $key => $product) { + $productOptions = $order_account_model->getOrderOptions(static::ORDER_WITH_CUST_ID, $product['order_product_id']); + + if (!empty($productOptions)) { + $products[$key]['option'] = $productOptions; + } + } + + $converter = \retailcrm\factory\OrderConverterFactory::create(static::$registry); + + $order = $converter->initOrderData( + $order_data, + $products, + $totals + )->setDelivery()->getOrder(); + + $this->assertArrayHasKey('delivery', $order); + $this->assertNotEmpty($order['delivery']); + $this->assertEquals('flat', $order['delivery']['code']); + $this->assertEquals('Test', $order['delivery']['address']['city']); + $this->assertEquals('Rostov-na-Donu', $order['delivery']['address']['region']); + $this->assertEquals('111111', $order['delivery']['address']['index']); + } + + public function testSetItems() { + $order_checkout_model = $this->loadModel('checkout/order'); + $order_account_model = $this->loadModel('account/order'); + + $order_data = $order_checkout_model->getOrder(static::ORDER_WITH_CUST_ID); + $products = $order_account_model->getOrderProducts(static::ORDER_WITH_CUST_ID); + $totals = $order_account_model->getOrderTotals(static::ORDER_WITH_CUST_ID); + + foreach ($products as $key => $product) { + $productOptions = $order_account_model->getOrderOptions(static::ORDER_WITH_CUST_ID, $product['order_product_id']); + + if (!empty($productOptions)) { + $products[$key]['option'] = $productOptions; + } + } + + $converter = \retailcrm\factory\OrderConverterFactory::create(static::$registry); + + $order = $converter->initOrderData( + $order_data, + $products, + $totals + )->setItems()->getOrder(); + + $this->assertArrayHasKey('items', $order); + $this->assertNotEmpty($order['items']); + } +} diff --git a/tests/system/lib/service/SettingsManagerTest.php b/tests/system/lib/service/SettingsManagerTest.php new file mode 100644 index 0000000..321eb2e --- /dev/null +++ b/tests/system/lib/service/SettingsManagerTest.php @@ -0,0 +1,44 @@ +getSettings(); + + $this->assertNotEmpty($settings); + } + + public function testGetSetting() { + $settings_manager = new \retailcrm\service\SettingsManager(static::$registry); + + $setting = $settings_manager->getSetting('payment'); + $this->assertNotEmpty($setting); + + $setting = $settings_manager->getSetting('delivery'); + $this->assertNotEmpty($setting); + } + + public function testGetPaymentSettings() { + $settings_manager = new \retailcrm\service\SettingsManager(static::$registry); + + $settings = $settings_manager->getPaymentSettings(); + $this->assertNotEmpty($settings); + } + + public function testGetDeliverySettings() { + $settings_manager = new \retailcrm\service\SettingsManager(static::$registry); + + $settings = $settings_manager->getDeliverySettings(); + $this->assertNotEmpty($settings); + } + + public function testGetStatusesSettings() { + $settings_manager = new \retailcrm\service\SettingsManager(static::$registry); + + $settings = $settings_manager->getStatusSettings(); + $this->assertNotEmpty($settings); + } +}