Corporate clients support & ability to change customer

This commit is contained in:
Akolzin Dmitry 2020-08-07 12:39:59 +03:00 committed by GitHub
parent fb5d969ccc
commit 2981afb05a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
85 changed files with 4620 additions and 4989 deletions

View File

@ -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

26
.docker/entrypoint.sh Normal file
View File

@ -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 "$@"

View File

@ -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=

View File

@ -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

View File

@ -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"
}

View File

@ -2,35 +2,34 @@ version: '3'
services:
app:
build:
context: ./.docker
volumes:
- ./:/home/code
links:
- "mysql"
user: ${UID:-1000}:${GID:-1000}
depends_on:
- mysql
env_file:
- ./.env
environment:
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_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
volumes:
- ./:/opencart-module
links:
- "mysql"
ports:
- "${SERVER_PORT}:${SERVER_PORT}"
depends_on:
- mysql
env_file:
- .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}

View File

@ -16,6 +16,9 @@
<testsuite name="admin-tests">
<directory suffix="AdminTest.php">./tests/admin/</directory>
</testsuite>
<testsuite name="system-tests">
<directory suffix="Test.php">./tests/system/</directory>
</testsuite>
</testsuites>
<php>
<env name="OC_ROOT" value="./www/" />
@ -23,13 +26,16 @@
<env name="TEST_CONFIG" value="test-config" />
</php>
<filter>
<whitelist>
<whitelist addUncoveredFilesFromWhitelist="true">
<directory suffix="retailcrm.php">./www/admin/controller</directory>
<directory>./www/admin/model/extension/retailcrm</directory>
<directory suffix="retailcrm.php">./www/catalog/controller</directory>
<directory suffix="daemon_collector.php">./www/catalog/controller</directory>
<directory>./www/catalog/model/extension/retailcrm</directory>
<directory suffix=".php">./www/system/library/retailcrm</directory>
<exclude>
<directory suffix=".php">./www/system/library/retailcrm/lib/api</directory>
</exclude>
</whitelist>
</filter>
</phpunit>

View File

@ -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,33 +160,30 @@ 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']
$this->request->post[$this->moduleTitle . '_apikey']
);
$ordersHistory = $api->ordersHistory();
if ($ordersHistory->isSuccessful() && !empty($ordersHistory['history'])) {
if ($ordersHistory && $ordersHistory->isSuccessful() && !empty($ordersHistory['history'])) {
$ordersHistory = $api->ordersHistory(array(), $ordersHistory['pagination']['totalPageCount']);
if ($ordersHistory->isSuccessful()) {
if ($ordersHistory && $ordersHistory->isSuccessful()) {
$ordersHistoryArr = $ordersHistory['history'];
$lastChangeOrders = end($ordersHistoryArr);
$sinceIdOrders = $lastChangeOrders['id'];
$generatedAt = $ordersHistory['generatedAt'];
}
}
$customersHistory = $api->customersHistory();
if ($customersHistory->isSuccessful() && !empty($customersHistory['history'])) {
if ($customersHistory && $customersHistory->isSuccessful() && !empty($customersHistory['history'])) {
$customersHistory = $api->customersHistory(array(), $customersHistory['pagination']['totalPageCount']);
if ($customersHistory->isSuccessful()) {
if ($customersHistory && $customersHistory->isSuccessful()) {
$customersHistoryArr = $customersHistory['history'];
$lastChangeCustomers = end($customersHistoryArr);
$sinceIdCustomers = $lastChangeCustomers['id'];
@ -199,12 +194,10 @@ class ControllerExtensionModuleRetailcrm extends Controller
'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')
'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,13 +339,10 @@ 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();
}
}
$config_data = array(
$this->moduleTitle . '_status'
@ -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());
}
} else {
if (file_exists(DIR_APPLICATION . 'model/extension/retailcrm/custom/history/v4-5.php')) {
$this->load->model('extension/retailcrm/custom/history/v4-5');
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,29 +521,24 @@ 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) {
if (!$response->isSuccessful()) {
if (isset($response['errors'])) {
$error = implode("\n", $response['errors']);
@ -608,6 +564,8 @@ class ControllerExtensionModuleRetailcrm extends Controller
);
}
}
}
}
/**
* Export orders
@ -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,13 +635,9 @@ class ControllerExtensionModuleRetailcrm extends Controller
$response = $apiClient->apiVersions();
if ($response && $response->isSuccessful()) {
if (!in_array($versionsMap[$this->request->post[$this->moduleTitle . '_apiversion']], $response['versions'])) {
if (!$response || !$response->isSuccessful()) {
$this->_error['warning'] = $this->language->get('text_error_api');
}
} else {
$this->_error['warning'] = $this->language->get('text_error_save');
}
if (!$this->user->hasPermission('modify', 'extension/module/retailcrm')) {
$this->_error['warning'] = $this->language->get('error_permission');
@ -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,17 +869,6 @@ 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
);
$response = $apiClient->marketplaceSettingsEdit($configuration);
} else {
$configuration = array(
'clientId' => $clientId,
'code' => $integrationCode . '-' . $clientId,
@ -946,7 +880,6 @@ class ControllerExtensionModuleRetailcrm extends Controller
);
$response = $apiClient->integrationModulesEdit($configuration);
}
if (!$response) {
return false;

View File

@ -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';

View File

@ -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';

View File

@ -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'] = 'Тип цены, в который будет выгружаться цена по акции';

View File

@ -1,137 +1,29 @@
<?php
class ModelExtensionRetailcrmCustomer extends Model {
protected $settings;
protected $moduleTitle;
protected $retailcrmApiClient;
public function __construct($registry)
{
parent::__construct($registry);
$this->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;
}
}

View File

@ -1,194 +1,348 @@
<?php
class ModelExtensionRetailcrmHistory extends Model
{
/**
* Create order in OC
*
* @param array $order
*
* @return int $order_id
*/
public function addOrder($order)
{
$this->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'];
}
/**
* 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'] . "'");
}
if ($lastChangeCustomers !== null) {
$sinceIdCustomers = $lastChangeCustomers['id'];
}
/**
* Get total titles
*
* @return string $title
*/
protected function totalTitles()
{
if (version_compare(VERSION, '3.0', '<')) {
$title = '';
$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 {
$title = 'total_';
$newOrders[] = $order['id'];
}
}
return $title;
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;
}
/**
* Get country by iso code 2
* Create orders from history
*
* @param string $isoCode
* @param array $orders
* @param \RetailcrmProxy $retailcrmApiClient
*
* @return array
*/
public function getCountryByIsoCode($isoCode)
{
$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "country` WHERE iso_code_2 = '" . $isoCode . "'");
protected function createOrders($orders, $retailcrmApiClient) {
$customersIdsFix = array();
$ordersIdsFix = array();
return $query->row;
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);
}
/**
* Get zone by name
* Update orders from history
*
* @param string $name
* @param array $orders
* @param \RetailcrmProxy $retailcrmApiClient
*
* @return void
*/
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);
}
}
/**
* @param \RetailcrmProxy $retailcrmApiClient
* @param array $order
*
* @return array
*/
public function getZoneByName($name)
{
$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "zone` WHERE name = '" . $name . "'");
private function getCorporateCustomerAddress($retailcrmApiClient, $order) {
$addresses = $retailcrmApiClient->customersCorporateAddresses(
$order['customer']['id'],
array('ids' => array($order['customer']['mainAddress'])),
null,
null,
'id'
);
return $query->row;
if ($addresses->isSuccessful() && !empty($addresses['addresses'])) {
return $addresses['addresses'][0];
}
/**
* 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];
return array();
}
}

View File

@ -1,117 +0,0 @@
<?php
require_once 'v4_5.php';
class ModelExtensionRetailcrmHistoryV3 extends ModelExtensionRetailcrmHistoryV45
{
protected $createResult;
/**
* Getting changes from RetailCRM
*
* @param \RetailcrmProxy $retailcrmApiClient
*
* @return boolean
*/
public function request($retailcrmApiClient)
{
$moduleTitle = $this->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;
}
}

View File

@ -1,837 +0,0 @@
<?php
require_once __DIR__ . '/../history.php';
class ModelExtensionRetailcrmHistoryV45 extends ModelExtensionRetailcrmHistory
{
protected $createResult;
protected $settings;
protected $moduleTitle;
protected $opencartApiClient;
private $customFieldSetting;
public function __construct($registry)
{
parent::__construct($registry);
$this->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);
}
}
}

View File

@ -1,335 +1,29 @@
<?php
class ModelExtensionRetailcrmOrder extends Model {
protected $settings;
protected $moduleTitle;
protected $retailcrmApiClient;
protected static $lastRepsonse = null;
public function __construct($registry)
{
parent::__construct($registry);
$this->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;
}
}

View File

@ -151,6 +151,9 @@ class ModelExtensionRetailcrmReferences extends Model
public function getApiDeliveryTypes()
{
$response = $this->retailcrmApiClient->deliveryTypesList();
if (!$response) {
return array();
}
return (!$response->isSuccessful()) ? array() : $response->deliveryTypes;
}
@ -163,6 +166,9 @@ class ModelExtensionRetailcrmReferences extends Model
public function getApiOrderStatuses()
{
$response = $this->retailcrmApiClient->statusesList();
if (!$response) {
return array();
}
return (!$response->isSuccessful()) ? array() : $response->statuses;
}
@ -175,6 +181,9 @@ class ModelExtensionRetailcrmReferences extends Model
public function getApiPaymentTypes()
{
$response = $this->retailcrmApiClient->paymentTypesList();
if (!$response) {
return array();
}
return (!$response->isSuccessful()) ? array() : $response->paymentTypes;
}
@ -188,6 +197,9 @@ class ModelExtensionRetailcrmReferences extends Model
{
$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;
@ -207,6 +219,9 @@ class ModelExtensionRetailcrmReferences extends Model
public function getPriceTypes()
{
$response = $this->retailcrmApiClient->priceTypesList();
if (!$response) {
return array();
}
return (!$response->isSuccessful()) ? array() : $response->priceTypes;
}

View File

@ -40,9 +40,7 @@
<?php if (isset($saved_settings['retailcrm_apikey']) && $saved_settings['retailcrm_apikey'] != '' && isset($saved_settings['retailcrm_url']) && $saved_settings['retailcrm_url'] != ''): ?>
<li><a href="#tab-references" data-toggle="tab"><?php echo $references_tab_text; ?></a></li>
<li><a href="#tab-collector" data-toggle="tab"><?php echo $collector_tab_text; ?></a></li>
<?php if ($saved_settings['retailcrm_apiversion'] == 'v5') : ?>
<li><a href="#tab-custom_fields" data-toggle="tab"><?php echo $custom_fields_tab_text; ?></a></li>
<?php endif; ?>
<li><a href="#tab-logs" data-toggle="tab"><?php echo $logs_tab_text; ?></a></li>
<?php endif; ?>
</ul>
@ -51,16 +49,6 @@
<input type="hidden" name="retailcrm_status" value="1">
<fieldset>
<legend><?php echo $retailcrm_base_settings; ?></legend>
<div class="form-group retailcrm_unit">
<label class="col-sm-2 control-label" for="retailcrm_url"><?php echo $retailcrm_apiversion; ?></label>
<div class="col-lg-1 col-md-2 col-sm-2">
<select name="retailcrm_apiversion" class="form-control">
<?php foreach($api_versions as $version) : ?>
<option value="<?php echo $version; ?>" <?php if (isset($saved_settings['retailcrm_apiversion']) && $saved_settings['retailcrm_apiversion'] == $version) echo "selected='selected'"; elseif (!isset($saved_settings['retailcrm_apiversion']) && $default_apiversion == $version) echo "selected='selected'"; ?>><?php echo $version; ?></option>
<?php endforeach ?>
</select>
</div>
</div>
<div class="form-group retailcrm_unit">
<label class="col-sm-2 control-label" for="retailcrm_url"><?php echo $retailcrm_url; ?></label>
<div class="col-lg-4 col-md-6 col-sm-10">
@ -73,6 +61,21 @@
<input id="retailcrm_apikey" type="text" name="retailcrm_apikey" value="<?php if (isset($saved_settings['retailcrm_apikey'])): echo $saved_settings['retailcrm_apikey']; endif;?>" class="form-control" />
</div>
</div>
<div class="form-group retailcrm_unit">
<label class="col-sm-2 control-label" for="retailcrm_corporate_enabled"><?php echo $corporate_enabled_label; ?></label>
<div class="col-sm-10">
<label class="radio-inline">
<input type="radio" name="retailcrm_corporate_enabled" value="1"
<?php if(isset($saved_settings['retailcrm_corporate_enabled']) && $saved_settings['retailcrm_corporate_enabled'] == 1): echo 'checked'; endif;?>/>
<?php echo $text_yes; ?>
</label>
<label class="radio-inline">
<input type="radio" name="retailcrm_corporate_enabled" value="0"
<?php if(!isset($saved_settings['retailcrm_corporate_enabled']) || $saved_settings['retailcrm_corporate_enabled'] == 0): echo 'checked'; endif;?>/>
<?php echo $text_no; ?>
</label>
</div>
</div>
</fieldset>
<fieldset>
<legend><?php echo $retailcrm_countries_settings; ?></legend>
@ -166,7 +169,6 @@
</div>
</div>
</fieldset>
<?php if (isset($saved_settings['retailcrm_apiversion']) && $saved_settings['retailcrm_apiversion'] != 'v3') : ?>
<fieldset>
<legend><?php echo $special_price_settings; ?></legend>
<div class="form-group retailcrm_unit">
@ -190,7 +192,6 @@
<?php endforeach; ?>
</div>
</fieldset>
<?php endif; ?>
<fieldset>
<legend><?php echo $order_number; ?></legend>
<div class="form-group">
@ -455,7 +456,6 @@
<?php endforeach; ?>
</fieldset>
</div>
<?php if (isset($saved_settings['retailcrm_apiversion']) && $saved_settings['retailcrm_apiversion'] == 'v5' && isset($customFields)) : ?>
<div class="tab-pane" id="tab-custom_fields">
<fieldset>
<legend><?php echo $retailcrm_dict_custom_fields; ?></legend>
@ -543,7 +543,6 @@
<?php endif; ?>
</fieldset>
</div>
<?php endif; ?>
<div class="tab-pane" id="tab-logs">
<fieldset style="margin-bottom: 30px;">
<legend>retailCRM API error log</legend>

View File

@ -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 %}
<li><a href="#tab-references" data-toggle="tab">{{ references_tab_text }}</a></li>
<li><a href="#tab-collector" data-toggle="tab">{{ collector_tab_text }}</a></li>
{% if saved_settings.module_retailcrm_apiversion == 'v5' %}
<li><a href="#tab-custom_fields" data-toggle="tab"> {{ custom_fields_tab_text }} </a></li>
{% endif %}
<li><a href="#tab-logs" data-toggle="tab">{{ logs_tab_text }}</a></li>
{% endif %}
</ul>
@ -50,16 +48,6 @@
<input type="hidden" name="module_retailcrm_status" value="1">
<fieldset>
<legend>{{ retailcrm_base_settings }}</legend>
<div class="form-group retailcrm_unit">
<label class="col-sm-2 control-label" for="retailcrm_url">{{ retailcrm_apiversion }}</label>
<div class="col-lg-1 col-md-2 col-sm-2">
<select name="module_retailcrm_apiversion" class="form-control">
{% for version in api_versions %}
<option value="{{ version }}" {% if saved_settings.module_retailcrm_apiversion is defined and saved_settings.module_retailcrm_apiversion == version %} selected="selected" {% elseif saved_settings.module_retailcrm_apiversion is not defined and default_apiversion == version %} selected="selected" {% endif %}>{{ version }}</option>
{% endfor %}
</select>
</div>
</div>
<div class="form-group retailcrm_unit">
<label class="col-sm-2 control-label" for="retailcrm_url">{{ retailcrm_url }}</label>
<div class="col-lg-4 col-md-6 col-sm-10">
@ -72,6 +60,25 @@
<input class="form-control" id="retailcrm_apikey" type="text" name="module_retailcrm_apikey" value="{% if saved_settings.module_retailcrm_apikey is defined %}{{ saved_settings.module_retailcrm_apikey }}{% endif %}">
</div>
</div>
<div class="form-group retailcrm_unit">
<label class="col-sm-2 control-label" for="module_retailcrm_corporate_enabled">{{ corporate_enabled_label }}</label>
<div class="col-sm-10">
<label class="radio-inline">
<input type="radio" name="module_retailcrm_corporate_enabled" value="1"
{% if saved_settings.module_retailcrm_corporate_enabled is defined and saved_settings.module_retailcrm_corporate_enabled == 1 %}
checked
{% endif %} />
{{ text_yes }}
</label>
<label class="radio-inline">
<input type="radio" name="module_retailcrm_corporate_enabled" value="0"
{% if saved_settings.module_retailcrm_corporate_enabled is not defined or saved_settings.module_retailcrm_corporate_enabled == 0 %}
checked
{% endif %} />
{{ text_no }}
</label>
</div>
</div>
</fieldset>
<fieldset>
<legend>{{ retailcrm_countries_settings }}</legend>
@ -167,7 +174,6 @@
</div>
</div>
</fieldset>
{% if saved_settings.module_retailcrm_apiversion is defined and saved_settings.module_retailcrm_apiversion != 'v3' %}
<fieldset>
<legend>{{ special_price_settings }}</legend>
<div class="form-group retailcrm_unit">
@ -191,7 +197,6 @@
{% endfor %}
</div>
</fieldset>
{% endif %}
<fieldset>
<legend>{{ order_number }}</legend>
<div class="form-group">
@ -460,7 +465,6 @@
{% endfor %}
</fieldset>
</div>
{% if saved_settings.module_retailcrm_apiversion is defined and saved_settings.module_retailcrm_apiversion == 'v5' and customFields is defined %}
<div class="tab-pane" id="tab-custom_fields">
<fieldset>
<legend>{{ retailcrm_dict_custom_fields }}</legend>
@ -548,7 +552,6 @@
{% endif %}
</fieldset>
</div>
{% endif %}
<div class="tab-pane" id="tab-logs">
<fieldset style="margin-bottom: 30px;">
<legend>Retailcrm API error log</legend>

View File

@ -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);
}
}
}

View File

@ -1,104 +0,0 @@
<?php
class ModelExtensionRetailcrmCustomer extends Model {
protected $settings;
protected $moduleTitle;
public function __construct($registry)
{
parent::__construct($registry);
$this->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;
}
}

View File

@ -1,831 +0,0 @@
<?php
/**
* PHP version 5.3
*
* API client class
*
* @category RetailCrm
* @package RetailCrm
* @author RetailCrm <integration@retailcrm.ru>
* @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;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,58 +0,0 @@
<?php
/**
* Class RequestProxy
* @package RetailCrm\Component
*/
class RetailcrmProxy
{
private $api;
private $log;
public function __construct($url, $key, $log, $version = null)
{
switch ($version) {
case 'v5':
$this->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;
}
}
}

View File

@ -0,0 +1,23 @@
<?php
namespace retailcrm;
/**
* Class Base
*
* @property \Loader load
* @property \DB db
* @property \Config config
* @property \Language language
*/
abstract class Base {
protected $registry;
public function __construct(\Registry $registry) {
$this->registry = $registry;
}
public function __get($name) {
return $this->registry->get($name);
}
}

View File

@ -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();
}
}
}
/**

View File

@ -0,0 +1,41 @@
<?php
namespace retailcrm;
class ModelsProvider extends Base {
public function includeDependencies() {
$dependencies = $this->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'
)
);
}
}

View File

@ -0,0 +1,34 @@
<?php
namespace retailcrm;
class Utils {
public static function filterRecursive($haystack) {
foreach ($haystack as $key => $value) {
if (is_array($value)) {
$haystack[$key] = self::filterRecursive($haystack[$key]);
}
if ($haystack[$key] === null
|| $haystack[$key] === ''
|| (is_array($haystack[$key]) && empty($haystack[$key]))
) {
unset($haystack[$key]);
} elseif (!is_array($value)) {
$haystack[$key] = trim($value);
}
}
return $haystack;
}
public static function addressEquals($address1, $address2) {
foreach ($address1 as $field => $value) {
if (isset($address2[$field]) && $value !== $address2[$field]) {
return false;
}
}
return true;
}
}

View File

@ -12,7 +12,10 @@
*/
class RetailcrmApiClient5
{
const VERSION = 'v5';
protected $client;
protected $clientWithoutVersion;
/**
* Site code
@ -30,15 +33,14 @@ class RetailcrmApiClient5
*
* @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
*

View File

@ -0,0 +1,56 @@
<?php
/**
* Class RequestProxy
* @package RetailCrm\Component
*
* @method ordersCreate($order, $site = null)
* @method ordersEdit($order, $by = 'externalId', $site = null)
* @method ordersGet($order, $by = 'externalId', $site = null)
* @method ordersList($filter, $page, $limit)
* @method customersCreate($customer, $site = null)
* @method customersEdit($customer, $by = 'externalId', $site = null)
* @method customersList(array $filter = [], $page = null, $limit = null)
* @method customersGet($id, $by = 'externalId', $site = null)
* @method customersCorporateList(array $filter = [], $page = null, $limit = null)
* @method customersCorporateCreate(array $customerCorporate, $site = null)
* @method customersCorporateAddresses($id, array $filter = [], $page = null, $limit = null, $by = 'externalId', $site = null)
* @method customersCorporateAddressesCreate($id, array $address = [], $by = 'externalId', $site = null)
* @method customersCorporateAddressesEdit($customerId, $addressId, array $address = [], $customerBy = 'externalId', $addressBy = 'externalId', $site = null)
* @method customersCorporateCompanies($id, array $filter = [], $page = null, $limit = null, $by = 'externalId', $site = null)
* @method customersCorporateCompaniesCreate($id, array $company = [], $by = 'externalId', $site = null)
* @method customersCorporateCompaniesEdit($customerId, $companyId, array $company = [], $customerBy = 'externalId', $companyBy = 'externalId', $site = null)
* @method customersCorporateContacts($id, array $filter = [], $page = null, $limit = null, $by = 'externalId', $site = null)
*/
class RetailcrmProxy {
private $api;
private $log;
public function __construct($url, $key) {
$this->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;
}
}
}

View File

@ -0,0 +1,12 @@
<?php
namespace retailcrm\factory;
use retailcrm\service\RetailcrmCustomerConverter;
use retailcrm\service\SettingsManager;
class CustomerConverterFactory {
public static function create(\Registry $registry) {
return new RetailcrmCustomerConverter(new SettingsManager($registry));
}
}

View File

@ -0,0 +1,18 @@
<?php
namespace retailcrm\factory;
use retailcrm\service\RetailcrmOrderConverter;
use retailcrm\service\SettingsManager;
use retailcrm\repository\CustomerRepository;
use retailcrm\repository\ProductsRepository;
class OrderConverterFactory {
public static function create(\Registry $registry) {
return new RetailcrmOrderConverter(
new SettingsManager($registry),
new CustomerRepository($registry),
new ProductsRepository($registry)
);
}
}

View File

@ -0,0 +1,113 @@
<?php
namespace retailcrm\history;
use retailcrm\repository\CustomerRepository;
use retailcrm\repository\DataRepository;
use retailcrm\service\SettingsManager;
class Customer {
private $data_repository;
private $customer_repository;
private $settings_manager;
public function __construct(
DataRepository $data_repository,
CustomerRepository $customer_repository,
SettingsManager $settings_manager
) {
$this->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 : '';
}
}
}

View File

@ -0,0 +1,350 @@
<?php
namespace retailcrm\history;
use retailcrm\repository\DataRepository;
use retailcrm\repository\OrderRepository;
use retailcrm\repository\ProductsRepository;
use retailcrm\service\SettingsManager;
class Order {
private $data_repository;
private $settings_manager;
private $product_repository;
private $order_repository;
private $payment;
private $delivery;
private $oc_payment;
private $oc_delivery;
public function __construct(
DataRepository $data_repository,
SettingsManager $settings_manager,
ProductsRepository $product_repository,
OrderRepository $order_repository
) {
$this->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 : '';
}
}
}

View File

@ -0,0 +1,29 @@
<?php
namespace retailcrm\repository;
class CustomerRepository extends \retailcrm\Base {
public function getCustomer($customer_id) {
if (null !== $this->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);
}
}

View File

@ -0,0 +1,205 @@
<?php
namespace retailcrm\repository;
class DataRepository extends \retailcrm\Base {
/**
* Create order in OC
*
* @param array $order
*
* @return int $order_id
*/
public function addOrder($order) {
$this->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();
}
}

View File

@ -0,0 +1,29 @@
<?php
namespace retailcrm\repository;
class OrderRepository extends \retailcrm\Base {
public function getOrder($order_id) {
if (null !== $this->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();
}
}

View File

@ -0,0 +1,23 @@
<?php
namespace retailcrm\repository;
class ProductsRepository extends \retailcrm\Base {
public function getProductSpecials($product_id) {
$query = $this->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);
}
}

View File

@ -0,0 +1,217 @@
<?php
namespace retailcrm\service;
use retailcrm\repository\CustomerRepository;
use retailcrm\Utils;
class CorporateCustomer {
private $api;
private $customer_repository;
public function __construct(
\RetailcrmProxy $api,
CustomerRepository $customer_repository
) {
$this->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'
);
}
}
}

View File

@ -0,0 +1,109 @@
<?php
namespace retailcrm\service;
class CorporateCustomerBuilder {
private $data = array();
private $company;
public static function create($init = true) {
$self = new self();
if ($init) {
$self->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;
}
}
}
}

View File

@ -0,0 +1,102 @@
<?php
namespace retailcrm\service;
/**
* Class CustomerManager
*/
class CustomerManager {
protected $api;
protected $customer_converter;
public function __construct(\RetailcrmProxy $proxy, RetailcrmCustomerConverter $customer_converter) {
$this->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;
}
}

View File

@ -0,0 +1,173 @@
<?php
namespace retailcrm\service;
/**
* Class OrderManager
*/
class OrderManager {
protected $api;
protected $customer_manager;
protected $order_converter;
protected $corporate_customer_service;
protected $settings_manager;
/**
* OrderManager constructor.
* @param \RetailcrmProxy $proxy
* @param CustomerManager $customer_manager
* @param RetailcrmOrderConverter $order_converter
* @param CorporateCustomer $corporate_customer_service
* @param SettingsManager $settings_manager
*/
public function __construct(
\RetailcrmProxy $proxy,
CustomerManager $customer_manager,
RetailcrmOrderConverter $order_converter,
CorporateCustomer $corporate_customer_service,
SettingsManager $settings_manager
) {
$this->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);
}
}
}

View File

@ -0,0 +1,80 @@
<?php
namespace retailcrm\service;
class RetailcrmCustomerConverter {
protected $data;
protected $customer_data = array();
protected $address = array();
protected $settingsManager;
public function __construct(
SettingsManager $settingsManager
) {
$this->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;
}
}

View File

@ -0,0 +1,300 @@
<?php
namespace retailcrm\service;
use retailcrm\repository\CustomerRepository;
use retailcrm\repository\ProductsRepository;
class RetailcrmOrderConverter {
protected $data;
protected $order_data = array();
protected $order_products = array();
protected $order_totals = array();
protected $settingsManager;
protected $customerRepository;
protected $productsRepository;
public function __construct(
SettingsManager $settingsManager,
CustomerRepository $customerRepository,
ProductsRepository $productsRepository
) {
$this->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;
}
}

View File

@ -0,0 +1,39 @@
<?php
namespace retailcrm\service;
class SettingsManager extends \retailcrm\Base {
private $settings;
public function getSettings() {
if (!$this->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'];
}
}

View File

@ -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,8 +57,7 @@ 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());
if ($apiUrl === null && $apiKey === null) {
@ -38,17 +65,21 @@ class Retailcrm {
? $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 new \RetailcrmProxy($apiUrl, $apiKey, DIR_LOGS . 'retailcrm.log', $apiVersion);
}
if (!$apiUrl || !$apiKey) {
return false;
}
$this->registry->set(
\RetailcrmProxy::class,
new \RetailcrmProxy($apiUrl, $apiKey)
);
}
return $this->registry->get(\RetailcrmProxy::class);
}
/**
* Get opencart api client
*

View File

@ -1,5 +1,54 @@
<?php
class TestCase extends OpenCartTest
{
class TestCase extends OpenCartTest {
public function setUp() {
parent::setUp();
$this->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'");
}
}
}
}
}

View File

@ -1,5 +1,58 @@
<?php
class TestCase extends \Tests\OpenCartTest
{
class TestCase extends \Tests\OpenCartTest {
public function setUp() {
parent::setUp();
$this->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()
{
}
}

View File

@ -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()
{
}
}

View File

@ -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']);
}
}

View File

@ -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']);
}
}

View File

@ -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",

View File

@ -0,0 +1,11 @@
<?php
require_once __DIR__ . '/../' . getenv('TEST_SUITE') . '/TestCase.php';
class ControllerDaemonCollectorExtensionAnalyticsCatalogTest extends TestCase {
public function testIndex() {
$data = $this->load->controller('extension/analytics/daemon_collector');
$this->assertContains('RC-XXXXXXXXXX-X', $data);
}
}

View File

@ -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'");
}
}
}
}
}

View File

@ -1,64 +0,0 @@
<?php
require_once __DIR__ . '/../' . getenv('TEST_SUITE') . '/TestCase.php';
class ModelRetailcrmCustomerCatalogTest extends TestCase
{
private $customerModel;
private $apiClientMock;
const CUSTOMER_ID = 1;
public function setUp()
{
parent::setUp();
$this->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']);
}
}

View File

@ -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');

View File

@ -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');

View File

@ -0,0 +1,18 @@
<?php
require_once __DIR__ . '/../' . getenv('TEST_SUITE') . '/TestCase.php';
class RetailcrmTest extends TestCase {
public function testGetOrderManager() {
$retailcrm = new retailcrm\Retailcrm(static::$registry);
$proxy = $this->getMockBuilder(\RetailcrmProxy::class)
->disableOriginalConstructor()
->getMock();
static::$registry->set(\RetailcrmProxy::class, $proxy);
$manager = $retailcrm->getOrderManager();
$this->assertInstanceOf(\retailcrm\service\OrderManager::class, $manager);
}
}

View File

@ -0,0 +1,14 @@
<?php
require_once __DIR__ . '/../../' . getenv('TEST_SUITE') . '/TestCase.php';
class ModelsProviderAdminTest extends TestCase {
public function testAdminIncludeDependencies() {
// TODO should be run with "processIsolation", but with that not working asserting
// $provider = new \retailcrm\ModelsProvider(static::$registry);
//
// $provider->includeDependencies();
//
// $this->assertNotEmpty($this->model_sale_order);
}
}

View File

@ -0,0 +1,13 @@
<?php
require_once __DIR__ . '/../../' . getenv('TEST_SUITE') . '/TestCase.php';
class ModelsProviderTest extends TestCase {
public function testCatalogIncludeDependencies() {
$provider = new \retailcrm\ModelsProvider(static::$registry);
$provider->includeDependencies();
$this->assertNotEmpty($this->model_checkout_order);
}
}

View File

@ -0,0 +1,21 @@
<?php
require_once __DIR__ . '/../../' . getenv('TEST_SUITE') . '/TestCase.php';
class UtilsTest extends TestCase {
public function testFilterRecursive() {
$testArray = array(
'0' => 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);
}
}

View File

@ -0,0 +1,11 @@
<?php
require_once __DIR__ . '/../../../' . getenv('TEST_SUITE') . '/TestCase.php';
class CustomerConverterFactoryTest extends TestCase {
public function testCreate() {
$converter = \retailcrm\factory\CustomerConverterFactory::create(static::$registry);
$this->assertInstanceOf(\retailcrm\service\RetailcrmCustomerConverter::class, $converter);
}
}

View File

@ -0,0 +1,11 @@
<?php
require_once __DIR__ . '/../../../' . getenv('TEST_SUITE') . '/TestCase.php';
class OrderConverterFactoryTest extends TestCase {
public function testCreate() {
$converter = \retailcrm\factory\OrderConverterFactory::create(static::$registry);
$this->assertInstanceOf(\retailcrm\service\RetailcrmOrderConverter::class, $converter);
}
}

View File

@ -0,0 +1,65 @@
<?php
require_once __DIR__ . '/../../../' . getenv('TEST_SUITE') . '/TestCase.php';
class CustomerAdminTest extends TestCase {
private $customer;
public function setUp() {
parent::setUp();
$this->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']);
}
}

View File

@ -0,0 +1,147 @@
<?php
require_once __DIR__ . '/../../../' . getenv('TEST_SUITE') . '/TestCase.php';
class OrderAdminTest extends TestCase {
private $order;
private $order_history;
public function setUp() {
parent::setUp();
$this->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'
)
)
)
);
}
}

View File

@ -0,0 +1,17 @@
<?php
require_once __DIR__ . '/../../../' . getenv('TEST_SUITE') . '/TestCase.php';
class CustomerRespositoryAdminTest extends TestCase {
const CUSTOMER_ID = 1;
const ADDRESS_ID = 1;
public function testGetCustomer() {
$repository = new \retailcrm\repository\CustomerRepository(static::$registry);
$customer = $repository->getCustomer(static::CUSTOMER_ID);
$this->assertNotEmpty($customer);
$this->assertEquals(static::CUSTOMER_ID, $customer['customer_id']);
}
}

View File

@ -0,0 +1,17 @@
<?php
require_once __DIR__ . '/../../../' . getenv('TEST_SUITE') . '/TestCase.php';
class CustomerRespositoryTest extends TestCase {
const CUSTOMER_ID = 1;
const ADDRESS_ID = 1;
public function testGetCustomer() {
$repository = new \retailcrm\repository\CustomerRepository(static::$registry);
$customer = $repository->getCustomer(static::CUSTOMER_ID);
$this->assertNotEmpty($customer);
$this->assertEquals(static::CUSTOMER_ID, $customer['customer_id']);
}
}

View File

@ -0,0 +1,63 @@
<?php
require_once __DIR__ . '/../../../' . getenv('TEST_SUITE') . '/TestCase.php';
class DataRepositoryAdminTest extends TestCase {
public function testGetCountryByIsoCode() {
$repository = new \retailcrm\repository\DataRepository(static::$registry);
$country = $repository->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);
}
}

View File

@ -0,0 +1,22 @@
<?php
require_once __DIR__ . '/../../../' . getenv('TEST_SUITE') . '/TestCase.php';
class OrderRepositoryAdminTest extends TestCase {
public function testGetOrder() {
$repository = new \retailcrm\repository\OrderRepository(static::$registry);
$order = $repository->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);
}
}

View File

@ -0,0 +1,31 @@
<?php
require_once __DIR__ . '/../../../' . getenv('TEST_SUITE') . '/TestCase.php';
class ProductsRespositoryTest extends TestCase {
const CUSTOMER_ID = 1;
public function testGetProductSpecials() {
$repository = new \retailcrm\repository\ProductsRepository(static::$registry);
$specials = $repository->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);
}
}

View File

@ -0,0 +1,37 @@
<?php
require_once __DIR__ . '/../../../' . getenv('TEST_SUITE') . '/TestCase.php';
class CorporateCustomerBuilderTest extends TestCase {
public function testBuild() {
$data = array(
'payment_postcode' => '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']);
}
}

View File

@ -0,0 +1,107 @@
<?php
require_once __DIR__ . '/../../../' . getenv('TEST_SUITE') . '/TestCase.php';
class CorporateCustomerTest extends TestCase {
const ORDER_ID = 2;
public function testBuildCorporateCustomerFromOrder() {
$model = $this->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);
}
}

View File

@ -0,0 +1,77 @@
<?php
require_once __DIR__ . '/../../../' . getenv('TEST_SUITE') . '/TestCase.php';
class CustomerManagerTest extends TestCase {
const CUSTOMER_ID = 1;
public function testCreateCustomer() {
$customerModel = $this->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);
}
}

View File

@ -0,0 +1,250 @@
<?php
require_once __DIR__ . '/../../../' . getenv('TEST_SUITE') . '/TestCase.php';
class OrderManagerTest extends TestCase {
const CUSTOMER_ID = 1;
const ORDER_WITH_CUST_ID = 1;
const ORDER_ID = 2;
public function testCreateOrderWithCustomer() {
$proxy = $this->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'
)
)
);
}
}

View File

@ -0,0 +1,52 @@
<?php
require_once __DIR__ . '/../../../' . getenv('TEST_SUITE') . '/TestCase.php';
class RetailcrmCustomerConverterTest extends TestCase {
const CUSTOMER_ID = 1;
public function testSetCustomerData() {
$converter = \retailcrm\factory\CustomerConverterFactory::create(static::$registry);
$model = $this->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']
);
}
}

View File

@ -0,0 +1,134 @@
<?php
require_once __DIR__ . '/../../../' . getenv('TEST_SUITE') . '/TestCase.php';
class RetailcrmOrderConverterTest extends TestCase {
const CUSTOMER_ID = 1;
const ORDER_WITH_CUST_ID = 1;
const ORDER_ID = 2;
public function testSetOrderData() {
$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
)->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']);
}
}

View File

@ -0,0 +1,44 @@
<?php
require_once __DIR__ . '/../../../' . getenv('TEST_SUITE') . '/TestCase.php';
class SettingsManagerTest extends TestCase {
public function testGetSettings() {
$settings_manager = new \retailcrm\service\SettingsManager(static::$registry);
$settings = $settings_manager->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);
}
}